import type { Vault } from '@matatbread/matbot-plugin-api'; import { applyResolve, applyCreateSecret, assertStorableKey, unreferenceableKey } from '@matatbread/matbot-plugin-api'; /** * Default vault implementation: a single flat namespace of secrets keyed by name. * * Resolves ${NAME} placeholders by looking up `NAME`. There is no env/secret distinction — * an env var is simply a secret whose name happens to be its env-var name. A backend may * privately treat some prefixes specially, but the placeholder syntax and this interface do not. * * The caller loads any backing store (e.g. a .env file) into the snapshot passed to the * constructor; persistence beyond the current process is a subclass concern (see EnvFileVault). */ export class VaultImpl implements Vault { private readonly store = new Map(); constructor( secrets?: Record, env?: Record, ) { if (secrets) { for (const [k, v] of Object.entries(secrets)) { this.store.set(k, v); } } if (env) { for (const [k, v] of Object.entries(env)) { if (v !== undefined && !this.store.has(k)) this.store.set(k, v); } } } createSecret(name: string, value: string): Promise { return applyCreateSecret(this, name, value); } async writeSecret(name: string, value: string): Promise { if (value === '') { this.store.delete(name); return; } // `this`, not the base policy directly, so a subclass narrowing the rule (EnvFileVault) is // enforced through the inherited write rather than having to re-implement it. assertStorableKey(this, name); this.store.set(name, value); } /** A plain map stores anything that can be referenced; subclasses narrowing this call `super`. */ unstorableKey(name: string): string | undefined { return unreferenceableKey(name); } hasKey(name: string): boolean { return this.store.has(name); } findByValue(value: string): string | undefined { for (const [k, v] of this.store) if (v === value) return k; return undefined; } async readSecret(name: string): Promise { return this.store.get(name); } resolve(ref: string): Promise { return applyResolve(this, ref); } scrub(text: string): string { let result = text; for (const value of this.store.values()) { if (value.length >= 4) { result = result.split(value).join('[REDACTED]'); } } return result; } }