Cotton code
303 lines · 13.7 KB · TypeScriptRaw
/** * The vault's tools: `create_secret`, `list_secrets` and the owner's * `dev_reveal_secret` (crates/cotton-tools/src/mcp/handlers/secrets.rs, * dev.rs; the payload is crates/cotton-core/src/vault/payload.rs). * * A secret row keeps its value only as `sealed` — the payload's JSON sealed * with the row's id bound in. No `hint` is written or listed (keys DECISIONS.md S2, 25 Nov 2026): the tail a list * shows is worked out on the phone from the value. Nothing here answers a value except * dev_reveal_secret, which the front door admits for an owner token alone, * and no line here ever logs one. */import { SealedRows } from "../sealed_rows.ts";import { fail, isoTimestamp, optionalString, ToolFailure, type Data, type ToolContext } from "../../context.ts";import { Refused } from "../../../http.ts";import { col, typeOf, type Cond, type StoredRow } from "../../../store.ts";import { equalSql } from "./where.ts";import { arrivalKey } from "./write.ts";import { isArrivalValue, sealValueAtArrival } from "../../../arrival.ts";import { resolveTable } from "./table.ts";import { isSealedTable } from "../window.ts";const SECRET = "secret";const NAME_MAX = 120;const SERVICE_MAX = 60;const SITE_MAX = 255;const USERNAME_MAX = 255;interface Field {  name: string;  required: boolean;}/** Each kind's fields in the payload's own order, its primary first (`SECRET_KINDS`). */const KINDS: Record<string, Field[]> = {  login: [    { name: "password", required: true },    { name: "notes", required: false },    { name: "totp", required: false },    { name: "urls", required: false },  ],  api_key: [    { name: "key", required: true },    { name: "notes", required: false },  ],  note: [{ name: "body", required: true }],  card: [    { name: "number", required: true },    { name: "holder", required: false },    { name: "expiry", required: false },    { name: "cvv", required: false },    { name: "notes", required: false },  ],  identity: [    { name: "number", required: true },    { name: "id_type", required: false },    { name: "holder", required: false },    { name: "issued", required: false },    { name: "expires", required: false },    { name: "country", required: false },    { name: "notes", required: false },  ],  document: [{ name: "password", required: true }],  code: [    { name: "secret", required: true },    { name: "notes", required: false },  ],  wifi: [    { name: "password", required: true },    { name: "security", required: false },    { name: "notes", required: false },  ],  address: [    { name: "address", required: true },    { name: "full_name", required: false },    { name: "email", required: false },    { name: "phone", required: false },    { name: "notes", required: false },  ],  file: [    { name: "content", required: true },    { name: "file_name", required: false },    { name: "store_password", required: false },    { name: "key_alias", required: false },    { name: "key_password", required: false },    { name: "notes", required: false },  ],};const KIND_NAMES = Object.keys(KINDS);const KINDS_SENTENCE = `kind must be one of ${KIND_NAMES.join(", ")}`;function primary(kind: string): string {  return KINDS[kind]![0]!.name;}function capped(value: string, max: number, what: string): string {  if ([...value].length > max) fail(`${what} must be at most ${max} characters`);  return value;}function validateService(service: string): string {  if (service.length > SERVICE_MAX) fail(`service must be at most ${SERVICE_MAX} characters`);  if (!/^[a-z0-9][a-z0-9._-]*$/.test(service)) fail("service must be lowercase letters, digits, dots, hyphens or underscores, starting with a letter or a digit — 'anthropic', 'openai', 'my-bank'");  return service;}/** What serde says of a value that is not the string a field wants. */function serdeFound(v: unknown): string {  if (v === null) return "null";  if (typeof v === "boolean") return `boolean \`${v}\``;  if (typeof v === "number") return Number.isInteger(v) ? `integer \`${v}\`` : `floating point \`${v}\``;  if (Array.isArray(v)) return "sequence";  return "map";}/** The typed payload, internally tagged by kind, its optional fields left out when absent (`SecretPayload`). */function payloadFrom(kind: string, fields: Data): { payload: Data; primary: string } {  const spec = KINDS[kind]!;  const payload: Data = { kind };  for (const f of spec) {    const v = fields[f.name];    if (v === undefined || (v === null && !f.required)) {      if (f.required) throw new Error(`missing field \`${f.name}\``);      continue;    }    if (typeof v !== "string") throw new Error(`invalid type: ${serdeFound(v)}, expected a string`);    payload[f.name] = v;  }  return { payload, primary: payload[spec[0]!.name] as string };}function payloadOf(kind: string, args: Data): { payload: Data; primary: string } {  const fields = args.fields && typeof args.fields === "object" && !Array.isArray(args.fields) ? (args.fields as Data) : null;  const value = typeof args.value === "string" ? args.value : null;  if (fields && value !== null) fail("pass value OR fields, not both — value is the one primary field, fields is the whole typed payload");  if (fields) {    try {      return payloadFrom(kind, fields);    } catch (error) {      const names = KINDS[kind]!.map((f) => f.name).join(", ");      fail(`fields is not a ${kind} payload: ${(error as Error).message}. The fields of a ${kind} are ${names}.`);    }  }  if (value === null) fail(`value is required — the ${primary(kind)} of a ${kind}`);  if (value === "") fail("value is empty — pass the credential itself, or delete_secret to bin one");  return { payload: { kind, [primary(kind)]: value }, primary: value };}const VAULT_REFUSAL_TAIL = "Nothing was written. Do not retry.";/** The object's own tokens (the Google and Spotify grants): it uses them with no phone present, so they stay its own. */const OBJECT_SERVICES = ["google", "spotify"];/** * Seal a payload for one row, or refuse by name: no vault is never a value kept in the clear. Once the passwords are * sealed (the open tables lock past handing) and a phone has handed its arrival key, the value is sealed to that key * (keys DECISIONS.md S3, 25 Nov 2026): the object cannot open it again, and the phone moves it under the vault key. */async function seal(ctx: ToolContext, id: string, payload: Data, service: string | null): Promise<string> {  const arrival = service !== null && OBJECT_SERVICES.includes(service) ? null : arrivalKey(ctx);  if (arrival && ctx.defs().table(SECRET) && isSealedTable(resolveTable(ctx, SECRET))) return sealValueAtArrival(arrival, ctx.database.id, id, JSON.stringify(payload));  try {    return await ctx.seal(id, JSON.stringify(payload));  } catch (error) {    if (error instanceof Refused && error.code === "vault_unavailable") fail(`vault_unavailable: this Cotton build cannot open the owner's passwords — ${error.message}. ${VAULT_REFUSAL_TAIL}`);    if (error instanceof ToolFailure) throw error;    fail(`the secret could not be sealed. ${VAULT_REFUSAL_TAIL}`);  }}function str(row: StoredRow, key: string): string | null {  const v = row.data[key];  return typeof v === "string" && v !== "" ? v : null;}export async function createSecret(ctx: ToolContext, args: Data): Promise<Data> {  const name = capped(optionalString(args, "name") ?? fail("name is required"), NAME_MAX, "name");  const rawKind = optionalString(args, "kind");  const kind = rawKind === null ? "api_key" : KIND_NAMES.includes(rawKind) ? rawKind : fail(KINDS_SENTENCE);  const askedService = optionalString(args, "service");  const service = askedService !== null ? validateService(askedService) : kind === "api_key" ? fail("service is required for an api key — it is how the key is found again ('anthropic', 'openai')") : null;  const site = ((v) => (v === null ? null : capped(v, SITE_MAX, "site")))(optionalString(args, "site"));  const username = ((v) => (v === null ? null : capped(v, USERNAME_MAX, "username")))(optionalString(args, "username"));  const expiresRaw = optionalString(args, "expiresAt");  const expiresAt = expiresRaw === null ? null : (isoTimestamp(expiresRaw) ?? fail("expiresAt must be a date or a timestamp"));  const { payload } = payloadOf(kind, args);  // One row per (service, name) where there is a service; a login with none is always new.  const existing = service !== null ? (ctx.store.select(SECRET, [equalSql("service", service), equalSql("name", name)], "created_at, id", 1)[0] ?? null) : null;  // The id is decided before the seal: it is the seal's bound data.  const id = existing?.id ?? crypto.randomUUID();  const sealed = await seal(ctx, id, payload, service);  // No hint (S2): and a row saved again loses the one an earlier build wrote.  const patch: Data = { sealed, kind, ...(existing && existing.data.hint !== undefined ? { hint: null } : {}) };  if (site !== null) patch.site = site;  if (username !== null) patch.username = username;  if (expiresAt !== null) patch.expires_at = expiresAt;  // Re-pasting a binned key brings it back.  patch.trashed_at = null;  // The passwords sealed (OPEN TABLES, OPEN-TABLES.md §3): the name, site, user name and hint are sealed on arrival to  // the owner's key, so the object cannot read them back; an existing row is found only while its name is still clear.  const rows = await SealedRows.of(ctx, [SECRET]);  if (existing) {    const p = await rows.patchNow(SECRET, existing, patch);    ctx.write((w) => rows.changed(w, SECRET, existing, p));  } else {    patch.name = name;    if (service !== null) patch.service = service;    const p = await rows.createNow(SECRET, id, patch);    ctx.write((w) => rows.made(w, SECRET, id, p));  }  const out: Data = { id, kind, name };  if (site !== null) out.site = site;  if (username !== null) out.username = username;  if (service !== null) out.service = service;  return out;}const LIST_COLUMNS: [string, string][] = [  ["kind", "kind"],  ["name", "name"],  ["site", "site"],  ["username", "username"],  ["service", "service"],  ["last_used_at", "lastUsedAt"],  ["expires_at", "expiresAt"],];/** The columns `q` looks in, a substring without ASCII case. */const SEARCHED = ["name", "site", "username", "service"];/** * What is stored, and nothing of what it says: `sealed` is never read here. Once the passwords are sealed (OPEN * TABLES), a secret's name, site, user name and hint are sealed too: a listing says its id, kind, service, times and * whether it is set, and `q` finds by service alone. */export function listSecrets(ctx: ToolContext, args: Data): Data {  const rawKind = optionalString(args, "kind");  if (rawKind !== null && !KIND_NAMES.includes(rawKind)) fail(KINDS_SENTENCE);  const service = optionalString(args, "service");  const asked = optionalString(args, "q")?.toLowerCase() ?? null;  // Narrowed and ordered in SQL; the answer is every secret that holds, as the Rust list is.  const conds: Cond[] = [{ sql: `NOT (${typeOf("trashed_at")} = 'text' AND ${col("trashed_at")} <> '')`, args: [] }];  if (rawKind !== null) conds.push(equalSql("kind", rawKind));  if (service !== null) conds.push(equalSql("service", service));  if (asked !== null) {    const like = `%${asked.replace(/[\\%_]/g, (c) => `\\${c}`)}%`;    conds.push({ sql: SEARCHED.map((k) => `(${typeOf(k)} = 'text' AND ${col(k)} LIKE ? ESCAPE '\\')`).join(" OR "), args: SEARCHED.map(() => like) });  }  const rows = ctx.store.select(SECRET, conds, "updated_at DESC, id", -1);  return {    secrets: rows.map((r) => {      const out: Data = { id: r.id };      for (const [column, key] of LIST_COLUMNS) {        const v = str(r, column);        if (v !== null) out[key] = v;      }      out.createdAt = r.created_at;      out.updatedAt = r.updated_at;      // Whether a value has arrived: a named secret with nothing sealed in it is a real state.      out.isSet = str(r, "sealed") !== null || str(r, "value_enc") !== null;      return out;    }),  };}/** The one reader of a stored value; the front door admits an owner token alone. */export async function devRevealSecret(ctx: ToolContext, args: Data): Promise<Data> {  const id = optionalString(args, "secretId");  if (!id || !/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$/.test(id)) fail("secretId must be a uuid");  const row = ctx.get(SECRET, id) ?? fail(`no secret with id ${id}`);  const name = str(row, "name") ?? "";  const sealed = str(row, "sealed");  if (sealed === null) fail(`${name} is a named secret with nothing stored in it yet — list_secrets says isSet false for it`);  if (isArrivalValue(sealed)) fail(`${name} is sealed to the owner's own devices (it was saved over MCP after the passwords were sealed): only their phone opens it. Nothing was changed. Do not retry.`);  let opened: string | null;  try {    opened = await ctx.open(id, sealed);  } catch (error) {    if (error instanceof Refused && error.code === "vault_unavailable") fail(`vault_unavailable: this Cotton build cannot open the owner's passwords — ${error.message}. Do not retry.`);    throw error;  }  if (opened === null) fail(`the vault would not open ${name} — a wrong key version, a body that does not verify, or a vault that cannot open this database. Nothing was changed. Do not retry.`);  let payload: Data;  try {    const parsed = JSON.parse(opened) as Data;    const kind = typeof parsed.kind === "string" && KINDS[parsed.kind] ? parsed.kind : null;    if (!kind) throw new Error("no kind");    payload = payloadFrom(kind, parsed).payload;  } catch {    fail(`${name} opened but what is inside it is not a payload this build understands`);  }  return {    id,    kind: str(row, "kind"),    name,    service: str(row, "service"),    site: str(row, "site"),    username: str(row, "username"),    binned: str(row, "trashed_at") !== null,    payload,  };}