Created
August 12, 2026 07:50
-
-
Save cometkim/0334fcdd0ff2ed880798c7eea5c31213 to your computer and use it in GitHub Desktop.
Redacted value class should be a primitive for all codebase
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const registry = new WeakMap<Redacted<any>, any>(); | |
| /** | |
| * Redacted<T> is a basic primitive for handling credentials. | |
| * This prevents to leak your secrets to any output by implicit behaviors like `toString()`. | |
| * | |
| * @example | |
| * | |
| * ```ts | |
| * const password = Redacted.make('secret'); | |
| * | |
| * JSON.stringify({ password }); | |
| * // => '{"password":"<redacted>"}' | |
| * | |
| * console.log({ password }); | |
| * // => { password: <redacted> } | |
| * ``` | |
| */ | |
| export class Redacted<T> { | |
| static make<T>(value: T): Redacted<T> { | |
| const redacted = new Redacted<T>(); | |
| registry.set(redacted, value); | |
| return redacted; | |
| } | |
| static value<T>(self: Redacted<T>): T { | |
| const value = registry.get(self); | |
| if (value === undefined) { | |
| throw new Error('Redacted value was has not been registered.'); | |
| } | |
| return value; | |
| } | |
| toString(): string { | |
| return '<redacted>'; | |
| } | |
| toJSON(): string { | |
| return '<redacted>'; | |
| } | |
| get [Symbol.toStringTag](): string { | |
| return 'Redacted'; | |
| } | |
| [Symbol.toPrimitive](): string { | |
| return '<redacted>'; | |
| } | |
| [Symbol.for('nodejs.util.inspect.custom')](): string { | |
| return '<redacted>'; | |
| } | |
| get $Value(): T { | |
| throw new TypeError( | |
| "Don't use $Value directly. Use it as a type annotation only.", | |
| ); | |
| } | |
| } | |
| // Additionally a Zod integration. | |
| import type * as z from 'zod'; | |
| export function RedactedSchema<Out, In>( | |
| baseSchema: z.ZodType<Out, In>, | |
| ): z.ZodType<Redacted<Out>, In> { | |
| return baseSchema.transform(Redacted.make); | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment