Skip to content

Local-first 🧠 memory for Hermes Agent that lives in your Obsidian vault and remembers project context. Nightly 😴 dream passes turn repeat corrections into confirmed preferences with measurable confidence. Adapters ship for Claude Code, Codex, and OpenClaw, with an MCP server for anything else.

TypeScript
5.9 KB
Raw Blame
export interface SecretReference {
  readonly raw: string;
  readonly name: string;
}

export interface SecretReferenceStatus {
  readonly configKey: string;
  readonly name: string;
  readonly available: boolean;
  /**
   * Present (true) only on a value that is reference-SHAPED but fails the
   * reference grammar - `$secret:has space` with a body the grammar cannot
   * spell. Such a value resolves to a `SecretReferenceError` at use time no
   * matter what the store or the environment holds, so the inspection
   * surfaces must show it rather than silently drop it. Optional so
   * well-formed rows keep their exact shape.
   */
  readonly invalid?: boolean;
}

export type SecretProvider = Readonly<Record<string, string | undefined>>;

export class SecretReferenceError extends Error {
  readonly nameValue: string;

  constructor(message: string, nameValue: string) {
    super(message);
    this.name = "SecretReferenceError";
    this.nameValue = nameValue;
  }
}

/**
 * The reference body spells every name the custody store can hold (its
 * slugs are lowercase with `-` and `_`, starting alphanumeric) plus the
 * uppercase env-style names the environment fallback answers with. The
 * body's CASE is preserved: the store leg of a resolution normalizes it
 * ({@link storeSecretName}); the environment leg stays case-sensitive.
 */
const SECRET_REFERENCE_RE = /^\$secret:([A-Za-z0-9_][A-Za-z0-9_-]*)$/;
/** The syntax prefix every named-secret reference starts with. */
const REFERENCE_PREFIX = "$secret:";
const REDACTED = "***REDACTED***";

/**
 * The name a reference resolves through the custody STORE under: the store
 * normalizes names at set time (trim, lowercase - a slug), so the store leg
 * of a lookup normalizes the reference body the same way. Deliberately NOT
 * applied to the environment leg: env lookup is case-sensitive, so
 * `$secret:BRAVE` answers store entry `brave` but environment variable
 * `BRAVE` and nothing else.
 */
export function storeSecretName(name: string): string {
  return name.trim().toLowerCase();
}

export function parseSecretReference(value: unknown): SecretReference | null {
  if (typeof value !== "string") return null;
  const match = SECRET_REFERENCE_RE.exec(value.trim());
  if (!match) return null;
  return Object.freeze({ raw: value.trim(), name: match[1]! });
}

/**
 * Whether a config value claims to be a reference. `$secret:` with a
 * malformed body is still reference-shaped - it resolves to a
 * `SecretReferenceError`, never to the literal text.
 */
export function isSecretReferenceValue(value: unknown): boolean {
  return typeof value === "string" && value.trimStart().startsWith(REFERENCE_PREFIX);
}

/**
 * The reference body of a reference-SHAPED value the grammar cannot spell
 * (e.g. the spaced `has space` in `$secret:has space`), or null when the
 * value is not reference-shaped at all. This is the name the runtime
 * refusal names, so the inspection surfaces can show the same identifier
 * the operator must fix (rename the store entry, or change the config
 * value to a spellable reference).
 */
export function invalidSecretReferenceBody(value: unknown): string | null {
  if (!isSecretReferenceValue(value)) return null;
  const body = (value as string).trim().slice(REFERENCE_PREFIX.length);
  return body.length > 0 ? body : null;
}

export function resolveSecretReference(
  value: string,
  provider: SecretProvider = process.env,
): string {
  const ref = parseSecretReference(value);
  if (!ref) {
    throw new SecretReferenceError(`invalid secret reference: ${value}`, value);
  }
  const resolved = provider[ref.name];
  if (!resolved) {
    throw new SecretReferenceError(`missing secret provider value: ${ref.name}`, ref.name);
  }
  return resolved;
}

export function listSecretReferences(
  data: Readonly<Record<string, unknown>>,
  provider: SecretProvider = process.env,
): ReadonlyArray<SecretReferenceStatus> {
  const out: SecretReferenceStatus[] = [];
  for (const [configKey, value] of Object.entries(data)) {
    const ref = parseSecretReference(value);
    if (!ref) {
      const body = invalidSecretReferenceBody(value);
      if (body !== null) {
        out.push({ configKey, name: body, available: false, invalid: true });
      }
      continue;
    }
    out.push({
      configKey,
      name: ref.name,
      available: Boolean(provider[ref.name]),
    });
  }
  out.sort((a, b) => a.configKey.localeCompare(b.configKey));
  return Object.freeze(out);
}

/**
 * Dedupe, drop sub-floor entries, and order longest-first. The order is the
 * substitution-safety rule, not cosmetics: when one resolved value contains
 * another, a shorter-first replacement would destroy the longer value's
 * match and leak its head as a fragment, so every caller that substitutes
 * literal values into text goes through this.
 *
 * The minimum length is the over-redaction guard: a one- or two-character
 * resolved value would blank EVERY occurrence of those characters in the
 * surrounding text, destroying the diagnostic it rides on. The trade-off is
 * stated, not hidden: a credential shorter than the floor is NOT scrubbed
 * from egress text - accepted, because real credentials clear the floor and
 * the collateral damage of a short literal dwarfs its leak value.
 */
export const MIN_REDACTED_LITERAL_LENGTH = 8;

export function sortedDistinctLiterals(values: Iterable<string>): string[] {
  return [...new Set(values)]
    .filter((value) => value.length >= MIN_REDACTED_LITERAL_LENGTH)
    .sort((a, b) => b.length - a.length);
}

export function redactKnownSecretValues(
  text: string,
  references: ReadonlyArray<string>,
  provider: SecretProvider = process.env,
): string {
  let out = text;
  const values = sortedDistinctLiterals(
    references
      .map((raw) => parseSecretReference(raw))
      .filter((ref): ref is SecretReference => ref !== null)
      .map((ref) => provider[ref.name])
      .filter((value): value is string => Boolean(value)),
  );
  for (const value of values) {
    out = out.replaceAll(value, REDACTED);
  }
  return out;
}