Cotton code
80 lines · 4.9 KB · TypeScriptRaw
/** * ADMIN KEYS 3 (NEXT-ADMIN-KEYS-3, 27 Nov 2026): the allow-list machinery ships, and what a NEW key or OAuth connection * gets when nothing names it stays as today behind one server switch (KEY_DEFAULT: "today" on live, "narrow" on dev). * And `GET /v1/keys`, the account's keys for the Assistants screen: the owner's own device alone, never a hash. */import { env, runInDurableObject } from "cloudflare:test";import { describe, expect, it } from "vitest";import { keyDefault } from "../src/env.ts";import { DEFAULT_ALLOW } from "../src/key_allow.ts";import { http, mint, personalObject } from "./personal.ts";type Row = { id: string; data: Record<string, unknown> };async function tokens(slug: string): Promise<Row[]> {  return runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => [...(instance as unknown as { store: { scan(t: string): Iterable<Row> } }).store.scan("mcp_token")]);}/** Sets the switch as the Worker's var would (the pool's is "narrow", as dev's; passing "narrow" restores it). */async function setSwitch(slug: string, value: string): Promise<void> {  await runInDurableObject(env.BUSINESS.get(env.BUSINESS.idFromName(slug)), (instance) => {    (instance as unknown as { env: Record<string, unknown> }).env.KEY_DEFAULT = value;  });}describe("the KEY_DEFAULT switch", () => {  it("is today on live and wherever nothing says, narrow on dev and in tests, and an explicit value wins", () => {    expect(keyDefault({ ENV_LABEL: "production" })).toBe("today");    expect(keyDefault({})).toBe("today");    expect(keyDefault({ ENV_LABEL: "dev" })).toBe("narrow");    expect(keyDefault({ ENV_LABEL: "test" })).toBe("narrow");    expect(keyDefault({ ENV_LABEL: "production", KEY_DEFAULT: "narrow" })).toBe("narrow");    expect(keyDefault({ ENV_LABEL: "dev", KEY_DEFAULT: "today" })).toBe("today");    expect(keyDefault({ ENV_LABEL: "production", KEY_DEFAULT: "wide" })).toBe("today");  });  it("gives a new key no allow list while it says today, the narrowest useful set when narrow; a named allow either way", async () => {    const slug = "key-default-mint";    const { credential } = await personalObject(slug);    await setSwitch(slug, "today");    // `allow: null` sends none (the helper's default names "all").    await mint(slug, credential, "Invented today key", ["owner"], undefined, undefined, null);    const named = await http(slug, "POST", "/v1/act", { act: "mint_token", args: { name: "Invented named key", scopes: ["owner"], allow: { read: ["note"], write: [] } } }, { authorization: `Bearer ${credential}` });    expect(named.status, JSON.stringify(named.body)).toBe(200);    await setSwitch(slug, "narrow");    await mint(slug, credential, "Invented narrow key", ["owner"], undefined, undefined, null);    const rows = await tokens(slug);    const allow = (name: string) => rows.find((r) => r.data.name === name)!.data.allow ?? null;    expect(allow("Invented today key")).toBeNull();    expect(JSON.parse(String(allow("Invented narrow key")))).toEqual(DEFAULT_ALLOW);    expect(JSON.parse(String(allow("Invented named key")))).toMatchObject({ read: ["note"], write: [] });  });});describe("GET /v1/keys", () => {  it("lists the live keys to the owner's own device, newest first, with no hash; a key is refused", async () => {    const slug = "key-default-list";    const { credential, owner } = await personalObject(slug);    const phone = { authorization: `Bearer ${credential}` };    await mint(slug, credential, "Invented lane", ["read", "lane:invented"], 7);    await mint(slug, credential, "Invented gone", ["read"]);    const gone = (await tokens(slug)).find((r) => r.data.name === "Invented gone")!;    expect((await http(slug, "POST", "/v1/act", { act: "revoke_token", args: { id: gone.id } }, phone)).status).toBe(200);    const listed = await http<{ keys: Record<string, unknown>[] }>(slug, "GET", "/v1/keys", undefined, phone);    expect(listed.status, JSON.stringify(listed.body)).toBe(200);    const names = listed.body.keys.map((k) => k.name);    expect(names).toContain("Invented lane");    expect(names).not.toContain("Invented gone");    const text = JSON.stringify(listed.body);    expect(text).not.toMatch(/token_hash/);    for (const r of await tokens(slug)) expect(text).not.toContain(String(r.data.token_hash));    const lane = listed.body.keys.find((k) => k.name === "Invented lane")!;    expect(Object.keys(lane).sort()).toEqual(["allow", "connection_id", "connector", "created_at", "expires_at", "id", "last_used_at", "machine", "name", "scopes"]);    expect(lane.scopes).toEqual(["read", "lane:invented"]);    // A key never lists the account's keys: not the owner-scope key, not a lane token.    const asKey = await http<{ code: string }>(slug, "GET", "/v1/keys", undefined, { authorization: `Bearer ${owner}` });    expect([asKey.status, asKey.body.code]).toEqual([403, "owner_only"]);    expect((await http(slug, "GET", "/v1/keys")).status).toBeGreaterThanOrEqual(401);  }, 240_000);});