Skip to content

Instantly share code, notes, and snippets.

@cometkim
Created August 12, 2026 07:50
Show Gist options
  • Select an option

  • Save cometkim/0334fcdd0ff2ed880798c7eea5c31213 to your computer and use it in GitHub Desktop.

Select an option

Save cometkim/0334fcdd0ff2ed880798c7eea5c31213 to your computer and use it in GitHub Desktop.
Redacted value class should be a primitive for all codebase
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