Merge iterate/private's core/ at b0f5689c
Misha Kaletsky, 2026-11-26 00:00 UTC · d6807213afd797f380e91b4d7055abc27f10dd6d · a merge of 8d212b8 and 23c8ccf, shown against 8d212b8
47 files changed
- M core/alchemy/README.md
- M core/alchemy/src/config.ts
- M core/alchemy/src/stack.ts
- M core/auth-worker/src/asking-app.test.ts
- M core/auth-worker/src/asking-app.ts
- M core/auth-worker/src/authorize.ts
- M core/auth-worker/src/device/page.test.ts
- M core/auth-worker/src/device/page.ts
- M core/auth-worker/src/email-sign-in.ts
- M core/auth-worker/src/enrolment.test.ts
- M core/auth-worker/src/http.ts
- M core/auth-worker/src/members.test.ts
- M core/auth-worker/src/members.ts
- A core/auth-worker/src/mind-mark.test.ts
- A core/auth-worker/src/mind-mark.ts
- M core/auth-worker/src/pages.test.ts
- M core/auth-worker/src/pages.ts
- M core/auth-worker/src/stack-key.ts
- M core/auth-worker/src/test-support.ts
- M core/auth-worker/src/working-key.test.ts
- M core/itx/src/caller.ts
- M core/itx/src/context/built-ins.ts
- A core/itx/src/context/workers-mcp-call.test.ts
- M core/itx/src/index.ts
- M core/itx/src/serve-host.ts
- M core/itx/src/stream/facet-push-catch-up.test.ts
- M core/itx/src/stream/stream.ts
- M core/itx/src/stream/subscription-delivery.ts
- M core/lib/src/app-description.test.ts
- M core/lib/src/app-description.ts
- M core/lib/src/cli/README.md
- M core/lib/src/cli/cli.ts
- M core/lib/src/cli/deploy.test.ts
- M core/lib/src/cli/deploy.ts
- M core/lib/src/integrations.ts
- M core/lib/src/mind-config.ts
- M core/lib/src/mind-ingress.ts
- M core/lib/src/sdk/auth.ts
- M core/lib/src/sdk/index.ts
- A core/lib/src/sdk/mcp.ts
- M core/lib/src/standalone-page.ts
- M core/mind-worker/src/http.ts
- A core/mind-worker/src/mcp-config.test.ts
- A core/mind-worker/src/mcp-skill-frontmatter.ts
- A core/mind-worker/src/mcp-skills.test.ts
- A core/mind-worker/src/mcp-skills.ts
- M core/mind-worker/src/mcp.ts
M core/alchemy/README.md
@@ -81,6 +81,13 @@ A mind takes each of its zones whole: nothing else may use them. +`"mcpTarget": "mcp"` points the mind's own MCP server (`iterate.<zone>/mcp`) at a method of the +config worker's class: that method answers a class which gives the server its instructions, its +description of `run`, more tools and the mind's skills (`mcp.ts` of the default config). Absent, +the platform's defaults answer; and they answer too whenever the method fails, so the field +cannot break the server. `iterate deploy --mcp-target mcp` sets it, and `--mcp-target none` takes +it away. A stack built before this field refuses it. + `"ownerEmailPatterns": ["*@company.example"]` names more owners by pattern: every address at exactly that domain (no sub-domain) is an owner, with all that an owner may do. Such a person proves the address through Cloudflare Access, whose policy then names the whole domain, and adds a
M core/alchemy/src/config.ts
@@ -33,6 +33,10 @@ * added: an owner's block of that address on `/members` ends that one person * (core/auth-worker/src/members.ts `isMember`). Absent: no pattern. */ ownerEmailPatterns: z.array(OwnerEmailPattern).optional(), + /** The method of the config worker's class that answers the mind's part of its own MCP + * server (iterate/mind-config `mcpTarget`): "mcp" in the default config. Absent: the + * platform's defaults answer. */ + mcpTarget: z.string().optional(), /** Where the mind Worker runs: in the stack, or elsewhere, connecting in through the * boundary. */ topology: z.enum(["full-cloudflare", "external-mind-connects-into-cloudflare-boundary"]),
M core/alchemy/src/stack.ts
@@ -28,6 +28,7 @@ import { relative, resolve } from "node:path"; import * as Cloudflare from "@alchemy.run/cloudflare"; import * as Alchemy from "alchemy"; +import { adopt } from "alchemy/AdoptPolicy"; import * as Output from "alchemy/Output"; import * as Config from "effect/Config"; import * as ConfigProvider from "effect/ConfigProvider"; @@ -71,6 +72,8 @@ ownerEmails: config.ownerEmails, // absent with no pattern: JSON leaves it out, so such a mind's variable is as it was ownerEmailPatterns: config.ownerEmailPatterns?.length ? config.ownerEmailPatterns : undefined, + // absent when the deploy names none: the platform's own MCP defaults answer + mcpTarget: config.mcpTarget || undefined, topology: config.topology, }); /** A stream's fields, as a file of core/telemetry-worker/schemas lists them. */ @@ -596,17 +599,25 @@ script: boundary.workerName, }); } - const routing = yield* Cloudflare.Email.Routing(`EmailRouting-${zoneName}`, { + // The catch-all first, and Email Routing after it (it takes the zone from the catch-all, + // so Alchemy waits): Cloudflare publishes the zone's MX records when routing is turned + // on, and the boundary must be the handler by then. A zone that leaves goes the other way + // round: routing off, then the catch-all back as it was. Cloudflare takes a catch-all + // rule while routing is off (measured on a dev zone, 25 Nov 2026). + const catchAll = yield* Cloudflare.Email.CatchAll(`EmailCatchAll-${zoneName}`, { zone: zone.id, - }); - yield* Cloudflare.Email.CatchAll(`EmailCatchAll-${zoneName}`, { - zone: routing.zoneId, actions: [{ type: "worker", value: [boundary.workerName] }], }); + yield* Cloudflare.Email.Routing(`EmailRouting-${zoneName}`, { zone: catchAll.zoneId }); + // A mind takes each of its zones whole. So a sending domain that the zone has already + // (its owner turned Email Sending on in the dashboard) is taken over as it is, with its + // DKIM key and its return-path records, and it is the stack's from then on: it is + // deleted when the zone leaves the config, and at a destroy. Without `adopt`, Alchemy + // refuses a sending domain that it did not make, and the plan fails. const sending = yield* Cloudflare.Email.SendingSubdomain(`EmailSending-${zoneName}`, { zoneId: zone.id, name: zoneName, - }); + }).pipe(adopt(true)); // What became of a sent mail that did not arrive. Cloudflare refuses the subscription // until the zone is a sending domain, so its source waits for Email Sending, and a zone // whose DNS checks did not pass in time stops the deploy here, by its name.
M core/auth-worker/src/asking-app.test.ts
@@ -2,7 +2,9 @@ // and what the sign-in pages then show. import type { SignInMethod } from "iterate/principal"; import { expect, test, vi } from "vitest"; +import { isOwnerEmail } from "iterate/mind-config"; import { + allowedEmailsWords, appOf, appTakes, appTile, @@ -49,7 +51,7 @@ icon: `${ORIGIN}/icon.svg`, members: false, signIn: FOR_ANYONE, - emailDomains: null, + allowedEmails: null, }); // a path on the host is the host, as the authorization endpoint reads it expect(await askingAppOf(stack.env, next({ resource: `${ORIGIN}/mcp` }))).toMatchObject({ @@ -79,7 +81,7 @@ icon: null, members: false, signIn: FOR_ANYONE, - emailDomains: null, + allowedEmails: null, }; test.for([ @@ -130,11 +132,31 @@ said: { name: "Guestbook", signIn: ["email"] }, }, { - name: "the domains whose addresses a mailed code signs in, each once", - description: { name: "Shop", emailDomains: ["example.com", "second.example", "example.com"] }, - said: { name: "Shop", emailDomains: ["example.com", "second.example"] }, + name: "the addresses and the patterns that a mailed code signs in, each once and in lowercase", + description: { + name: "Shop", + allowedEmails: ["Eve@Elsewhere.test", "eve@elsewhere.test"], + allowedEmailPatterns: ["*@example.com", "*@second.example", "*@example.com"], + }, + said: { + name: "Shop", + allowedEmails: { + emails: ["eve@elsewhere.test"], + patterns: ["*@example.com", "*@second.example"], + }, + }, }, { + name: "addresses alone, and patterns alone", + description: { name: "Shop", allowedEmails: ["eve@elsewhere.test"] }, + said: { name: "Shop", allowedEmails: { emails: ["eve@elsewhere.test"], patterns: [] } }, + }, + { + name: "patterns alone", + description: { name: "Shop", allowedEmailPatterns: ["*@example.com"] }, + said: { name: "Shop", allowedEmails: { emails: [], patterns: ["*@example.com"] } }, + }, + { name: "what a browser's manifest would say is passed over", description: { name: "Guestbook", short_name: "Book", icons: [{ src: "/other.svg" }] }, said: { name: "Guestbook" }, @@ -146,12 +168,31 @@ description: { name: "G", signIn: ["email", "google"] }, said: null, }, - { name: "an empty list of domains", description: { name: "G", emailDomains: [] }, said: null }, - ...["@example.com", "*.example.com", "Example.com", "example", "a@example.com"].map((domain) => ({ - name: `a domain that is none: ${domain}`, - description: { name: "G", emailDomains: [domain] }, + { + // a restriction that this issuer does not read is never dropped: the last policy stays + name: "a list of domains, which this issuer does not read", + description: { name: "G", emailDomains: ["example.com"] }, said: null, - })), + }, + { + name: "an empty list of patterns", + description: { name: "G", allowedEmailPatterns: [] }, + said: null, + }, + { name: "an empty list of addresses", description: { name: "G", allowedEmails: [] }, said: null }, + { + name: "an address that is none", + description: { name: "G", allowedEmails: ["example.com"] }, + said: null, + }, + // a pattern is `*@<domain>` in lowercase and nothing else, as an owner email pattern + ...["example.com", "@example.com", "*@*.example.com", "*@Example.com", "a*@example.com"].map( + (pattern) => ({ + name: `a pattern that is none: ${pattern}`, + description: { name: "G", allowedEmailPatterns: [pattern] }, + said: null, + }), + ), { name: "an empty list of methods", description: { name: "G", signIn: [] }, said: null }, { name: "methods that are no list", description: { name: "G", signIn: "email" }, said: null }, { @@ -175,10 +216,10 @@ test("a JSON object that broke off, or that is too long to read, is no word of the app", () => { const long = JSON.stringify({ name: "Shop", - emailDomains: Array.from({ length: 2000 }, (_, n) => `shop-${n}.example.com`), + allowedEmailPatterns: Array.from({ length: 2000 }, (_, n) => `*@shop-${n}.example.com`), }); expect(long.length).toBeGreaterThan(20_000); - for (const text of ['{"name":"Shop","emailDomains":["exam', " {", "{<", long]) + for (const text of ['{"name":"Shop","allowedEmailPatterns":["*@exam', " {", "{<", long]) expect(saidIn(text, DESCRIPTION), text.slice(0, 40)).toBeNull(); }); @@ -200,7 +241,7 @@ icon: `${ORIGIN}/icon.svg`, members: false, signIn: ["passkey"], - emailDomains: null, + allowedEmails: null, }); expect(await appOf(stack.env, ORIGIN)).toEqual(app); // the one address that is asked: no web app manifest is read @@ -251,7 +292,7 @@ icon: `${ORIGIN}/icon.svg`, members: true, signIn: FOR_MEMBERS, - emailDomains: null, + allowedEmails: null, }); expect(stack.askedAgainIn(HOST, before)).toBe("1 minute"); // and the client that the list of sign-ins reads still names the app @@ -262,45 +303,99 @@ }, ); -test("an app whose description is wrong is still what it last said, and is asked again after a minute; one that the issuer never heard takes the passkey alone until it says", async () => { +test("a row that an issuer kept with a list of domains is read as the patterns of those domains, and never as any address, also while the app does not answer", async () => { const stack = stackWith({}); + const key = `iterate-app-description:${HOST}`; + const row = (askAfter: number) => + JSON.stringify({ + name: "Shop", + icon: null, + members: false, + signIn: FOR_ANYONE, + emailDomains: ["example.com"], + askAfter, + }); + const patterns = { emails: [], patterns: ["*@example.com"] }; + // not due yet: the row is read as it is, and the app is not asked + await stack.env.OAUTH_KV.put(key, row(Date.now() + 60_000)); { + using web = answers({ name: "Shop" }); + const app = (await appOf(stack.env, ORIGIN))!; + expect(app).toMatchObject({ allowedEmails: patterns }); + expect(takesAddress(app, "eve@example.com")).toBe(true); + expect(takesAddress(app, "eve@elsewhere.test")).toBe(false); + expect(web).toMatchObject({ asked: [] }); + } + // due, and the app does not answer: it is what the row said, in this issuer's shape + await stack.env.OAUTH_KV.put(key, row(0)); + { + const spy = vi + .spyOn(globalThis, "fetch") + .mockImplementation(async () => new Response("down", { status: 503 })); + using _down = { [Symbol.dispose]: () => spy.mockRestore() }; + expect(await appOf(stack.env, ORIGIN)).toMatchObject({ allowedEmails: patterns }); + expect(JSON.parse((await stack.env.OAUTH_KV.get(key))!)).toMatchObject({ + allowedEmails: patterns, + }); + } + // due, and the app still answers with its list of domains: the row's restriction stays + stack.due(HOST); + { using _web = answers({ name: "Shop", emailDomains: ["example.com"] }); + const before = Date.now(); + expect(await appOf(stack.env, ORIGIN)).toMatchObject({ allowedEmails: patterns }); + expect(stack.askedAgainIn(HOST, before)).toBe("1 minute"); + } + // due, and the app answers with its list in this issuer's fields: that is what it is + stack.due(HOST); + using _web = answers({ name: "Shop", allowedEmails: ["eve@elsewhere.test"] }); + expect(await appOf(stack.env, ORIGIN)).toMatchObject({ + allowedEmails: { emails: ["eve@elsewhere.test"], patterns: [] }, + }); +}); + +test("an app whose description is wrong is still what it last said, and is asked again after a minute; one that the issuer never heard takes the passkey alone until it says", async () => { + const stack = stackWith({}); + { + using _web = answers({ name: "Shop", allowedEmailPatterns: ["*@example.com"] }); await appOf(stack.env, ORIGIN); } stack.due(HOST); const policyOf = async (origin: string) => { const app = (await appOf(stack.env, origin))!; - return { signIn: app.signIn, emailDomains: app.emailDomains }; + return { signIn: app.signIn, allowedEmails: app.allowedEmails }; }; { // a list that is not whole, in a description that is otherwise right - using _web = answers({ name: "Shop", for: "members", emailDomains: ["@example.com"] }); + using _web = answers({ name: "Shop", for: "members", allowedEmailPatterns: ["@example.com"] }); const before = Date.now(); - expect(await policyOf(ORIGIN)).toEqual({ signIn: FOR_ANYONE, emailDomains: ["example.com"] }); + expect(await policyOf(ORIGIN)).toEqual({ + signIn: FOR_ANYONE, + allowedEmails: { emails: [], patterns: ["*@example.com"] }, + }); expect(stack.askedAgainIn(HOST, before)).toBe("1 minute"); } // NOTHING IS KEPT OF THESE: the app's first answer is wrong, or it does not answer. The issuer // mails no code and takes no mailed code's session for an app that it has not heard. for (const [n, answer] of [ - () => Response.json({ name: "Shop", emailDomains: ["@example.com"] }), + () => Response.json({ name: "Shop", allowedEmailPatterns: ["@example.com"] }), () => new Response("down", { status: 503 }), () => new Response("too many requests", { status: 429 }), - () => new Response('{"name":"Shop","emailDomains":["exam'), + () => new Response('{"name":"Shop","allowedEmailPatterns":["*@exam'), () => Promise.reject(new Error("no answer")), ].entries()) { const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => answer()); using _down = { [Symbol.dispose]: () => spy.mockRestore() }; const origin = `https://shop-${n}.${DOMAIN}`; - expect(await policyOf(origin), String(n)).toEqual({ signIn: ["passkey"], emailDomains: null }); + expect(await policyOf(origin), String(n)).toEqual({ signIn: ["passkey"], allowedEmails: null }); // and once it answers, it is what it says spy.mockImplementation(async () => - Response.json({ name: "Shop", emailDomains: ["a.example"] }), + Response.json({ name: "Shop", allowedEmails: ["eve@a.example"] }), ); stack.due(`shop-${n}.${DOMAIN}`); expect(await policyOf(origin), String(n)).toEqual({ signIn: FOR_ANYONE, - emailDomains: ["a.example"], + allowedEmails: { emails: ["eve@a.example"], patterns: [] }, }); } }); @@ -321,7 +416,7 @@ icon: null, members: false, signIn: FOR_ANYONE, - emailDomains: null, + allowedEmails: null, }); expect(await oauthHelpers(stack.env, ORIGIN).lookupClient(client)).toMatchObject({ clientName: HOST, @@ -339,7 +434,7 @@ icon: null, members: false, signIn: FOR_ANYONE, - emailDomains: null, + allowedEmails: null, }); expect(appTile(app)).toBe(`<div class="tile" data-app-mark="initials">GU</div>`); await appOf(stack.env, ORIGIN); @@ -375,8 +470,8 @@ expect(await signInOf(stack.env, mcp)).toEqual({ app: null, methods: ["passkey"], - // a row that was kept before the issuer read `emailDomains` names none - mailedCode: expect.objectContaining({ name: "Guestbook", emailDomains: null }), + // a row that was kept before the issuer read `allowedEmails` names none + mailedCode: expect.objectContaining({ name: "Guestbook", allowedEmails: null }), }); // the control plane's own sign-in, and one for the mind's API or its MCP server for (const next of [ @@ -392,42 +487,82 @@ }); }); -test("an app that names domains takes a mailed code's session for an address at one of them alone; a passkey's session counts whatever its address", () => { +test("an app that names addresses and patterns takes a mailed code's session for an address that one of them names alone, by the rule that says who owns a mind; a passkey's session counts whatever its address", () => { const shop = { signIn: FOR_ANYONE as SignInMethod[], - emailDomains: ["example.com", "second.example"], + allowedEmails: { + emails: ["guest@elsewhere.test"], + patterns: ["*@example.com", "*@second.example"], + }, }; const takes = (method: SignInMethod, email: string) => appTakes(shop, { method, email }); expect({ - atADomain: takes("email", "eve@example.com"), + atAPattern: takes("email", "eve@example.com"), atTheOther: takes("email", "eve@second.example"), inCapitals: takes("email", "Eve@EXAMPLE.com"), + named: takes("email", "guest@elsewhere.test"), + namedInCapitals: takes("email", "Guest@Elsewhere.test"), // a subdomain is another domain, and so is a name that ends as the domain does atASubdomain: takes("email", "eve@mail.example.com"), atALookalike: takes("email", "eve@notexample.com"), - // the address is the text after the last "@" + twoAts: takes("email", "eve@elsewhere.test@example.com"), quotedLocalPart: takes("email", '"eve@example.com"@elsewhere.test'), - elsewhere: takes("email", "eve@elsewhere.test"), + // another address at the domain of a named address is not named + besideTheNamed: takes("email", "eve@elsewhere.test"), passkeyElsewhere: takes("passkey", "ada@elsewhere.test"), }).toEqual({ - atADomain: true, + atAPattern: true, atTheOther: true, inCapitals: true, + named: true, + namedInCapitals: true, atASubdomain: false, atALookalike: false, + twoAts: false, quotedLocalPart: false, - elsewhere: false, + besideTheNamed: false, passkeyElsewhere: true, }); + // THE SAME ANSWER AS THE MIND CONFIG'S OWN MATCHER, for every address above + for (const email of [ + "eve@example.com", + "Guest@Elsewhere.test", + "eve@mail.example.com", + "x@y@example.com", + ]) + expect(takesAddress(shop, email), email).toBe( + isOwnerEmail( + { ownerEmails: shop.allowedEmails.emails, ownerEmailPatterns: shop.allowedEmails.patterns }, + email, + ), + ); // the list binds the mailed code alone: a method that the app does not name is still refused, - // and an app that names no domains takes any address + // and an app that names nobody takes any address expect( appTakes( - { signIn: ["passkey"], emailDomains: ["example.com"] }, + { signIn: ["passkey"], allowedEmails: { emails: [], patterns: ["*@example.com"] } }, { method: "email", email: "eve@example.com" }, ), ).toBe(false); - expect(takesAddress({ emailDomains: null }, "eve@elsewhere.test")).toBe(true); + expect(takesAddress({ allowedEmails: null }, "eve@elsewhere.test")).toBe(true); + // the pages' words name the domains of the patterns, and no address that the app names + expect([ + allowedEmailsWords({ name: "Shop", ...shop }), + allowedEmailsWords({ + name: "Shop", + allowedEmails: { emails: [], patterns: ["*@example.com"] }, + }), + allowedEmailsWords({ + name: "Shop", + allowedEmails: { emails: ["guest@elsewhere.test"], patterns: [] }, + }), + allowedEmailsWords({ name: "Shop", allowedEmails: null }), + ]).toEqual([ + "Shop takes an address at example.com or second.example, and the addresses that it names, only.", + "Shop takes an address at example.com only.", + "Shop takes only the addresses that it names.", + "", + ]); }); test("the mailed code's page for an app's sign-in names the host it signs in to, under the app's own icon", async () => { @@ -471,7 +606,7 @@ name: "Guestbook", icon: `${ORIGIN}/icon.svg`, members: false, - emailDomains: null, + allowedEmails: null, signIn: ["email", "passkey"] as SignInMethod[], }; stack.challenge.next = next; @@ -544,7 +679,7 @@ name: "Dash", icon: null, members: true, - emailDomains: null, + allowedEmails: null, signIn: ["passkey"] as SignInMethod[], }; expect(appSignIn(dash)).toMatchObject({ @@ -583,7 +718,7 @@ name: HOST, icon: null, members: false, - emailDomains: null, + allowedEmails: null, signIn: ["email", "passkey"] as SignInMethod[], }; const passkey = await signInPage({ @@ -649,7 +784,7 @@ keyOf(host), JSON.stringify({ members: false, - emailDomains: null, + allowedEmails: null, signIn: FOR_ANYONE, ...value, askAfter: Date.now() + 5 * 60_000,
M core/auth-worker/src/asking-app.ts
@@ -34,17 +34,20 @@ // methods alone, in the app's order (`signInOf`). It is read from the app, never from the // request, so an MCP client that signs a person in to the app gets the same list. // -// WHOSE ADDRESS A MAILED CODE SIGNS IN (`emailDomains`) is enforced with it: for an app that -// names domains, no code is mailed to an address at any other (./email-sign-in.ts), and a session -// that a mailed code opened for such an address gets no code for the app's host (`appTakes`). So -// the list holds at the sign-up, and not only at the app's own guard. It binds the method -// "email" alone; a list that changes binds the grants made after it. +// WHOSE ADDRESS A MAILED CODE SIGNS IN (`allowedEmails`, `allowedEmailPatterns`) is enforced +// with it, by the rule that says who owns a mind (iterate/mind-config `isOwnerEmail`): addresses, +// each whole, and patterns `*@<domain>`. For an app that names either, no code is mailed to an +// address that neither names (./email-sign-in.ts), and a session that a mailed code opened for +// such an address gets no code for the app's host (`appTakes`). So the list holds at the sign-up, +// and not only at the app's own guard. It binds the method "email" alone; a list that changes +// binds the grants made after it. // // AN APP IS AN OAUTH CLIENT, as Codex is: the host's client holds the app's name and icon (its // `clientName` and `logoUri`), written here whenever the description is read and says something // else. So the list of a person's sign-ins by client (./oauth.ts `sessionsByClientOf`) names the // app as the sign-in pages do, and asks no app for it. import { APP_DESCRIPTION_PATH, AppDescription } from "iterate/app-description"; +import { domainOfOwnerEmailPattern, isOwnerEmail } from "iterate/mind-config"; import type { SignInMethod } from "iterate/principal"; import { admitted } from "./device/limits.ts"; import { configOf, type Env, issuerOf } from "./env.ts"; @@ -70,8 +73,8 @@ /** How the app's people sign in, in the app's order: what it names, or the default for whom it * is for (`saidIn`). The sign-in page opens on the first. */ signIn: SignInMethod[]; - /** The domains whose addresses a mailed code signs in to the app, or null: any address. */ - emailDomains: string[] | null; + /** Whose address a mailed code signs in to the app (`takesAddress`), or null: any address. */ + allowedEmails: AllowedEmails | null; }; const text = (value: string) => @@ -96,7 +99,7 @@ methods: SignInMethod[]; /** For a mind hostname's sign-in: the app's name, and whose address a mailed code signs in to * it (`takesAddress`). The pages' refusal names the app by it, whichever client asks. */ - mailedCode: Pick<AskingApp, "name" | "emailDomains"> | null; + mailedCode: Pick<AskingApp, "name" | "allowedEmails"> | null; } | null> { const authorization = hostAuthorizationIn(env, next); if (!authorization) return { app: null, methods: CONTROL_PLANE_SIGN_IN, mailedCode: null }; @@ -121,19 +124,26 @@ * app, and any other when the app names its method. A mailed code's counts only for an address * that the app takes (`takesAddress`). */ export const appTakes = ( - app: Pick<AskingApp, "signIn" | "emailDomains">, + app: Pick<AskingApp, "signIn" | "allowedEmails">, session: { method: SignInMethod; email: string }, ) => session.method === "passkey" || (app.signIn.includes(session.method) && (session.method !== "email" || takesAddress(app, session.email))); -/** WHETHER A MAILED CODE SIGNS `email` IN TO THE APP: the app names no domains, or the address is - * at one of them, whole (the text after its last "@", in lowercase). */ -export const takesAddress = (app: Pick<AskingApp, "emailDomains">, email: string) => - !app.emailDomains || - app.emailDomains.includes(email.slice(email.lastIndexOf("@") + 1).toLowerCase()); +/** The addresses and the patterns (`*@<domain>`) that an app names for the mailed code. */ +export type AllowedEmails = { emails: string[]; patterns: string[] }; +/** WHETHER A MAILED CODE SIGNS `email` IN TO THE APP: the app names nobody, or the address is one + * that it names, by the one rule that says who owns a mind (iterate/mind-config + * `isOwnerEmail`). */ +export const takesAddress = (app: Pick<AskingApp, "allowedEmails">, email: string) => + !app.allowedEmails || + isOwnerEmail( + { ownerEmails: app.allowedEmails.emails, ownerEmailPatterns: app.allowedEmails.patterns }, + email, + ); + /** `next` as an authorization request of this issuer for a mind hostname: the hostname's origin, * and the request's parameters. Null for anything else. */ function hostAuthorizationIn(env: Env, next: string) { @@ -164,7 +174,7 @@ export async function appOf(env: Env, origin: string): Promise<AskingApp | null> { const { host } = new URL(origin); const key = `iterate-app-description:${host}`; - let kept = await env.OAUTH_KV.get<Kept>(key, "json"); + let kept = inThisShape(await env.OAUTH_KV.get<Kept & DomainsRow>(key, "json")); if ( !kept && !(await keptHostClientOf(env, host)) && @@ -205,11 +215,28 @@ icon: kept.icon, members: kept.members, signIn: kept.signIn, - // a row that was kept before the issuer read this field has none - emailDomains: kept.emailDomains || null, + allowedEmails: kept.allowedEmails, }; } +/** A ROW OF AN ISSUER THAT READ A LIST OF DOMAINS (`emailDomains`) where this one reads + * `allowedEmails`. The mind's KV outlives a deploy, so this issuer may read such a row for the + * five minutes until the app is asked again. */ +type DomainsRow = { emailDomains?: string[] | null; allowedEmails?: AllowedEmails | null }; + +/** Such a row as this issuer keeps it: a domain is the pattern `*@<domain>`, which names the same + * addresses. So a row that held a list never reads as "any address". */ +function inThisShape(row: (Kept & DomainsRow) | null): Kept | null { + if (!row) return null; + const { emailDomains, ...kept } = row; + if (kept.allowedEmails || !emailDomains) + return { ...kept, allowedEmails: kept.allowedEmails || null }; + return { + ...kept, + allowedEmails: { emails: [], patterns: emailDomains.map((domain) => `*@${domain}`) }, + }; +} + /** What an app said of itself (`saidIn`), and when to ask it again. */ type Kept = typeof NOTHING & { askAfter: number }; @@ -231,13 +258,13 @@ icon: string | null; members: boolean; signIn: SignInMethod[]; - emailDomains: string[] | null; -} = { name: null, icon: null, members: false, signIn: ["email", "passkey"], emailDomains: null }; + allowedEmails: AllowedEmails | null; +} = { name: null, icon: null, members: false, signIn: ["email", "passkey"], allowedEmails: null }; /** AN APP THAT THE ISSUER HAS NO WORD OF YET: it did not answer, or its description is wrong, and * nothing that it said before is kept. The issuer does not know whom the app takes, so it takes * the passkey alone until the app says: a code that is mailed meanwhile, or a grant for an - * address, could be one that the app's own list refuses (`signIn`, `emailDomains`). */ + * address, could be one that the app's own list refuses (`signIn`, `allowedEmails`). */ const UNHEARD: typeof NOTHING = { ...NOTHING, signIn: ["passkey"] }; /** WHAT THE TEXT OF AN APP'S DESCRIPTION SAYS (iterate/app-description `AppDescription`): a name @@ -247,7 +274,7 @@ * and email then passkey for any other, and whose address a mailed code signs in. A text that is * no JSON object says nothing: an app with no description answers with a page, or with none. * NULL: A JSON OBJECT THAT IS NO `AppDescription`, such as one that names a method this issuer - * does not know, or a domain that is none, and one that broke off or is over 20,000 characters. The app wrote a description and it is wrong, so it is + * does not know, or a pattern that is none, and one that broke off or is over 20,000 characters. The app wrote a description and it is wrong, so it is * held to no list that it did not write, and it is not opened to anyone either: the caller keeps * what the app last said (`appOf`). */ export function saidIn(descriptionText: string, descriptionUrl: string): typeof NOTHING | null { @@ -263,6 +290,9 @@ return unread; } if (typeof json !== "object" || !json || Array.isArray(json)) return NOTHING; + // A list of domains (`emailDomains`) is a restriction that this issuer does not read. The parse + // would drop it and leave the app for any address, so such a description is wrong. + if ("emailDomains" in json) return null; const parsed = AppDescription.safeParse(json); if (!parsed.success) return null; const name = parsed.data.name @@ -273,6 +303,7 @@ const { origin } = new URL(descriptionUrl); const icon = parsed.data.icon ? new URL(parsed.data.icon, descriptionUrl) : null; const members = parsed.data.for === "members"; + const { allowedEmails, allowedEmailPatterns } = parsed.data; return { name: name || null, // a path that begins `//` names another host: an icon is the app's own origin's alone @@ -281,8 +312,29 @@ signIn: [ ...new Set<SignInMethod>(parsed.data.signIn || (members ? ["passkey"] : NOTHING.signIn)), ], - emailDomains: parsed.data.emailDomains ? [...new Set(parsed.data.emailDomains)] : null, + allowedEmails: + allowedEmails || allowedEmailPatterns + ? { + emails: [...new Set(allowedEmails || [])], + patterns: [...new Set(allowedEmailPatterns || [])], + } + : null, }; +} + +/** WHOM AN APP'S MAILED CODE IS FOR, IN WORDS, or "" for an app that takes any address. The + * pages name the domains of the patterns, and never an address that the app names: the page is + * for anyone. */ +export function allowedEmailsWords(app: Pick<AskingApp, "name" | "allowedEmails">): string { + if (!app.allowedEmails) return ""; + const { emails, patterns } = app.allowedEmails; + const domains = new Intl.ListFormat("en", { type: "disjunction" }).format( + patterns.map(domainOfOwnerEmailPattern), + ); + if (!patterns.length) return `${app.name} takes only the addresses that it names.`; + return emails.length + ? `${app.name} takes an address at ${domains}, and the addresses that it names, only.` + : `${app.name} takes an address at ${domains} only.`; } /** The app's tile (plain-page.css `.tile`): its icon, or its initials. Never a built-in mark of
M core/auth-worker/src/authorize.ts
@@ -37,6 +37,7 @@ mindHostResourceOf, } from "./oauth.ts"; import { isMemberSession } from "./members.ts"; +import { mindMarkOf } from "./mind-mark.ts"; import { CHOICE_FIELD, chooserPage, consentPage, errorPage, notMemberPage } from "./pages.ts"; import { signInHref } from "./sign-in.ts"; import { admitted, TOO_MANY } from "./device/limits.ts"; @@ -206,6 +207,7 @@ if (asked === "select_account") return chooserPage({ mind: config.controlPlaneHostname, + mindMark: await mindMarkOf(env), email: session.email, here, // an app's own sign-in says which app, to a person who is no member: a member's page is @@ -261,6 +263,7 @@ handle: consent.handle, email: session.email, mind: config.controlPlaneHostname, + mindMark: await mindMarkOf(env), resource: resourceInWords(env, authRequest.resource), host: hostResource ? new URL(hostResource).host : undefined, here,
M core/auth-worker/src/device/page.test.ts
@@ -280,7 +280,12 @@ statements.map((statement) => statement.counted()), }, OAUTH_KV: { - get: async (key: string) => kept.get(key) ?? null, + // a mind with no logo of its own, read just now (../mind-mark.ts): no page here asks the + // mind's website, which would be a request to the real internet + get: async (key: string) => + key === "iterate-mind-mark" + ? { icon: null, askAfter: Number.MAX_SAFE_INTEGER } + : (kept.get(key) ?? null), put: async (key: string, value: string) => void kept.set(key, value), }, // the cast: the device page reads these bindings and no other
M core/auth-worker/src/device/page.ts
@@ -7,6 +7,7 @@ import { clientTile } from "../client-mark.ts"; import { errorPage, factsTable, notMemberPage, otherAccountForm, page, text } from "../pages.ts"; import { signedChangeBy, signerOf, signScript } from "../signed-change.ts"; +import { mindMarkOf } from "../mind-mark.ts"; import { signInHref } from "../sign-in.ts"; import { CALLBACK_PATH, normalizeUserCode, VERIFICATION_PATH } from "./protocol.ts"; import { type DeviceRequest, deviceStore } from "./store.ts"; @@ -85,7 +86,7 @@ (device.status === "confirmed" && device.confirmedBy === session.userId)); if (!found || !waits) return enter(mind, userCode, "No device is waiting for this code. It may have expired."); - if (request.method === "GET") return confirm(env, userCode, device, session.email); + if (request.method === "GET") return await confirm(env, userCode, device, session.email); // Only Decline declines: Continue with no signature (a page whose script did not run) says // what it takes, and the request waits on. @@ -108,7 +109,13 @@ ? null : "the signed statement is for another request."; if (refused || "refused" in press) - return confirm(env, userCode, device, session.email, `The device is not signed in: ${refused}`); + return await confirm( + env, + userCode, + device, + session.email, + `The device is not signed in: ${refused}`, + ); const facts = new AccountFacts(); facts.add(session.userId, { type: DEVICE_CONFIRMED, @@ -150,7 +157,13 @@ * name is the device's own claim. */ export const deviceTile = (name: string) => clientTile({ name, redirectUri: "", redirectHost: "" }); -function confirm(env: Env, userCode: string, device: DeviceRequest, email: string, error?: string) { +async function confirm( + env: Env, + userCode: string, + device: DeviceRequest, + email: string, + error?: string, +) { const mind = configOf(env).controlPlaneHostname; const where = [device.requestedFrom.city, device.requestedFrom.country] .filter(Boolean) @@ -168,6 +181,7 @@ <p id="status" class="muted" role="status">Your passkey signs this request.</p> <div class="muted">Signed in as ${text(email)}. Not you? ${otherAccountForm(`${VERIFICATION_PATH}?${new URLSearchParams({ user_code: userCode })}`)}</div>`; const shown = { + mindMark: await mindMarkOf(env), status: error ? 403 : 200, script: `${signScript(mind)}${PRESS_SCRIPT}`, };
M core/auth-worker/src/email-sign-in.ts
@@ -12,11 +12,11 @@ // or with none (`memberRefusal`): the passkey, Cloudflare Access for an owner // (./access-sign-in.ts), an owner's sign-in link for an added member // -// AN APP MAY NAME WHOSE ADDRESS A CODE SIGNS IN (`emailDomains`, ./asking-app.ts). For such an -// app the address page says which domains, and an address at any other is refused there with -// that reason, for every such address alike, a member's too: no challenge is made and nothing is -// mailed, so it spends none of the limits below. The app's description is public, so the words -// tell nothing that it does not. +// AN APP MAY NAME WHOSE ADDRESS A CODE SIGNS IN (`allowedEmails`, `allowedEmailPatterns`, +// ./asking-app.ts). For such an app the address page says so, and an address that the app does +// not name is refused there with that reason, for every such address alike, a member's too: no +// challenge is made and nothing is mailed, so it spends none of the limits below. The words name +// the domains of the app's patterns and never an address that it names. // // A SIGN-IN THAT DOES NOT NAME "email" HAS NO SUCH PAGE: an app says how its people sign in // (./asking-app.ts `signInOf`), and for one that names the passkey alone, as for the control @@ -32,7 +32,13 @@ import { zoneOf } from "iterate/mind-config"; import { z } from "zod"; import { AccountFacts } from "./account-facts.ts"; -import { type AskingApp, askingAppOf, signInOf, takesAddress } from "./asking-app.ts"; +import { + allowedEmailsWords, + type AskingApp, + askingAppOf, + signInOf, + takesAddress, +} from "./asking-app.ts"; import { isBlocked } from "./blocked.ts"; import { isOwner } from "./config.ts"; import { emailSessionCookie, MIND_FORM_PATH, sessionsOverRemoved } from "./cookies.ts"; @@ -189,16 +195,12 @@ }); } -/** The domains that an app's mailed code is for, as a list in words: "a.com or b.com". */ -const domainsOf = (domains: string[]) => - new Intl.ListFormat("en", { type: "disjunction" }).format(domains); +/** One more sentence on the address page of an app that names whose address it takes. */ +const onlyAt = ({ mailedCode }: SignIn) => { + const words = mailedCode && allowedEmailsWords(mailedCode); + return words ? ` ${text(words)}` : ""; +}; -/** One more sentence on the address page of an app that names domains: whose address it takes. */ -const onlyAt = ({ mailedCode }: SignIn) => - mailedCode?.emailDomains - ? ` ${text(mailedCode.name)} takes an address at ${text(domainsOf(mailedCode.emailDomains))} only.` - : ""; - /** The way to "sign in with your mind" (./mind-sign-in.ts), for an app that names it. */ const mindWay = (next: string) => `<form method="get" action="${MIND_FORM_PATH}" class="stack"> <input type="hidden" name="next" value="${text(next)}"> @@ -218,12 +220,10 @@ const email = typed.trim().toLowerCase(); const again = (error: string) => emailAddressPage(env, next, signIn, error, typed); if (!z.email().safeParse(email).success) return again("Enter an email address."); - // an app that names domains: no code for an address at any other, and no challenge - if (signIn.mailedCode?.emailDomains && !takesAddress(signIn.mailedCode, email)) { - console.info({ event: "auth.sign-in-refused", method: "email", reason: "domain" }); - return again( - `${signIn.mailedCode.name} takes an address at ${domainsOf(signIn.mailedCode.emailDomains)} only. Use such an address.`, - ); + // an app that names whose address it takes: no code for any other, and no challenge + if (signIn.mailedCode && !takesAddress(signIn.mailedCode, email)) { + console.info({ event: "auth.sign-in-refused", method: "email", reason: "not-allowed" }); + return again(`${allowedEmailsWords(signIn.mailedCode)} Use such an address.`); } const id = crypto.randomUUID(); const code = String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, "0");
M core/auth-worker/src/enrolment.test.ts
@@ -898,16 +898,19 @@ expect(stack.mailed).toHaveLength(before); }); -// AN APP NAMES WHOSE ADDRESS A MAILED CODE SIGNS IN (iterate/app-description `emailDomains`), and -// the issuer holds the sign-up to the list: at the mail, and at every code for the app's host. -test("an app that names domains: no code is mailed to an address at another domain and no challenge is made, from the app's own page and from an MCP client alike; a session of such an address gets no code for the host; a passkey's session passes", async () => { +// AN APP NAMES WHOSE ADDRESS A MAILED CODE SIGNS IN (iterate/app-description `allowedEmails`, +// `allowedEmailPatterns`), and the issuer holds the sign-up to them: at the mail, and at every +// code for the app's host. +test("an app that names addresses and patterns: no code is mailed to an address that neither names and no challenge is made, from the app's own page and from an MCP client alike; a session of such an address gets no code for the host; a passkey's session passes", async () => { const stack = stackOf(); const shop = "https://shop.example.com"; const inside = "eve@shop-people.dev"; + const named = "kit@kits-mail.dev"; stack.described.set("shop.example.com", { name: "Shop", signIn: ["email", "passkey"], - emailDomains: ["shop-people.dev"], + allowedEmails: [named], + allowedEmailPatterns: ["*@shop-people.dev"], }); const mcp = await oauthHelpers(stack.env).createClient({ clientName: "An MCP client", @@ -925,7 +928,7 @@ for (const next of [own, fromMcp]) expect( await (await ask(stack.env, `/sign-in/email?${new URLSearchParams({ next })}`)).text(), - ).toContain("Shop takes an address at shop-people.dev only."); + ).toContain("Shop takes an address at shop-people.dev, and the addresses that it names, only."); const challenges = () => stack.db.prepare("select count(*) as n from email_challenges").get() as { n: number }; @@ -946,13 +949,16 @@ status: 400, mailed: 0, challenges: 0, - says: "Shop takes an address at shop-people.dev only. Use such an address.", + says: "Shop takes an address at shop-people.dev, and the addresses that it names, only. Use such an address.", }; expect({ - // an address at another domain, a subdomain of the app's, and a member's: one answer for all + // an address that neither names, at a subdomain of a pattern's, beside the named one at its + // domain, and a member's: one answer for all outsider: await asked(GUEST, own), outsiderFromMcp: await asked(GUEST, fromMcp), subdomain: await asked("eve@mail.shop-people.dev", own), + besideTheNamed: await asked("eve@kits-mail.dev", own), + named: await asked(named, own), member: await asked(MEMBER, own), insider: await asked(inside, own), insiderInCapitals: await asked("Bo@Shop-People.dev", fromMcp), @@ -960,6 +966,8 @@ outsider: refused, outsiderFromMcp: refused, subdomain: refused, + besideTheNamed: refused, + named: { status: 303, mailed: 1, challenges: 1, says: "" }, member: refused, insider: { status: 303, mailed: 1, challenges: 1, says: "" }, insiderInCapitals: { status: 303, mailed: 1, challenges: 1, says: "" },
M core/auth-worker/src/http.ts
@@ -51,6 +51,7 @@ import { passkeySignInResponse } from "./passkey-sign-in.ts"; import { selfTestResponse } from "./self-test.ts"; import { SESSIONS_PATH, sessionsResponse } from "./sessions-page.ts"; +import { mindMarkOf } from "./mind-mark.ts"; import { AFTER_SIGN_OUT, SIGN_IN_PATH, signOutResponse } from "./sign-in.ts"; import { statementDraftsResponse } from "./statement-drafts.ts"; import { statementsResponse } from "./statements.ts"; @@ -147,6 +148,8 @@ if (methods[0] === "email") return emailAddressPage(env, next, signIn); return signInPage({ mind: configOf(env).controlPlaneHostname, + // an app's own sign-in shows the app's icon + mindMark: signIn.app ? null : await mindMarkOf(env), next, app: signIn.app, offersEmail: methods.includes("email"),
M core/auth-worker/src/members.test.ts
@@ -7,6 +7,7 @@ import { configVars, keyRows, stackKeyPair } from "./test-support.ts"; const LINK = "events.iterate.com/account/member-link-made"; +const REMOVE_KEYS = "events.iterate.com/account/member-keys-removed"; test.for([ ["a sign-in link for a member", "link"], @@ -33,9 +34,11 @@ ).toContain("This takes a press of your passkey"); expect(stack).toMatchObject({ changed: [] }); const signed = await stack.owner.signed(LINK, { email: "member@example.org" }); - expect(await stack.post({ action: "link", email: "member@example.org", signed })).toContain( - "Give this link to member@example.org", - ); + const linkPage = await stack.post({ action: "link", email: "member@example.org", signed }); + expect(linkPage).toContain("Sign-in link for member@example.org"); + expect(linkPage).toContain("Give this link to member@example.org"); + expect(linkPage).toContain('data-copy="https://iterate.example.com/keys/first#'); + expect(linkPage).toContain(">Copy link</button>"); expect(stack).toMatchObject({ changed: ["a link for member@example.org"] }); }); @@ -52,6 +55,107 @@ expect(stack).toMatchObject({ changed: [] }); }); +test("removing a lost passkey with make-link removes keys, ends access, and immediately makes a sign-in link with a copy button", async () => { + const stack = await stackOf({ + withPasskey: ["member@example.org"], + kept: [ + "grant:user_member:g1", + "token:user_member:g1:t1", + "grant:user_other:g9", + "token:user_other:g9:t1", + ], + }); + const signed = await stack.owner.signed(REMOVE_KEYS, { + email: "member@example.org", + makeLink: true, + }); + const page = await stack.post({ + action: "remove-keys", + email: "member@example.org", + "make-link": "1", + signed, + }); + expect(page).toContain("Sign-in link for member@example.org"); + expect(page).toContain( + "member@example.org has no keys now, and is signed out of every app and device.", + ); + expect(page).toContain('data-copy="https://iterate.example.com/keys/first#'); + expect(page).toContain(">Copy link</button>"); + expect(page).toContain("Give this link to member@example.org"); + expect(stack).toMatchObject({ + changed: ["keys removed of member@example.org", "a link for member@example.org"], + kept: ["grant:user_other:g9", "token:user_other:g9:t1"], + }); +}); + +test("removing a lost passkey without make-link removes keys and makes no sign-in link", async () => { + const stack = await stackOf({ withPasskey: ["member@example.org"] }); + const signed = await stack.owner.signed(REMOVE_KEYS, { email: "member@example.org" }); + const page = await stack.post({ + action: "remove-keys", + email: "member@example.org", + signed, + }); + expect(page).toContain( + "member@example.org has no keys now, and is signed out of every app and device.", + ); + expect(page).toContain("Make a sign-in link for this member below when you are ready"); + expect(page).not.toContain('class="link-callout"'); + expect(stack).toMatchObject({ changed: ["keys removed of member@example.org"] }); +}); + +test("a remove-keys signature must match whether a sign-in link is requested", async () => { + const stack = await stackOf({ withPasskey: ["member@example.org"] }); + const withoutLink = await stack.owner.signed(REMOVE_KEYS, { email: "member@example.org" }); + expect( + await stack.post({ + action: "remove-keys", + email: "member@example.org", + "make-link": "1", + signed: withoutLink, + }), + ).toContain("the signed statement does not match this request"); + const withLink = await stack.owner.signed(REMOVE_KEYS, { + email: "member@example.org", + makeLink: true, + }); + expect( + await stack.post({ + action: "remove-keys", + email: "member@example.org", + signed: withLink, + }), + ).toContain("the signed statement does not match this request"); + expect(stack).toMatchObject({ changed: [] }); +}); + +test("removing keys of a former member with make-link removes keys but makes no sign-in link", async () => { + const stack = await stackOf({ + members: ["member@example.org"], + withPasskey: ["former@example.org"], + }); + const signed = await stack.owner.signed(REMOVE_KEYS, { + email: "former@example.org", + makeLink: true, + }); + const page = await stack.post({ + action: "remove-keys", + email: "former@example.org", + "make-link": "1", + signed, + }); + expect(page).toContain("No sign-in link was made because former@example.org is not a member."); + expect(page).not.toContain('class="link-callout"'); + expect(stack).toMatchObject({ changed: ["keys removed of former@example.org"] }); +}); + +test("GET /members offers making a sign-in link by default when removing a lost passkey", async () => { + const stack = await stackOf(); + const page = await stack.get(); + expect(page).toContain('name="make-link" value="1" checked'); + expect(page).toContain("Remove keys and make a sign-in link"); +}); + test("removal of a member ends what the member was given, each grant with its tokens, and no other person's", async () => { const stack = await stackOf({ kept: [ @@ -90,11 +194,13 @@ /** A stack with an owner who is signed in with a passkey, and two added members. Of D1, what the * members page and a statement's check read and write. `changed` names each write that counts. */ async function stackOf({ + members = ["member@example.org", "other@example.org"], withPasskey = [], kept = [], -}: { withPasskey?: string[]; kept?: string[] } = {}) { +}: { members?: string[]; withPasskey?: string[]; kept?: string[] } = {}) { const [ownerKey, otherKey, stackKey] = [await keyPair(), await keyPair(), await stackKeyPair()]; const changed: string[] = []; + const heldPasskeys = new Set(withPasskey); // the OAuth library's store, by its keys: a grant, and each token of it under the grant's name const store = new Map( kept.map((name) => [name, { id: name.split(":")[2], userId: name.split(":")[1] }]), @@ -117,18 +223,26 @@ changed.push(`${String(bound[0])} removed`); return { email: bound[0] }; } - if (sql.includes("from members where email")) return { 1: 1 }; + if (sql.includes("from members where email")) + return members.includes(String(bound[0])) ? { 1: 1 } : null; if (sql.startsWith("select id from users where email")) return { id: `user_${String(bound[0]).split("@")[0]}` }; if (sql.includes("format = 'webauthn'")) - return withPasskey.includes(String(bound[0])) ? { 1: 1 } : null; + return heldPasskeys.has(String(bound[0])) ? { 1: 1 } : null; throw new Error(`not expected: ${sql}`); }, all: async () => { const session = sessions.statementOf(sql, bound); if (session) return session.all(); - if (sql.startsWith("update keys set revoked_at")) - changed.push(`keys removed of ${String(bound[1])}`); + if (sql.startsWith("update keys set revoked_at")) { + const email = String(bound[1]); + if (!heldPasskeys.has(email)) return { results: [] }; + heldPasskeys.delete(email); + changed.push(`keys removed of ${email}`); + return { + results: [{ id: "key_1", label: "Passkey", userId: `user_${email.split("@")[0]}` }], + }; + } return { results: [] }; }, run: async () => { @@ -195,6 +309,18 @@ }, owner: member(ownerKey), other: member(otherKey), + /** The members page itself, fetched by the owner's session. */ + get: async () => { + const answer = await membersResponse( + env, + new Request(`${ISSUER}/members`, { method: "GET", headers: { cookie } }), + async () => null, + ); + if (!answer) throw new Error("the members page did not answer"); + return (await answer.text()).replaceAll(/&#(\d+);/g, (_all, code) => + String.fromCharCode(Number(code)), + ); + }, /** The members page's own form, posted by the owner's session. Answers the page's text. */ post: async (fields: Record<string, string>) => { const answer = await membersResponse(
M core/auth-worker/src/members.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/mind-mark.test.ts
@@ -0,0 +1,230 @@ +// The mind's own logo at the head of the sign-in and consent pages (./mind-mark.ts): what the +// issuer takes from the mind's profile, how long it keeps it, and how the pages show it. +import { expect, test, vi } from "vitest"; +import type { Env } from "./env.ts"; +import { mindMarkOf } from "./mind-mark.ts"; +import { consentPage, signInPage } from "./pages.ts"; +import { configVars } from "./test-support.ts"; + +const WEBSITE = "https://example.com"; +const ICON = `${WEBSITE}/favicon.svg`; +const TILE = `<div class="tile" data-mind-mark="icon"><img src="${ICON}" alt="" referrerpolicy="no-referrer"></div>`; + +test("the mind's logo is the icon of its website's profile, read once in five minutes with no redirect followed", async () => { + const stack = stackOf(); + using web = answers(() => Response.json({ name: "Ada's mind", description: "", icon: ICON })); + expect(await mindMarkOf(stack.env)).toEqual({ html: TILE, origin: WEBSITE }); + expect(await mindMarkOf(stack.env)).toEqual({ html: TILE, origin: WEBSITE }); + expect(web).toMatchObject({ + asked: [{ url: `${WEBSITE}/.well-known/iterate-profile`, redirect: "manual" }], + }); +}); + +test.for([ + { name: "a mind with no icon", answer: () => Response.json({ name: "Ada", icon: null }) }, + { name: "a website with no profile", answer: () => new Response("Not found", { status: 404 }) }, + // the website's own origin over https, and nothing else + ...[ + "https://elsewhere.test/logo.svg", + "https://sub.example.com/logo.svg", + "http://example.com/favicon.svg", + "//elsewhere.test/logo.svg", + "/favicon.svg", + "javascript:alert(1)", + `data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg"/>`, + ].map((icon) => ({ name: `an icon at ${icon}`, answer: () => Response.json({ icon }) })), +])("$name is no logo: the pages show iterate's mark", async ({ answer }) => { + const stack = stackOf(); + using _web = answers(answer); + expect(await mindMarkOf(stack.env)).toBeNull(); +}); + +test.for([ + { name: "a 503", answer: () => new Response("down", { status: 503 }) }, + { name: "a redirect", answer: () => new Response(null, { status: 302 }) }, + { name: "no answer", answer: () => Promise.reject(new Error("no answer")) }, + { name: "a text that is no JSON", answer: () => new Response("<!doctype html>") }, + { name: "an object that is no profile", answer: () => Response.json({ icon: 7 }) }, +])( + "a website that answers with $name has said nothing new: the logo is what it was, and the website is asked again after a minute", + async ({ answer }) => { + const stack = stackOf(); + // nothing kept yet: no logo, and the next page does not ask again + { + using web = answers(answer); + expect(await mindMarkOf(stack.env)).toBeNull(); + expect(await mindMarkOf(stack.env)).toBeNull(); + expect(web.asked).toHaveLength(1); + } + // a logo that was kept stays + stack.keep({ icon: ICON, askAfter: 0 }); + using _web = answers(answer); + const before = Date.now(); + expect(await mindMarkOf(stack.env)).toMatchObject({ html: TILE }); + await stack.asked(); + expect(stack.kept()).toMatchObject({ icon: ICON }); + expect(Math.round((stack.kept().askAfter - before) / 60_000)).toBe(1); + }, +); + +test("a page that finds the logo older than five minutes shows what is kept and waits for nothing: the website is asked after the answer", async () => { + const stack = stackOf(); + stack.keep({ icon: ICON, askAfter: 0 }); + let answered = () => {}; + const slow = new Promise<void>((resolve) => (answered = resolve)); + using web = answers(async () => { + await slow; + return Response.json({ icon: null }); + }); + // the page has its logo while the website has not answered yet + expect(await mindMarkOf(stack.env)).toMatchObject({ html: TILE }); + expect(web.asked).toHaveLength(1); + answered(); + await stack.asked(); + // the website took its icon away: the next page shows iterate's mark + expect(await mindMarkOf(stack.env)).toBeNull(); +}); + +test("a logo never stops a page: a store that fails at the read or at the write, and a profile that is too long, leave iterate's mark or the logo that was read", async () => { + const profile = () => Response.json({ icon: ICON }); + // the store does not answer: no logo, and no error + { + const stack = stackOf(); + stack.env.OAUTH_KV.get = () => Promise.reject(new Error("the store is down")); + using _web = answers(profile); + expect(await mindMarkOf(stack.env)).toBeNull(); + } + // the row cannot be written: this page has the logo that was read + { + const stack = stackOf(); + stack.env.OAUTH_KV.put = () => Promise.reject(new Error("too many writes of one key")); + using _web = answers(profile); + expect(await mindMarkOf(stack.env)).toMatchObject({ html: TILE }); + } + // a profile over the bound is read no further than the bound, and is no word of the website + const stack = stackOf(); + let sent = 0; + let cancelled = false; + using _web = answers( + () => + new Response( + new ReadableStream({ + pull(stream) { + sent += 1; + stream.enqueue(new TextEncoder().encode(" ".repeat(8_000))); + }, + cancel: () => void (cancelled = true), + }), + ), + ); + expect(await mindMarkOf(stack.env)).toBeNull(); + expect({ cancelled, readNoFurther: sent < 6 }).toEqual({ cancelled: true, readNoFurther: true }); +}); + +test("a kept row is read again as it is shown: an icon of another origin in it is no logo", async () => { + const stack = stackOf(); + stack.keep({ icon: "https://elsewhere.test/logo.svg", askAfter: Date.now() + 60_000 }); + expect(await mindMarkOf(stack.env)).toBeNull(); +}); + +test("the consent page and the mind's sign-in page show the mind's logo where iterate's mark was, and the page's policy allows its one origin beside the client's", async () => { + const mindMark = { html: TILE, origin: WEBSITE }; + const consent = (mark: typeof mindMark | null, details: object = {}) => + consentPage({ + details: { + clientName: "Claude", + redirectUri: "https://claude.ai/api/mcp/auth_callback", + redirectHost: "claude.ai", + redirectIsLoopback: false, + ...details, + } as never, + handle: "handle", + email: "owner@example.net", + mind: "iterate.example.com", + mindMark: mark, + resource: "its MCP server", + here: "/oauth2/auth?client_id=c&state=s", + headers: new Headers(), + }); + const withLogo = consent(mindMark); + expect(withLogo.headers.get("content-security-policy")?.split("; ")).toContain( + `img-src data: ${WEBSITE}`, + ); + const html = await withLogo.text(); + // the mind's logo, the dotted line, the client's tile: and no mark of iterate's + expect(html).toContain(`<div class="asks">${TILE}<span class="joins" aria-hidden="true"></span>`); + expect(html).not.toContain(`class="mark"`); + // a mind with no logo is as before + expect(await consent(null).text()).toContain(`<div class="asks"><div class="mark"`); + // a client with a logo of its own: both origins, and both pictures + const both = consent(mindMark, { + clientName: "Notes", + redirectUri: "https://notes.example.org/callback", + redirectHost: "notes.example.org", + clientDomain: "example.org", + logoUri: "https://cdn.example.org/logo.png", + }); + expect(both.headers.get("content-security-policy")?.split("; ")).toContain( + `img-src data: https://cdn.example.org ${WEBSITE}`, + ); + expect(await both.text()).toContain( + `${TILE}<span class="joins" aria-hidden="true"></span><div class="tile" data-client-mark="logo">`, + ); + // a client with no tile: the mind's logo is the card's one mark + const alone = consent(mindMark, { + clientName: "Notes", + redirectUri: "https://notes.example.org/callback", + redirectHost: "notes.example.org", + }); + expect(await alone.text()).toContain(`<main class="centered">${TILE}<h1>`); + + const signIn = (mark: typeof mindMark | null) => + signInPage({ + mind: "iterate.example.com", + mindMark: mark, + next: "/oauth2/auth?client_id=c", + app: null, + offersEmail: false, + offersGuest: false, + asksAtOpen: false, + noPasskeyYet: false, + }).text(); + expect(await signIn(mindMark)).toContain(`<main class="centered">${TILE}<h1>Sign in to`); + expect(await signIn(null)).toContain(`<main class="centered"><div class="mark"`); +}); + +type Kept = { icon: string | null; askAfter: number }; + +/** A mind at `iterate.example.com` whose website is `https://example.com`, with the issuer's KV + * as a map. */ +function stackOf() { + const kv = new Map<string, string>(); + // the cast: the logo's code reads the config and this one binding + const env = { + ...configVars(), + OAUTH_KV: { + get: async (key: string) => JSON.parse(kv.get(key) || "null"), + put: async (key: string, value: string) => void kv.set(key, value), + }, + } as unknown as Env; + return { + env, + keep: (row: Kept) => void kv.set("iterate-mind-mark", JSON.stringify(row)), + kept: () => JSON.parse(kv.get("iterate-mind-mark")!) as Kept, + // what a page left to run after its answer has written its row + asked: () => + vi.waitFor(() => + expect(JSON.parse(kv.get("iterate-mind-mark")!).askAfter).toBeGreaterThan(0), + ), + }; +} + +/** The web for a test: every request gets `answer`, and `asked` lists them. */ +function answers(answer: () => Response | Promise<Response>) { + const asked: { url: string; redirect?: string }[] = []; + const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + asked.push({ url: String(input), redirect: init?.redirect }); + return answer(); + }); + return { asked, [Symbol.dispose]: () => spy.mockRestore() }; +}
A core/auth-worker/src/mind-mark.ts
@@ -0,0 +1,125 @@ +// mind-mark.ts — THE MIND'S OWN LOGO, at the head of the pages where a person signs in to the +// mind or lets a client in: the sign-in page, the chooser, the consent page and a device's +// confirmation. A person sees which mind they give access to by its own picture, where the pages +// showed iterate's mark before. +// +// WHERE THE LOGO COMES FROM. The mind's website answers what the mind says of itself, for anyone, +// at `/.well-known/iterate-profile` of its zone: `{ name, description, icon }` (the template's +// profile.ts). This Worker reads it over the public internet, as it reads an app's description +// (./asking-app.ts), and follows no redirect. The icon counts only over https from the website's +// own origin, so the page's policy allows that one origin. Nothing else of the profile is read +// here: the pages name the mind by its control-plane hostname, which the mind's code cannot write. +// +// THE MIND'S CODE WROTE IT, and that code may be hostile. So the logo is shown as an image +// (`<img>`, which runs nothing), with no referrer, and it proves nothing: the words of each page +// say which mind it is and where access goes. A mind that draws another's mark as its own logo +// changes no word of the page. +// +// NO PAGE WAITS FOR IT TWICE. The answer is kept for five minutes. A page that finds it older +// shows what is kept and asks again after the answer (`waitUntil`). Only a page that finds +// nothing kept waits, for two seconds at most. A website that does not answer, or whose answer +// is no profile, has said nothing new: the logo is what it was, or iterate's mark, and the +// website is asked again after a minute. A website with no icon (`icon: null`, a 404) has said +// so: the pages show iterate's mark. +import { waitUntil } from "cloudflare:workers"; +import { reportIssue } from "iterate/lib"; +import { zoneOf } from "iterate/mind-config"; +import { z } from "zod"; +import { configOf, type Env } from "./env.ts"; +import { text } from "./pages.ts"; + +/** Where a mind's website answers its profile (the template's profile.ts `PROFILE_PATH`). */ +const PROFILE_PATH = "/.well-known/iterate-profile"; + +const KEY = "iterate-mind-mark"; +/** A profile is a name, a description of a thousand characters and an address. */ +const PROFILE_MAX_BYTES = 20_000; + +/** The mind's logo for a page: the tile's HTML, and the one origin that its image comes from. */ +export type MindMark = { html: string; origin: string }; + +type Kept = { icon: string | null; askAfter: number }; + +/** The mind's logo as a page shows it, or null for a mind that has none: the page then shows + * iterate's mark. */ +export async function mindMarkOf(env: Env): Promise<MindMark | null> { + // A LOGO NEVER STOPS A PAGE: when the store fails, the page shows iterate's mark. + return shown(env).catch((error) => { + reportIssue("mind-mark.failed", error); + return null; + }); +} + +async function shown(env: Env): Promise<MindMark | null> { + const config = configOf(env); + // the mind's website is the apex of the zone that its control plane is in + const origin = `https://${zoneOf(config, config.controlPlaneHostname) || config.zones[0]}`; + let kept = await env.OAUTH_KV.get<Kept>(KEY, "json"); + if (!kept) kept = await read(env, origin, null); + else if (kept.askAfter <= Date.now()) + waitUntil(read(env, origin, kept).catch((error) => reportIssue("mind-mark.failed", error))); + // a row is read again as it is shown: only an icon of the website's own origin is one + const icon = kept.icon && iconAt(kept.icon, origin); + if (!icon) return null; + return { + html: `<div class="tile" data-mind-mark="icon"><img src="${text(icon)}" alt="" referrerpolicy="no-referrer"></div>`, + origin, + }; +} + +/** Asks the website, and keeps what it said. `last` is what was kept before. */ +async function read(env: Env, origin: string, last: Kept | null): Promise<Kept> { + const heard = await fetch(`${origin}${PROFILE_PATH}`, { + headers: { accept: "application/json" }, + redirect: "manual", + signal: AbortSignal.timeout(2000), + }) + .then(async (answer) => { + // a website with no profile has no logo; any other answer but a profile is no word of it + if (answer.status === 404) return { icon: null }; + if (answer.status !== 200) return null; + const profile = await textUpTo(answer, PROFILE_MAX_BYTES); + // too long, or empty: no profile + if (!profile) return null; + const said = z + .object({ icon: z.string().max(2048).nullable() }) + .safeParse(JSON.parse(profile)); + return said.success ? { icon: said.data.icon && iconAt(said.data.icon, origin) } : null; + }) + .catch(() => null); + const kept = heard + ? { ...heard, askAfter: Date.now() + 5 * 60_000 } + : { icon: last?.icon || null, askAfter: Date.now() + 60_000 }; + // a row that could not be written is asked for again by the next page: this page has its answer + await env.OAUTH_KV.put(KEY, JSON.stringify(kept), { expirationTtl: 24 * 3600 }).catch((error) => + reportIssue("mind-mark.not-kept", error), + ); + return kept; +} + +/** The answer's text, read up to `maxBytes` and no further: null for a longer one, whose rest is + * not read. The profile is anyone's to write, so its length is not trusted. */ +async function textUpTo(answer: Response, maxBytes: number): Promise<string | null> { + if (!answer.body) return ""; + const reader = answer.body.getReader(); + const chunks: Uint8Array[] = []; + let bytes = 0; + for (;;) { + const { done, value } = await reader.read(); + if (done) break; + bytes += value.byteLength; + if (bytes > maxBytes) { + await reader.cancel(); + return null; + } + chunks.push(value); + } + return new TextDecoder().decode(await new Blob(chunks).arrayBuffer()); +} + +/** `icon` as an address of the website's own origin over https, or null. */ +function iconAt(icon: string, origin: string): string | null { + if (!URL.canParse(icon)) return null; + const url = new URL(icon); + return url.origin === origin && url.protocol === "https:" ? url.href : null; +}
M core/auth-worker/src/pages.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/auth-worker/src/pages.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/auth-worker/src/stack-key.ts
@@ -14,6 +14,7 @@ fromBase64url, isMindControlPlaneHostname, isMindId, + MIND_FETCH_STATEMENT_TYPE, signedMlDsa65, type StackKeyDocument, statementText, @@ -132,7 +133,14 @@ * the signer (the vault's ask of the Cloud, which reads a hostname there). Refused until the mind's identity * lists the stack's key, with an error that has no code: this ends when a record lists the key, * so a subscription that sends to another mind must try again later. A coded refusal such as - * FORBIDDEN would halt its row for good (core/itx subscription-delivery.ts). */ + * FORBIDDEN would halt its row for good (core/itx subscription-delivery.ts). + * + * A STATEMENT FOR THIS MIND ITSELF is signed for one type alone: a signed request + * (`MIND_FETCH_STATEMENT_TYPE`), which a secret by proxy sends to a service that this mind names + * as its own (iterate's mind is a customer of iterate Cloud, which it runs: Jonas, 25 Nov 2026). + * The service checks it as any mind's. This mind's own door still takes no such statement: a + * mind is no caller of itself (./mind-fetch.ts refuses it). For every other + * type a statement that names this mind is refused, as before. */ export async function signedByStack( env: Env, input: Parameters<AuthService["sign"]>[0], @@ -144,9 +152,11 @@ throw new Error( "the mind's identity lists no working key of this stack yet, so the mind signs nothing as itself", ); + const requestToItself = type === MIND_FETCH_STATEMENT_TYPE; if ( mind && - ((!isMindId(mind) && !isMindControlPlaneHostname(mind)) || [mindId, own].includes(mind)) + ((!isMindId(mind) && !isMindControlPlaneHostname(mind)) || + ([mindId, own].includes(mind) && !requestToItself)) ) throw codedError( "INVALID_INPUT", @@ -159,8 +169,10 @@ throw codedError("INVALID_INPUT", "a statement expires between a second and a day ahead"); // An id signs at once. A hostname is read once to its id (a minute's cache in the reader): a // proxy secret's cell from before holds one until the connect sets it again. - const peer = !mind || isMindId(mind) ? mind : await mindIdAt(mind); - if (peer === mindId) throw codedError("INVALID_INPUT", `${mind} is this mind`); + // (this mind's own hostname is its own id: no log is read for it) + const peer = !mind || isMindId(mind) ? mind : mind === own ? mindId : await mindIdAt(mind); + if (peer === mindId && !requestToItself) + throw codedError("INVALID_INPUT", `${mind} is this mind`); const at = Date.now(); const statement = statementText({ ...(peer ? { mind: peer, from: mindId, fromHost: own } : { mind: own }),
M core/auth-worker/src/test-support.ts
@@ -108,7 +108,11 @@ execute, }; }; - const kv = new Map<string, string>(); + // A mind with no logo of its own, read just now: no test's page asks the mind's website for + // one (./mind-mark.ts), which would be a request to the real internet. + const kv = new Map<string, string>([ + ["iterate-mind-mark", JSON.stringify({ icon: null, askAfter: Number.MAX_SAFE_INTEGER })], + ]); const mailed: { from: { email: string; name: string }; to: string[];
M core/auth-worker/src/working-key.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/caller.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/context/built-ins.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/workers-mcp-call.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/index.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/serve-host.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/stream/facet-push-catch-up.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/stream/stream.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/itx/src/stream/subscription-delivery.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/app-description.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/app-description.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/cli/README.md
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/cli/cli.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/cli/deploy.test.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/cli/deploy.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/integrations.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/mind-config.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/mind-ingress.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/sdk/auth.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/sdk/index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/lib/src/standalone-page.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/mind-worker/src/http.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp-config.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp-skill-frontmatter.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp-skills.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp-skills.ts
Not shown: the change is larger than this page shows. A clone has it.
M core/mind-worker/src/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.