iterate.com / kernel

git clone https://git.iterate.com/repos/kernel

kernel / core / mind-worker / src / context / cf-artifacts.test.tsmain at 949894f

// A repo's tokens through `itx.cfArtifacts.get(path)` (./cf-artifacts.ts), against a stand-in for
// the Artifacts binding that answers as Artifacts did on a dev mind (26 Nov 2026): each repo's
// tokens apart, an ended token not listed, and true again for a second revocation.
import { expect, test } from "vitest";
import { type ArtifactsNamespace, mindScopedArtifacts } from "./cf-artifacts.ts";

test("a repo's tokens are listed with no token's text, and one is ended by its id", async () => {
  const store = storeOf(["repos--config", "repos--git"]);
  const artifacts = mindScopedArtifacts({ namespace: store.namespace });
  const config = await artifacts.get("/repos/config");
  const minted = await config.createToken("write", 300);
  await config.createToken("read", 60);

  const listed = await config.listTokens();
  expect(listed).toEqual({
    tokens: [
      { id: "tok_1", scope: "write", state: "active", createdAt: CREATED, expiresAt: EXPIRES },
      { id: "tok_2", scope: "read", state: "active", createdAt: CREATED, expiresAt: EXPIRES },
    ],
    total: 2,
  });
  // not the token, and no field that the stand-in adds beside the known ones
  expect(JSON.stringify(listed)).not.toContain("art_");
  expect(JSON.stringify(listed)).not.toContain("note");

  expect(await config.revokeToken(minted.id!)).toBe(true);
  // an ended token is not listed
  expect((await config.listTokens()).tokens.map(({ id }) => id)).toEqual(["tok_2"]);
  // an id that the repo never had: not found
  expect(await config.revokeToken("tok_9")).toBe(false);
});

test("a repo's handle sees and ends that repo's tokens alone", async () => {
  const store = storeOf(["repos--config", "repos--git"]);
  const artifacts = mindScopedArtifacts({ namespace: store.namespace });
  const config = await artifacts.get("/repos/config");
  const git = await artifacts.get("/repos/git");
  const ofConfig = await config.createToken("write", 300);

  expect(await git.listTokens()).toEqual({ tokens: [], total: 0 });
  expect(await git.revokeToken(ofConfig.id!)).toBe(false);
  expect((await config.listTokens()).tokens[0]!.state).toBe("active");
});

test("a revocation whose answer was lost is asked again, and is true for the token that the first attempt ended", async () => {
  const store = storeOf(["repos--config"]);
  const config = await mindScopedArtifacts({ namespace: store.namespace }).get("/repos/config");
  const minted = await config.createToken("write", 300);

  // Artifacts ends the token, and its answer is the internal error that the proxy tries again on
  store.loseNextRevokeAnswer();
  expect(await config.revokeToken(minted.id!)).toBe(true);
  expect(store.revokeAsked).toEqual([minted.id, minted.id]);
  store.loseNextRevokeAnswer();
  expect(await config.revokeToken("tok_9")).toBe(false);
});

test("a token's own text is refused before the binding is asked, so no caller learns to pass one", async () => {
  const store = storeOf(["repos--config"]);
  const config = await mindScopedArtifacts({ namespace: store.namespace }).get("/repos/config");
  const minted = await config.createToken("write", 300);

  for (const text of [minted.plaintext, "art_v1_abc", "", "an id with spaces", "x".repeat(129)])
    await expect(config.revokeToken(text)).rejects.toThrow("takes a token's id");
  expect(store.revokeAsked).toEqual([]);
  expect((await config.listTokens()).tokens[0]!.state).toBe("active");
});

test("a repo that is not there fails with the binding's own words", async () => {
  const store = storeOf([]);
  const away = await mindScopedArtifacts({ namespace: store.namespace }).get("/repos/away");
  await expect(away.listTokens()).rejects.toThrow("not found");
  await expect(away.revokeToken("tok_1")).rejects.toThrow("not found");
});

const CREATED = "2026-11-26T15:00:00.000Z";
const EXPIRES = "2026-11-26T15:05:00.000Z";

/** The binding, as much as the proxy calls: repos by name, each with its own tokens. A token's
 *  row holds a field that the proxy does not know (`note`). */
function storeOf(names: string[]) {
  type Row = { id: string; scope: "read" | "write"; state: "active" | "revoked"; text: string };
  const repos = new Map<string, Row[]>(names.map((name) => [name, []]));
  const revokeAsked: string[] = [];
  let made = 0;
  let answerIsLost = false;
  const namespace = {
    async get(name: string) {
      const rows = repos.get(name);
      if (!rows) throw new Error(`Repository not found: ${name}`);
      const live = () => rows.filter((row) => row.state === "active");
      return {
        info: async () => ({ remote: `https://artifacts.test/${name}.git` }),
        async createToken(scope: "read" | "write") {
          const row: Row = { id: `tok_${++made}`, scope, state: "active", text: `art_v1_${made}?expires=1` };
          rows.push(row);
          return { id: row.id, plaintext: row.text, scope, expiresAt: EXPIRES };
        },
        listTokens: async () => ({
          tokens: live().map(({ id, scope, state }) => ({
            id,
            scope,
            state,
            createdAt: CREATED,
            expiresAt: EXPIRES,
            note: "a field of a later version",
          })),
          total: live().length,
        }),
        async revokeToken(tokenOrId: string) {
          revokeAsked.push(tokenOrId);
          const row = rows.find((row) => row.id === tokenOrId);
          if (row) row.state = "revoked";
          if (answerIsLost) {
            answerIsLost = false;
            throw new Error("An internal error occurred.");
          }
          return Boolean(row);
        },
      };
    },
    // the cast: these tests call `get` alone
  } as unknown as ArtifactsNamespace;
  return { namespace, revokeAsked, loseNextRevokeAnswer: () => void (answerIsLost = true) };
}