-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathSecret.ts
97 lines (86 loc) · 2.24 KB
/
Secret.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
// local
import type { Identity, StringKeys } from '@transcend-io/type-utils';
const REDACTED = '[redacted]';
/**
* A secret that must be explicitly released. It is made to be annoying, so that
* users must really make an effort to release the stored value.
* The goal is to prevent accidentally logging secret values.
*/
export class Secret<T> {
/** The secret value */
private value: T;
/**
* Constructor
* @param value - The secret value
*/
constructor(value: T) {
this.value = value;
}
/* eslint-disable class-methods-use-this */
/**
* Ensure secrets are not coerced to their secret values.
*
* toJSON is called in cases like JSON.stringify(obj)
* @returns a redacted message
*/
public toJSON(): string {
return REDACTED;
}
/**
* Ensure secrets are not coerced to their secret values.
* @returns a redacted message
*/
public valueOf(): string {
return REDACTED;
}
/**
* Ensure secrets are not coerced to their secret values.
*
* This is the method used by `console.log` on objects
* @returns a redacted message
*/
[Symbol.for('nodejs.util.inspect.custom')](): string {
return REDACTED;
}
/**
* Ensure secrets are not coerced to their secret values.
* @returns a redacted message
*/
public toLocaleString(): string {
return REDACTED;
}
/**
* Ensure secrets are not coerced to their secret values.
* @returns a redacted message
*/
public toString(): string {
return REDACTED;
}
/* eslint-enable class-methods-use-this */
/**
* Releases the secret for usage
* @returns the secret value
*/
public release(): T {
return this.value;
}
/**
* Apply a function to the secret value, and returns a new Secret with that value.
* @param transformFunc - Function to apply to the current value
* @returns the new secret for chaining other commands
*/
public map<R>(transformFunc: (value: T) => R): Secret<R> {
return new Secret(transformFunc(this.value));
}
}
/**
* Set the type of values in an object to be Secret<value> by name of object key
*/
export type Secretify<
T extends object,
TSecretKey extends StringKeys<T>,
> = Identity<
{
[k in keyof T]: k extends TSecretKey ? Secret<T[k]> : T[k];
}
>;