core/ of iterate/private at 216369eb, as its public copy has it
Misha Kaletsky, 2026-11-24 18:00 UTC · d75488a30968135beb95c96fc3a14759b62e7713 · the first commit
871 files changed
- A .gitignore
- A .nvmrc
- A LICENSE
- A README.md
- A core/AGENTS.md
- A core/alchemy/.gitignore
- A core/alchemy/README.md
- A core/alchemy/alchemy.run.ts
- A core/alchemy/package.json
- A core/alchemy/src/access-team.test.ts
- A core/alchemy/src/access-team.ts
- A core/alchemy/src/analytics-sql-binding.ts
- A core/alchemy/src/artifacts-namespace.ts
- A core/alchemy/src/artifacts-repo-subscription.ts
- A core/alchemy/src/catalog-tables-of-sinks.ts
- A core/alchemy/src/config.test.ts
- A core/alchemy/src/config.ts
- A core/alchemy/src/container-snapshots.test.ts
- A core/alchemy/src/container-snapshots.ts
- A core/alchemy/src/mind-made-telemetry-tables.test.ts
- A core/alchemy/src/mind-made-telemetry-tables.ts
- A core/alchemy/src/realtime.test.ts
- A core/alchemy/src/realtime.ts
- A core/alchemy/src/retired-cloudflare-oauth-client.test.ts
- A core/alchemy/src/retired-cloudflare-oauth-client.ts
- A core/alchemy/src/stack-bindings.snapshot.json
- A core/alchemy/src/stack-bindings.test.ts
- A core/alchemy/src/stack.ts
- A core/alchemy/src/telemetry-token.test.ts
- A core/alchemy/src/telemetry-token.ts
- A core/alchemy/tsconfig.json
- A core/auth-worker/migrations/0000_users.sql
- A core/auth-worker/migrations/0001_email_challenges.sql
- A core/auth-worker/migrations/0002_members.sql
- A core/auth-worker/migrations/0003_keys.sql
- A core/auth-worker/migrations/0004_stack_key.sql
- A core/auth-worker/migrations/0005_admissions.sql
- A core/auth-worker/migrations/0006_passkey_sign_in.sql
- A core/auth-worker/migrations/0007_keys_by_credential.sql
- A core/auth-worker/migrations/0008_key_scope.sql
- A core/auth-worker/migrations/0009_blocked.sql
- A core/auth-worker/migrations/0010_member_tickets.sql
- A core/auth-worker/migrations/0011_browser_sessions.sql
- A core/auth-worker/migrations/0012_cloudflare_people_by_subject.sql
- A core/auth-worker/migrations/0013_statement_drafts.sql
- A core/auth-worker/migrations/0014_mind_melds.sql
- A core/auth-worker/migrations/0015_statement_draft_signer.sql
- A core/auth-worker/migrations/0016_outsider_keys.sql
- A core/auth-worker/migrations/0017_identity_records.sql
- A core/auth-worker/migrations/0018_stack_key_ml_dsa.sql
- A core/auth-worker/migrations/0019_key_origin.sql
- A core/auth-worker/migrations/0020_statement_draft_asked_by.sql
- A core/auth-worker/migrations/0021_mind_melds_by_id.sql
- A core/auth-worker/migrations/0022_page_event_days.sql
- A core/auth-worker/package.json
- A core/auth-worker/src/access-list.test.ts
- A core/auth-worker/src/access-list.ts
- A core/auth-worker/src/access-sign-in.test.ts
- A core/auth-worker/src/access-sign-in.ts
- A core/auth-worker/src/account-facts.ts
- A core/auth-worker/src/asking-app.test.ts
- A core/auth-worker/src/asking-app.ts
- A core/auth-worker/src/authorize.ts
- A core/auth-worker/src/blocked.test.ts
- A core/auth-worker/src/blocked.ts
- A core/auth-worker/src/browser-sessions-fake.ts
- A core/auth-worker/src/client-mark.test.ts
- A core/auth-worker/src/client-mark.ts
- A core/auth-worker/src/cloud-key.ts
- A core/auth-worker/src/config.test.ts
- A core/auth-worker/src/config.ts
- A core/auth-worker/src/cookies.ts
- A core/auth-worker/src/device/callback.ts
- A core/auth-worker/src/device/limits.test.ts
- A core/auth-worker/src/device/limits.ts
- A core/auth-worker/src/device/page.test.ts
- A core/auth-worker/src/device/page.ts
- A core/auth-worker/src/device/poll.ts
- A core/auth-worker/src/device/protocol.ts
- A core/auth-worker/src/device/start.ts
- A core/auth-worker/src/device/store.ts
- A core/auth-worker/src/email-sign-in.ts
- A core/auth-worker/src/enrolment.test.ts
- A core/auth-worker/src/enrolment.ts
- A core/auth-worker/src/env.ts
- A core/auth-worker/src/guest-sign-in.test.ts
- A core/auth-worker/src/guest-sign-in.ts
- A core/auth-worker/src/http.test.ts
- A core/auth-worker/src/http.ts
- A core/auth-worker/src/identity.test.ts
- A core/auth-worker/src/identity.ts
- A core/auth-worker/src/key-rules.test.ts
- A core/auth-worker/src/key-rules.ts
- A core/auth-worker/src/key-tokens.test.ts
- A core/auth-worker/src/key-tokens.ts
- A core/auth-worker/src/keys-pages.test.ts
- A core/auth-worker/src/keys-pages.ts
- A core/auth-worker/src/keys.ts
- A core/auth-worker/src/members.test.ts
- A core/auth-worker/src/members.ts
- A core/auth-worker/src/mind-fetch.ts
- A core/auth-worker/src/mind-sign-in.test.ts
- A core/auth-worker/src/mind-sign-in.ts
- A core/auth-worker/src/minds-page.test.ts
- A core/auth-worker/src/minds-page.ts
- A core/auth-worker/src/minds.test.ts
- A core/auth-worker/src/minds.ts
- A core/auth-worker/src/oauth.test.ts
- A core/auth-worker/src/oauth.ts
- A core/auth-worker/src/page-events.test.ts
- A core/auth-worker/src/page-events.ts
- A core/auth-worker/src/page-tag.test.ts
- A core/auth-worker/src/page-tag.ts
- A core/auth-worker/src/pages.test.ts
- A core/auth-worker/src/pages.ts
- A core/auth-worker/src/passkey-sign-in.ts
- A core/auth-worker/src/rpc.ts
- A core/auth-worker/src/self-test.ts
- A core/auth-worker/src/sessions-page.test.ts
- A core/auth-worker/src/sessions-page.ts
- A core/auth-worker/src/sign-in.ts
- A core/auth-worker/src/signed-change.test.ts
- A core/auth-worker/src/signed-change.ts
- A core/auth-worker/src/stack-key.ts
- A core/auth-worker/src/statement-drafts.test.ts
- A core/auth-worker/src/statement-drafts.ts
- A core/auth-worker/src/statements.test.ts
- A core/auth-worker/src/statements.ts
- A core/auth-worker/src/test-support.ts
- A core/auth-worker/src/users.ts
- A core/auth-worker/src/vouch.ts
- A core/auth-worker/src/who-is.ts
- A core/auth-worker/src/worker.ts
- A core/auth-worker/src/working-key.test.ts
- A core/auth-worker/tsconfig.json
- A core/auth-worker/vitest.config.ts
- A core/boundary-worker/package.json
- A core/boundary-worker/src/artifacts-events.test.ts
- A core/boundary-worker/src/artifacts-events.ts
- A core/boundary-worker/src/cloudflare-events.ts
- A core/boundary-worker/src/config.ts
- A core/boundary-worker/src/control-plane-api.test.ts
- A core/boundary-worker/src/control-plane-api.ts
- A core/boundary-worker/src/env.ts
- A core/boundary-worker/src/host-session.test.ts
- A core/boundary-worker/src/host-session.ts
- A core/boundary-worker/src/http.test.ts
- A core/boundary-worker/src/http.ts
- A core/boundary-worker/src/identity-delivery.test.ts
- A core/boundary-worker/src/identity-delivery.ts
- A core/boundary-worker/src/mail-outcomes.test.ts
- A core/boundary-worker/src/mail-outcomes.ts
- A core/boundary-worker/src/mail.test.ts
- A core/boundary-worker/src/mail.ts
- A core/boundary-worker/src/mind-host-sign-in.test.ts
- A core/boundary-worker/src/mind-host-sign-in.ts
- A core/boundary-worker/src/mind-stamp.test.ts
- A core/boundary-worker/src/mind-transport.ts
- A core/boundary-worker/src/outside-placeholders.test.ts
- A core/boundary-worker/src/own-request.test.ts
- A core/boundary-worker/src/own-request.ts
- A core/boundary-worker/src/provided-door.test.ts
- A core/boundary-worker/src/provided-door.ts
- A core/boundary-worker/src/provided-mind.test.ts
- A core/boundary-worker/src/provided-mind.ts
- A core/boundary-worker/src/rpc.test.ts
- A core/boundary-worker/src/rpc.ts
- A core/boundary-worker/src/session-cookies.ts
- A core/boundary-worker/src/session-mind.ts
- A core/boundary-worker/src/stamp.test.ts
- A core/boundary-worker/src/stamp.ts
- A core/boundary-worker/src/worker.ts
- A core/boundary-worker/tsconfig.json
- A core/boundary-worker/vitest.config.ts
- A core/configs/LICENSE
- A core/configs/README.md
- A core/configs/default/AGENTS.md
- A core/configs/default/accounts.md
- A core/configs/default/agent-kinds.md
- A core/configs/default/agent-kinds/agent.test.mjs
- A core/configs/default/agent-kinds/agent.ts
- A core/configs/default/agent-kinds/index.ts
- A core/configs/default/agent-prompt.ts
- A core/configs/default/agent-start.ts
- A core/configs/default/agent-tests/files.test.mjs
- A core/configs/default/agent-tests/processor.test.mjs
- A core/configs/default/agent-tests/script-envelope.test.mjs
- A core/configs/default/agent-tests/start-boundary.test.mjs
- A core/configs/default/agent-tests/start.test.mjs
- A core/configs/default/agent-tests/subagent.test.mjs
- A core/configs/default/agent-tests/test-support.mjs
- A core/configs/default/agent-ui.ts
- A core/configs/default/agent/contract.ts
- A core/configs/default/agent/facet.ts
- A core/configs/default/agent/facets.json
- A core/configs/default/agent/facets.ts
- A core/configs/default/agent/files.d.ts
- A core/configs/default/agent/fragments.ts
- A core/configs/default/agent/llm-api.ts
- A core/configs/default/agent/llm-apis/anthropic-messages.ts
- A core/configs/default/agent/llm-apis/chat-completions.ts
- A core/configs/default/agent/llm-apis/google-generate-content.ts
- A core/configs/default/agent/llm-apis/openai-responses.ts
- A core/configs/default/agent/llm-request.ts
- A core/configs/default/agent/package.json
- A core/configs/default/agent/processor.ts
- A core/configs/default/agent/script-envelope.ts
- A core/configs/default/agent/start.ts
- A core/configs/default/agents.ts
- A core/configs/default/api.ts
- A core/configs/default/apps.md
- A core/configs/default/apps/dash/app.ts
- A core/configs/default/apps/dash/index.html
- A core/configs/default/apps/dash/links.ts
- A core/configs/default/apps/dash/public/app.css
- A core/configs/default/apps/dash/public/app.js
- A core/configs/default/apps/dash/public/brands/cloudflare.svg
- A core/configs/default/apps/dash/public/brands/github.svg
- A core/configs/default/apps/dash/public/brands/google.svg
- A core/configs/default/apps/dash/public/brands/slack.svg
- A core/configs/default/apps/dash/public/brands/x.svg
- A core/configs/default/apps/dash/public/call-facet.js
- A core/configs/default/apps/dash/public/mcp-page.js
- A core/configs/default/apps/dash/public/share-links.js
- A core/configs/default/apps/docs/app.ts
- A core/configs/default/apps/docs/index.html
- A core/configs/default/apps/docs/notes.ts
- A core/configs/default/apps/docs/processors/anchor.ts
- A core/configs/default/apps/docs/processors/classes.ts
- A core/configs/default/apps/docs/processors/comments.ts
- A core/configs/default/apps/docs/processors/doc.ts
- A core/configs/default/apps/docs/processors/frames.ts
- A core/configs/default/apps/docs/processors/merge.ts
- A core/configs/default/apps/docs/processors/root.ts
- A core/configs/default/apps/docs/public/app.css
- A core/configs/default/apps/docs/public/app.js
- A core/configs/default/apps/guestbook/app.ts
- A core/configs/default/apps/guestbook/entries.ts
- A core/configs/default/apps/guestbook/index.html
- A core/configs/default/apps/guestbook/mcp.ts
- A core/configs/default/apps/guestbook/public/app.css
- A core/configs/default/apps/guestbook/public/app.js
- A core/configs/default/apps/live-reload/live-reload.js
- A core/configs/default/apps/mcp/app.ts
- A core/configs/default/apps/mcp/server.ts
- A core/configs/default/apps/meet/app.ts
- A core/configs/default/apps/meet/index.html
- A core/configs/default/apps/meet/meeting.ts
- A core/configs/default/apps/meet/public/app.css
- A core/configs/default/apps/meet/public/app.js
- A core/configs/default/apps/meet/public/share-links.js
- A core/configs/default/apps/meet/public/snapshot-capture.js
- A core/configs/default/apps/onboarding/app.ts
- A core/configs/default/apps/onboarding/cloud-ai.ts
- A core/configs/default/apps/onboarding/cloud-credit.ts
- A core/configs/default/apps/onboarding/contract.ts
- A core/configs/default/apps/onboarding/launch.ts
- A core/configs/default/apps/onboarding/open-cloud.ts
- A core/configs/default/apps/onboarding/steps.ts
- A core/configs/default/apps/onboarding/steps/connect-cloudflare.ts
- A core/configs/default/apps/onboarding/steps/connect-iterate-cloud.ts
- A core/configs/default/apps/onboarding/verify-ai.ts
- A core/configs/default/apps/open-files.ts
- A core/configs/default/apps/tasks/app.ts
- A core/configs/default/apps/tasks/index.html
- A core/configs/default/apps/tasks/public/app.css
- A core/configs/default/apps/tasks/public/app.js
- A core/configs/default/apps/tasks/public/manifest.webmanifest
- A core/configs/default/apps/tasks/public/tasks-model.js
- A core/configs/default/apps/tasks/tasks-model.test.mjs
- A core/configs/default/apps/telemetry/backend.ts
- A core/configs/default/apps/telemetry/crashes.test.mjs
- A core/configs/default/apps/telemetry/crashes.ts
- A core/configs/default/apps/telemetry/cut.ts
- A core/configs/default/apps/telemetry/day-budget.ts
- A core/configs/default/apps/telemetry/exceptions.test.mjs
- A core/configs/default/apps/telemetry/exceptions.ts
- A core/configs/default/apps/telemetry/page-events.test.mjs
- A core/configs/default/apps/telemetry/page-events.ts
- A core/configs/default/apps/telemetry/page-speed.test.mjs
- A core/configs/default/apps/telemetry/page-speed.ts
- A core/configs/default/apps/telemetry/page-tag.ts
- A core/configs/default/apps/telemetry/public/page.js
- A core/configs/default/apps/theme.css
- A core/configs/default/calendar.ts
- A core/configs/default/call.ts
- A core/configs/default/call/outbound.ts
- A core/configs/default/call/rules.ts
- A core/configs/default/call/share-api.ts
- A core/configs/default/call/share.ts
- A core/configs/default/call/snapshot.ts
- A core/configs/default/cloud-accounts.ts
- A core/configs/default/cloud-deliveries.ts
- A core/configs/default/cloud-handover.ts
- A core/configs/default/cloud-scopes.ts
- A core/configs/default/cloudflare.md
- A core/configs/default/cloudflare.ts
- A core/configs/default/context-descriptions.ts
- A core/configs/default/debug.ts
- A core/configs/default/deliveries.ts
- A core/configs/default/docs-app.md
- A core/configs/default/errors.md
- A core/configs/default/every-event.ts
- A core/configs/default/files.d.ts
- A core/configs/default/gmail.ts
- A core/configs/default/homepage.ts
- A core/configs/default/init.ts
- A core/configs/default/integrations.ts
- A core/configs/default/iterate-core.ts
- A core/configs/default/mail-replies.md
- A core/configs/default/mail-replies.ts
- A core/configs/default/mail.ts
- A core/configs/default/minds.md
- A core/configs/default/package.json
- A core/configs/default/page-events.md
- A core/configs/default/people.md
- A core/configs/default/profile.ts
- A core/configs/default/profile/icon.svg
- A core/configs/default/profile/profile.json
- A core/configs/default/sandboxes.md
- A core/configs/default/secrets.md
- A core/configs/default/slack.ts
- A core/configs/default/telemetry.ts
- A core/configs/default/template-updates.md
- A core/configs/default/top-of-mind.md
- A core/configs/default/tsconfig.json
- A core/configs/default/website.ts
- A core/configs/default/worker.ts
- A core/configs/doctor.config.mjs
- A core/configs/minimal/AGENTS.md
- A core/configs/minimal/package.json
- A core/configs/minimal/tsconfig.json
- A core/configs/minimal/worker.ts
- A core/home-lab/.gitignore
- A core/home-lab/README.md
- A core/home-lab/package.json
- A core/home-lab/src/fixtures/snapshot-request.ts
- A core/home-lab/src/link/local-entrance.test.ts
- A core/home-lab/src/link/local-entrance.ts
- A core/home-lab/src/link/own-host.test.ts
- A core/home-lab/src/link/own-host.ts
- A core/home-lab/src/link/relay.ts
- A core/home-lab/src/link/worker.ts
- A core/home-lab/src/main.ts
- A core/home-lab/src/repos/artifacts.ts
- A core/home-lab/src/repos/server.test.ts
- A core/home-lab/src/repos/server.ts
- A core/home-lab/src/repos/token.ts
- A core/home-lab/src/sandbox-sidecars.test.ts
- A core/home-lab/src/sandbox-sidecars.ts
- A core/home-lab/src/snapshot-request.test.ts
- A core/home-lab/tsconfig.json
- A core/itx/package.json
- A core/itx/src/alarm-coordinator.ts
- A core/itx/src/caller.test.ts
- A core/itx/src/caller.ts
- A core/itx/src/cause.test.ts
- A core/itx/src/cause.ts
- A core/itx/src/context-stub.test.ts
- A core/itx/src/context-stub.ts
- A core/itx/src/context/awake.test.ts
- A core/itx/src/context/awake.ts
- A core/itx/src/context/built-ins.ts
- A core/itx/src/context/call-context.test.ts
- A core/itx/src/context/connections.ts
- A core/itx/src/context/context-catalog.ts
- A core/itx/src/context/context-summary.test.ts
- A core/itx/src/context/context-summary.ts
- A core/itx/src/context/critical-section-deadline.ts
- A core/itx/src/context/dispatch.test.ts
- A core/itx/src/context/dispatch.ts
- A core/itx/src/context/egress.ts
- A core/itx/src/context/facet-host.test.ts
- A core/itx/src/context/facet-host.ts
- A core/itx/src/context/facet-public-methods.ts
- A core/itx/src/context/fetch-upgrade-splice.ts
- A core/itx/src/context/fetch-upgrade.ts
- A core/itx/src/context/held-verbs-across-contexts.test.ts
- A core/itx/src/context/held-verbs.test.ts
- A core/itx/src/context/held-verbs.ts
- A core/itx/src/context/itx-expression-rewriting.ts
- A core/itx/src/context/jail-rows-reach.test.ts
- A core/itx/src/context/lent-names.test.ts
- A core/itx/src/context/lent-names.ts
- A core/itx/src/context/loaded-code-rows.test.ts
- A core/itx/src/context/parent-rule-and-child.test.ts
- A core/itx/src/context/paths.ts
- A core/itx/src/context/redial.test.ts
- A core/itx/src/context/redial.ts
- A core/itx/src/context/residency.ts
- A core/itx/src/context/rpc-stub-relay.ts
- A core/itx/src/context/rpc-stubs.test.ts
- A core/itx/src/context/rpc-stubs.ts
- A core/itx/src/context/rule-snapshots.test.ts
- A core/itx/src/context/rule-snapshots.ts
- A core/itx/src/context/run.ts
- A core/itx/src/context/signed-fetch.test.ts
- A core/itx/src/context/stateless-context.ts
- A core/itx/src/context/telemetry-query-rule.test.ts
- A core/itx/src/context/websocket-close.ts
- A core/itx/src/context/whoami.test.ts
- A core/itx/src/context/worker-loader.ts
- A core/itx/src/context/worker-manifest.ts
- A core/itx/src/context/workers-root-email.test.ts
- A core/itx/src/end-when-silent.test.ts
- A core/itx/src/end-when-silent.ts
- A core/itx/src/fetch-routes.test.ts
- A core/itx/src/fetch-routes.ts
- A core/itx/src/first-party-facets.ts
- A core/itx/src/host.ts
- A core/itx/src/index.ts
- A core/itx/src/iterate-context-durable-object.ts
- A core/itx/src/iterate-context.test.ts
- A core/itx/src/iterate-context.ts
- A core/itx/src/loaded-code-cd.test.ts
- A core/itx/src/metrics.ts
- A core/itx/src/on-behalf-of.test.ts
- A core/itx/src/on-behalf-of.ts
- A core/itx/src/person-context.test.ts
- A core/itx/src/person-context.ts
- A core/itx/src/request-body.test.ts
- A core/itx/src/request-body.ts
- A core/itx/src/request-stamps.test.ts
- A core/itx/src/serve-host.ts
- A core/itx/src/session.test.ts
- A core/itx/src/session.ts
- A core/itx/src/stream/core-events.ts
- A core/itx/src/stream/core-processor.test.ts
- A core/itx/src/stream/core-processor.ts
- A core/itx/src/stream/event-expressions.ts
- A core/itx/src/stream/scheduled-appends.ts
- A core/itx/src/stream/stream-versions.test.ts
- A core/itx/src/stream/stream-wait-for-event.test.ts
- A core/itx/src/stream/stream-wake-events.test.ts
- A core/itx/src/stream/stream.ts
- A core/itx/src/stream/subscription-delivery.ts
- A core/itx/src/stream/wake-events.test.ts
- A core/itx/src/stream/wake-events.ts
- A core/itx/src/unavailable.test.ts
- A core/itx/src/unavailable.ts
- A core/itx/tsconfig.json
- A core/itx/vitest.config.ts
- A core/lib/LICENSE
- A core/lib/README.md
- A core/lib/bin/iterate.js
- A core/lib/package.json
- A core/lib/scripts/plain-page-css.ts
- A core/lib/src/acts.test.ts
- A core/lib/src/acts.ts
- A core/lib/src/agents/README.md
- A core/lib/src/agents/api.ts
- A core/lib/src/agents/at-work.test.ts
- A core/lib/src/agents/at-work.ts
- A core/lib/src/agents/catalog.test.ts
- A core/lib/src/agents/catalog.ts
- A core/lib/src/agents/collection.test.ts
- A core/lib/src/agents/collection.ts
- A core/lib/src/agents/contract.ts
- A core/lib/src/agents/index.ts
- A core/lib/src/agents/install.test.ts
- A core/lib/src/agents/install.ts
- A core/lib/src/agents/kinds.ts
- A core/lib/src/agents/message.ts
- A core/lib/src/agents/recent.test.ts
- A core/lib/src/agents/recent.ts
- A core/lib/src/api.ts
- A core/lib/src/app-config.test.ts
- A core/lib/src/app-config.ts
- A core/lib/src/app-description.test.ts
- A core/lib/src/app-description.ts
- A core/lib/src/app-server.test.ts
- A core/lib/src/app-server.ts
- A core/lib/src/app-session.ts
- A core/lib/src/app.test.ts
- A core/lib/src/app.ts
- A core/lib/src/cause.ts
- A core/lib/src/cli/README.md
- A core/lib/src/cli/bridge-key.test.ts
- A core/lib/src/cli/bridge-key.ts
- A core/lib/src/cli/chatgpt.test.ts
- A core/lib/src/cli/chatgpt.ts
- A core/lib/src/cli/cli.test.ts
- A core/lib/src/cli/cli.ts
- A core/lib/src/cli/cloudflare-access.test.ts
- A core/lib/src/cli/cloudflare-access.ts
- A core/lib/src/cli/coding-agent.ts
- A core/lib/src/cli/config.ts
- A core/lib/src/cli/deploy.test.ts
- A core/lib/src/cli/deploy.ts
- A core/lib/src/cli/device-login/flow.test.ts
- A core/lib/src/cli/device-login/flow.ts
- A core/lib/src/cli/device-login/index.ts
- A core/lib/src/cli/device-login/poll.test.ts
- A core/lib/src/cli/device-login/poll.ts
- A core/lib/src/cli/fs.test.ts
- A core/lib/src/cli/fs.ts
- A core/lib/src/cli/identity.test.ts
- A core/lib/src/cli/identity.ts
- A core/lib/src/cli/oauth.ts
- A core/lib/src/cli/open-page.test.ts
- A core/lib/src/cli/open-page.ts
- A core/lib/src/cli/provide-state.ts
- A core/lib/src/cli/provide.test.ts
- A core/lib/src/cli/provide.ts
- A core/lib/src/cli/recover.test.ts
- A core/lib/src/cli/recover.ts
- A core/lib/src/cli/run-command.ts
- A core/lib/src/cli/share-my-computer.ts
- A core/lib/src/cli/tunnel.test.ts
- A core/lib/src/cli/tunnel.ts
- A core/lib/src/cli/use-my-computer.ts
- A core/lib/src/client/connected-mind.ts
- A core/lib/src/client/event-log.test.ts
- A core/lib/src/client/event-log.ts
- A core/lib/src/client/heartbeat.ts
- A core/lib/src/client/live-state.test.ts
- A core/lib/src/client/live-state.ts
- A core/lib/src/client/new-version.ts
- A core/lib/src/client/oauth.test.ts
- A core/lib/src/client/oauth.ts
- A core/lib/src/client/react.tsx
- A core/lib/src/client/socket.test.ts
- A core/lib/src/client/socket.ts
- A core/lib/src/cloudflare-read-scopes.test.ts
- A core/lib/src/compatibility-date.ts
- A core/lib/src/config-default-agent.test.ts
- A core/lib/src/config-default-calendar.test.ts
- A core/lib/src/config-default-call.test.ts
- A core/lib/src/config-default-cloud-accounts.test.ts
- A core/lib/src/config-default-cloud-deliveries.test.ts
- A core/lib/src/config-default-cloudflare-card.test.ts
- A core/lib/src/config-default-cloudflare.test.ts
- A core/lib/src/config-default-context-descriptions.test.ts
- A core/lib/src/config-default-dash.test.ts
- A core/lib/src/config-default-docs.test.ts
- A core/lib/src/config-default-gmail.test.ts
- A core/lib/src/config-default-guestbook.test.ts
- A core/lib/src/config-default-handover.test.ts
- A core/lib/src/config-default-iterate-core.test.ts
- A core/lib/src/config-default-mail-replies.test.ts
- A core/lib/src/config-default-mcp.test.ts
- A core/lib/src/config-default-meet.test.ts
- A core/lib/src/config-default-mirror.test.ts
- A core/lib/src/config-default-onboarding.test.ts
- A core/lib/src/config-default-profile.test.ts
- A core/lib/src/config-default-publish-hook.test.ts
- A core/lib/src/config-default-signature-prompts.test.ts
- A core/lib/src/config-default-slack.test.ts
- A core/lib/src/config-default-tasks.test.ts
- A core/lib/src/config-default-telemetry-query-rule.test.ts
- A core/lib/src/config-default-telemetry.test.ts
- A core/lib/src/dash-routes.fixture.json
- A core/lib/src/email.ts
- A core/lib/src/expression.test.ts
- A core/lib/src/expression.ts
- A core/lib/src/facts.test.ts
- A core/lib/src/facts.ts
- A core/lib/src/integrations.test.ts
- A core/lib/src/integrations.ts
- A core/lib/src/lib.test.ts
- A core/lib/src/lib.ts
- A core/lib/src/mind-api.test.ts
- A core/lib/src/mind-api.ts
- A core/lib/src/mind-config.test.ts
- A core/lib/src/mind-config.ts
- A core/lib/src/mind-identity-log.test.ts
- A core/lib/src/mind-identity-log.ts
- A core/lib/src/mind-identity.test.ts
- A core/lib/src/mind-identity.ts
- A core/lib/src/mind-ingress.ts
- A core/lib/src/node-renewal.test.ts
- A core/lib/src/node.test.ts
- A core/lib/src/node.ts
- A core/lib/src/oauth-scopes.test.ts
- A core/lib/src/oauth-scopes.ts
- A core/lib/src/package-builds.test.ts
- A core/lib/src/package-builds.ts
- A core/lib/src/platform-retry.test.ts
- A core/lib/src/platform-retry.ts
- A core/lib/src/principal.test.ts
- A core/lib/src/principal.ts
- A core/lib/src/released-answer.test.ts
- A core/lib/src/sdk/auth.test.ts
- A core/lib/src/sdk/auth.ts
- A core/lib/src/sdk/call-with-cause.ts
- A core/lib/src/sdk/code-failed.ts
- A core/lib/src/sdk/cut.ts
- A core/lib/src/sdk/direct-append.test.ts
- A core/lib/src/sdk/direct-append.ts
- A core/lib/src/sdk/files.ts
- A core/lib/src/sdk/index.test.ts
- A core/lib/src/sdk/index.ts
- A core/lib/src/sdk/itx-scope.test.ts
- A core/lib/src/sdk/itx-scope.ts
- A core/lib/src/sdk/loaded-worker.test.ts
- A core/lib/src/sdk/loaded-worker.ts
- A core/lib/src/secret-placeholder.test.ts
- A core/lib/src/secret-placeholder.ts
- A core/lib/src/signed.test.ts
- A core/lib/src/signed.ts
- A core/lib/src/sshsig.test.ts
- A core/lib/src/sshsig.ts
- A core/lib/src/standalone-page.test.ts
- A core/lib/src/standalone-page.ts
- A core/lib/src/stream/contract.ts
- A core/lib/src/stream/processor-rules.test.ts
- A core/lib/src/stream/processor.test.ts
- A core/lib/src/stream/processor.ts
- A core/lib/src/stream/run.ts
- A core/lib/src/stream/test-support.ts
- A core/lib/src/test-support/cloudflare-workers-shim.ts
- A core/lib/src/test-support/config-default-instance.ts
- A core/lib/src/test-support/identity-log.ts
- A core/lib/src/test-support/ssh-signer.ts
- A core/lib/src/theme/plain-page-css.gen.ts
- A core/lib/src/theme/plain-page.css
- A core/lib/src/theme/theme.css
- A core/lib/src/theme/tokens.css
- A core/lib/src/workers.ts
- A core/lib/tsconfig.cli.json
- A core/lib/tsconfig.json
- A core/lib/tsconfig.node.build.json
- A core/lib/tsconfig.node.json
- A core/lib/tsdown.config.ts
- A core/lib/vitest.config-file-imports.ts
- A core/lib/vitest.config.ts
- A core/mind-worker/.gitignore
- A core/mind-worker/images/iterate-dev-image/Dockerfile
- A core/mind-worker/package.json
- A core/mind-worker/scripts/build.ts
- A core/mind-worker/src/agent-spans.ts
- A core/mind-worker/src/approved-acts.test.ts
- A core/mind-worker/src/approved-acts.ts
- A core/mind-worker/src/config.ts
- A core/mind-worker/src/context/approvals.test.ts
- A core/mind-worker/src/context/approvals.ts
- A core/mind-worker/src/context/browser.ts
- A core/mind-worker/src/context/cf-artifacts.ts
- A core/mind-worker/src/context/config-code-failed.test.ts
- A core/mind-worker/src/context/file-urls.test.ts
- A core/mind-worker/src/context/file-urls.ts
- A core/mind-worker/src/context/fixtures/signed-upload.ts
- A core/mind-worker/src/context/held-verb-rules.test.ts
- A core/mind-worker/src/context/held-verb-rules.ts
- A core/mind-worker/src/context/hop-caller.ts
- A core/mind-worker/src/context/images.ts
- A core/mind-worker/src/context/mind-fetch.test.ts
- A core/mind-worker/src/context/minds.test.ts
- A core/mind-worker/src/context/minds.ts
- A core/mind-worker/src/context/module-resolution.test.ts
- A core/mind-worker/src/context/module-resolution.ts
- A core/mind-worker/src/context/r2.ts
- A core/mind-worker/src/context/secret-fact-after-answer.test.ts
- A core/mind-worker/src/context/secrets.test.ts
- A core/mind-worker/src/context/secrets.ts
- A core/mind-worker/src/context/signed-upload.test.ts
- A core/mind-worker/src/context/telemetry-facet.test.ts
- A core/mind-worker/src/context/telemetry.test.ts
- A core/mind-worker/src/context/telemetry.ts
- A core/mind-worker/src/context/url.test.ts
- A core/mind-worker/src/context/url.ts
- A core/mind-worker/src/context/webhooks.ts
- A core/mind-worker/src/context/worker-loader.ts
- A core/mind-worker/src/email/durable-object.ts
- A core/mind-worker/src/email/processor.test.ts
- A core/mind-worker/src/email/processor.ts
- A core/mind-worker/src/env.ts
- A core/mind-worker/src/generated/config-templates.d.ts
- A core/mind-worker/src/generated/platform-modules.d.ts
- A core/mind-worker/src/generated/sandbox-files-tool.d.ts
- A core/mind-worker/src/http.test.ts
- A core/mind-worker/src/http.ts
- A core/mind-worker/src/integrations/email-hook.test.ts
- A core/mind-worker/src/integrations/email-hook.ts
- A core/mind-worker/src/integrations/email.test.ts
- A core/mind-worker/src/integrations/email.ts
- A core/mind-worker/src/integrations/mcp.ts
- A core/mind-worker/src/integrations/registry.ts
- A core/mind-worker/src/integrations/webhooks.ts
- A core/mind-worker/src/itx-ai.test.ts
- A core/mind-worker/src/itx-ai.ts
- A core/mind-worker/src/itx-host.ts
- A core/mind-worker/src/lender-root.test.ts
- A core/mind-worker/src/lender-root.ts
- A core/mind-worker/src/library.ts
- A core/mind-worker/src/library/capnweb.ts
- A core/mind-worker/src/library/connection.ts
- A core/mind-worker/src/library/mcp.ts
- A core/mind-worker/src/library/openapi.ts
- A core/mind-worker/src/mcp.test.ts
- A core/mind-worker/src/mcp.ts
- A core/mind-worker/src/mind/collection.test.ts
- A core/mind-worker/src/mind/collection.ts
- A core/mind-worker/src/mind/context-birth-events.ts
- A core/mind-worker/src/mind/contract.ts
- A core/mind-worker/src/mind/durable-object.ts
- A core/mind-worker/src/mind/entity-lifecycle.ts
- A core/mind-worker/src/mind/processor.test.ts
- A core/mind-worker/src/mind/processor.ts
- A core/mind-worker/src/mind/publication.ts
- A core/mind-worker/src/mind/seed-repos.ts
- A core/mind-worker/src/mind/template-update.test.ts
- A core/mind-worker/src/mind/template-update.ts
- A core/mind-worker/src/platform-append.ts
- A core/mind-worker/src/platform-entries.test.ts
- A core/mind-worker/src/platform-entries.ts
- A core/mind-worker/src/repo/contract.ts
- A core/mind-worker/src/repo/durable-object.test.ts
- A core/mind-worker/src/repo/durable-object.ts
- A core/mind-worker/src/repo/git-wire.test.ts
- A core/mind-worker/src/repo/git-wire.ts
- A core/mind-worker/src/repo/remote-commit.test.ts
- A core/mind-worker/src/repo/remote-commit.ts
- A core/mind-worker/src/rpc.ts
- A core/mind-worker/src/sandbox/container.ts
- A core/mind-worker/src/sandbox/contract.test.ts
- A core/mind-worker/src/sandbox/contract.ts
- A core/mind-worker/src/sandbox/durable-object.test.ts
- A core/mind-worker/src/sandbox/durable-object.ts
- A core/mind-worker/src/sandbox/egress-rule.test.ts
- A core/mind-worker/src/sandbox/egress-rule.ts
- A core/mind-worker/src/sandbox/egress.ts
- A core/mind-worker/src/sandbox/exec-record.ts
- A core/mind-worker/src/sandbox/files.ts
- A core/mind-worker/src/sandbox/image.test.ts
- A core/mind-worker/src/sandbox/image.ts
- A core/mind-worker/src/sandbox/own-session.test.ts
- A core/mind-worker/src/sandbox/own-session.ts
- A core/mind-worker/src/sandbox/ports.test.ts
- A core/mind-worker/src/sandbox/ports.ts
- A core/mind-worker/src/sandbox/processor.test.ts
- A core/mind-worker/src/sandbox/processor.ts
- A core/mind-worker/src/sandbox/session-filter-under-a-parent.test.ts
- A core/mind-worker/src/worker.ts
- A core/mind-worker/src/workspace/contract.ts
- A core/mind-worker/src/workspace/durable-object.ts
- A core/mind-worker/tsconfig.json
- A core/mind-worker/vitest.config.ts
- A core/repos/onboarding/AGENTS.md
- A core/repos/onboarding/files.d.ts
- A core/repos/onboarding/index.html
- A core/repos/onboarding/onboarding.md
- A core/repos/onboarding/onboarding/agent-loop.md
- A core/repos/onboarding/onboarding/approvals.md
- A core/repos/onboarding/onboarding/apps.md
- A core/repos/onboarding/onboarding/computer.md
- A core/repos/onboarding/onboarding/connect-iterate-cloud.md
- A core/repos/onboarding/onboarding/connect.md
- A core/repos/onboarding/onboarding/finish.md
- A core/repos/onboarding/onboarding/follow-up.md
- A core/repos/onboarding/onboarding/github.md
- A core/repos/onboarding/onboarding/instructions.md
- A core/repos/onboarding/onboarding/let-iterate-in.md
- A core/repos/onboarding/onboarding/links.md
- A core/repos/onboarding/onboarding/look.md
- A core/repos/onboarding/onboarding/mail.md
- A core/repos/onboarding/onboarding/mcp.md
- A core/repos/onboarding/onboarding/other-minds.md
- A core/repos/onboarding/onboarding/pays.md
- A core/repos/onboarding/onboarding/people.md
- A core/repos/onboarding/onboarding/reach.md
- A core/repos/onboarding/onboarding/research.md
- A core/repos/onboarding/onboarding/sandbox.md
- A core/repos/onboarding/onboarding/secrets.md
- A core/repos/onboarding/onboarding/sign-up-record.md
- A core/repos/onboarding/onboarding/signed-requests.md
- A core/repos/onboarding/onboarding/speak.md
- A core/repos/onboarding/onboarding/subagents.md
- A core/repos/onboarding/onboarding/telemetry.md
- A core/repos/onboarding/onboarding/voice.md
- A core/repos/onboarding/onboarding/website.md
- A core/repos/onboarding/package.json
- A core/repos/onboarding/public/app.css
- A core/repos/onboarding/public/app.js
- A core/repos/onboarding/tasks/onboarding-build-an-app.md
- A core/repos/onboarding/tasks/onboarding-connect-iterate-cloud.md
- A core/repos/onboarding/tasks/onboarding-connect-mcp.md
- A core/repos/onboarding/tasks/onboarding-connect-tools.md
- A core/repos/onboarding/tasks/onboarding-devices-and-character.md
- A core/repos/onboarding/tasks/onboarding-invite-people.md
- A core/repos/onboarding/tasks/onboarding-look.md
- A core/repos/onboarding/tasks/onboarding-mail.md
- A core/repos/onboarding/tasks/onboarding-remove-onboarding-app.md
- A core/repos/onboarding/tasks/onboarding-research.md
- A core/repos/onboarding/tasks/onboarding-sandbox.md
- A core/repos/onboarding/tasks/onboarding-secrets-and-approvals.md
- A core/repos/onboarding/tasks/onboarding-telemetry.md
- A core/repos/onboarding/tasks/onboarding-voice-call.md
- A core/repos/onboarding/tasks/onboarding-website.md
- A core/repos/onboarding/tsconfig.json
- A core/repos/onboarding/worker.ts
- A core/secrets-worker/package.json
- A core/secrets-worker/src/acts-gate.test.ts
- A core/secrets-worker/src/acts-gate.ts
- A core/secrets-worker/src/acts-page.test.ts
- A core/secrets-worker/src/acts-page.ts
- A core/secrets-worker/src/approval.test.ts
- A core/secrets-worker/src/approval.ts
- A core/secrets-worker/src/approvals-index.ts
- A core/secrets-worker/src/approvals-page.test.ts
- A core/secrets-worker/src/approvals-page.ts
- A core/secrets-worker/src/body-placement.test.ts
- A core/secrets-worker/src/body-placement.ts
- A core/secrets-worker/src/callback-page.test.ts
- A core/secrets-worker/src/callback-page.ts
- A core/secrets-worker/src/cloud-client.test.ts
- A core/secrets-worker/src/cloud-client.ts
- A core/secrets-worker/src/config.test.ts
- A core/secrets-worker/src/config.ts
- A core/secrets-worker/src/env.ts
- A core/secrets-worker/src/grant-ceiling.test.ts
- A core/secrets-worker/src/grant-refresh.test.ts
- A core/secrets-worker/src/grant-refresh.ts
- A core/secrets-worker/src/http.ts
- A core/secrets-worker/src/markdown.test.ts
- A core/secrets-worker/src/markdown.ts
- A core/secrets-worker/src/objects.ts
- A core/secrets-worker/src/rpc.ts
- A core/secrets-worker/src/secret-at-rest.ts
- A core/secrets-worker/src/secret-collect.test.ts
- A core/secrets-worker/src/secret-collect.ts
- A core/secrets-worker/src/secret-list.test.ts
- A core/secrets-worker/src/secret-list.ts
- A core/secrets-worker/src/secret-oauth-callback.test.ts
- A core/secrets-worker/src/secret-oauth-callback.ts
- A core/secrets-worker/src/secret-oauth-start.test.ts
- A core/secrets-worker/src/secret-oauth-start.ts
- A core/secrets-worker/src/secret-oauth.ts
- A core/secrets-worker/src/secret/body-placement.test.ts
- A core/secrets-worker/src/secret/by-proxy.test.ts
- A core/secrets-worker/src/secret/contract.ts
- A core/secrets-worker/src/secret/durable-object.test.ts
- A core/secrets-worker/src/secret/durable-object.ts
- A core/secrets-worker/src/secret/exchange-jail.ts
- A core/secrets-worker/src/secret/key-ops.ts
- A core/secrets-worker/src/secret/refusals.test.ts
- A core/secrets-worker/src/secret/refusals.ts
- A core/secrets-worker/src/secret/signing-key.test.ts
- A core/secrets-worker/src/secrets.test.ts
- A core/secrets-worker/src/secrets.ts
- A core/secrets-worker/src/stack-secrets.test.ts
- A core/secrets-worker/src/stack-secrets.ts
- A core/secrets-worker/src/worker.ts
- A core/secrets-worker/tsconfig.json
- A core/secrets-worker/vitest.config.ts
- A core/telemetry-worker/package.json
- A core/telemetry-worker/schemas/events.json
- A core/telemetry-worker/schemas/logs.json
- A core/telemetry-worker/schemas/spans.json
- A core/telemetry-worker/src/bounds.ts
- A core/telemetry-worker/src/config.test.ts
- A core/telemetry-worker/src/config.ts
- A core/telemetry-worker/src/env.ts
- A core/telemetry-worker/src/event-points.test.ts
- A core/telemetry-worker/src/event-points.ts
- A core/telemetry-worker/src/events-row.ts
- A core/telemetry-worker/src/http.ts
- A core/telemetry-worker/src/otlp.ts
- A core/telemetry-worker/src/query.ts
- A core/telemetry-worker/src/rpc.ts
- A core/telemetry-worker/src/store-query.test.ts
- A core/telemetry-worker/src/store-query.ts
- A core/telemetry-worker/src/worker.ts
- A core/telemetry-worker/tsconfig.json
- A package.json
- A patches/@cloudflare__workers-oauth-provider@1.2.4.patch
- A patches/zod@4.6.5.patch
- A pnpm-lock.yaml
- A pnpm-workspace.yaml
- A tsconfig.app.json
- A tsconfig.base.json
A .gitignore
@@ -0,0 +1,25 @@ +# What installing, building, testing and running iterate OS leaves behind. +node_modules +.pnpm-store +*.tsbuildinfo +.tanstack +build +dist +.output +.mf +.wrangler +.cache +.dev.vars* +!.dev.vars.example +.env* +!.env.example +.secrets +.cloudflare +*.log +.DS_Store +test-results/ +playwright-report/ +*.db +*.sqlite +*.db-* +*.sqlite-*
A .nvmrc
@@ -0,0 +1,1 @@ +26
A LICENSE
@@ -0,0 +1,661 @@ + GNU AFFERO GENERAL PUBLIC LICENSE + Version 3, 19 November 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU Affero General Public License is a free, copyleft license for +software and other kinds of works, specifically designed to ensure +cooperation with the community in the case of network server software. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +our General Public Licenses are intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + Developers that use our General Public Licenses protect your rights +with two steps: (1) assert copyright on the software, and (2) offer +you this License which gives you legal permission to copy, distribute +and/or modify the software. + + A secondary benefit of defending all users' freedom is that +improvements made in alternate versions of the program, if they +receive widespread use, become available for other developers to +incorporate. Many developers of free software are heartened and +encouraged by the resulting cooperation. However, in the case of +software used on network servers, this result may fail to come about. +The GNU General Public License permits making a modified version and +letting the public access it on a server without ever releasing its +source code to the public. + + The GNU Affero General Public License is designed specifically to +ensure that, in such cases, the modified source code becomes available +to the community. It requires the operator of a network server to +provide the source code of the modified version running there to the +users of that server. Therefore, public use of a modified version, on +a publicly accessible server, gives the public access to the source +code of the modified version. + + An older license, called the Affero General Public License and +published by Affero, was designed to accomplish similar goals. This is +a different license, not a version of the Affero GPL, but Affero has +released a new version of the Affero GPL which permits relicensing under +this license. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU Affero General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Remote Network Interaction; Use with the GNU General Public License. + + Notwithstanding any other provision of this License, if you modify the +Program, your modified version must prominently offer all users +interacting with it remotely through a computer network (if your version +supports such interaction) an opportunity to receive the Corresponding +Source of your version by providing access to the Corresponding Source +from a network server at no charge, through some standard or customary +means of facilitating copying of software. This Corresponding Source +shall include the Corresponding Source for any work covered by version 3 +of the GNU General Public License that is incorporated pursuant to the +following paragraph. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the work with which it is combined will remain governed by version +3 of the GNU General Public License. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU Affero General Public License from time to time. Such new versions +will be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU Affero General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU Affero General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU Affero General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU Affero General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU Affero General Public License for more details. + + You should have received a copy of the GNU Affero General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If your software can interact with users remotely through a computer +network, you should also make sure that it provides a way for users to +get its source. For example, if your program is a web application, its +interface could display a "Source" link that leads users to an archive +of the code. There are many ways you could offer source, and different +solutions will be better for different programs; see section 13 for the +specific requirements. + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU AGPL, see +<https://www.gnu.org/licenses/>.
A README.md
@@ -0,0 +1,44 @@ +# iterate/core + +The platform behind [iterate](https://iterate.com). A **mind** is one deployment: a small stack of Cloudflare Workers in its owner's own Cloudflare account, at its own domain. It holds agents, their memory as event logs, git repos, secrets and the apps its owner writes. Its people are members, who reach all of it, and anyone else, who reaches only what its apps serve. + +## What is where + +| Folder | What it is | +| ----------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `core/boundary-worker` | The only public Worker. Every request comes in through it, and it says who is calling. Every request that leaves with a secret goes out through it. | +| `core/auth-worker` | Who is a member, sign-in (passkeys, mailed codes) and the mind's own OAuth server, at `iterate.<domain>`. | +| `core/secrets-worker` | The vault. A secret's value never reaches the mind's code: the vault fills it into an outgoing request, after an approval when a rule asks for one. | +| `core/mind-worker` | The mind itself: its contexts (each a Durable Object with an event log), repos, sandboxes, and the owner's config code, which it loads from the mind's `/repos/config`. | +| `core/telemetry-worker` | Optional: events, logs and traces in the owner's account. | +| `core/itx` | The kernel the Workers share: a context, its log, and `itx`, the handle code uses to reach a mind. | +| `core/lib` | npm `iterate`: the SDK a mind's code builds on, the agents, and the `iterate` CLI. | +| `core/alchemy` | The one Alchemy script that deploys a stack. | +| `core/home-lab` | Runs the mind Worker on your own machine, behind a deployed boundary. | +| `core/configs` | The templates a new mind's config repo starts from. `default/` has its apps (agents, onboarding, and a guestbook as an example of an app for end users). | + +## Deploy a mind + +- With the wizard at [cloud.iterate.com](https://cloud.iterate.com), which runs the same deploy in your Cloudflare account. +- Or by hand: [core/alchemy/README.md](core/alchemy/README.md). + +## Read the code in this order + +1. [core/configs/default/AGENTS.md](core/configs/default/AGENTS.md) and its `worker.ts`: what a mind's owner writes. +2. [core/lib/README.md](core/lib/README.md): the SDK that code uses. +3. [core/alchemy/README.md](core/alchemy/README.md) and `core/alchemy/src/stack.ts`: the whole stack in one file. +4. Each Worker's `src/worker.ts`, the boundary's first. +5. `core/itx/src`: the kernel. + +The packages built on core are in [iterate/packages](https://github.com/iterate/packages). + +## License, and how to contribute + +AGPL-3.0 ([LICENSE](LICENSE)), except the SDK (`core/lib`, npm `iterate`) and the templates (`core/configs`), which are Apache-2.0 by the LICENSE in each folder. + +This repo is a read-only copy of `core/` from iterate's own repo, made by [Copybara](https://github.com/google/copybara) after each change to it. Paths are the same in both, and each commit ends in `GitOrigin-RevId: <sha>`, naming the commit it came from. A comment here may name a file outside `core/` (`docs/`, `tasks/`, `lint/`, `packages/`): that file is in iterate's own repo, or in iterate/packages. + +- Found a bug, or want something? [Open an issue](https://github.com/iterate/core/issues). +- Have a fix in mind? Push it to a fork and link the compare view in an issue. Pull requests are turned off here: the next copy would overwrite them. + +This README lives in iterate's repo at `copybara/core/README.md`.
A core/AGENTS.md
@@ -0,0 +1,24 @@ +# core + +What goes public as `iterate/core`: a mind's stack. + +- A mind is a stack of Workers, each in a folder named `<part>-worker`: `mind-worker/` (it hosts + the mind's contexts), `boundary-worker/`, `secrets-worker/`, `auth-worker/` and + `telemetry-worker/`. The boundary is one build for every topology: a mind that runs elsewhere + hands itself in at the API's address (`boundary-worker/src/provided-mind.ts`). +- `itx/` is the kernel library they share, and `alchemy/` deploys a stack. +- `home-lab/` runs the mind Worker on your own machine. +- `lib/` is npm `iterate`: the SDK, the agents app (`iterate/agents`) and the `iterate` CLI. +- `configs/` are the templates a mind starts from. +- `repos/` are the repos a new mind starts with beside its config: `repos/onboarding` is + `/repos/onboarding`, which `iterate deploy` names for the build ([configs/README.md](configs/README.md)). + +- **Core builds from a clone of itself.** Nothing in `core/` imports outside `core/`; outside code may + import core, never the reverse. `.oxlintrc.json` enforces it (`lint/oxlintrc-core-boundary.test.ts`). +- **Core's configs** (`configs/`) are the templates a mind starts from, and the documentation of + how a mind is configured: each depends on nothing outside core (`iterate/*` and `zod` come from + the platform). +- **Internal tooling stays outside:** iterate's own deploys, tasks and CI. +- **No ids or keys**, here or in `packages/`, tests included: no UUID, account id, key, or long hex, + base64 or digit string (`lint/public-copies.test.ts`). An id goes in `envs.ts`, a secret in + Doppler; a test uses an obvious fake (`aaaaabbbbbccccc111112222233333aaaaabbbbb`).
A core/alchemy/.gitignore
@@ -0,0 +1,2 @@ +# A config with a real account and real zones (README.md, "Deploy"). +mind.config*.local.json
A core/alchemy/README.md
@@ -0,0 +1,217 @@ +# core/alchemy + +One Alchemy script that deploys one mind into its owner's own Cloudflare account. Read +`src/stack.ts` from top to bottom: it declares every resource, and its header says what each +Worker is. `alchemy.run.ts` is the entry that Alchemy's CLI runs. This file says only what the +script does not. + +[`iterate deploy`](../lib/src/cli/README.md#deploy-a-mind) is the command for a person: it signs in +to Cloudflare, writes the one input below and runs this script. `iterate recover` gives an owner +with no passkey left a way back in. What follows is the deploy by hand. + +## What it makes + +- Five Workers: telemetry, auth, secrets, mind and boundary. Only the boundary has routes. With + the topology `external-mind-connects-into-cloudflare-boundary`, the stack has no mind Worker + and nothing that only a mind Worker binds. +- `src/stack-bindings.snapshot.json` lists each Worker's bindings, by name and kind and never by + value, as `src/stack.ts` declares them for three fixed configs. A pull request that adds, + removes or renames a binding must change that file, so the change shows in its diff: + `src/stack-bindings.test.ts` fails until it does. If the change is meant, rewrite the file with + `UPDATE_STACK_BINDINGS=1 pnpm --filter core-alchemy test`. +- Every resource of the account is named `iterate-<alchemy.stageName>-…` (`namesOf` in + `src/config.ts`), but the Access application: it is named by the control plane's hostname, + because Cloudflare's code page shows its name to the owner ("Log in to iterate.example.com"). +- The stack's state, with the generated keys, the telemetry API token's value and the secrets of + the SFU app and the TURN key, is in the Worker `iterate-<alchemy.stageName>-state` of the same account. +- No OAuth client. A member connects the mind to its own account through Cloudflare's MCP + server, for which the mind is its own client (core/configs/default/cloudflare.ts). A stack + deployed before 19 Nov 2026 has a client `iterate-<alchemy.stageName>-cloudflare`: its row + leaves the state at the next deploy with no call (`src/retired-cloudflare-oauth-client.ts`), + and the client stays in the account until a member deletes it (Manage Account, OAuth + clients). +- One Realtime SFU app, `iterate-<alchemy.stageName>-realtime-sfu`, and one TURN key, + `iterate-<alchemy.stageName>-turn`, by Alchemy's own resources. The secrets Worker alone holds + their secrets, and serves them as `/secrets/cloudflare-realtime-sfu` and + `/secrets/cloudflare-turn`. They cost nothing until a call uses them. +- An egress gateway, only when the input names one (`cloudflare.egressGatewayWorker`): a Worker + of the account that the stack does not make. The vault and the boundary get it as + `EGRESS_GATEWAY` and send through it what a mind's `itx.fetch` sends out of the stack, each + request with its secret in. The field's doc in `src/config.ts` lists what does not go through + it. The boundary alone gets the gateway's entrypoint `EgressGatewayProviders` as + `EGRESS_GATEWAY_PROVIDERS`. Give each stack a gateway Worker of its own: one gateway serves + one stack. An input that names none binds nothing, and Cloudflare's own fetch sends. + - **Never roll the vault or the boundary back to a Worker version from before the deploy that + named the gateway.** A version holds a Worker's code, bindings and variables together, so + that version has no gateway: its requests leave by Cloudflare's own fetch, the vault's with + the secret in. The way back from a bad gateway is `--egress-gateway none` or a new deploy, + never a version id. + - **Never edit the vault's or the boundary's bindings by hand** (the dashboard, or an upload + that keeps the variables). A version that is written without the gateway's binding sends by + Cloudflare's own fetch, as the version from before the gateway does. + - A gateway that throws, that answers an error, or that was deleted fails the sends. Nothing + then leaves another way. + - A plan or a deploy that names a Worker which does not exist fails, and changes nothing: + Alchemy looks the Worker up by its name. A destroy does not look it up: it passes when the + gateway Worker is gone. Nothing checks that the Worker has the entrypoint + `EgressGatewayProviders`: without it the deploy passes, and a dial of `/api/egress-gateway` + is a 500. +- Our own providers beside the script handle what Alchemy does not do yet (read in 2.0.0-beta.85 + and beta.87, the version that `pnpm-workspace.yaml` pins), along with thin wrappers of Alchemy's + providers (`src/realtime.ts`, `src/telemetry-token.ts`). The header of each file says what, and + when the file can go. + +## The one input + +A JSON file that `ITERATE_MIND_CONFIG` names, parsed by `MindConfig` in `src/config.ts`, where +each field has its doc. No environment variable changes what it means. The boundary Worker keeps +the whole input as its variable `DEPLOY_CONFIG`, which no Worker reads: `iterate deploy` over a +mind starts from it, so a field that no Worker holds, such as `cloudflare.containerImage`, stays. + +```json +{ + "mindId": "<the mind's id: 64 hex characters>", + "controlPlaneHostname": "iterate.example.com", + "ownerEmails": ["ada@example.org"], + "topology": "full-cloudflare", + "alchemy": { "stageName": "example" }, + "cloudflare": { "accountId": "<the account's id>", "zones": ["example.com"] } +} +``` + +A mind takes each of its zones whole: nothing else may use them. + +Every Worker of the stack keeps every log line and, by default, every trace in Cloudflare's own +Workers Logs. `"telemetry": { "traceSampling": 0.1 }` keeps the trace of one request in ten (from 0 +to 1; Cloudflare's head sampling rate). `iterate deploy --trace-sampling 0.1` writes it, and +`--trace-sampling default` goes back to every trace. On iterate.com on 21 Nov 2026, spans were +about 86 % of what the store took in. + +Each mail to an address at a zone reaches the mind: the boundary stores its files under the mind's +`/email/`, and a failure there fails the delivery, so Cloudflare delivers again. Then the mind's +config gets it while the delivery is live, in its `email` method (iterate/sdk +`IterateConfigEntrypoint`). There `save()` records it on `/integrations/email` (`email/received`); +a save that the mind does not take fails the delivery too. A mail is off the log only when the +config's `email` returns without saving it; when the hook throws, runs out of time or is missing, +or the mind cannot be reached for it, the boundary records the mail itself, with an +`email/hook-failed` fact beside it. `forward(to)` sends the original on, as it arrived, with Email Routing's +own forward: its From is the sender's, so a reply goes to the sender. + +- The address must be a verified destination address of the account's Email Routing: add it in + the dashboard (Email Routing, Destination addresses) and confirm the link Cloudflare mails to it. +- Cloudflare forwards only a mail whose sender is proven. `forward` throws a coded error instead of + forwarding: NOT_FORWARDABLE, FORWARDED_BEFORE (a mail goes to one address once, and never to an + address that its `X-Forwarded-To` names, so an address that leads back makes no loop), REFUSED + (Cloudflare's words) or EXPIRED (after the delivery, or after the hook's time). +- Each forward is an `events.iterate.com/email/forwarded` fact. The boundary gives the hook 15 s + of its own time: the clock stops while Cloudflare answers a forward, which took 3 to 10 s on + 19 Nov 2026. A forward whose answer does not come within 20 s more is the same fact with + `answered: false`. A hook that throws, that runs past its own time, or that the mind could not + be reached for, and a config with no `email` (one fact for each config commit), are + `events.iterate.com/email/hook-failed` facts, and the boundary records the mail: the delivery + stands, unless the mind does not take that record. + +**The older way, which goes:** with `"mail": { "forwardTo": "team@example.org" }` the boundary +forwards each mail there itself, before the config's hook and through the same forward, so the +hook cannot forward the same mail there again. Such a stack records every mail on the log before +its forward, whatever its config's hook does: a record after the forward could fail the delivery +after the copy went, and the redelivery would forward a second copy; and a refused forward fails +the delivery before the hook runs, which must not cost the mail its place on the log. The config refuses an address at a zone of the +mind: its mail would come back. Each forward that fails is an +`events.iterate.com/email/forward-failed` fact, with Cloudflare's words; a mail whose sender is not +proven stays in the mind alone, and the delivery stands. **The cost of a forward address that does +not work:** while the address is not verified, is removed from the account, or refuses mail, every +mail to the mind fails for its sender: the mind keeps the mail, the delivery fails, the sender gets +it back, and the config's hook does not run. A mind's config forwards in its own `email` instead. + +`mindId` is the SHA-256 of the mind's signed genesis record (`iterate/mind-identity`). The stack +signs and checks nothing with it: every Worker gets it as config, and the auth Worker accepts the +genesis that hashes to it at `POST https://<controlPlaneHostname>/.well-known/iterate`. Until a +record lists a working key of the stack, the mind signs nothing as itself; all else works. + +## Deploy and destroy + +From `core/alchemy`, with the config in `mind.config.local.json` (git ignores that name): + +```sh +export ITERATE_MIND_CONFIG=mind.config.local.json +pnpm exec alchemy login # or CLOUDFLARE_API_TOKEN, a token of the config's account +pnpm run deploy --stage <alchemy.stageName> +pnpm run destroy --stage <alchemy.stageName> # --yes with nobody at the terminal +``` + +- `deploy` is the mind Worker's build (`core/mind-worker/scripts/build.ts`: the SDK and the + templates that the Worker carries), then `alchemy deploy alchemy.run.ts`. No step comes before + or after. Alchemy's other commands and flags work the same way: + `pnpm exec alchemy plan alchemy.run.ts --stage <alchemy.stageName>`. +- A command for another stage or another account than the config's is refused before it opens + the state. This holds for a deploy and for a destroy. +- What a sign-in or an API token must hold for a deploy is one list with a reason for each entry: + `STACK_SCOPES` in [cloudflare-access.ts](../lib/src/cli/cloudflare-access.ts). A sign-in's + scope is an API token's permission under another spelling (`workers-scripts.write` is "Workers + Scripts Write"). +- Telemetry tables (`events`, `logs`, `spans`, and `metrics` SQL) have three modes, read from the + stack's state (`src/telemetry-token.ts`, `telemetryModeOf`). A deploy takes no telemetry token. + - **`minted`:** the state holds `TelemetryCatalogToken` or `TelemetryAnalyticsToken`: the stack + declares the catalog token's `AccountApiToken`, the catalog, sinks and pipelines, so its sinks + keep their credentials. The analytics token is no longer declared, and the next deploy deletes + it: `metrics` is read on the Analytics SQL binding, with no token. When Cloudflare refuses that + delete, the deploy fails and the token stays in state: its log line names the token and the + dashboard page to delete it on, and the next deploy deletes it again. + - **`given`:** the state holds `TelemetryToken`, an owner-created token: the stack keeps using + it. **Do not delete or roll it:** the sinks keep the token they were made with. + - **`off`:** neither. The stack makes the telemetry bucket, the three streams and the OTLP + destinations, and no catalog, sink, pipeline or token. The mind makes and reads its tables + itself, with a token kept as its secret `/secrets/cloudflare-telemetry` + (core/configs/default/telemetry.ts); the streams keep what they are sent until then. A + destroy removes what the mind made (`src/mind-made-telemetry-tables.ts`). +- The deploy makes a Realtime SFU app and a TURN key (`src/realtime.ts`), which need the + permission to make Realtime (Calls) resources: "Calls Write" (`calls.write`), which the deploy + asks for, or "Realtime" or "Realtime Admin". A credential without it is no failure either: the deploy makes neither, + says so in one line, and the secrets Worker answers `/secrets/cloudflare-realtime-sfu` and + `/secrets/cloudflare-turn` as not set, with that reason. Each later deploy asks again. +- Every zone must be in the account already. Alchemy does not take over a resource that exists, + such as a DNS record of the zone: remove it, or pass `--adopt`. + +Two refusals of a first deploy are known: + +- **The new state store.** A first deploy makes the state store, and a new store can refuse + requests in its first seconds ("State store request failed"), also in the middle of the + apply. It did so for every new store in the proofs of 18 Nov 2026. Nothing is made without + state: run the deploy again. +- **Another stack's records in the store.** The live minds' earlier stack used the same store's + name. A deploy over such a stack's records, not moved by hand, stops in its plan with + "OwnedBySomeoneElse" for the zone's records and routes, and changes nothing. Destroy that + stack, or move it with its runbook; never pass `--adopt` to get past it: the old records + would then delete what the new ones took over. The first deploy over a Worker record of the + earlier stack ends with Alchemy's "Reconciling worker routes (0)": it deletes every route of + the boundary in the zone, also the two that the Route resources adopted in the same run: the + mind answered 522 for 54 s on one move and for 2 s on the other (18 and 19 Nov 2026). After that + deploy the record holds no route, and later deploys delete none. + +## What a destroy leaves + +A destroy erases the mind: its contexts, files, repos, members and secrets. It leaves: + +- The state store: the Worker `iterate-<alchemy.stageName>-state`, and its two secrets + in the account's Secrets Store, which are named after the Worker. A Secrets Store holds a + limited number. +- The TXT record `_dmarc.<zone>`, which Cloudflare's Email Sending wrote. +- R2's record of the telemetry bucket's data catalog, as inactive. No API removes it. +- The OAuth client of a stack deployed before 19 Nov 2026: a member deletes it in the + dashboard. +- The SFU app and the TURN key, when the destroy's credential lacks the permission to delete Realtime (Calls) + resources: the destroy + says so and goes on. +- A sandbox's saved snapshots: tags in the registry repository + `<account>/cloudchamber-snapshots/<id>`, which may also hold other applications' snapshots. + Cloudflare's container registry refuses their delete, and Cloudflare keeps them after the + container application is deleted (measured 20 Nov 2026). The destroy names each repository with + the number of this mind's tags and goes on. Each tag holds a copy of a sandbox's files + (`src/container-snapshots.ts`). +- The account's Zero Trust organization and its one-time PIN login. They belong to the account, + and other things in it may use them (`src/access-team.ts`). +- The zones. + +A deploy of the same stage one second after its destroy can fail with "This Worker does not +exist": run it again.
A core/alchemy/alchemy.run.ts
@@ -0,0 +1,96 @@ +// alchemy.run.ts — `alchemy deploy alchemy.run.ts --stage <alchemy.stageName>`: one mind, from one +// config (src/config.ts), into the account that the config names. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import { PLACEHOLDER_STAGE } from "alchemy/Alchemist/Operations"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { AccessTeamProvider } from "./src/access-team.ts"; +import { ArtifactsNamespaceProvider } from "./src/artifacts-namespace.ts"; +import { ArtifactsRepoSubscriptionProvider } from "./src/artifacts-repo-subscription.ts"; +import { CatalogTablesOfSinksProvider } from "./src/catalog-tables-of-sinks.ts"; +import { loadMindConfig, namesOf } from "./src/config.ts"; +import { MindMadeTelemetryTablesProvider } from "./src/mind-made-telemetry-tables.ts"; +import { ContainerSnapshotProviders } from "./src/container-snapshots.ts"; +import { CallsWithoutWriteProviders } from "./src/realtime.ts"; +import { RetiredCloudflareOAuthClientProvider } from "./src/retired-cloudflare-oauth-client.ts"; +import { mindStack, refuseDeploy } from "./src/stack.ts"; +import { + AccountApiTokenDeleteFallbackProvider, + telemetryModeOf, + TelemetryTokenProvider, +} from "./src/telemetry-token.ts"; + +const config = loadMindConfig(); + +/** Ends a command that is for another stage or another Cloudflare account than the config's. */ +const refuseAnotherStageOrAccount = Effect.gen(function* () { + const stage = yield* Alchemy.Stage; + if (stage !== config.alchemy.stageName) + return yield* refuseDeploy( + `the stage is ${stage}: pass --stage ${config.alchemy.stageName}, the config's alchemy.stageName`, + ); + // an API token of the environment gets the config's account (`secrets` below); a sign-in by + // `alchemy login` keeps the account that the person chose + const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; + if (accountId !== config.cloudflare.accountId) + return yield* refuseDeploy( + `the Cloudflare sign-in is for the account ${accountId}, and the config's account is ${config.cloudflare.accountId}: sign in to the config's account (alchemy login), or set CLOUDFLARE_API_TOKEN to a token of it`, + ); +}); + +export default Alchemy.Stack( + "mind", + { + providers: Layer.mergeAll( + AccessTeamProvider(), + ArtifactsNamespaceProvider(), + ArtifactsRepoSubscriptionProvider(), + CatalogTablesOfSinksProvider(), + // the telemetry tables that a mind made itself: a destroy removes them + // (src/mind-made-telemetry-tables.ts) + MindMadeTelemetryTablesProvider(), + // the stack's former OAuth client: its row leaves the state with no call + // (src/retired-cloudflare-oauth-client.ts) + RetiredCloudflareOAuthClientProvider(), + // the telemetry token that a stack keeps in state from an earlier deploy + TelemetryTokenProvider(), + // legacy AccountApiToken cleanup succeeds even without API-token write scope on fresh sign-ins + AccountApiTokenDeleteFallbackProvider(), + // Alchemy's own providers of the SFU app and TURN key, where a credential without "Calls + // Write" leaves them not made (src/realtime.ts): these win over `Cloudflare.providers()` + CallsWithoutWriteProviders(), + // Alchemy's own provider of the sandbox's container application, where a destroy deletes it + // although the registry refuses its saved snapshots, and names them (src/container-snapshots.ts) + ContainerSnapshotProviders(), + ).pipe(Layer.provideMerge(Cloudflare.providers())), + // The state, with the generated keys, lives in the mind's own account. Alchemy opens it for + // a deploy and for a destroy, and a destroy does not run the stack's program: so both are + // refused here, before the state is opened. A command that addresses no deployment + // (`alchemy login`, `alchemy state`) builds the stack with Alchemy's placeholder stage. + state: Layer.unwrap( + Effect.gen(function* () { + if ((yield* Alchemy.Stage) !== PLACEHOLDER_STAGE) yield* refuseAnotherStageOrAccount; + return Cloudflare.state({ + workerName: namesOf(config).state, + accountId: config.cloudflare.accountId, + }); + }).pipe(Effect.orDie), + ).pipe(Layer.provide(Cloudflare.CloudflareApiLive()), Layer.orDie), + // Alchemy reads the account of an API token from CLOUDFLARE_ACCOUNT_ID: the config's answers, + // after the shell, so that it wins over a variable of the shell. + secrets: [ + Alchemy.Secrets.ProcessEnv(), + ConfigProvider.layerAdd( + ConfigProvider.fromUnknown({ CLOUDFLARE_ACCOUNT_ID: config.cloudflare.accountId }), + { asPrimary: true }, + ), + ], + }, + // the check again: a deploy runs the program, and none may take the placeholder stage + refuseAnotherStageOrAccount.pipe( + Effect.andThen(telemetryModeOf(config.alchemy.stageName).pipe(Effect.orDie)), + Effect.flatMap((telemetryMode) => mindStack(config, { telemetryMode })), + ), +);
A core/alchemy/package.json
@@ -0,0 +1,24 @@ +{ + "name": "core-alchemy", + "type": "module", + "description": "The Alchemy script that deploys one mind as a stack of Workers", + "scripts": { + "typecheck": "tsc --noEmit", + "test": "node --test 'src/**/*.test.ts'", + "deploy": "pnpm --filter core-mind-worker build && alchemy deploy alchemy.run.ts", + "destroy": "alchemy destroy alchemy.run.ts" + }, + "dependencies": { + "@alchemy.run/cloudflare": "catalog:", + "@distilled.cloud/cloudflare": "catalog:", + "@effect/platform-node": "catalog:", + "alchemy": "catalog:", + "effect": "catalog:", + "iterate": "workspace:*", + "zod": "catalog:" + }, + "devDependencies": { + "@types/node": "catalog:", + "typescript": "catalog:" + } +}
A core/alchemy/src/access-team.test.ts
@@ -0,0 +1,71 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import * as Effect from "effect/Effect"; +import { accessTeamFoundOrMade } from "./access-team.ts"; + +void test("an account with a team and a PIN login: both are used, and nothing is made", async () => { + const { account, made } = accountWith({ team: "ada.cloudflareaccess.com", pinLogin: "pin-1" }); + assert.deepEqual(await Effect.runPromise(accessTeamFoundOrMade(account)), { + teamDomain: "ada.cloudflareaccess.com", + pinLoginId: "pin-1", + }); + assert.deepEqual(made, []); +}); + +void test("an account with a team and no PIN login: the login alone is made", async () => { + const { account, made } = accountWith({ team: "ada.cloudflareaccess.com", pinLogin: null }); + assert.deepEqual(await Effect.runPromise(accessTeamFoundOrMade(account)), { + teamDomain: "ada.cloudflareaccess.com", + pinLoginId: "made-pin", + }); + assert.deepEqual(made, ["pin login"]); +}); + +void test("an account with no team: the organization is made, read again for its domain, and the login is made", async () => { + const { account, made } = accountWith({ team: null, pinLogin: null }); + assert.deepEqual(await Effect.runPromise(accessTeamFoundOrMade(account)), { + teamDomain: "made-team.cloudflareaccess.com", + pinLoginId: "made-pin", + }); + assert.deepEqual(made, ["organization", "pin login"]); +}); + +void test("a new organization that brings its own PIN login keeps that login", async () => { + const { account, made } = accountWith({ team: null, pinLogin: "cloudflares-own" }); + assert.equal( + (await Effect.runPromise(accessTeamFoundOrMade(account))).pinLoginId, + "cloudflares-own", + ); + assert.deepEqual(made, ["organization"]); +}); + +void test("an account where Cloudflare makes no organization fails the deploy, and makes no login", async () => { + const { account, made } = accountWith({ team: null, pinLogin: null }); + const exit = await Effect.runPromiseExit( + accessTeamFoundOrMade({ ...account, makeOrganization: Effect.void }), + ); + assert.match(JSON.stringify(exit), /made no Zero Trust organization/); + assert.deepEqual(made, []); +}); + +/** An account as the provider's four calls see it, and what the provider made in it. A fresh + * account answers an organization with no domain, as Cloudflare does. */ +function accountWith(has: { team: string | null; pinLogin: string | null }) { + const made: string[] = []; + let team = has.team; + return { + made, + account: { + organization: Effect.sync(() => ({ authDomain: team })), + makeOrganization: Effect.sync(() => { + made.push("organization"); + team = "made-team.cloudflareaccess.com"; + }), + pinLogin: Effect.sync(() => (has.pinLogin ? { id: has.pinLogin } : undefined)), + makePinLogin: Effect.sync(() => { + made.push("pin login"); + return { id: "made-pin" }; + }), + }, + }; +}
A core/alchemy/src/access-team.ts
@@ -0,0 +1,91 @@ +// access-team.ts — THE ACCOUNT'S ZERO TRUST TEAM AND ITS ONE-TIME PIN LOGIN, AS THE STACK FINDS +// THEM. Cloudflare Access proves an owner's address (./stack.ts), and Access needs two things +// that belong to the whole account, not to a mind: the Zero Trust organization (the "team", whose +// domain signs the tokens) and the login that mails a six-digit code (Cloudflare's "one-time +// PIN"). An account has one of each at most, and other things in the account may use them. So +// this resource reads them, makes one only where the account has none, changes nothing that +// exists, and deletes nothing. +// +// Alchemy's own resources (2.0.0-beta.85 and beta.87) do not fit an account that is shared: +// `Cloudflare.Access.Organization` writes the whole organization on every deploy, with its +// default for every setting the stack does not declare, and `Cloudflare.Access.IdentityProvider` +// takes an existing PIN login as its own (it finds it by its type) and deletes it at a destroy. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; + +export type AccessTeam = Resource< + "Iterate.AccessTeam", + {}, + { + /** `<team name>.cloudflareaccess.com`: the issuer of the team's tokens, where its keys are. */ + teamDomain: string; + /** The id of the team's one-time PIN login: an identity provider of the type `onetimepin`. */ + pinLoginId: string; + }, + never, + Cloudflare.Providers +>; +export const AccessTeam = Resource<AccessTeam>("Iterate.AccessTeam"); + +export const AccessTeamProvider = () => + Provider.succeed(AccessTeam, { + stables: ["teamDomain", "pinLoginId"], + reconcile: Effect.fn(function* () { + const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; + return yield* accessTeamFoundOrMade({ + // an account that never used Zero Trust answers 404, or an organization with no domain + organization: zeroTrust + .listOrganizationsForAccount({ accountId }) + .pipe(Effect.catchTag("OrganizationNotFound", () => Effect.undefined)), + // With no name given, Cloudflare picks the team's name (`adjective-noun-hex4`): a name is + // unique among all accounts and stays taken for good, so the stack proposes none. Another + // deploy in the account may make the organization between the two calls: that one is used. + makeOrganization: zeroTrust + .createOrganizationForAccount({ accountId }) + .pipe(Effect.catchTag("OrganizationAlreadyExists", () => Effect.void)), + pinLogin: zeroTrust.listIdentityProvidersForAccount.items({ accountId }).pipe( + Stream.filter(({ type }) => type === "onetimepin"), + Stream.runHead, + Effect.map(Option.getOrUndefined), + ), + makePinLogin: zeroTrust.createIdentityProviderForAccount({ + accountId, + name: "One-time PIN", + type: "onetimepin", + config: {}, + }), + }); + }), + // the team and its login are the account's: other applications in it may sign people in + delete: () => Effect.void, + }); + +/** THE PROVIDER'S DECISIONS, over the four calls of Cloudflare's API that it makes: what exists + * is used as it is, and only what the account lacks is made. The organization is read again + * after it is made: the answer to the create need not name its domain. */ +export const accessTeamFoundOrMade = <E, R>(account: { + organization: Effect.Effect<{ authDomain?: string | null } | undefined, E, R>; + makeOrganization: Effect.Effect<unknown, E, R>; + pinLogin: Effect.Effect<{ id?: string | null } | undefined, E, R>; + makePinLogin: Effect.Effect<{ id?: string | null }, E, R>; +}) => + Effect.gen(function* () { + const teamDomain = + (yield* account.organization)?.authDomain || + (yield* account.makeOrganization.pipe(Effect.andThen(account.organization)))?.authDomain; + if (!teamDomain) + return yield* Effect.die( + "Cloudflare made no Zero Trust organization for the account: set one up at https://one.dash.cloudflare.com, then deploy again.", + ); + const pinLoginId = ((yield* account.pinLogin) || (yield* account.makePinLogin)).id; + if (!pinLoginId) + return yield* Effect.die( + "Cloudflare answered a one-time PIN login with no id: deploy again, or add the login at https://one.dash.cloudflare.com (Integrations, Identity providers).", + ); + return { teamDomain, pinLoginId }; + });
A core/alchemy/src/analytics-sql-binding.ts
@@ -0,0 +1,14 @@ +// analytics-sql-binding.ts — THE ANALYTICS SQL BINDING OF A WORKER: Cloudflare's Analytics SQL over +// the Worker's whole account, with no API token (https://developers.cloudflare.com/analytics/sql-api/workers-binding/). +// Alchemy 2.0.0-beta.87 has no form of it, so it goes into the Worker's metadata as Wrangler +// 4.166.0 writes the config key `analytics`: `{ type: "analytics", name }`, and nothing else. The +// Worker's own `bind` adds it beside what its `env` declares. Remove this file once Alchemy +// declares the binding itself. +import type * as Cloudflare from "@alchemy.run/cloudflare"; + +export const bindAnalyticsSql = (worker: Cloudflare.Worker, name: string) => + worker.bind(name, { + // The SDK's binding union is generated from Cloudflare's API schema, which does not list this + // type yet; the upload schema passes a binding's fields through as they are. + bindings: [{ type: "analytics", name } as unknown as Cloudflare.WorkerBinding], + });
A core/alchemy/src/artifacts-namespace.ts
@@ -0,0 +1,96 @@ +// artifacts-namespace.ts — THE MIND'S ARTIFACTS NAMESPACE AS A RESOURCE. Alchemy's own +// `Cloudflare.Artifacts.Namespace` is a binding's marker and makes nothing: Cloudflare makes a +// namespace at the first repo created under its name. That holds through the REST API, but a repo +// created through a Worker's binding makes no namespace (18 Nov 2026). So the stack makes it, and +// a destroy deletes it, with the repos in it. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import { formatHeaders } from "@distilled.cloud/cloudflare/Credentials"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import { z } from "zod"; + +export type ArtifactsNamespace = Resource< + "Iterate.ArtifactsNamespace", + { namespace: string }, + { namespace: string }, + never, + Cloudflare.Providers +>; +export const ArtifactsNamespace = Resource<ArtifactsNamespace>("Iterate.ArtifactsNamespace"); + +const Repos = z.object({ result: z.array(z.object({ name: z.string() })) }); + +export const ArtifactsNamespaceProvider = () => + Provider.succeed(ArtifactsNamespace, { + stables: ["namespace"], + reconcile: Effect.fn(function* ({ news: { namespace } }) { + // looked up by its own path: its list of repos answers 200 for any name + const found = yield* namespacesApi("GET", `/${namespace}`); + if (found.status === 200) return { namespace }; + // only a 404 says that it is not there: no other answer leads to a create + if (found.status !== 404) + return yield* Effect.die( + `Cloudflare did not say whether the Artifacts namespace ${namespace} exists (${found.status}): ${found.text.slice(0, 300)}`, + ); + const made = yield* namespacesApi("POST", "", { namespace }); + // 10201: it exists, made between the two calls + if (made.status >= 300 && !/"code":\s*10201\b/.test(made.text)) + return yield* Effect.die( + `Cloudflare did not make the Artifacts namespace ${namespace} (${made.status}): ${made.text.slice(0, 300)}`, + ); + return { namespace }; + }), + // A destroy erases the mind: its repos go first, because Cloudflare refuses to delete a + // namespace that holds one (409 "Namespace is not empty"). + delete: Effect.fn(function* ({ output: { namespace } }) { + // a page of repos at a time, until a page is empty: 200 pages of 50 at most + for (let page = 1; page <= 200; page += 1) { + const listed = yield* namespacesApi("GET", `/${namespace}/repos`); + if (listed.status === 404) return; + const repos = Repos.safeParse(listed.status === 200 && JSON.parse(listed.text)); + if (!repos.success) + return yield* Effect.die( + `Cloudflare did not list the repos of the Artifacts namespace ${namespace} (${listed.status}): ${listed.text.slice(0, 300)}`, + ); + if (repos.data.result.length === 0) break; + for (const { name } of repos.data.result) { + const gone = yield* namespacesApi( + "DELETE", + `/${namespace}/repos/${encodeURIComponent(name)}`, + ); + if (gone.status >= 300 && gone.status !== 404) + return yield* Effect.die( + `Cloudflare did not delete the repo ${name} of the Artifacts namespace ${namespace} (${gone.status}): ${gone.text.slice(0, 300)}`, + ); + } + // Cloudflare takes a repo's delete (202) before the repo is gone + yield* Effect.sleep("1 second"); + } + const gone = yield* namespacesApi("DELETE", `/${namespace}`); + // a refused delete fails, so the stack's state keeps the namespace; a 404 is gone already + if (gone.status >= 300 && gone.status !== 404) + return yield* Effect.die( + `Cloudflare did not delete the Artifacts namespace ${namespace} (${gone.status}): ${gone.text.slice(0, 300)}`, + ); + }), + }); + +/** One call of Cloudflare's namespaces API, for which the SDK under Alchemy has no call + * (1.0.0-rc.18): in the deploy's account, with Alchemy's own credentials and HTTP client. + * Answers the status and the body's text. */ +const namespacesApi = (method: "GET" | "POST" | "DELETE", path: string, json?: unknown) => + Effect.gen(function* () { + const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; + const credentials = yield* yield* Cloudflare.Credentials; + const request = HttpClientRequest.make(method)( + `${credentials.apiBaseUrl}/accounts/${accountId}/artifacts/namespaces${path}`, + { headers: formatHeaders(credentials) }, + ); + const answer = yield* (yield* HttpClient.HttpClient).execute( + json === undefined ? request : HttpClientRequest.bodyJsonUnsafe(request, json), + ); + return { status: answer.status, text: yield* answer.text }; + });
A core/alchemy/src/artifacts-repo-subscription.ts
@@ -0,0 +1,114 @@ +// artifacts-repo-subscription.ts — THE EVENTS OF ONE ARTIFACTS REPO, ON A QUEUE, AS A RESOURCE. +// Cloudflare's event subscriptions take an Artifacts repo as a source +// (https://developers.cloudflare.com/queues/event-subscriptions/), and so do the calls of the +// Cloudflare SDK under Alchemy, which this provider makes. Alchemy's own +// `Cloudflare.Queues.Subscription` does not list that source and reads none back +// (2.0.0-beta.85 and beta.87). When it does, this file goes. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as queues from "@distilled.cloud/cloudflare/queues"; +import { isResolved } from "alchemy/Diff"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; +import * as Option from "effect/Option"; +import * as Stream from "effect/Stream"; + +export type ArtifactsRepoSubscription = Resource< + "Iterate.ArtifactsRepoSubscription", + { + name: string; + /** The repo `repo` of the Artifacts namespace `namespace`: fixed once the subscription is made. */ + namespace: string; + repo: string; + /** The repo's event types to deliver, as Cloudflare names them: `pushed`, `token.created`. */ + events: string[]; + queueId: string; + }, + { subscriptionId: string }, + never, + Cloudflare.Providers +>; +export const ArtifactsRepoSubscription = Resource<ArtifactsRepoSubscription>( + "Iterate.ArtifactsRepoSubscription", +); + +export const ArtifactsRepoSubscriptionProvider = () => + Provider.succeed(ArtifactsRepoSubscription, { + stables: ["subscriptionId"], + // a subscription's source is fixed once it is made + diff: ({ olds, news }) => + Effect.succeed( + isResolved(news) && (olds.namespace !== news.namespace || olds.repo !== news.repo) + ? ({ action: "replace" } as const) + : undefined, + ), + reconcile: Effect.fn(function* ({ news, output }) { + const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; + const wanted = { + name: news.name, + enabled: true, + events: news.events, + destination: { type: "queues.queue", queueId: news.queueId }, + }; + // The id in the state is a hint: a subscription that somebody deleted (404) is made again. + // Any other failure of the read fails the deploy. + const kept = + output && + (yield* queues + .getSubscription({ accountId, subscriptionId: output.subscriptionId }) + .pipe(Effect.catchTag("SubscriptionNotFound", () => Effect.undefined))); + const observed = + kept || + (yield* queues + .createSubscription({ + ...wanted, + accountId, + source: { type: "artifacts.repo", namespace: news.namespace, repoName: news.repo }, + }) + .pipe( + // Cloudflare takes one subscription for a repo, to any queue, and answers 405 to a + // second. A create that is cut off before its id is stored leaves this stack's own: the + // repo's subscription to this stack's queue. One to another queue is not ours. + Effect.catchTag("SubscriptionAlreadyExists", (exists) => + Effect.gen(function* () { + const ofTheRepo = yield* queues.listSubscriptions + .items({ accountId, order: "created_at", direction: "desc", perPage: 100 }) + .pipe( + // the newest 5,000: an account can hold tens of thousands of old ones + Stream.take(5_000), + Stream.filter( + ({ source }) => + source.type === "artifacts.repo" && + source.namespace === news.namespace && + source.repoName === news.repo, + ), + Stream.runHead, + Effect.map(Option.getOrUndefined), + ); + if (ofTheRepo?.destination.queueId === news.queueId) return ofTheRepo; + return yield* Effect.die( + `The repo ${news.repo} of ${news.namespace} already has an event subscription` + + (ofTheRepo + ? ` (${ofTheRepo.id}, to the queue ${ofTheRepo.destination.queueId})` + : "") + + `, which this stack did not make. Delete it (DELETE /accounts/${accountId}/event_subscriptions/subscriptions/<id>), then deploy again. Cloudflare said: ${exists.message}`, + ); + }), + ), + )); + const differs = + observed.name !== wanted.name || + !observed.enabled || + observed.destination.queueId !== news.queueId || + [...observed.events].sort().join() !== [...news.events].sort().join(); + if (differs) + yield* queues.patchSubscription({ ...wanted, accountId, subscriptionId: observed.id }); + return { subscriptionId: observed.id }; + }), + delete: Effect.fn(function* ({ output }) { + const { accountId } = yield* yield* Cloudflare.CloudflareEnvironment; + yield* queues + .deleteSubscription({ accountId, subscriptionId: output.subscriptionId }) + .pipe(Effect.catchTag("SubscriptionNotFound", () => Effect.void)); + }), + });
A core/alchemy/src/catalog-tables-of-sinks.ts
@@ -0,0 +1,77 @@ +// catalog-tables-of-sinks.ts — THE TABLES THAT THE STACK'S SINKS WRITE, AS A RESOURCE. A catalog +// sink makes its own Iceberg table, and Cloudflare makes no sink for a table that exists +// ("writing to existing Catalog tables is not yet supported"). R2 keeps a catalog's tables when +// the catalog is turned off and when its bucket is deleted, and gives them back to a new bucket +// of the same name. So without this resource a destroyed stage cannot deploy again. +// +// This resource makes nothing. The sinks take their tables' namespace from it, so a destroy +// deletes the pipelines and the sinks first, then drops the tables here, and then turns the +// catalog off. Alchemy's own `Cloudflare.Basin.Table` cannot stand in: it makes the table, which +// a sink then refuses (2.0.0-beta.85 and beta.87). +import type * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientRequest from "effect/http/HttpClientRequest"; +import * as Redacted from "effect/Redacted"; +import { z } from "zod"; + +export type CatalogTablesOfSinks = Resource< + "Iterate.CatalogTablesOfSinks", + { + /** The data catalog's Iceberg address and its id (`Cloudflare.R2.DataCatalog`'s outputs). */ + catalogUri: string; + catalogId: string; + /** An API token that may write the catalog. */ + token: Redacted.Redacted<string>; + /** The Iceberg namespace of the tables, and each table's name. */ + namespace: string; + tables: string[]; + }, + { namespace: string }, + never, + Cloudflare.Providers +>; +export const CatalogTablesOfSinks = Resource<CatalogTablesOfSinks>("Iterate.CatalogTablesOfSinks"); + +/** The Iceberg REST catalog's list of a namespace's tables. */ +const TablesOfNamespace = z.object({ identifiers: z.array(z.object({ name: z.string() })) }); + +export const CatalogTablesOfSinksProvider = () => + Provider.succeed(CatalogTablesOfSinks, { + reconcile: ({ news }) => Effect.succeed({ namespace: news.namespace }), + delete: Effect.fn(function* ({ olds }) { + const http = yield* HttpClient.HttpClient; + const namespace = `${olds.catalogUri}/v1/${olds.catalogId}/namespaces/${olds.namespace}`; + const catalog = (method: "GET" | "DELETE", url: string) => + http.execute( + HttpClientRequest.make(method)(url, { + headers: { authorization: `Bearer ${Redacted.value(olds.token)}` }, + }), + ); + // Listed first: the catalog answers a drop of a table that is not there with a 403, which + // also means "not allowed". A namespace that is not there (404) holds no table. + const listed = yield* catalog("GET", `${namespace}/tables`); + if (listed.status === 404) return; + const tables = TablesOfNamespace.safeParse(listed.status === 200 && (yield* listed.json)); + if (!tables.success) + return yield* Effect.die( + `Cloudflare's data catalog did not list the tables of ${namespace} (${listed.status}): ${(yield* listed.text).slice(0, 300)}`, + ); + const there = tables.data.identifiers.map(({ name }) => name); + // each table of the sinks, then the namespace when it holds no other table + for (const url of [ + ...olds.tables + .filter((table) => there.includes(table)) + .map((table) => `${namespace}/tables/${table}`), + ...(there.every((table) => olds.tables.includes(table)) ? [namespace] : []), + ]) { + const gone = yield* catalog("DELETE", url); + if (gone.status >= 300 && gone.status !== 404) + return yield* Effect.die( + `Cloudflare's data catalog did not drop ${url} (${gone.status}): ${(yield* gone.text).slice(0, 300)}`, + ); + } + }), + });
A core/alchemy/src/config.test.ts
@@ -0,0 +1,137 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { MindConfig, namesOf } from "./config.ts"; + +void test("a config with every field parses, and a field it does not name is refused", () => { + assert.equal(MindConfig.safeParse(config()).success, true); + assert.equal(MindConfig.safeParse({ ...config(), domain: "example.com" }).success, false); +}); + +void test("the mind id is 64 lowercase hex characters, and never left out", () => { + const { mindId: _, ...withoutMindId } = config(); + assert.equal(MindConfig.safeParse(withoutMindId).success, false); + for (const mindId of ["a".repeat(63), "a".repeat(65), "A".repeat(64), "g".repeat(64)]) { + const refused = MindConfig.safeParse({ ...config(), mindId }); + assert.deepEqual(refused.error?.issues[0]?.path, ["mindId"]); + } +}); + +void test("the control plane's hostname is a zone of the mind, or one label under one", () => { + for (const controlPlaneHostname of [ + "example.com", + "iterate.example.com", + "control.sub.example.net", + ]) + assert.equal(MindConfig.safeParse({ ...config(), controlPlaneHostname }).success, true); +}); + +void test("a hostname two labels under a zone, or one that only ends like a zone, is refused", () => { + for (const controlPlaneHostname of [ + "a.b.example.com", + "evil-example.com", + "iterate.example.org", + ]) { + const refused = MindConfig.safeParse({ ...config(), controlPlaneHostname }); + assert.deepEqual(refused.error?.issues[0]?.path, ["controlPlaneHostname"]); + assert.match(refused.error?.issues[0]?.message || "", /certificate/); + } +}); + +void test("an owner's address is at no zone of the mind, and at no name under one", () => { + for (const email of ["ada@example.com", "ada@mail.sub.example.net"]) { + const refused = MindConfig.safeParse({ ...config(), ownerEmails: [email] }); + assert.deepEqual(refused.error?.issues[0]?.path, ["ownerEmails"]); + } +}); + +void test("a topology is one of the two, and never left out", () => { + const { topology: _, ...withoutTopology } = config(); + assert.equal(MindConfig.safeParse(withoutTopology).success, false); + assert.equal(MindConfig.safeParse({ ...config(), topology: "home-lab" }).success, false); +}); + +void test("every resource's name starts with iterate-<stage>, with _ where Cloudflare takes no -", () => { + const names = namesOf(MindConfig.parse(config())); + assert.equal(names.state, "iterate-example-com-state"); + assert.equal(names.cloudflareEvents, "iterate-example-com-events"); + assert.equal(names.telemetryMetrics, "iterate_example_com_metrics"); + assert.equal(names.telemetryTables, "iterate_example_com_telemetry"); + for (const name of Object.values(names)) assert.match(name, /^iterate[-_]example[-_]com[-_]/); +}); + +void test("no config field names another state store: the store is iterate-<stage>-state", () => { + const refused = MindConfig.safeParse({ + ...config(), + alchemy: { stageName: "example-com", stateStoreName: "iterate-example-state" }, + }); + assert.deepEqual(refused.error?.issues[0]?.path, ["alchemy"]); +}); + +void test("a mind's mail is forwarded to one address, or to none", () => { + assert.equal(MindConfig.parse(config()).mail, undefined); + assert.deepEqual( + MindConfig.parse({ ...config(), mail: { forwardTo: "team@group.example" } }).mail, + { forwardTo: "team@group.example" }, + ); +}); + +void test("the trace sampling is a share from 0 to 1, or absent; a telemetry setting with another key is refused", () => { + assert.equal(MindConfig.parse(config()).telemetry, undefined); + for (const traceSampling of [0, 0.1, 1]) + assert.deepEqual(MindConfig.parse({ ...config(), telemetry: { traceSampling } }).telemetry, { + traceSampling, + }); + for (const telemetry of [ + { traceSampling: 1.5 }, + { traceSampling: -0.1 }, + { traceSampling: "1" }, + { traceSampling: 1, lake: true }, + {}, + ]) + assert.equal( + MindConfig.safeParse({ ...config(), telemetry }).success, + false, + JSON.stringify(telemetry), + ); +}); + +void test("a forward address that is no address, and a mail setting with another key, are refused", () => { + for (const mail of [ + { forwardTo: "the team" }, + { forwardTo: "team@group.example", cc: "x" }, + {}, + true, + ]) + assert.equal(MindConfig.safeParse({ ...config(), mail }).success, false, JSON.stringify(mail)); +}); + +void test("a forward address at a zone of the mind, or under one, is refused: such a mail comes back to the mind", () => { + for (const forwardTo of ["team@example.com", "team@mail.example.com", "team@SUB.example.net"]) { + const refused = MindConfig.safeParse({ ...config(), mail: { forwardTo } }); + assert.deepEqual(refused.error?.issues[0]?.path, ["mail", "forwardTo"], forwardTo); + } + // another domain that only ends in the same letters is no part of it + assert.equal( + MindConfig.safeParse({ ...config(), mail: { forwardTo: "team@notexample.com" } }).success, + true, + ); +}); + +void test("an egress gateway's name that is empty is refused", () => { + const cloudflare = { ...config().cloudflare, egressGatewayWorker: "" }; + assert.deepEqual(MindConfig.safeParse({ ...config(), cloudflare }).error?.issues[0]?.path, [ + "cloudflare", + "egressGatewayWorker", + ]); +}); + +function config() { + return { + mindId: "a".repeat(64), + controlPlaneHostname: "iterate.example.com", + ownerEmails: ["ada@example.org"], + topology: "full-cloudflare", + alchemy: { stageName: "example-com" }, + cloudflare: { accountId: "a".repeat(32), zones: ["example.com", "sub.example.net"] }, + }; +}
A core/alchemy/src/config.ts
@@ -0,0 +1,137 @@ +// config.ts — THE ONE INPUT of the stack (./stack.ts): what `iterate deploy` learned from +// the person and from Cloudflare. A JSON file, named in ITERATE_MIND_CONFIG. No field is optional +// for a reason of history, and no variable of the environment changes what it means. +import { readFileSync } from "node:fs"; +import { z } from "zod"; + +const hostname = z + .string() + .toLowerCase() + .regex(/^(?=.{4,253}$)([a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?\.)+[a-z]{2,63}$/, "a hostname"); + +export const MindConfig = z + .strictObject({ + /** The mind's id: the SHA-256 of its signed genesis, 64 lowercase hex characters + * (iterate/mind-identity). `iterate deploy` signs the genesis before the deploy and posts it + * after: the stack does no identity cryptography. */ + mindId: z.string().regex(/^[0-9a-f]{64}$/, "a mind id: 64 lowercase hex characters"), + /** Where the mind's control plane answers: its sign-in, its API and its MCP server. A zone of + * the mind, or one label under one. Every other hostname of the zones is the mind's own. */ + controlPlaneHostname: hostname, + /** The mind's owners, each by email address: a member from the first deploy, who signs in + * with a code mailed to that address and then adds a passkey. An owner may remove another + * member's passkeys. Members added later are in the mind, not here. */ + ownerEmails: z.array(z.email().toLowerCase()).min(1), + /** 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"]), + alchemy: z.strictObject({ + /** The Alchemy stage, and the middle of every resource's name: `iterate-<stageName>-auth`. + * `iterate deploy` infers it from the first zone. At most 32 characters: the state store's + * name, `iterate-<stageName>-state`, may have 54. */ + stageName: z.string().regex(/^[a-z][a-z0-9-]{0,31}$/, "lower case, digits and -, at most 32"), + }), + cloudflare: z.strictObject({ + accountId: z.string().regex(/^[0-9a-f]{32}$/, "a Cloudflare account id: 32 hex characters"), + /** The zones the mind takes, each whole: its sites, its mail. `sub.example.com` when that + * is a zone of its own. Nothing else may use them. */ + zones: z.array(hostname).min(1), + /** An image in the account's registry that sandboxes start. Absent: Cloudflare's own small + * image. Only iterate's own mind sets it. */ + containerImage: z.string().min(1).optional(), + /** THE STACK'S EGRESS GATEWAY: a Worker of this account, by name. The vault and the + * boundary get it as `EGRESS_GATEWAY` and send through its fetch, with no other way out + * (iterate/lib `fetchLeavingTheStack`), each request with its secret in. So whoever deploys + * names it, and nothing in a mind can. One gateway Worker serves one stack. + * - THROUGH IT: what a mind sends by `itx.fetch` to a host outside its zones (a script, + * an agent, loaded code, a sandbox), with a secret or without; a secret's token + * refresh and its exchange code; a request signed for another mind. + * - NOT THROUGH IT: the vault's calls to an iterate Cloud; the auth, mind and telemetry + * Workers' own fetches (other minds' identity, module downloads, Git, Cloudflare's + * API); the managed bindings (AI, Browser, Images, mail). + * Absent: no binding, and the platform's fetch sends. */ + egressGatewayWorker: z.string().min(1).optional(), + }), + /** A FORWARD BY THE STACK, beside the config's own `email` method (iterate/sdk), where a + * mind's config forwards. Absent: the config's `email` alone decides where a mail goes. `forwardTo`: + * each mail is also forwarded there as it arrived (a team's mailbox or group), before the + * config's `email` runs. The address must be a verified destination address of the + * account's Email Routing, which a person confirms once by the link Cloudflare mails to it. */ + mail: z.strictObject({ forwardTo: z.email() }).optional(), + /** THE MIND'S TELEMETRY in Cloudflare's own store. `traceSampling` is the share of requests + * whose trace Cloudflare keeps, for every Worker of the stack, from 0 (no trace) to 1 (each + * one): the head sampling rate of Workers traces + * (https://developers.cloudflare.com/workers/observability/traces/). Log lines are always + * kept whole. Absent: 1, every trace. `iterate deploy --trace-sampling` sets it. */ + telemetry: z.strictObject({ traceSampling: z.number().min(0).max(1) }).optional(), + }) + // One label, because Cloudflare's certificate for a zone covers the zone and `*.<zone>` alone. + .refine( + ({ controlPlaneHostname, cloudflare }) => + cloudflare.zones.some( + (zone) => + controlPlaneHostname === zone || + controlPlaneHostname.split(".").slice(1).join(".") === zone, + ), + { + path: ["controlPlaneHostname"], + error: + "a zone of the mind, or one label under one: Cloudflare's certificate for a zone covers the zone and *.<zone> alone, so a deeper name would get a route and no certificate", + }, + ) + .refine( + ({ ownerEmails, cloudflare }) => + ownerEmails.every((email) => + cloudflare.zones.every((zone) => !`.${email.split("@")[1]}`.endsWith(`.${zone}`)), + ), + { + path: ["ownerEmails"], + error: "no address at a zone of the mind: the mind takes that mail", + }, + ) + .refine( + ({ mail, cloudflare }) => + !mail || + cloudflare.zones.every( + (zone) => !`.${mail.forwardTo.split("@")[1]}`.toLowerCase().endsWith(`.${zone}`), + ), + { + path: ["mail", "forwardTo"], + error: + "not an address at a zone of the mind: its mail comes to the mind, so the forward would come back", + }, + ); +export type MindConfig = z.infer<typeof MindConfig>; + +/** The config of this deploy, from the JSON file that ITERATE_MIND_CONFIG names. */ +export function loadMindConfig(): MindConfig { + const file = process.env.ITERATE_MIND_CONFIG; + if (!file) + throw new Error("ITERATE_MIND_CONFIG names no file: the stack has one input, its config"); + return MindConfig.parse(JSON.parse(readFileSync(file, "utf8"))); +} + +/** Every name the stack gives a resource of the account. */ +export const namesOf = ({ alchemy }: { alchemy: { stageName: string } }) => { + const prefix = `iterate-${alchemy.stageName}`; + return { + state: `${prefix}-state`, + auth: `${prefix}-auth`, + authDb: `${prefix}-auth-db`, + authKv: `${prefix}-auth-kv`, + secrets: `${prefix}-secrets`, + realtimeSfu: `${prefix}-realtime-sfu`, + turnKey: `${prefix}-turn`, + mind: `${prefix}-mind`, + mindKv: `${prefix}-mind-kv`, + files: `${prefix}-files`, + repos: `${prefix}-repos`, + boundary: `${prefix}-boundary`, + cloudflareEvents: `${prefix}-events`, + telemetry: `${prefix}-telemetry`, + telemetryBucket: `${prefix}-telemetry`, + // Analytics Engine and Pipelines take no `-` in a name + telemetryMetrics: `${prefix.replaceAll("-", "_")}_metrics`, + telemetryTables: `${prefix.replaceAll("-", "_")}_telemetry`, + }; +};
A core/alchemy/src/container-snapshots.test.ts
@@ -0,0 +1,142 @@ +// A destroy of a container application whose saved snapshots the registry refuses to delete +// (container-snapshots.ts), against a pretend Alchemy provider and pretend Cloudflare calls. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type * as Cloudflare from "@alchemy.run/cloudflare"; +import { providerForMode, type ProviderService } from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import { + isSnapshotRefusal, + type Leftover, + leftoverLine, + snapshotRefusalProvider, +} from "./container-snapshots.ts"; + +/** The registry's 403, as Alchemy's snapshot clean-up gives it. */ +const refusal = { + _tag: "ContainerSnapshotCleanupError", + message: + "Container registry DELETE /v2/account-1/cloudchamber-snapshots/8b2c/manifests/rootfs-set-1abf returned HTTP 403", +}; +const application = { accountId: "account-1", applicationId: "app-1" }; +const leftovers: Leftover[] = [ + { repository: "account-1/cloudchamber-snapshots/8b2c", tags: 40 }, + { repository: "account-1/cloudchamber-snapshots/6cef", tags: 3 }, +]; + +void test("only the registry's 403 on a snapshot's delete counts as the refusal", () => { + assert.equal(isSnapshotRefusal(refusal), true); + assert.equal( + isSnapshotRefusal({ ...refusal, message: refusal.message.replace("403", "500") }), + false, + ); + // the registry could not be reached + assert.equal( + isSnapshotRefusal({ + _tag: "ContainerSnapshotCleanupError", + message: "Container registry DELETE /v2/x/manifests/y failed", + }), + false, + ); + assert.equal(isSnapshotRefusal({ _tag: "ContainerApplicationNotFound" }), false); + assert.equal(isSnapshotRefusal(undefined), false); +}); + +void test("a refused snapshot: the application is deleted, and each repository is named with its tag count", async () => { + const run = destroy(refusal, { deleteFails: null }); + await Effect.runPromise(run.provider.delete(deleteInput())); + assert.deepEqual(run.deleted, [application]); + assert.deepEqual(run.said, leftovers.map(leftoverLine)); + assert.match( + run.said[0]!, + /^account-1\/cloudchamber-snapshots\/8b2c keeps 40 tags of this mind.s sandbox snapshots: /, + ); +}); + +void test("an application that is already gone: the destroy goes on", async () => { + const run = destroy(refusal, { deleteFails: { _tag: "ContainerApplicationNotFound" } }); + const exit = await Effect.runPromiseExit(run.provider.delete(deleteInput())); + assert.equal(Exit.isSuccess(exit), true); + assert.equal(run.said.length, 2); +}); + +void test("any other failure still fails the destroy, and the application is not deleted", async () => { + for (const failure of [ + { + _tag: "ContainerSnapshotCleanupError", + message: "Container registry GET /v2/_catalog failed", + }, + { _tag: "CloudflareError", message: "Authentication error" }, + ]) { + const run = destroy(failure, { deleteFails: null }); + const exit = await Effect.runPromiseExit(run.provider.delete(deleteInput())); + assert.equal(Exit.isFailure(exit), true); + assert.deepEqual(run.deleted, []); + assert.deepEqual(run.said, []); + } + // a refusal, then a failure of the application's own delete + const run = destroy(refusal, { deleteFails: { _tag: "CloudflareError" } }); + assert.equal( + Exit.isFailure(await Effect.runPromiseExit(run.provider.delete(deleteInput()))), + true, + ); +}); + +void test("a destroy that Alchemy finishes says nothing and calls nothing more", async () => { + const run = destroy(null, { deleteFails: null }); + await Effect.runPromise(run.provider.delete(deleteInput())); + assert.deepEqual(run.deleted, []); + assert.deepEqual(run.said, []); +}); + +void test("Alchemy's engine reaches the wrapped delete through the provider's live mode", async () => { + // a dual registration, as Alchemy's: the engine calls `providerForMode(service, mode)` + const run = destroy(refusal, { deleteFails: null, dual: true }); + const live = await Effect.runPromise(providerForMode(run.provider, "live")); + await Effect.runPromise(live.delete(deleteInput())); + assert.deepEqual(run.deleted, [application]); + assert.deepEqual(run.said, leftovers.map(leftoverLine)); + // the local variant has no registry, and stays Alchemy's own + const local = await Effect.runPromise(providerForMode(run.provider, "local")); + assert.equal(Exit.isFailure(await Effect.runPromiseExit(local.delete(deleteInput()))), true); +}); + +type ApplicationService = ProviderService<Cloudflare.Containers.DurableObjectApplication>; + +/** The wrapper over a pretend Alchemy provider whose delete fails with `failure` (or succeeds with + * none), and a pretend application delete that fails with `deleteFails` (or records the call). + * `dual`: the provider is registered for two modes, as `ProviderLayer.dual` makes it. */ +function destroy( + failure: object | null, + options: { deleteFails: { _tag: string } | null; dual?: boolean }, +) { + const said: string[] = []; + const deleted: object[] = []; + // The cast: of the provider, only `delete` is called here. + const variant = { + delete: () => (failure ? Effect.fail(failure) : Effect.void), + } as unknown as ApplicationService; + const base = options.dual + ? { ...variant, modes: { live: Effect.succeed(variant), local: Effect.succeed(variant) } } + : variant; + const provider = snapshotRefusalProvider( + base, + { + leftovers: () => Effect.succeed(leftovers), + deleteContainerApplication: (input) => + options.deleteFails + ? Effect.fail(options.deleteFails) + : Effect.sync(() => void deleted.push(input)), + }, + (line) => void said.push(line), + ); + return { provider, said, deleted }; +} + +// The cast: the wrapper reads only `output` of its input. +function deleteInput() { + return { id: "SandboxContainer-Containers", output: application } as unknown as Parameters< + ApplicationService["delete"] + >[0]; +}
A core/alchemy/src/container-snapshots.ts
@@ -0,0 +1,124 @@ +// container-snapshots.ts — A DESTROY THAT FINISHES WHEN CLOUDFLARE KEEPS A SANDBOX'S SNAPSHOTS. +// A sandbox that saved itself (`ctx.container.snapshotContainer()`) leaves its snapshot in the +// account's container registry, under `<account>/cloudchamber-snapshots/<id>`. Alchemy's container +// application deletes those tags before the application. Cloudflare's registry refuses that DELETE +// with HTTP 403, with every credential its API makes (`pull`, `push`), under tokens that hold +// "Cloudchamber Write" and "Workers Containers Write"; the same credentials delete a tag in an +// ordinary image repository. Alchemy's provider then fails, and the whole destroy with it. +// +// THAT REFUSAL IS AN EXPECTED OUTCOME: the application is deleted all the same, and the destroy +// says, for each snapshot repository, that it stays in the account and how many tags it holds. +// Cloudflare keeps the snapshots after their application is deleted, and no API that we know of +// removes them. Any other failure fails the destroy, as Alchemy's provider would. A deploy is not +// touched. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import { + listApplicationDurableObjects, + listSnapshotImages, +} from "@alchemy.run/cloudflare/Containers/ContainerSnapshots"; +import * as Containers from "@distilled.cloud/cloudflare/containers"; +import * as Provider from "alchemy/Provider"; +import type { ProviderError } from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import { z } from "zod"; +import { eachLineOnce } from "./realtime.ts"; + +type ApplicationService = Provider.ProviderService<Cloudflare.Containers.DurableObjectApplication>; +type Application = Parameters<ApplicationService["delete"]>[0]["output"]; + +/** One snapshot repository that the registry would not delete, and how many of its tags this + * application's Durable Objects saved. One repository may hold the snapshots of several + * applications. */ +export type Leftover = { repository: string; tags: number }; + +/** The registry's refusal of a snapshot tag's DELETE, as Alchemy gives it + * (`ContainerSnapshotCleanupError`, "Container registry DELETE … returned HTTP 403"). A registry + * that cannot be reached, or another status, is not it. */ +export const isSnapshotRefusal = (error: unknown) => SnapshotRefusal.safeParse(error).success; +const SnapshotRefusal = z.object({ + _tag: z.literal("ContainerSnapshotCleanupError"), + message: z.string().regex(/^Container registry DELETE \S+ returned HTTP 403$/), +}); + +export const leftoverLine = ({ repository, tags }: Leftover) => + `${repository} keeps ${tags} tags of this mind's sandbox snapshots: Cloudflare's container registry refuses to delete them, and keeps them after the container application is deleted. They hold copies of the sandboxes' files. The repository may also hold other applications' snapshots.`; + +/** Alchemy's provider `base` of a container application, whose `delete` deletes the application + * when the registry refuses a snapshot (`isSnapshotRefusal`), and says `leftoverLine` for each + * snapshot repository that `calls.leftovers` names, read before the application goes. + * + * Alchemy registers this provider for two modes (`ProviderLayer.dual`), and its engine calls the + * variant in `modes` (`providerForMode`), not the registered service's own `delete`: so the live + * variant is wrapped too. The local variant has no registry and stays as it is. */ +export function snapshotRefusalProvider( + base: ApplicationService, + calls: { + leftovers: (application: Application) => Effect.Effect<ReadonlyArray<Leftover>, ProviderError>; + deleteContainerApplication: (input: { + accountId: string; + applicationId: string; + }) => Effect.Effect<unknown, ProviderError>; + }, + say: (line: string) => void, +): ApplicationService { + const wrap = (service: ApplicationService): ApplicationService => ({ + ...service, + delete: (input) => + service.delete(input).pipe( + Effect.catchIf(isSnapshotRefusal, () => + Effect.gen(function* () { + const left = yield* calls.leftovers(input.output); + yield* calls + .deleteContainerApplication({ + accountId: input.output.accountId, + applicationId: input.output.applicationId, + }) + .pipe( + Effect.catchIf( + (error) => error._tag === "ContainerApplicationNotFound", + () => Effect.void, + ), + ); + for (const leftover of left) say(leftoverLine(leftover)); + }), + ), + ), + }); + const wrapped = wrap(base); + if (!base.modes) return wrapped; + return { ...wrapped, modes: { ...base.modes, live: Effect.map(base.modes.live, wrap) } }; +} + +/** The snapshot repositories of an application's Durable Objects, with their tag counts. */ +const leftoversOf = (application: Application) => + Effect.gen(function* () { + const objects = yield* listApplicationDurableObjects( + application.accountId, + application.applicationId, + ); + const tags = yield* listSnapshotImages(application.accountId, objects); + const counts = new Map<string, number>(); + for (const { repository } of tags) counts.set(repository, (counts.get(repository) ?? 0) + 1); + return [...counts].map(([repository, count]) => ({ repository, tags: count })); + }); + +/** The stack's provider of container applications: put it over `Cloudflare.providers()`, which it + * overrides for this type. */ +export const ContainerSnapshotProviders = () => + Provider.effect( + Cloudflare.Containers.DurableObjectApplication, + Effect.gen(function* () { + // the deploy's Cloudflare credentials and HTTP client, which Alchemy's own calls use + const context = yield* Effect.context<Containers.CloudflareOpContext>(); + return snapshotRefusalProvider( + yield* Cloudflare.Containers.DurableObjectApplication.Provider, + { + leftovers: (application) => leftoversOf(application).pipe(Effect.provideContext(context)), + deleteContainerApplication: (input) => + Containers.deleteContainerApplication(input).pipe(Effect.provideContext(context)), + }, + eachLineOnce(console.log), + ); + }), + ).pipe(Layer.provide(Cloudflare.Containers.DurableObjectApplicationProvider()));
A core/alchemy/src/mind-made-telemetry-tables.test.ts
@@ -0,0 +1,20 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { CloudflareError, Forbidden, NotFound } from "@distilled.cloud/cloudflare/Errors"; +import { noCatalogThere } from "./mind-made-telemetry-tables.ts"; + +void test("a destroy passes a bucket that never had a catalog, and no other refusal", () => { + // what Cloudflare answers for a bucket whose tables were never turned on, as the SDK gives it + assert.equal(noCatalogThere(new NotFound({ message: "Warehouse not found" })), true); + for (const code of [7003, 10006, 40406]) + assert.equal( + noCatalogThere(new CloudflareError({ status: 400, errors: [{ code, message: "no" }] })), + true, + ); + assert.equal(noCatalogThere(new CloudflareError({ status: 404, errors: [] })), true); + assert.equal( + noCatalogThere(new CloudflareError({ status: 500, errors: [{ code: 1, message: "x" }] })), + false, + ); + assert.equal(noCatalogThere(new Forbidden({ message: "Authentication error" })), false); +});
A core/alchemy/src/mind-made-telemetry-tables.ts
@@ -0,0 +1,90 @@ +// mind-made-telemetry-tables.ts — THE TELEMETRY TABLES THAT A MIND MADE ITSELF, AS A RESOURCE. A +// stack with no telemetry token makes the bucket and the streams, and the mind's own code makes +// the catalog, the sinks and the pipelines (core/configs/default/telemetry.ts). This resource makes +// nothing. Its delete removes what the mind made, with the deploy's own credential: the pipelines, +// then the sinks, then the catalog with its tables. It reads the bucket's and the streams' names +// from their resources, so a destroy runs it before they go. +import type * as Cloudflare from "@alchemy.run/cloudflare"; +import * as pipelines from "@distilled.cloud/cloudflare/pipelines"; +import * as catalog from "@distilled.cloud/cloudflare/r2-data-catalog"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; +import * as Schedule from "effect/Schedule"; +import * as Stream from "effect/Stream"; + +export type MindMadeTelemetryTables = Resource< + "Iterate.MindMadeTelemetryTables", + { + accountId: string; + bucket: string; + /** Read for the order of a destroy alone. */ + streams: string[]; + /** The start of every name (core/alchemy/src/config.ts `namesOf().telemetryTables`). */ + tables: string; + }, + { bucket: string }, + never, + Cloudflare.Providers +>; +export const MindMadeTelemetryTables = Resource<MindMadeTelemetryTables>( + "Iterate.MindMadeTelemetryTables", +); + +/** A table's stream, sink and pipeline, by name: the stack's and the mind's own spell them so. */ +export const telemetryTableNames = (tables: string, table: "events" | "logs" | "spans") => ({ + stream: `${tables}_${table}_stream`, + sink: `${tables}_${table}_sink`, + pipeline: `${tables}_${table}`, +}); + +export const MindMadeTelemetryTablesProvider = () => + Provider.succeed(MindMadeTelemetryTables, { + reconcile: ({ news }) => Effect.succeed({ bucket: news.bucket }), + // Through Cloudflare's SDK, which retries 429 and 5xx, and as Alchemy's own Pipelines + // providers delete (2.0.0-beta.87): a pipeline before its sink, and a sink's 422 "in use" + // waited out while its pipeline's delete propagates (at most 8 tries, 500 ms doubling). + delete: Effect.fn(function* ({ olds: { accountId, bucket, tables } }) { + const named = (["events", "logs", "spans"] as const).map((table) => + telemetryTableNames(tables, table), + ); + // `name` is a case-insensitive substring filter: the exact names are compared after + for (const { id, name } of yield* Stream.runCollect( + pipelines.listV1Pipeline.items({ accountId, name: tables, perPage: 100 }), + )) + if (named.some(({ pipeline }) => pipeline === name)) + yield* pipelines + .deleteV1Pipeline({ accountId, pipelineId: id }) + .pipe(Effect.catchTag("PipelineNotExists", () => Effect.void)); + for (const { id, name } of yield* Stream.runCollect( + pipelines.listSinks.items({ accountId, name: tables, perPage: 100 }), + )) + if (named.some(({ sink }) => sink === name)) + yield* pipelines.deleteSink({ accountId, sinkId: id }).pipe( + Effect.retry({ + while: (error) => error._tag === "SinkInUse", + schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]), + }), + Effect.catchTags({ SinkNotFound: () => Effect.void, InvalidSinkId: () => Effect.void }), + ); + // The catalog with its namespaces and tables; its files stay, and the bucket's + // `forceDestroy` removes them. + yield* catalog + .Delete({ accountId, bucketName: bucket, force: true }) + .pipe(Effect.catchIf(noCatalogThere, () => Effect.void)); + }), + }); + +/** Whether a refused delete of the catalog says that there is none: a mind that never turned its + * tables on has a bucket with no catalog, and its destroy must pass. Cloudflare answers 404 + * "Warehouse not found", which the SDK gives as its `NotFound`; an account with no data catalog + * answers 7003, and a bucket that is gone 10006 or 40406. */ +export const noCatalogThere = (error: { + _tag: string; + status?: number; + errors?: readonly { code?: number }[]; +}) => + error._tag === "NotFound" || + (error._tag === "CloudflareError" && + (error.status === 404 || + Boolean(error.errors?.some(({ code }) => [7003, 10006, 40406].includes(code ?? 0)))));
A core/alchemy/src/realtime.test.ts
@@ -0,0 +1,200 @@ +// The SFU app and TURN key of a deploy that may not make them (realtime.ts), against a pretend +// Alchemy provider, and the secrets Worker's value of the two. +import assert from "node:assert/strict"; +import { test } from "node:test"; +import type * as Cloudflare from "@alchemy.run/cloudflare"; +import { Forbidden } from "@distilled.cloud/cloudflare/calls"; +import { Unauthorized } from "@distilled.cloud/cloudflare/Errors"; +import type { ProviderService } from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Exit from "effect/Exit"; +import * as Redacted from "effect/Redacted"; +import { + CALLS_REFUSAL, + callsWithoutWriteProvider, + eachLineOnce, + isCallsRefusal, + NO_CALLS_PERMISSION_LINE, + REALTIME_SFU, + realtimeConfigOf, +} from "./realtime.ts"; + +/** Cloudflare's refusal of a Calls call to a token without the permission, as Alchemy's client + * gives it: HTTP 403 is `Forbidden`, and Cloudflare's code is 10000. */ +const refusal = new Forbidden({ code: 10000, message: "Authentication error" }); +const made = { + appId: "app-1", + accountId: "account-1", + secret: Redacted.make("the app's secret"), + name: "iterate-a-realtime-sfu", + created: "", + modified: "", +}; + +void test("only Cloudflare's refusal for a missing permission counts", () => { + assert.equal(isCallsRefusal(refusal), true); + assert.equal(isCallsRefusal(new Forbidden({ code: 10001, message: "x" })), false); + // HTTP 401, a token that is not valid: the SDK's global `Unauthorized`, with no code + assert.equal(isCallsRefusal(new Unauthorized({ message: "Authentication error" })), false); + assert.equal(isCallsRefusal({ _tag: "CloudflareError", code: 10000 }), false); + assert.equal(isCallsRefusal({ _tag: "TooManyRequests" }), false); + assert.equal(isCallsRefusal(undefined), false); +}); + +void test("a deploy that may not make the app goes on without it, and says so once", async () => { + const said: string[] = []; + const provider = wrapped(pretendAlchemy(refusal), said); + const output = await Effect.runPromise(provider.reconcile(reconcileInput(undefined))); + assert.equal(output.appId, ""); + assert.equal(Redacted.value(output.secret), ""); + assert.equal(output.accountId, "account-1"); + assert.deepEqual(said, [NO_CALLS_PERMISSION_LINE]); + // "Calls Write" is not the one permission that allows it: "Realtime" or "Realtime Admin" does too + assert.doesNotMatch(NO_CALLS_PERMISSION_LINE, /Calls Write/); + assert.match( + NO_CALLS_PERMISSION_LINE, + /lacks the permission to make Realtime \(Calls\) resources/, + ); + assert.match( + NO_CALLS_PERMISSION_LINE, + /\/secrets\/cloudflare-realtime-sfu and \/secrets\/cloudflare-turn are not set/, + ); +}); + +void test("an app that an earlier deploy made stays as it is when Cloudflare refuses", async () => { + const said: string[] = []; + const provider = wrapped(pretendAlchemy(refusal), said); + const output = await Effect.runPromise(provider.reconcile(reconcileInput(made))); + assert.equal(output, made); + assert.deepEqual(said, []); +}); + +void test("any other failure still fails the deploy", async () => { + for (const failure of [ + new Forbidden({ code: 10001, message: "Method not allowed for token" }), + { _tag: "CloudflareError", code: 10000 }, + ]) { + const provider = wrapped(pretendAlchemy(failure), []); + const exit = await Effect.runPromiseExit(provider.reconcile(reconcileInput(undefined))); + assert.equal(Exit.isFailure(exit), true); + } +}); + +void test("an app that is not made is asked for again at the next deploy, with no stable attribute", async () => { + const provider = wrapped(pretendAlchemy(null), []); + const notMade = { ...made, appId: "", secret: Redacted.make("") }; + assert.deepEqual(await Effect.runPromise(provider.diff!(diffInput(notMade))), { + action: "update", + stables: [], + }); + assert.equal(await Effect.runPromise(provider.diff!(diffInput(made))), undefined); +}); + +void test("an app that is not made has nothing to delete; a made one is deleted by Alchemy", async () => { + const deleted: string[] = []; + const provider = wrapped(pretendAlchemy(null, deleted), []); + await Effect.runPromise(provider.delete(deleteInput({ ...made, appId: "" }))); + assert.deepEqual(deleted, []); + await Effect.runPromise(provider.delete(deleteInput(made))); + assert.deepEqual(deleted, ["app-1"]); +}); + +void test("a destroy whose credential may not delete the app goes on, and says so", async () => { + const said: string[] = []; + const provider = wrapped(pretendAlchemy(refusal), said); + await Effect.runPromise(provider.delete(deleteInput(made))); + assert.match(said.join(), /app-1 stays in the account/); +}); + +void test("a deploy's line is said once, and a destroy names each leftover", () => { + const lines: string[] = []; + const say = eachLineOnce((line) => void lines.push(line)); + say(NO_CALLS_PERMISSION_LINE); + say(NO_CALLS_PERMISSION_LINE); + say("app-1 stays in the account"); + say("key-1 stays in the account"); + assert.deepEqual(lines, [ + NO_CALLS_PERMISSION_LINE, + "app-1 stays in the account", + "key-1 stays in the account", + ]); +}); + +void test("the secrets Worker gets each one's id and secret, or why it was not made", () => { + const value = realtimeConfigOf({ + appId: "app-1", + appSecret: Redacted.make("the app's secret"), + keyId: "", + key: Redacted.make(""), + }); + assert.deepEqual(value, { + sfu: { appId: "app-1", appSecret: "the app's secret" }, + turn: { refusal: CALLS_REFUSAL }, + }); + // made, and its secret lost: another reason + const lost = realtimeConfigOf({ + appId: "app-1", + appSecret: Redacted.make(""), + keyId: "key-1", + key: Redacted.make("the key"), + }); + assert.match( + JSON.stringify(lost.sfu), + /"refusal":"Cloudflare made app-1 and the stack holds no secret/, + ); + assert.deepEqual(lost.turn, { keyId: "key-1", apiToken: "the key" }); +}); + +void test("another resource of the same type is Alchemy's own", async () => { + const said: string[] = []; + const provider = wrapped(pretendAlchemy(refusal), said); + const exit = await Effect.runPromiseExit( + provider.reconcile({ ...reconcileInput(undefined), id: "AnotherApp" }), + ); + assert.equal(Exit.isFailure(exit), true); + assert.deepEqual(said, []); +}); + +type AppService = ProviderService<Cloudflare.Calls.App>; + +function wrapped(base: AppService, said: string[]) { + return callsWithoutWriteProvider( + base, + { + id: REALTIME_SFU, + cloudflareIdOf: (output) => output.appId, + notMade: (accountId) => ({ ...made, accountId, appId: "", secret: Redacted.make("") }), + }, + { accountId: Effect.succeed("account-1"), say: (line) => void said.push(line) }, + ); +} + +/** Alchemy's app provider, whose reconcile fails with `failure` (or makes the app with none). */ +function pretendAlchemy(failure: object | null, deleted: string[] = []) { + // The cast: of the provider, only `diff`, `reconcile` and `delete` are called here. + return { + diff: () => Effect.succeed(undefined), + reconcile: () => (failure ? Effect.fail(failure) : Effect.succeed(made)), + delete: (input: { output: typeof made }) => + failure ? Effect.fail(failure) : Effect.sync(() => void deleted.push(input.output.appId)), + } as unknown as AppService; +} + +// The casts below: the pretend provider reads only `id` and `output` of its input. +function reconcileInput(output: typeof made | undefined) { + return { id: REALTIME_SFU, news: {}, output } as unknown as Parameters< + ReturnType<typeof wrapped>["reconcile"] + >[0]; +} + +function diffInput(output: typeof made) { + return { id: REALTIME_SFU, news: {}, olds: {}, output } as unknown as Parameters< + NonNullable<ReturnType<typeof wrapped>["diff"]> + >[0]; +} + +function deleteInput(output: typeof made) { + return { id: REALTIME_SFU, output } as unknown as Parameters< + ReturnType<typeof wrapped>["delete"] + >[0]; +}
A core/alchemy/src/realtime.ts
@@ -0,0 +1,198 @@ +// realtime.ts — THE STACK'S REALTIME SFU APP AND TURN KEY AT CLOUDFLARE, AND A DEPLOY THAT MAY NOT +// MAKE THEM. Every stack makes one SFU app and one TURN key (./stack.ts), with Alchemy's own +// resources, and gives their ids and secrets to the secrets Worker alone, which serves them as +// two secrets that the stack made (core/secrets-worker src/stack-secrets.ts). Neither costs +// anything until a call uses it. +// +// A CREDENTIAL THAT MAY NOT MAKE REALTIME (CALLS) RESOURCES IS AN EXPECTED OUTCOME, and no +// failure. "Calls Write" is not the only permission that allows it: a sub-token without "Calls +// Read" and "Calls Write" still made both when it held "Realtime" or "Realtime Admin" (19 Nov +// 2026). For a credential that may not, Cloudflare answers +// HTTP 403, code 10000, "Authentication error" (asked on 18 Nov 2026), which the SDK gives as the +// Calls service's `Forbidden` with the code. A token that is not valid gets 401 with the same +// words, which the SDK gives as `Unauthorized`: that one still fails the deploy. On the refusal +// the resource is kept as not made (an empty id), the deploy says so in one line and goes on, and +// the secrets Worker gets `{ refusal }` for it. The next deploy asks again. What an earlier +// deploy made stays as the state keeps it. Any other failure fails the deploy, as Alchemy's +// provider would. +// +// The SDK takes "Authentication error" as a passing blip as well, and asks again up to eight +// times before the refusal reaches this file: some seconds of each such deploy. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Provider from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Layer from "effect/Layer"; +import * as Redacted from "effect/Redacted"; +import { z } from "zod"; + +/** The stack's resource ids of the two (./stack.ts). */ +export const REALTIME_SFU = "RealtimeSfu"; +export const TURN_KEY = "TurnKey"; + +/** Cloudflare's words for the refusal, with what they mean: the secrets Worker gives them as the + * reason why the stack's two secrets are not set. */ +export const CALLS_REFUSAL = + "Authentication error (HTTP 403, code 10000): the deploy's credential may not make Realtime apps and TURN keys. A deploy whose credential may make Realtime (Calls) resources makes them."; + +/** The one line that a deploy says whose credential may not make Realtime (Calls) resources. */ +export const NO_CALLS_PERMISSION_LINE = + "This deploy's Cloudflare credential lacks the permission to make Realtime (Calls) resources: the stack goes on without its Realtime SFU app and TURN key, and /secrets/cloudflare-realtime-sfu and /secrets/cloudflare-turn are not set."; + +/** Cloudflare's refusal of a Calls call to a token without the permission: HTTP 403 (the Calls + * service's `Forbidden`) with code 10000. */ +const CallsRefusal = z.object({ _tag: z.literal("Forbidden"), code: z.literal(10000) }); +export const isCallsRefusal = (error: unknown) => CallsRefusal.safeParse(error).success; + +type AppService = Provider.ProviderService<Cloudflare.Calls.App>; +type TurnKeyService = Provider.ProviderService<Cloudflare.Calls.TurnKey>; +type Attributes<S extends AppService | TurnKeyService> = Parameters<S["delete"]>[0]["output"]; + +/** Alchemy's provider `base` of the resource, where Cloudflare's refusal (`isCallsRefusal`) of the + * resource with logical id `resource.id` counts as not made: + * + * - `reconcile`: on the refusal, an earlier output with a Cloudflare id stays; with none, the + * resource is not made, in the account `accountId` gives, and `say` gets + * `NO_CALLS_PERMISSION_LINE`. + * - `diff`: a resource that is not made is updated at each deploy, and none of its attributes is + * taken as stable, so the secrets Worker's value comes from the new answer. + * - `delete`: a resource that is not made has nothing to delete, and one that the credential may + * not delete stays in the account, said in a line. */ +export function callsWithoutWriteProvider<S extends AppService | TurnKeyService>( + base: S, + resource: { + id: string; + cloudflareIdOf: (output: Attributes<S>) => string; + notMade: (accountId: string) => Attributes<S>; + }, + options: { accountId: Effect.Effect<string>; say: (line: string) => void }, +): S { + // The casts: `base` is one of two providers whose members take and give that provider's own + // attributes, and `resource` reads and makes the same provider's attributes. TypeScript cannot + // call a member of a union of two providers, so the wrapper is written for one of them. + const service = base as AppService; + const cloudflareIdOf = resource.cloudflareIdOf as (output: Attributes<AppService>) => string; + const notMade = resource.notMade as (accountId: string) => Attributes<AppService>; + const ours = (id: string) => id === resource.id; + const made = (output: Attributes<AppService> | undefined) => + Boolean(output && cloudflareIdOf(output)); + const wrapped: AppService = { + ...service, + diff: (input) => + ours(input.id) && input.output && !made(input.output) + ? Effect.succeed({ action: "update" as const, stables: [] }) + : service.diff!(input), + reconcile: (input) => + service.reconcile(input).pipe( + Effect.catchIf( + (error: unknown) => ours(input.id) && isCallsRefusal(error), + () => + Effect.gen(function* () { + if (input.output && made(input.output)) return input.output; + options.say(NO_CALLS_PERMISSION_LINE); + return notMade(yield* options.accountId); + }), + ), + ), + delete: (input) => + !ours(input.id) + ? service.delete(input) + : !made(input.output) + ? Effect.void + : service.delete(input).pipe( + // a destroy by a credential that may not delete it still erases the mind: the + // thing stays in the account, and nothing holds its secret once the state is gone + Effect.catchIf(isCallsRefusal, () => + Effect.sync(() => + options.say( + `${cloudflareIdOf(input.output)} stays in the account: this credential lacks the permission to delete Realtime (Calls) resources. Delete it in Cloudflare's dashboard, under Realtime.`, + ), + ), + ), + ), + }; + return wrapped as S; +} + +/** The deploy's account, as Alchemy's Cloudflare providers read it. */ +const accountIdOfDeploy = Effect.map(Cloudflare.CloudflareEnvironment, (environment) => + Effect.map(environment, ({ accountId }) => accountId), +); + +const notMadeAt = (accountId: string) => ({ accountId, name: "", created: "", modified: "" }); + +/** `write`, with a line that was said already left out. */ +export const eachLineOnce = (write: (line: string) => void) => { + const said = new Set<string>(); + return (line: string) => { + if (said.has(line)) return; + said.add(line); + write(line); + }; +}; + +/** The stack's providers of the two: put it over `Cloudflare.providers()`, which it overrides for + * these two types. It says the line of a deploy that may not make them once, for both; a destroy's + * line names one leftover each, so each is said. */ +export const CallsWithoutWriteProviders = () => { + const say = eachLineOnce(console.log); + const app = Provider.effect( + Cloudflare.Calls.App, + Effect.gen(function* () { + const accountId = yield* accountIdOfDeploy; + return callsWithoutWriteProvider( + yield* Cloudflare.Calls.App.Provider, + { + id: REALTIME_SFU, + cloudflareIdOf: (output) => output.appId, + notMade: (accountId) => ({ + ...notMadeAt(accountId), + appId: "", + secret: Redacted.make(""), + }), + }, + { accountId, say }, + ); + }), + ).pipe(Layer.provide(Cloudflare.Calls.AppProvider())); + const turnKey = Provider.effect( + Cloudflare.Calls.TurnKey, + Effect.gen(function* () { + const accountId = yield* accountIdOfDeploy; + return callsWithoutWriteProvider( + yield* Cloudflare.Calls.TurnKey.Provider, + { + id: TURN_KEY, + cloudflareIdOf: (output) => output.keyId, + notMade: (accountId) => ({ ...notMadeAt(accountId), keyId: "", key: Redacted.make("") }), + }, + { accountId, say }, + ); + }), + ).pipe(Layer.provide(Cloudflare.Calls.TurnKeyProvider())); + return Layer.mergeAll(app, turnKey); +}; + +/** THE SECRETS WORKER'S VALUE OF THE TWO (core/secrets-worker src/config.ts + * `cloudflareRealtime`): each one's id and secret, or `{ refusal }` when it was not made. */ +export const realtimeConfigOf = (made: { + appId: string; + appSecret: Redacted.Redacted<string>; + keyId: string; + key: Redacted.Redacted<string>; +}) => ({ + sfu: + made.appId && Redacted.value(made.appSecret) + ? { appId: made.appId, appSecret: Redacted.value(made.appSecret) } + : { refusal: refusalOf(made.appId) }, + turn: + made.keyId && Redacted.value(made.key) + ? { keyId: made.keyId, apiToken: Redacted.value(made.key) } + : { refusal: refusalOf(made.keyId) }, +}); + +/** Why one of the two has no secret: not made, or made and its secret lost (Cloudflare shows it + * once, at the create). */ +const refusalOf = (id: string) => + id + ? `Cloudflare made ${id} and the stack holds no secret of it: delete it in Cloudflare's dashboard, under Realtime, then deploy again.` + : CALLS_REFUSAL;
A core/alchemy/src/retired-cloudflare-oauth-client.test.ts
@@ -0,0 +1,62 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { tryFindProviderRegistrationByType } from "alchemy/Provider"; +import * as Effect from "effect/Effect"; +import * as Logger from "effect/Logger"; +import * as Option from "effect/Option"; +import { + RetiredCloudflareOAuthClientProvider, + retiredClientDropped, +} from "./retired-cloudflare-oauth-client.ts"; + +// A DEPLOY OVER A STACK THAT HAS A CLIENT: the program declares none, so Alchemy plans a delete +// of the row `CloudflareClient` with this provider. The delete must succeed with no call, and the +// row (with the client's secret) leaves the state. + +/** The delete's outcome, and every line it logged. The effect needs no service: the type says + * `Effect<void>`, and it runs here with none, so no credential and no HTTP client exist. */ +async function dropped(output: { clientId?: string }, olds: { name?: string }) { + const lines: string[] = []; + const logger = Logger.make(({ message }) => void lines.push(String(message))); + const exit = await Effect.runPromiseExit( + retiredClientDropped({ output, olds }).pipe(Effect.provide(Logger.layer([logger]))), + ); + return { ok: exit._tag === "Success", lines }; +} + +void test("a stack with a client: the row leaves with no call, and the deploy says how to delete the client", async () => { + const { ok, lines } = await dropped( + { clientId: "example-client-id" }, + { name: "iterate-example-com-cloudflare" }, + ); + assert.equal(ok, true); + assert.equal(lines.length, 1); + assert.match( + lines[0] || "", + /client iterate-example-com-cloudflare \(example-client-id\) stays in the account.*Manage Account, OAuth clients/, + ); +}); + +void test("a stack whose deploy was refused a client: the row leaves with no call and no words", async () => { + assert.deepEqual( + await dropped({ clientId: undefined }, { name: "iterate-example-com-cloudflare" }), + { + ok: true, + lines: [], + }, + ); +}); + +void test("the old row's type has a provider: Alchemy's plan of the orphan delete finds it, and does not die", async () => { + // alchemy src/Plan.ts dies with `missingProviderError` when this lookup finds nothing + const found = await Effect.runPromise( + tryFindProviderRegistrationByType("Iterate.CloudflareOAuthClient").pipe( + Effect.provide(RetiredCloudflareOAuthClientProvider()), + ), + ); + assert.equal(Option.isSome(found), true); + const missing = await Effect.runPromise( + tryFindProviderRegistrationByType("Iterate.CloudflareOAuthClient"), + ); + assert.equal(Option.isNone(missing), true); +});
A core/alchemy/src/retired-cloudflare-oauth-client.ts
@@ -0,0 +1,50 @@ +// retired-cloudflare-oauth-client.ts — A STACK'S OWN OAUTH CLIENT AT CLOUDFLARE, AS A ROW OF THE +// STATE TO DROP. A stack's state may hold one private OAuth client of the mind's account, with its +// secret, as a resource of the type `Iterate.CloudflareOAuthClient`. The stack declares no such +// client: a mind connects to Cloudflare through Cloudflare's MCP server, as its own client +// (core/configs/default/cloudflare.ts). +// +// A ROW WITH NO PROVIDER FAILS THE DEPLOY. Alchemy plans a delete for each row that the program no +// longer declares, and dies when no provider is registered for the row's type (alchemy +// src/Plan.ts, `missingProviderError`). So the type keeps this provider, and its delete makes NO +// call: the deploy's credential may not delete OAuth clients (that needs "OAuth Client Write"), +// and a refused call would cost the deploy Cloudflare's retries. The row and the secret in it +// leave the state; the client stays in the account, and the deploy says how to delete it. The +// vault refreshes no grant through it. This file goes once no state holds such a row. +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import * as Effect from "effect/Effect"; + +export type RetiredCloudflareOAuthClient = Resource< + "Iterate.CloudflareOAuthClient", + { name?: string }, + { clientId?: string | undefined }, + never, + never +>; +const RetiredCloudflareOAuthClient = Resource<RetiredCloudflareOAuthClient>( + "Iterate.CloudflareOAuthClient", +); + +/** The delete: no call of Cloudflare's API, only the words, and none for a stack that never had + * a client (Cloudflare refused to make one). Its effect needs no service at all, so no + * credential and no HTTP client can be reached from it. */ +export const retiredClientDropped = (input: { + output: { clientId?: string | undefined }; + olds: { name?: string }; +}): Effect.Effect<void> => + input.output.clientId + ? Effect.logWarning( + `The stack no longer has its own OAuth client at Cloudflare: the mind connects through Cloudflare's MCP server. The client ${input.olds.name || ""} (${input.output.clientId}) stays in the account, and nothing uses it: delete it in Cloudflare's dashboard, under Manage Account, OAuth clients.`, + ) + : Effect.void; + +export const RetiredCloudflareOAuthClientProvider = () => + Provider.succeed(RetiredCloudflareOAuthClient, { + // no program declares the resource: only a row of an earlier deploy can reach this provider + reconcile: () => + Effect.die( + "Iterate.CloudflareOAuthClient is retired: the stack declares no OAuth client at Cloudflare", + ), + delete: retiredClientDropped, + });
A core/alchemy/src/stack-bindings.snapshot.json
@@ -0,0 +1,152 @@ +{ + "full-cloudflare, mail forward": { + "Telemetry": [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__CATALOG_TOKEN:output of TelemetryToken.value", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream" + ], + "Auth": [ + "DB:Cloudflare.D1Database AuthDb", + "ITERATE:output of AccessTeam.teamDomain, OwnerEmailProof.aud", + "ITERATE__SIGNING_KEY:output of AuthSigningKey.text", + "OAUTH_KV:Cloudflare.KV.Namespace AuthKv", + "SEND_EMAIL:Cloudflare.Email.SendEmail" + ], + "Secrets": [ + "ACTS:Cloudflare.DurableObject (class ActsGate)", + "APPROVALS:Cloudflare.DurableObject (class ApprovalsIndex)", + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "ITERATE:plain_text", + "ITERATE__AT_REST_KEY:output of SecretsAtRestKey.text", + "ITERATE__CLOUDFLARE_REALTIME:output of RealtimeSfu.appId, RealtimeSfu.secret, TurnKey.keyId, TurnKey.key", + "LOADER:Cloudflare.DynamicWorker", + "SECRET:Cloudflare.DurableObject (class SecretDurableObject)" + ], + "Mind": [ + "AI:Cloudflare.Workers.AI", + "ARTIFACTS:Cloudflare.Artifacts.Namespace", + "BROWSER:Cloudflare.Browser", + "CF_VERSION_METADATA:Cloudflare.Workers.VersionMetadata", + "CONTEXTS:Cloudflare.DurableObject (class IterateContextDurableObject)", + "DOOR:Cloudflare.WorkerEntrypoint (worker Boundary, entrypoint Door)", + "FILES:Cloudflare.R2.Bucket FILES", + "IMAGES:Cloudflare.Images.Images", + "ITERATE:plain_text", + "ITERATE__SIGNING_KEY:output of MindSigningKey.text", + "LOADER:Cloudflare.DynamicWorker", + "MIND_KV:Cloudflare.KV.Namespace MindKv", + "SANDBOX_CONTAINER:Cloudflare.DurableObject (class SandboxContainer, containers SandboxContainer)", + "TELEMETRY_METRICS:Cloudflare.AnalyticsEngine.Dataset" + ], + "Boundary": [ + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "DEPLOY_CONFIG:plain_text", + "ITERATE:plain_text", + "MAIL_FORWARD_TO:plain_text", + "MIND:Cloudflare.WorkerEntrypoint (worker Mind, entrypoint Mind)", + "SECRETS:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint Secrets)", + "SECRET_USE:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint SecretUse)", + "SEND_EMAIL:Cloudflare.Email.SendEmail", + "TELEMETRY:Cloudflare.WorkerEntrypoint (worker Telemetry, entrypoint Telemetry)" + ] + }, + "full-cloudflare, no mail forward": { + "Telemetry": [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__CATALOG_TOKEN:output of TelemetryToken.value", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream" + ], + "Auth": [ + "DB:Cloudflare.D1Database AuthDb", + "ITERATE:output of AccessTeam.teamDomain, OwnerEmailProof.aud", + "ITERATE__SIGNING_KEY:output of AuthSigningKey.text", + "OAUTH_KV:Cloudflare.KV.Namespace AuthKv", + "SEND_EMAIL:Cloudflare.Email.SendEmail" + ], + "Secrets": [ + "ACTS:Cloudflare.DurableObject (class ActsGate)", + "APPROVALS:Cloudflare.DurableObject (class ApprovalsIndex)", + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "ITERATE:plain_text", + "ITERATE__AT_REST_KEY:output of SecretsAtRestKey.text", + "ITERATE__CLOUDFLARE_REALTIME:output of RealtimeSfu.appId, RealtimeSfu.secret, TurnKey.keyId, TurnKey.key", + "LOADER:Cloudflare.DynamicWorker", + "SECRET:Cloudflare.DurableObject (class SecretDurableObject)" + ], + "Mind": [ + "AI:Cloudflare.Workers.AI", + "ARTIFACTS:Cloudflare.Artifacts.Namespace", + "BROWSER:Cloudflare.Browser", + "CF_VERSION_METADATA:Cloudflare.Workers.VersionMetadata", + "CONTEXTS:Cloudflare.DurableObject (class IterateContextDurableObject)", + "DOOR:Cloudflare.WorkerEntrypoint (worker Boundary, entrypoint Door)", + "FILES:Cloudflare.R2.Bucket FILES", + "IMAGES:Cloudflare.Images.Images", + "ITERATE:plain_text", + "ITERATE__SIGNING_KEY:output of MindSigningKey.text", + "LOADER:Cloudflare.DynamicWorker", + "MIND_KV:Cloudflare.KV.Namespace MindKv", + "SANDBOX_CONTAINER:Cloudflare.DurableObject (class SandboxContainer, containers SandboxContainer)", + "TELEMETRY_METRICS:Cloudflare.AnalyticsEngine.Dataset" + ], + "Boundary": [ + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "DEPLOY_CONFIG:plain_text", + "ITERATE:plain_text", + "MIND:Cloudflare.WorkerEntrypoint (worker Mind, entrypoint Mind)", + "SECRETS:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint Secrets)", + "SECRET_USE:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint SecretUse)", + "SEND_EMAIL:Cloudflare.Email.SendEmail", + "TELEMETRY:Cloudflare.WorkerEntrypoint (worker Telemetry, entrypoint Telemetry)" + ] + }, + "external mind, no mail forward": { + "Telemetry": [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__CATALOG_TOKEN:output of TelemetryToken.value", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream" + ], + "Auth": [ + "DB:Cloudflare.D1Database AuthDb", + "ITERATE:output of AccessTeam.teamDomain, OwnerEmailProof.aud", + "ITERATE__SIGNING_KEY:output of AuthSigningKey.text", + "OAUTH_KV:Cloudflare.KV.Namespace AuthKv", + "SEND_EMAIL:Cloudflare.Email.SendEmail" + ], + "Secrets": [ + "ACTS:Cloudflare.DurableObject (class ActsGate)", + "APPROVALS:Cloudflare.DurableObject (class ApprovalsIndex)", + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "ITERATE:plain_text", + "ITERATE__AT_REST_KEY:output of SecretsAtRestKey.text", + "ITERATE__CLOUDFLARE_REALTIME:output of RealtimeSfu.appId, RealtimeSfu.secret, TurnKey.keyId, TurnKey.key", + "LOADER:Cloudflare.DynamicWorker", + "SECRET:Cloudflare.DurableObject (class SecretDurableObject)" + ], + "Boundary": [ + "AUTH:Cloudflare.WorkerEntrypoint (worker Auth, entrypoint Auth)", + "DEPLOY_CONFIG:plain_text", + "ITERATE:plain_text", + "PROVIDED_MIND:Cloudflare.DurableObject (class ProvidedMind)", + "SECRETS:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint Secrets)", + "SECRET_USE:Cloudflare.WorkerEntrypoint (worker Secrets, entrypoint SecretUse)", + "SEND_EMAIL:Cloudflare.Email.SendEmail", + "TELEMETRY:Cloudflare.WorkerEntrypoint (worker Telemetry, entrypoint Telemetry)" + ] + } +}
A core/alchemy/src/stack-bindings.test.ts
@@ -0,0 +1,407 @@ +// What each Worker of a stack holds, from the stack's own declaration (./stack.ts), against the +// checked-in ./stack-bindings.snapshot.json. A pull request that adds, removes or renames a +// binding changes that file, so the change shows in its diff. The program runs with no provider, +// no credential and no state: Alchemy records each resource's props as it is declared, and the +// one call to Cloudflare (the zone's lookup) gets a local answer. Each binding is its name and its +// kind, and for a resource, a service or a class what it names: never a value. +// +// If a change is meant, rewrite the file: UPDATE_STACK_BINDINGS=1 pnpm --filter core-alchemy test +import assert from "node:assert/strict"; +import { readFileSync, writeFileSync } from "node:fs"; +import { test } from "node:test"; +import { inspect } from "node:util"; +import { fromApiToken } from "@distilled.cloud/cloudflare/Credentials"; +import type { Named } from "alchemy/Named"; +import { isResource } from "alchemy/Resource"; +import { isExpr } from "alchemy/Output"; +import { StackContext } from "alchemy/StackContext"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as HttpClientResponse from "effect/http/HttpClientResponse"; +import * as Redacted from "effect/Redacted"; +import { MindConfig } from "./config.ts"; +import { mindStack } from "./stack.ts"; +import type { TelemetryMode } from "./telemetry-token.ts"; + +const SNAPSHOT = new URL("stack-bindings.snapshot.json", import.meta.url); +const accountId = "aaaaabbbbbccccc111112222233333aa"; +const base = { + mindId: "a".repeat(64), + controlPlaneHostname: "example.com", + ownerEmails: ["owner@owner.example"], + alchemy: { stageName: "example-com" }, + cloudflare: { accountId, zones: ["example.com"] }, +}; +const CASES = { + "full-cloudflare, mail forward": { + ...base, + topology: "full-cloudflare", + mail: { forwardTo: "team@group.example" }, + }, + "full-cloudflare, no mail forward": { ...base, topology: "full-cloudflare" }, + "external mind, no mail forward": { + ...base, + topology: "external-mind-connects-into-cloudflare-boundary", + }, +}; + +/** Cloudflare's answer to the zone's lookup (`listZones`), given here: the program asks nothing else. */ +const zoneLookup = HttpClient.make((request) => + Effect.succeed( + HttpClientResponse.fromWeb( + request, + Response.json({ + success: true, + errors: [], + messages: [], + result: [{ id: "zone-1", name: "example.com", account: { id: accountId } }], + }), + ), + ), +); + +/** Where an Output comes from: the resources and attributes it reads, not what it holds. */ +const sourcesOf = (expr: any): string[] => + expr.kind === "ResourceExpr" + ? [expr.src.LogicalId] + : expr.kind === "PropExpr" + ? sourcesOf(expr.expr).map((source) => `${source}.${String(expr.identifier)}`) + : expr.kind === "AllExpr" + ? expr.outs.flatMap(sourcesOf) + : sourcesOf(expr.expr); + +/** A Worker that the stack does not make (`Cloudflare.Worker.lookup`, the egress gateway): Node + * prints it as `Cloudflare.Worker.lookup(<its name>)`. */ +const lookedUp = (value: any) => isExpr(value) && (value as any).Type === "Cloudflare.Worker"; + +const kindOf = (value: any): string => { + if (typeof value === "string") return "plain_text"; + // the one Effect left here is one that carries its kind (see `bindingsOf`) + if (Effect.isEffect(value)) return (value as any)["~alchemy/Kind"]; + if (Redacted.isRedacted(value)) return "secret_text"; + if (lookedUp(value)) return inspect(value); + if (isExpr(value)) return `output of ${sourcesOf(value).join(", ")}`; + if (isResource(value)) return `${value.Type} ${value.LogicalId}`; + if (value.kind === "Cloudflare.WorkerEntrypoint") + return `${value.kind} (worker ${lookedUp(value.worker) ? inspect(value.worker) : value.worker.LogicalId}, entrypoint ${value.entrypoint})`; + if (value.kind === "Cloudflare.DurableObject") { + const containers = (value.containers ?? []).map( + (container: Named<string>) => container["~alchemy/Id"], + ); + return `${value.kind} (class ${value.className}${value.scriptName ? `, worker ${value.scriptName}` : ""}${containers.length ? `, containers ${containers.join(" ")}` : ""})`; + } + return value.kind; +}; + +/** What `declaredOf` answers: each Worker's bindings by kind, each resource's type, each + * Worker's variables that are plain text, and each Worker's observability settings. */ +type Declared = { + workers: Record<string, string[]>; + resources: Record<string, string>; + texts: Record<string, Record<string, string>>; + observability: Record<string, any>; + /** each Access application's name, by its logical id */ + accessNames: Record<string, string>; +}; + +/** Each Worker's bindings and declared resources, as the program declares them for one config. */ +const declaredOf = (config: MindConfig, options?: { telemetryMode?: TelemetryMode }) => + Effect.gen(function* () { + const stack = { + name: "mind", + stage: config.alchemy.stageName, + resources: {} as Record<string, any>, + bindings: {} as Record<string, { sid: string; data: { bindings?: { type?: string }[] } }[]>, + actions: {}, + }; + const inStack = <A, E, R>(effect: Effect.Effect<A, E, R>) => + effect.pipe( + Effect.provideService(StackContext, stack), + Effect.provideService(HttpClient.HttpClient, zoneLookup), + Effect.provide(fromApiToken({ apiToken: Redacted.make("none") })), + ); + yield* inStack(mindStack(config, options)); + const workers: Record<string, string[]> = {}; + /** each Worker's variables that are plain text, as the text itself */ + const texts: Record<string, Record<string, string>> = {}; + /** each Worker's observability settings, as declared */ + const observability: Record<string, any> = {}; + for (const resource of Object.values(stack.resources).filter( + (r) => r.Type === "Cloudflare.Worker", + )) { + observability[resource.LogicalId] = resource.Props.observability; + texts[resource.LogicalId] = Object.fromEntries( + Object.entries<any>(resource.Props.env ?? {}).filter( + ([, value]) => typeof value === "string", + ), + ); + const lines: string[] = []; + // An Effect is run, as Alchemy runs it (another Worker's entrypoint), unless it carries its + // kind (`~alchemy/Kind`, the Worker Loader): Alchemy reads that one as it is. + for (const [name, value] of Object.entries<any>(resource.Props.env ?? {})) + lines.push( + `${name}:${kindOf(Effect.isEffect(value) && !("~alchemy/Kind" in value) ? yield* inStack(value as Effect.Effect<unknown, unknown, never>) : value)}`, + ); + // a binding that the stack adds beside `env` with the Worker's own `bind` + // (./analytics-sql-binding.ts), by its name and Cloudflare's type + const env = resource.Props.env ?? {}; + for (const { sid, data } of stack.bindings[resource.FQN] ?? []) + if (!Object.hasOwn(env, sid)) + lines.push(`${sid}:${(data.bindings || []).map((binding) => binding.type).join(" ")}`); + workers[resource.LogicalId] = lines.sort(); + } + const resources = Object.fromEntries( + Object.values(stack.resources).map((r) => [r.LogicalId, r.Type as string]), + ); + const accessNames = Object.fromEntries( + Object.values(stack.resources) + .filter((r) => r.Type === "Cloudflare.Access.Application") + .map((r) => [r.LogicalId, r.Props.name]), + ); + return { workers, resources, texts, observability, accessNames }; + }); + +void test("each Worker of the stack holds what stack-bindings.snapshot.json says", async () => { + const listing: Record<string, Record<string, string[]>> = {}; + for (const [name, config] of Object.entries(CASES)) + listing[name] = ( + await Effect.runPromise(declaredOf(MindConfig.parse(config)) as Effect.Effect<Declared>) + ).workers; + if (process.env.UPDATE_STACK_BINDINGS) + writeFileSync(SNAPSHOT, `${JSON.stringify(listing, null, 2)}\n`); + const snapshot: typeof listing = JSON.parse(readFileSync(SNAPSHOT, "utf8")); + const changes: string[] = []; + for (const name of new Set([...Object.keys(snapshot), ...Object.keys(listing)])) + for (const worker of new Set([ + ...Object.keys(snapshot[name] ?? {}), + ...Object.keys(listing[name] ?? {}), + ])) { + const before = snapshot[name]?.[worker] ?? []; + const after = listing[name]?.[worker] ?? []; + const went = before.filter((line) => !after.includes(line)).map((line) => ` - ${line}`); + const came = after.filter((line) => !before.includes(line)).map((line) => ` + ${line}`); + if (went.length || came.length) changes.push(`${name} / ${worker}:`, ...went, ...came); + } + if (changes.length) + assert.fail( + `The stack's bindings differ from the snapshot:\n${changes.join("\n")}\nIf this change is meant, update the snapshot: UPDATE_STACK_BINDINGS=1 pnpm --filter core-alchemy test`, + ); +}); + +const declared = (config: object) => + Effect.runPromise(declaredOf(MindConfig.parse(config)) as Effect.Effect<Declared>); + +// Cloudflare's code page says "Log in to <the application's name>" to an owner with no passkey +void test("the one Access application is named by the control plane's hostname", async () => { + const { accessNames } = await declared({ + ...CASES["full-cloudflare, no mail forward"], + controlPlaneHostname: "iterate.example.com", + }); + assert.deepEqual(accessNames, { OwnerEmailProof: "iterate.example.com" }); +}); + +// A STACK THAT NAMES NO GATEWAY IS AS IT WAS BEFORE THE GATEWAY'S FIELD EXISTED. Its config +// variables are written out here character by character: a marker or a new key there would +// change every mind. Its bindings are read from the declaration and never from the snapshot +// file, so a rewrite of the snapshot cannot hide one. This reads the declaration, not what +// Alchemy sends to Cloudflare: a plan of a stack shows that. +void test("a stack that names no egress gateway binds none, and has the same ITERATE and DEPLOY_CONFIG, byte for byte", async () => { + const id = "a".repeat(64); + const external = "external-mind-connects-into-cloudflare-boundary"; + for (const [name, topology, mail] of [ + [ + "full-cloudflare, mail forward", + "full-cloudflare", + ',"mail":{"forwardTo":"team@group.example"}', + ], + ["full-cloudflare, no mail forward", "full-cloudflare", ""], + ["external mind, no mail forward", external, ""], + ] as const) { + const { texts, workers } = await declared(CASES[name]); + // the two Workers that send what leaves the stack; a mind's and a telemetry Worker's `ITERATE` + // has fields of its own after these, and the loop below reads every Worker's + for (const worker of ["Secrets", "Boundary"]) + assert.equal( + texts[worker]!.ITERATE, + `{"mindId":"${id}","controlPlaneHostname":"example.com","zones":["example.com"],"ownerEmails":["owner@owner.example"],"topology":"${topology}"}`, + `${name} / ${worker}`, + ); + // A QUERY READS THE LOG LINES OF EVERY WORKER OF THE STACK, so the crash job sees a crash of + // any: the mind (when it is in the stack), the boundary, auth, secrets and telemetry, and no + // other Worker. THE SPANS STAY the mind's and the boundary's: the vault's can hold a value. + const telemetryConfig = JSON.parse(texts.Telemetry!.ITERATE!) as Record<string, unknown>; + assert.deepEqual( + telemetryConfig.workerNamesThatQueriesReadWhole, + [ + ...(topology === external ? [] : ["iterate-example-com-mind"]), + "iterate-example-com-boundary", + ], + name, + ); + assert.deepEqual( + telemetryConfig.workerNamesWhoseLogsQueriesRead, + [ + ...(topology === external ? [] : ["iterate-example-com-mind"]), + "iterate-example-com-boundary", + "iterate-example-com-auth", + "iterate-example-com-secrets", + "iterate-example-com-telemetry", + ], + name, + ); + assert.equal( + texts.Boundary!.DEPLOY_CONFIG, + `{"mindId":"${id}","controlPlaneHostname":"example.com","ownerEmails":["owner@owner.example"],"topology":"${topology}","alchemy":{"stageName":"example-com"},"cloudflare":{"accountId":"${accountId}","zones":["example.com"]}${mail}}`, + name, + ); + // no binding of any Worker, and no plain-text variable, names a gateway + for (const worker of Object.keys(workers)) + assert.deepEqual( + [ + ...workers[worker]!.filter((line) => /egress/i.test(line)), + ...Object.entries(texts[worker]!).filter(([key, value]) => /egress/i.test(key + value)), + ], + [], + `${name} / ${worker}`, + ); + } +}); + +for (const name of ["full-cloudflare, no mail forward", "external mind, no mail forward"] as const) + void test(`${name}, and an egress gateway: the vault and the boundary get the gateway, found by its name; the boundary alone gets its Providers entrypoint; nothing else of the stack changes`, async () => { + const gateway = "Cloudflare.Worker.lookup(owners-egress-gateway)"; + const { workers } = await declared({ + ...CASES[name], + cloudflare: { ...base.cloudflare, egressGatewayWorker: "owners-egress-gateway" }, + }); + const without = (await declared(CASES[name])).workers; + const added = (worker: string) => + workers[worker]!.filter((line) => !without[worker]!.includes(line)); + assert.deepEqual(added("Secrets"), [`EGRESS_GATEWAY:${gateway}`]); + assert.deepEqual(added("Boundary"), [ + `EGRESS_GATEWAY:${gateway}`, + `EGRESS_GATEWAY_PROVIDERS:Cloudflare.WorkerEntrypoint (worker ${gateway}, entrypoint EgressGatewayProviders)`, + ]); + // no other Worker gets a line, and every other line of every Worker is the same stack's with + // no gateway + for (const [worker, lines] of Object.entries(workers)) { + if (worker !== "Secrets" && worker !== "Boundary") + assert.deepEqual(added(worker), [], worker); + assert.deepEqual( + lines.filter((line) => !added(worker).includes(line)), + without[worker], + worker, + ); + } + }); + +void test("telemetry modes: minted keeps both AccountApiToken resources, given uses TelemetryToken, and off makes the bucket and streams but no token, catalog, sink or pipeline, while other Workers stay identical", async () => { + const config = MindConfig.parse(CASES["full-cloudflare, no mail forward"]); + const runMode = (telemetryMode: TelemetryMode) => + Effect.runPromise(declaredOf(config, { telemetryMode }) as Effect.Effect<Declared>); + const [minted, given, off] = await Promise.all([ + runMode("minted"), + runMode("given"), + runMode("off"), + ]); + + // Minted mode declares both AccountApiToken resources and their Worker bindings + assert.deepEqual(minted.workers.Telemetry, [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__CATALOG_TOKEN:output of TelemetryCatalogToken.value", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream", + ]); + assert.equal(minted.resources.TelemetryCatalogToken, "Cloudflare.ApiToken.AccountApiToken"); + // the analytics token is gone: `metrics` is read on the Analytics SQL binding, with no token + assert.equal(minted.resources.TelemetryAnalyticsToken, undefined); + assert.equal(minted.resources.TelemetryToken, undefined); + + // Given mode declares TelemetryToken + assert.deepEqual(given.workers.Telemetry, [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__CATALOG_TOKEN:output of TelemetryToken.value", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream", + ]); + assert.equal(given.resources.TelemetryToken, "Iterate.TelemetryToken"); + assert.equal(given.resources.TelemetryCatalogToken, undefined); + assert.equal(given.resources.TelemetryAnalyticsToken, undefined); + // the tables that a mind made itself are only an "off" stack's + assert.equal(given.resources.TelemetryTablesOfTheMind, undefined); + assert.equal(minted.resources.TelemetryTablesOfTheMind, undefined); + + // Off mode binds the three streams and declares the bucket, the streams and the destinations, + // and no token, catalog, sink or pipeline: the mind can make those itself + assert.deepEqual(off.workers.Telemetry, [ + "ANALYTICS:analytics", + "EVENTS:Cloudflare.Pipelines.Stream Telemetry_events_stream", + "ITERATE:plain_text", + "ITERATE__OTLP_SECRET:output of TelemetryOtlpSecret.text", + "LOGS:Cloudflare.Pipelines.Stream Telemetry_logs_stream", + "METRICS:Cloudflare.AnalyticsEngine.Dataset", + "SPANS:Cloudflare.Pipelines.Stream Telemetry_spans_stream", + ]); + for (const declared of [ + "TelemetryBucket", + "Telemetry_events_stream", + "Telemetry_logs_stream", + "Telemetry_spans_stream", + "Telemetry_logs", + "Telemetry_traces", + "TelemetryTablesOfTheMind", + ]) + assert.ok(off.resources[declared], `${declared} should be declared when off`); + for (const omitted of [ + "TelemetryToken", + "TelemetryCatalogToken", + "TelemetryAnalyticsToken", + "TelemetryCatalog", + "TelemetrySinkTables", + "Telemetry_events_sink", + "Telemetry_events_pipeline", + "Telemetry_logs_sink", + "Telemetry_logs_pipeline", + "Telemetry_spans_sink", + "Telemetry_spans_pipeline", + ]) { + assert.equal(off.resources[omitted], undefined, `${omitted} should be omitted when off`); + } + + // Every other Worker's bindings stay identical across all three telemetry modes + for (const worker of ["Auth", "Secrets", "Mind", "Boundary"] as const) { + assert.deepEqual(minted.workers[worker], given.workers[worker]); + assert.deepEqual(off.workers[worker], given.workers[worker]); + } +}); + +void test("every Worker keeps every log line, and the traces' share is the config's telemetry.traceSampling, else 1", async () => { + const sharesOf = async (config: object) => { + const { observability } = await declared(config); + const shares: Record<string, { logs: number; traces: number }> = {}; + for (const [worker, settings] of Object.entries(observability)) + shares[worker] = { + logs: settings.logs.headSamplingRate, + traces: settings.traces.headSamplingRate, + }; + return shares; + }; + for (const name of Object.keys(CASES) as (keyof typeof CASES)[]) { + const every = await sharesOf(CASES[name]); + assert.ok(Object.keys(every).length >= 4, name); + for (const [worker, share] of Object.entries(every)) + assert.deepEqual(share, { logs: 1, traces: 1 }, `${name} / ${worker}`); + const some = await sharesOf({ ...CASES[name], telemetry: { traceSampling: 0.25 } }); + assert.deepEqual(Object.keys(some), Object.keys(every), name); + for (const [worker, share] of Object.entries(some)) + assert.deepEqual(share, { logs: 1, traces: 0.25 }, `${name} / ${worker}`); + } +});
A core/alchemy/src/stack.ts
@@ -0,0 +1,616 @@ +// stack.ts — A MIND AS ONE PLAIN ALCHEMY STACK: five Workers in the owner's own Cloudflare account, +// and what they bind. One input (./config.ts), one deploy that makes everything, and no step +// before or after `alchemy deploy` but the mind Worker's build. +// +// telemetry takes the other Workers' logs and spans, and the mind's events and metrics +// auth the mind's own sign-in: people, passkeys, the OAuth issuer at the control-plane hostname +// secrets the mind's secrets, and the approvals of what leaves the mind +// mind the one Worker that hosts the mind's contexts, its repos, files and sandboxes +// boundary the only Worker on the mind's zones: every request and every mail comes in here +// +// One more address is public: the telemetry Worker's, on workers.dev, where Cloudflare posts the +// other Workers' logs and spans with a bearer secret. It answers nothing else. +// +// `config.topology` says where the mind runs. "full-cloudflare": the mind Worker is in this stack. +// "external-mind-connects-into-cloudflare-boundary": it runs on a machine of the owner's and +// connects in. The stack then has no mind Worker and nothing that only a mind Worker binds, and +// the boundary, the same build, holds the connection in a Durable Object of its own. +// +// The stack generates four keys (three with an external mind) and keeps one owner-created +// telemetry API token in state, when it is given one. With a token it makes the telemetry +// tables; with none it makes their bucket and streams, and the mind can make the tables itself +// with a secret of its own (core/configs/default/telemetry.ts). It makes no OAuth client: a +// member connects the mind to the account through Cloudflare's MCP server, for which the mind is +// its own client (core/configs/default/cloudflare.ts). +// An owner signs in first with a code mailed to their address, by the mind or by Cloudflare +// Access, and adds a passkey. +import { readFileSync } from "node:fs"; +import { relative, resolve } from "node:path"; +import * as Cloudflare from "@alchemy.run/cloudflare"; +import * as Alchemy from "alchemy"; +import * as Output from "alchemy/Output"; +import * as Config from "effect/Config"; +import * as ConfigProvider from "effect/ConfigProvider"; +import * as Effect from "effect/Effect"; +import * as Redacted from "effect/Redacted"; +import { COMPATIBILITY_DATE } from "iterate/compatibility-date"; +import { z } from "zod"; +import { AccessTeam } from "./access-team.ts"; +import { ArtifactsNamespace } from "./artifacts-namespace.ts"; +import { ArtifactsRepoSubscription } from "./artifacts-repo-subscription.ts"; +import { CatalogTablesOfSinks } from "./catalog-tables-of-sinks.ts"; +import { type MindConfig, namesOf } from "./config.ts"; +import { bindAnalyticsSql } from "./analytics-sql-binding.ts"; +import { MindMadeTelemetryTables, telemetryTableNames } from "./mind-made-telemetry-tables.ts"; +import { REALTIME_SFU, realtimeConfigOf, TURN_KEY } from "./realtime.ts"; +import { type TelemetryMode, TelemetryToken } from "./telemetry-token.ts"; + +const core = (path: string) => resolve(import.meta.dirname, "../..", path); +/** A Worker's fetch to a hostname of its own zone reaches the Worker routed there. */ +const STRICTLY_PUBLIC = "global_fetch_strictly_public"; +/** WebCrypto's ML-DSA-65, which a record of a mind's identity is signed with + * (iterate/mind-identity): the auth Worker checks each record that is posted to it, and the mind + * Worker checks another mind's log. Without the flag the runtime has no such key. */ +const ML_DSA = "webcrypto_modern_algorithms"; +/** A generated key's props: 32 random bytes, as hex. Alchemy keeps a key's value in the state + * whatever its props say, but plans an update for a change of them; the live minds' keys were + * made with these props written out. */ +const KEY = { bytes: 32 }; +/** Every log line and every span, kept in Cloudflare's own Workers Logs. A stack's traces take + * their share from its config (`telemetry.traceSampling`, ./config.ts); its log lines are kept + * whole. */ +const KEEP_ALL = { enabled: true, headSamplingRate: 1, persist: true }; +/** What every Worker of the mind gets as its variable `ITERATE` (iterate/mind-config + * `MindConfig`): the same object for each, since they have the same trust level. */ +const sharedConfigOf = (config: MindConfig) => ({ + mindId: config.mindId, + controlPlaneHostname: config.controlPlaneHostname, + zones: config.cloudflare.zones, + ownerEmails: config.ownerEmails, + topology: config.topology, +}); +/** A stream's fields, as a file of core/telemetry-worker/schemas lists them. */ +const TelemetryStreamFields = z.strictObject({ + fields: z.array( + z.strictObject({ + name: z.string(), + type: z.enum(["string", "int32", "int64", "float64", "timestamp"]), + required: z.boolean(), + }), + ), +}); + +export const mindStack = (config: MindConfig, options: { telemetryMode?: TelemetryMode } = {}) => + Effect.gen(function* () { + const names = namesOf(config); + const { accountId, zones } = config.cloudflare; + const mindIsInTheStack = config.topology === "full-cloudflare"; + const telemetryMode = options.telemetryMode || "given"; + // the share of requests whose trace Cloudflare keeps: every one unless the config says less + const traces = { ...KEEP_ALL, headSamplingRate: config.telemetry?.traceSampling ?? 1 }; + + // ── keys, generated once and kept in the stack's state: each is a secret of its Worker ── + const atRestKey = yield* Alchemy.makeRandom("SecretsAtRestKey", KEY); + const authSigningKey = yield* Alchemy.makeRandom("AuthSigningKey", KEY); + const otlpSecret = yield* Alchemy.makeRandom("TelemetryOtlpSecret", KEY); + + // ── telemetry: first, because every other Worker exports its logs and spans to it ── + // Three modes (./telemetry-token.ts `telemetryModeOf`): + // - "minted": two stack-managed AccountApiToken resources. + // - "given": one owner-created TelemetryToken kept in state. + // A deploy takes no new token, so a stack's mode never changes from "off". + // - "off": no token. The bucket, the streams and the OTLP destinations are made, and no + // catalog, sink or pipeline: the mind can make those itself, with a secret of its own + // (core/configs/default/telemetry.ts). A stream with no pipeline keeps what it is sent, + // and a pipeline made later writes it into the table (measured on 20 Nov 2026). + const telemetryBucket = yield* Cloudflare.R2.Bucket("TelemetryBucket", { + name: names.telemetryBucket, + forceDestroy: true, + // A sink leaves multipart uploads open, and a destroy can abort them only with a token + // that it can read. With this rule R2 aborts them itself after a day. + lifecycleRules: [ + { + id: "abort-stale-uploads", + abortMultipartUploadsTransition: { condition: { type: "Age", maxAge: 86_400 } }, + }, + ], + }); + /** The stream that a Worker writes, one for each table. A changed schema replaces the stream, + * and what the old one still held is lost: a column change is a new table. */ + const streamOf = (table: "events" | "logs" | "spans") => + Cloudflare.Pipelines.Stream(`Telemetry_${table}_stream`, { + name: telemetryTableNames(names.telemetryTables, table).stream, + format: { type: "json" }, + http: false, + workerBinding: { enabled: true }, + schema: TelemetryStreamFields.parse( + JSON.parse(readFileSync(core(`telemetry-worker/schemas/${table}.json`), "utf8")), + ), + }); + const streams = { + EVENTS: yield* streamOf("events"), + LOGS: yield* streamOf("logs"), + SPANS: yield* streamOf("spans"), + }; + // The tables that the mind made itself, which a destroy removes before the bucket and the + // streams go. A stack's mode never changes, so a live stack never loses this resource. + if (telemetryMode === "off") + yield* MindMadeTelemetryTables("TelemetryTablesOfTheMind", { + accountId, + bucket: telemetryBucket.bucketName, + streams: [streams.EVENTS.name, streams.LOGS.name, streams.SPANS.name], + tables: names.telemetryTables, + }); + let telemetryTokenBindings: + | { ITERATE__CATALOG_TOKEN: Output.Output<Redacted.Redacted<string>> } + | undefined; + if (telemetryMode !== "off") { + let catalogTokenValue: Output.Output<Redacted.Redacted<string>>; + if (telemetryMode === "minted") { + // The stack-managed catalog token keeps existing sinks bound to the credential they were + // created with; removing or replacing it stops catalog sink writes. (A stack minted an + // analytics token beside it until 22 Nov 2026; nothing reads it now, since `metrics` is + // read on the Analytics SQL binding, so a deploy deletes it.) + const catalogToken = yield* Cloudflare.ApiToken.AccountApiToken("TelemetryCatalogToken", { + name: `${names.telemetryBucket}-catalog`, + policies: [ + { + effect: "allow", + permissionGroups: ["Workers R2 Data Catalog Write"], + resources: { [`com.cloudflare.api.account.${accountId}`]: "*" }, + }, + { + effect: "allow", + permissionGroups: ["Workers R2 Storage Bucket Item Write", "Workers R2 SQL Read"], + resources: { + [`com.cloudflare.edge.r2.bucket.${accountId}_default_${names.telemetryBucket}`]: + "*", + }, + }, + ], + }); + catalogTokenValue = catalogToken.value; + } else { + // One API token of the account, created by the owner in Cloudflare's dashboard and kept in + // Alchemy's state (./telemetry-token.ts). It holds Workers R2 Data Catalog Write, Workers R2 + // Storage Bucket Item Write and Workers R2 SQL Read, and the telemetry Worker alone + // receives it, for the catalog, the sinks and the tables' queries. + const telemetryToken = yield* TelemetryToken("TelemetryToken", { + name: names.telemetryBucket, + }); + catalogTokenValue = telemetryToken.value; + } + const telemetryCatalog = yield* Cloudflare.R2.DataCatalog("TelemetryCatalog", { + bucket: telemetryBucket, + token: catalogTokenValue, + compaction: { state: "enabled" }, + snapshotExpiration: { state: "enabled", maxSnapshotAge: "1d", minSnapshotsToKeep: 5 }, + }); + // The sinks' tables, which a destroy drops after the sinks and before the catalog: R2 keeps + // a catalog's tables, and Cloudflare makes no sink for a table that exists. + const sinkTables = yield* CatalogTablesOfSinks("TelemetrySinkTables", { + catalogUri: telemetryCatalog.catalogUri, + catalogId: telemetryCatalog.catalogId, + token: catalogTokenValue, + namespace: "telemetry", + tables: ["events", "logs", "spans"], + }); + // Each table's sink, which writes its stream's rows into the table as Parquet, and the + // pipeline between the two. + for (const [table, stream] of [ + ["events", streams.EVENTS], + ["logs", streams.LOGS], + ["spans", streams.SPANS], + ] as const) { + const sink = yield* Cloudflare.Pipelines.Sink(`Telemetry_${table}_sink`, { + name: telemetryTableNames(names.telemetryTables, table).sink, + type: "basin_catalog", + catalog: telemetryCatalog, + table: { namespace: sinkTables.namespace, name: table }, + token: catalogTokenValue, + format: { type: "parquet", compression: "zstd", rowGroupBytes: 32 * 1024 * 1024 }, + rollingPolicy: { intervalSeconds: 60 }, + }); + yield* Cloudflare.Pipelines.Pipeline(`Telemetry_${table}_pipeline`, { + name: telemetryTableNames(names.telemetryTables, table).pipeline, + sql: Output.interpolate`INSERT INTO ${sink.name} SELECT * FROM ${stream.name}`, + }); + } + telemetryTokenBindings = { ITERATE__CATALOG_TOKEN: catalogTokenValue }; + } + const telemetryMetrics = yield* Cloudflare.AnalyticsEngine.Dataset("TELEMETRY_METRICS", { + dataset: names.telemetryMetrics, + }); + const telemetry = yield* Cloudflare.Worker("Telemetry", { + name: names.telemetry, + main: core("telemetry-worker/src/worker.ts"), + compatibility: { date: COMPATIBILITY_DATE }, + // never exported to itself: a failure to land would make more of what failed to land + observability: { ...KEEP_ALL, logs: { ...KEEP_ALL, invocationLogs: true }, traces }, + // Cloudflare's export posts to this workers.dev address. The other Workers name the + // export's destinations, so the intake cannot be behind one of them. + workersDev: { enabled: true, previewsEnabled: false }, + env: { + ITERATE: JSON.stringify({ + ...sharedConfigOf(config), + accountId, + telemetryBucketName: names.telemetryBucket, + metricsDatasetName: names.telemetryMetrics, + // an external mind writes no log to Cloudflare, and no Worker writes its events + workerNamesThatQueriesReadWhole: mindIsInTheStack + ? [names.mind, names.boundary] + : [names.boundary], + // Every Worker of the stack: the mind reads the log lines of them all, so its crash job + // sees a crash of any (core/configs/default/apps/telemetry/crashes.ts). Their spans + // stay out: a span of the vault's outbound fetch can hold what the vault put in. + workerNamesWhoseLogsQueriesRead: [ + ...(mindIsInTheStack ? [names.mind] : []), + names.boundary, + names.auth, + names.secrets, + names.telemetry, + ], + eventsWriterName: mindIsInTheStack ? names.mind : "external-mind", + }), + ITERATE__OTLP_SECRET: otlpSecret, + ...telemetryTokenBindings, + ...streams, + METRICS: telemetryMetrics, + }, + }); + // `ANALYTICS`: Cloudflare's own datasets, read with no token and cut to the mind's rows + // (core/telemetry-worker/src/store-query.ts) + yield* bindAnalyticsSql(telemetry, "ANALYTICS"); + const telemetryDestination = (dataset: "logs" | "traces") => + Cloudflare.Workers.ObservabilityDestination(`Telemetry_${dataset}`, { + name: `${names.telemetry}-${dataset}`, + url: Output.interpolate`${telemetry.url}/v1/${dataset}`, + headers: { + authorization: Output.map(otlpSecret, (secret) => + Redacted.make(`Bearer ${Redacted.value(secret)}`), + ), + }, + logpushDataset: `opentelemetry-${dataset}`, + enabled: true, + // a fresh workers.dev hostname is not routed everywhere yet (1042) + skipPreflightCheck: true, + }); + const logsDestination = yield* telemetryDestination("logs"); + const tracesDestination = yield* telemetryDestination("traces"); + + // ── the settings that the four Workers below share ── + const sharedWorkerProps = { + observability: { + ...KEEP_ALL, + logs: { + ...KEEP_ALL, + invocationLogs: true, + destinations: [logsDestination.slug], + }, + traces: { + ...traces, + destinations: [tracesDestination.slug], + }, + }, + // a Durable Object runs a deploy's code at once, as the Worker in front of it does + codeUpdateStrategy: { mode: "immediate" } satisfies Cloudflare.WorkerCodeUpdateStrategy, + workersDev: { enabled: false, previewsEnabled: false }, + }; + + // ── Cloudflare Access proves an owner's address: one application, at one path ── + // An owner with no passkey yet opens that path. Cloudflare mails a code to the address, from + // its own domain, and then signs a token that names the address. The auth Worker checks the + // token itself (core/auth-worker/src/access-sign-in.ts). The policy names the owners alone: + // nobody else gets a code, so no other person ever takes a seat of the account's team. + // Its name is the control plane's hostname: Cloudflare's code page says "Log in to <name>" + // to the owner. A new name changes the application in place, and its `aud` stays. + const accessTeam = yield* AccessTeam("AccessTeam"); + const ownerEmailProof = yield* Cloudflare.Access.Application("OwnerEmailProof", { + type: "self_hosted", + name: config.controlPlaneHostname, + domain: `${config.controlPlaneHostname}/sign-in/access`, + // the token's cookie goes to that path alone, and to no other page of the control plane + pathCookieAttribute: true, + // the PIN login alone, and no page that offers the account's other logins + allowedIdps: [accessTeam.pinLoginId], + autoRedirectToIdentity: true, + appLauncherVisible: false, + // how long a token proves the address: the time to add the passkey, and little more + sessionDuration: "15m", + policies: [ + { + name: "owners", + decision: "allow", + include: config.ownerEmails.map((email) => ({ email })), + require: [{ loginMethod: accessTeam.pinLoginId }], + }, + ], + }); + + // ── auth ── + const auth = yield* Cloudflare.Worker("Auth", { + ...sharedWorkerProps, + name: names.auth, + main: core("auth-worker/src/worker.ts"), + compatibility: { date: COMPATIBILITY_DATE, flags: [STRICTLY_PUBLIC, ML_DSA] }, + env: { + // the shared config, and whose tokens prove an owner's address: the team's, for the + // application above + ITERATE: Output.all(accessTeam.teamDomain, ownerEmailProof.aud).pipe( + Output.map(([cloudflareAccessTeamDomain, cloudflareAccessAudienceTag]) => + JSON.stringify({ + ...sharedConfigOf(config), + cloudflareAccessTeamDomain, + cloudflareAccessAudienceTag, + }), + ), + ), + ITERATE__SIGNING_KEY: authSigningKey, + DB: yield* Cloudflare.D1.Database("AuthDb", { + name: names.authDb, + // from the working directory, never absolute: the path is kept in the stack's state, + // and an absolute one differs between the machines that deploy + migrations: relative(process.cwd(), core("auth-worker/migrations")), + }), + OAUTH_KV: yield* Cloudflare.KV.Namespace("AuthKv", { title: names.authKv }), + // The auth Worker mails a sign-in code from the zone of the app that a person signs in + // to, and its own self-test: from these addresses alone. + SEND_EMAIL: yield* Cloudflare.Email.SendEmail("AUTH_SEND_EMAIL", { + allowedSenderAddresses: [ + ...zones.map((zone) => `sign-in@${zone}`), + `self-test@${zones[0]}`, + ], + }), + }, + }); + + // ── the stack's Realtime SFU app and TURN key at Cloudflare: calls work from the first deploy ── + // Neither costs anything until a call uses it. Cloudflare shows each one's secret only when + // it makes it: the stack's state keeps it. A deploy whose credential may not make Realtime + // (Calls) resources makes neither, and says so in one line (./realtime.ts). + const realtimeSfu = yield* Cloudflare.Calls.App(REALTIME_SFU, { name: names.realtimeSfu }); + const turnKey = yield* Cloudflare.Calls.TurnKey(TURN_KEY, { name: names.turnKey }); + + // ── the egress gateway that this deploy names: a Worker of the owner's, in the account ── + // The stack does not make it: `lookup` finds it by its name, the deploy fails when no Worker + // has that name, and Alchemy never updates or deletes it. The vault and the boundary get it + // as a service binding and send what leaves the stack through its fetch (iterate/lib + // `fetchLeavingTheStack`). A deploy that names none binds nothing, and the platform's fetch + // sends. + const egressGatewayName = config.cloudflare.egressGatewayWorker; + const egressGateway = egressGatewayName + ? Cloudflare.Worker.lookup({ name: egressGatewayName }) + : undefined; + const egressGatewayBindings: Record<string, Cloudflare.Worker> = egressGateway + ? { EGRESS_GATEWAY: egressGateway } + : {}; + + // ── secrets ── + const secrets = yield* Cloudflare.Worker("Secrets", { + ...sharedWorkerProps, + name: names.secrets, + main: core("secrets-worker/src/worker.ts"), + compatibility: { date: COMPATIBILITY_DATE, flags: ["nodejs_compat", STRICTLY_PUBLIC] }, + env: { + ITERATE: JSON.stringify(sharedConfigOf(config)), + ITERATE__AT_REST_KEY: atRestKey, + // The SFU app and TURN key above, for this Worker alone, which serves them as two secrets + // that the stack made: each one's id and secret, or why it was not made. One secret + // variable, as JSON (core/secrets-worker/src/config.ts `cloudflareRealtime`). + ITERATE__CLOUDFLARE_REALTIME: Output.all( + realtimeSfu.appId, + realtimeSfu.secret, + turnKey.keyId, + turnKey.key, + ).pipe( + Output.map(([appId, appSecret, keyId, key]) => + Redacted.make(JSON.stringify(realtimeConfigOf({ appId, appSecret, keyId, key }))), + ), + ), + AUTH: Cloudflare.WorkerEntrypoint(auth, { entrypoint: "Auth" }), + SECRET: Cloudflare.DurableObject("SECRET", { className: "SecretDurableObject" }), + APPROVALS: Cloudflare.DurableObject("APPROVALS", { className: "ApprovalsIndex" }), + ACTS: Cloudflare.DurableObject("ACTS", { className: "ActsGate" }), + LOADER: Cloudflare.Workers.WorkerLoader("LOADER"), + ...egressGatewayBindings, + }, + }); + + // ── the stack's one queue of Cloudflare events: the subscriptions below feed it ── + const cloudflareEvents = yield* Cloudflare.Queues.Queue("CloudflareEvents", { + name: names.cloudflareEvents, + }); + + // ── the boundary: one build, and one binding to the mind by the topology ── + const declaredBoundary = Cloudflare.Worker("Boundary", { + ...sharedWorkerProps, + name: names.boundary, + main: core("boundary-worker/src/worker.ts"), + compatibility: { date: COMPATIBILITY_DATE, flags: [STRICTLY_PUBLIC] }, + // One session of the API is one long invocation here, as it is one in the mind Worker: every + // call of the session passes through it. The mind's own limits. + limits: { subrequests: 1_000_000, cpuMs: 300_000 }, + env: { + ITERATE: JSON.stringify(sharedConfigOf(config)), + // This deploy's whole config, which no Worker reads: `iterate deploy` over the mind + // starts from it (core/lib/src/cli/deploy.ts `mindConfigIn`), so a field that no Worker + // holds, such as the sandboxes' image, stays at the next deploy. + DEPLOY_CONFIG: JSON.stringify(config), + AUTH: Cloudflare.WorkerEntrypoint(auth, { entrypoint: "Auth" }), + SECRETS: Cloudflare.WorkerEntrypoint(secrets, { entrypoint: "Secrets" }), + SECRET_USE: Cloudflare.WorkerEntrypoint(secrets, { entrypoint: "SecretUse" }), + SEND_EMAIL: yield* Cloudflare.Email.SendEmail("SEND_EMAIL"), + // absent without `mail`: such a mind's boundary has no binding more + ...(config.mail && { MAIL_FORWARD_TO: config.mail.forwardTo }), + TELEMETRY: Cloudflare.WorkerEntrypoint(telemetry, { entrypoint: "Telemetry" }), + ...egressGatewayBindings, + // the boundary alone: the gateway's entrypoint for the computers that provide its way out + ...(egressGateway && { + EGRESS_GATEWAY_PROVIDERS: Cloudflare.WorkerEntrypoint(egressGateway, { + entrypoint: "EgressGatewayProviders", + }), + }), + ...(mindIsInTheStack + ? { + // The mind and the boundary bind each other. Each binding is the other Worker's + // declaration, and Alchemy makes both Workers before it gives each its binding. A + // reference (`Cloudflare.Worker.ref`) in place of the declaration makes the plan + // of a first deploy wait forever (Alchemy 2.0.0-beta.85). + MIND: Effect.map( + // the type is written out: each declaration's type would else depend on the other's + Effect.suspend( + (): Effect.Effect<Cloudflare.Worker, unknown, unknown> => mindInTheStack, + ), + (mind) => Cloudflare.WorkerEntrypoint(mind, { entrypoint: "Mind" }), + ), + } + : { + // the boundary's own object, which holds the mind that connects in from elsewhere + PROVIDED_MIND: Cloudflare.DurableObject("PROVIDED_MIND", { + className: "ProvidedMind", + }), + }), + }, + }); + + // ── the mind Worker, and what only it needs: with "full-cloudflare" alone ── + const mindInTheStack = Effect.gen(function* () { + const repos = yield* ArtifactsNamespace("Repos", { namespace: names.repos }); + // A push to the mind's config repo publishes the mind, and a write token of that repo is a + // right to publish it: each becomes an event on the mind's `/repos/config`. + yield* ArtifactsRepoSubscription("ConfigRepoEvents", { + name: `${names.cloudflareEvents}-config-repo`, + namespace: repos.namespace, + // the Artifacts name of the mind's `/repos/config` + repo: "repos--config", + events: ["pushed", "token.created"], + queueId: cloudflareEvents.queueId, + }); + return yield* Cloudflare.Worker("Mind", { + ...sharedWorkerProps, + name: names.mind, + main: core("mind-worker/src/worker.ts"), + // allow_irrevocable_stub_storage: loaded code stores its ITX stub and replays it + compatibility: { + date: COMPATIBILITY_DATE, + flags: ["nodejs_compat", "allow_irrevocable_stub_storage", ML_DSA], + }, + // one capnweb session or MCP run is one long invocation + limits: { subrequests: 1_000_000, cpuMs: 300_000 }, + env: { + ITERATE: JSON.stringify(sharedConfigOf(config)), + ITERATE__SIGNING_KEY: yield* Alchemy.makeRandom("MindSigningKey", KEY), + DOOR: Effect.map(declaredBoundary, (boundary) => + Cloudflare.WorkerEntrypoint(boundary, { entrypoint: "Door" }), + ), + CONTEXTS: Cloudflare.DurableObject("MIND_CONTEXT", { + className: "IterateContextDurableObject", + }), + CF_VERSION_METADATA: Cloudflare.Workers.VersionMetadata(), + LOADER: Cloudflare.Workers.WorkerLoader("LOADER"), + MIND_KV: yield* Cloudflare.KV.Namespace("MindKv", { title: names.mindKv }), + // the name is the resource's output, so the mind is uploaded after its namespace is made + ARTIFACTS: { + kind: "Cloudflare.Artifacts.Namespace", + name: "ARTIFACTS", + namespace: repos.namespace, + }, + // a destroy erases the mind's files: it empties the bucket, then deletes it + FILES: yield* Cloudflare.R2.Bucket("FILES", { name: names.files, forceDestroy: true }), + AI: Cloudflare.Workers.AI(), + BROWSER: Cloudflare.Workers.Browser(), + IMAGES: Cloudflare.Images.Images(), + TELEMETRY_METRICS: telemetryMetrics, + // The sandboxes. One Durable Object class owns one container application. With no + // image it starts Cloudflare's own small one; the config's image is a second image + // that this class may start. + SANDBOX_CONTAINER: Cloudflare.DurableObject("SandboxContainer", { + containers: [ + Cloudflare.Container("SandboxContainer", { schedulingPolicy: "durable_object" }), + ...(config.cloudflare.containerImage + ? [ + Cloudflare.Container("iterate-dev-image", { + schedulingPolicy: "durable_object", + image: config.cloudflare.containerImage, + }), + ] + : []), + ], + }), + }, + }); + }); + if (mindIsInTheStack) yield* mindInTheStack; + const boundary = yield* declaredBoundary; + // The boundary is the queue's one consumer. An event that the mind does not take is tried + // again a minute later, ten times, then dropped. + yield* Cloudflare.Queues.Consumer("CloudflareEventsConsumer", { + queueId: cloudflareEvents.queueId, + scriptName: boundary.workerName, + settings: { maxRetries: 10, retryDelay: 60 }, + }); + + // ── each zone: its hostnames reach the boundary, and its mail goes in and out ── + for (const zoneName of zones) { + const zone = yield* Cloudflare.Zone.findZoneByName({ accountId, name: zoneName }).pipe( + Effect.orDie, + ); + if (!zone) return yield* refuseDeploy(`the account ${accountId} has no zone ${zoneName}`); + // A route fires only on a proxied hostname; with a Worker as the only origin, `AAAA 100::` + // is the placeholder. + for (const [id, hostname] of [ + ["Apex", zoneName], + ["Wildcard", `*.${zoneName}`], + ] as const) { + yield* Cloudflare.DNS.Record(`${id}Record-${zoneName}`, { + zoneId: zone.id, + name: hostname, + type: "AAAA", + content: "100::", + proxied: true, + }); + yield* Cloudflare.Workers.WorkerRoute(`${id}Route-${zoneName}`, { + zoneId: zone.id, + pattern: `${hostname}/*`, + script: boundary.workerName, + }); + } + const routing = yield* Cloudflare.Email.Routing(`EmailRouting-${zoneName}`, { + zone: zone.id, + }); + yield* Cloudflare.Email.CatchAll(`EmailCatchAll-${zoneName}`, { + zone: routing.zoneId, + actions: [{ type: "worker", value: [boundary.workerName] }], + }); + const sending = yield* Cloudflare.Email.SendingSubdomain(`EmailSending-${zoneName}`, { + zoneId: zone.id, + name: zoneName, + }); + // 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. + yield* Cloudflare.Queues.Subscription(`MailEvents-${zoneName}`, { + source: { + type: "email.sending", + zoneId: sending.zoneId, + domain: sending.enabled.pipe( + Output.mapEffect((enabled) => + enabled + ? Effect.succeed(zoneName) + : Effect.die( + `Email Sending is not enabled on ${zoneName} yet: Cloudflare has not validated the zone's DKIM, SPF and return-path records. Deploy again when the zone's Email Sending page shows them as valid.`, + ), + ), + ), + }, + events: ["message.bounced", "message.failed", "message.rejected", "message.complained"], + queueId: cloudflareEvents.queueId, + }); + } + return { controlPlaneHostname: config.controlPlaneHostname }; + }); + +/** Ends a deploy or a destroy before it changes anything, with one line that Alchemy prints as + * it is. */ +export const refuseDeploy = (message: string) => + Effect.fail(new Config.ConfigError(new ConfigProvider.SourceError({ message })));
A core/alchemy/src/telemetry-token.test.ts
@@ -0,0 +1,206 @@ +import assert from "node:assert/strict"; +import { test } from "node:test"; +import { Forbidden, InternalServerError, Unauthorized } from "@distilled.cloud/cloudflare/Errors"; +import { + State, + StateStoreError, + type PersistedState, + type StateService, +} from "alchemy/State/State"; +import * as Effect from "effect/Effect"; +import * as Redacted from "effect/Redacted"; +import { + deleteAnalyticsToken, + deleteLegacyAccountApiToken, + isTelemetryTokenPersisted, + TelemetryToken, + TelemetryTokenProvider, + telemetryModeFromState, + telemetryModeOf, +} from "./telemetry-token.ts"; + +void test("a stack's telemetry token is the one its state keeps, and a stack with none in state takes no new one", async () => { + const kept = { value: Redacted.make("cf-telemetry-v1") }; + const reconcile = (output: typeof kept | undefined) => + Effect.gen(function* () { + const provider = yield* TelemetryToken.Provider; + // reconcile reads only `output`; the rest of Alchemy's context is left out + return yield* provider.reconcile({ + id: "TelemetryToken", + news: { name: "iterate-ada-telemetry" }, + output, + } as Parameters<typeof provider.reconcile>[0]); + }).pipe(Effect.provide(TelemetryTokenProvider())); + const reused = await Effect.runPromise(reconcile(kept)); + assert.equal(Redacted.value(reused.value), "cf-telemetry-v1"); + const none = await Effect.runPromiseExit(reconcile(undefined)); + assert.equal(none._tag, "Failure"); + assert.match(JSON.stringify(none), /takes no new one/); +}); + +void test("telemetryModeOf reads minted, given, and off from the state and fails on state-store errors", async () => { + const rowOf = ( + fqn: string, + resourceType: string, + attr: Record<string, unknown> = { value: Redacted.make("tok") }, + ) => + ({ + resourceType, + namespace: undefined, + fqn, + logicalId: fqn, + instanceId: `inst-${fqn}`, + providerVersion: 1, + status: "created", + downstream: [], + bindings: [], + props: {}, + attr, + }) as const satisfies PersistedState; + + const mintedCatalog = rowOf("TelemetryCatalogToken", "Cloudflare.ApiToken.AccountApiToken"); + const mintedAnalytics = rowOf("TelemetryAnalyticsToken", "Cloudflare.ApiToken.AccountApiToken"); + const givenRow = rowOf("TelemetryToken", "Iterate.TelemetryToken"); + + assert.equal(isTelemetryTokenPersisted(undefined), false); + assert.equal(isTelemetryTokenPersisted(givenRow), true); + assert.equal(isTelemetryTokenPersisted({ ...givenRow, status: "deleting" }), false); + assert.equal(isTelemetryTokenPersisted({ ...givenRow, attr: {} }), false); + + assert.equal( + telemetryModeFromState({ catalogToken: mintedCatalog, analyticsToken: mintedAnalytics }), + "minted", + ); + assert.equal(telemetryModeFromState({ givenToken: givenRow }), "given"); + assert.equal(telemetryModeFromState({}), "off"); + + // State service integration across all three fixtures + const stateWith = (rows: Record<string, PersistedState | undefined>) => + ({ + get: ({ stack, stage, fqn }) => { + assert.equal(stack, "mind"); + assert.equal(stage, "ada"); + return Effect.succeed(rows[fqn]); + }, + }) as Pick<StateService, "get"> as StateService; + + assert.equal( + await Effect.runPromise( + telemetryModeOf("ada").pipe( + Effect.provideService( + State, + Effect.succeed( + stateWith({ + TelemetryCatalogToken: mintedCatalog, + TelemetryAnalyticsToken: mintedAnalytics, + }), + ), + ), + ), + ), + "minted", + ); + assert.equal( + await Effect.runPromise( + telemetryModeOf("ada").pipe( + Effect.provideService(State, Effect.succeed(stateWith({ TelemetryToken: givenRow }))), + ), + ), + "given", + ); + assert.equal( + await Effect.runPromise( + telemetryModeOf("ada").pipe(Effect.provideService(State, Effect.succeed(stateWith({})))), + ), + "off", + ); + + // A state-store read failure must fail the deploy, never silently return "off" + const brokenState = { + get: () => Effect.fail(new StateStoreError({ message: "state store unreachable" })), + } as Pick<StateService, "get"> as StateService; + const failed = await Effect.runPromiseExit( + telemetryModeOf("ada").pipe(Effect.provideService(State, Effect.succeed(brokenState))), + ); + assert.equal(failed._tag, "Failure"); + // and so must a run with no state at all + assert.equal((await Effect.runPromiseExit(telemetryModeOf("ada")))._tag, "Failure"); +}); + +void test("legacy AccountApiToken delete succeeds when permitted, logs and continues on permission refusal with valid credential, and fails on invalid credential or 5xx", async () => { + const accountId = "a".repeat(32); + const token = { + accountId, + name: "iterate-ada-telemetry-catalog", + tokenId: "tok-123", + }; + + // Credential with delete permission removes the token cleanly without warning + const okLines: string[] = []; + await Effect.runPromise( + deleteLegacyAccountApiToken(Effect.void, Effect.void, token, (line) => okLines.push(line)), + ); + assert.deepEqual(okLines, []); + + // Sign-in lacking API-token write scope (Unauthorized "Authentication error" or Forbidden "Method not allowed for token") + for (const refusal of [ + new Unauthorized({ message: "Authentication error" }), + new Forbidden({ message: "Method not allowed for token" }), + ]) { + const lines: string[] = []; + await Effect.runPromise( + deleteLegacyAccountApiToken(Effect.fail(refusal), Effect.succeed("valid"), token, (line) => + lines.push(line), + ), + ); + assert.equal(lines.length, 1); + assert.match(lines[0]!, /iterate-ada-telemetry-catalog/); + assert.match(lines[0]!, new RegExp(`https://dash\\.cloudflare\\.com/${accountId}/api-tokens`)); + } + + // Invalid credential fails even on Unauthorized "Authentication error" + const invalidExit = await Effect.runPromiseExit( + deleteLegacyAccountApiToken( + Effect.fail(new Unauthorized({ message: "Authentication error" })), + Effect.fail(new Unauthorized({ message: "Authentication error" })), + token, + () => {}, + ), + ); + assert.equal(invalidExit._tag, "Failure"); + + // Non-permission errors (500) still fail + const serverErrorExit = await Effect.runPromiseExit( + deleteLegacyAccountApiToken( + Effect.fail(new InternalServerError({ message: "internal error" })), + Effect.succeed("valid"), + token, + () => {}, + ), + ); + assert.equal(serverErrorExit._tag, "Failure"); +}); + +void test("a refused delete of the analytics token fails the deploy, and its line names the token and how to delete it", async () => { + const accountId = "a".repeat(32); + const token = { accountId, name: "iterate-ada-telemetry-analytics", tokenId: "tok-456" }; + const quiet: string[] = []; + await Effect.runPromise(deleteAnalyticsToken(Effect.void, token, (line) => quiet.push(line))); + assert.deepEqual(quiet, []); + for (const refusal of [ + new Unauthorized({ message: "Authentication error" }), + new Forbidden({ message: "Method not allowed for token" }), + new InternalServerError({ message: "internal error" }), + ]) { + const lines: string[] = []; + const exit = await Effect.runPromiseExit( + deleteAnalyticsToken(Effect.fail(refusal), token, (line) => lines.push(line)), + ); + // a failed delete keeps the row in Alchemy's state (Apply.ts deletes the row after it) + assert.equal(exit._tag, "Failure"); + assert.equal(lines.length, 1); + assert.match(lines[0]!, /iterate-ada-telemetry-analytics \(tok-456\)/); + assert.match(lines[0]!, /stays in the stack's state, and this deploy fails/); + assert.match(lines[0]!, new RegExp(`https://dash\\.cloudflare\\.com/${accountId}/api-tokens`)); + } +});
A core/alchemy/src/telemetry-token.ts
@@ -0,0 +1,206 @@ +// telemetry-token.ts — THE TELEMETRY TOKEN THAT A STACK ALREADY KEEPS IN STATE. A stack whose +// tables an earlier deploy made with a token keeps that token: its Pipelines catalog sinks keep +// the token they were made with. A deploy takes no new token: a mind turns its tables on itself +// (core/configs/default/telemetry.ts). The mode is read from the stack's state alone. +// +// `AccountApiTokenDeleteFallbackProvider` wraps Alchemy's `AccountApiTokenProvider` so deleting +// an `AccountApiToken` resource succeeds even with a deploy sign-in that lacks API-token write +// permission: when Cloudflare refuses deletion for missing permission, it verifies the credential +// is valid, logs the token name and dashboard URL for manual removal, and lets Alchemy clear state. +// The one exception is `TelemetryAnalyticsToken` (`ANALYTICS_TOKEN`): a refusal fails the deploy. +import * as Cloudflare from "@alchemy.run/cloudflare"; +import { Credentials } from "@distilled.cloud/cloudflare/Credentials"; +import * as Retry from "@distilled.cloud/cloudflare/Retry"; +import * as zones from "@distilled.cloud/cloudflare/zones"; +import * as Provider from "alchemy/Provider"; +import { Resource } from "alchemy/Resource"; +import { isResourceState, type PersistedState, State } from "alchemy/State/State"; +import type { ResourceState } from "alchemy/State/ResourceState"; +import * as Effect from "effect/Effect"; +import * as HttpClient from "effect/http/HttpClient"; +import * as Layer from "effect/Layer"; +import * as Option from "effect/Option"; +import * as Predicate from "effect/Predicate"; +import * as Redacted from "effect/Redacted"; +import { z } from "zod"; + +export type TelemetryToken = Resource< + "Iterate.TelemetryToken", + { + /** Descriptive name of the token (`iterate-<stage>-telemetry`). */ + name: string; + }, + { + /** The API token value, kept redacted in Alchemy's state. */ + value: Redacted.Redacted<string>; + }, + never, + Cloudflare.Providers +>; +export const TelemetryToken = Resource<TelemetryToken>("Iterate.TelemetryToken"); + +/** How the stack wires telemetry tables, as its state says: + * - `"minted"`: state holds `TelemetryCatalogToken` or `TelemetryAnalyticsToken` — declare the + * catalog token's `AccountApiToken` so catalog sinks keep their original credentials. The + * analytics token, which nothing reads since 22 Nov 2026, is not declared: a deploy deletes it. + * - `"given"`: state holds `TelemetryToken` — use that one owner-created token. + * - `"off"`: neither — the bucket and the streams are made, and no token, catalog, sink or + * pipeline: the mind can make those itself (./mind-made-telemetry-tables.ts). */ +export type TelemetryMode = "minted" | "given" | "off"; + +const isLiveResource = (persisted: PersistedState | undefined): persisted is ResourceState => + Boolean(persisted && isResourceState(persisted) && persisted.status !== "deleting"); + +/** Whether a persisted state row represents a live `TelemetryToken` with a stored value. */ +export const isTelemetryTokenPersisted = (persisted: PersistedState | undefined): boolean => + Boolean(isLiveResource(persisted) && persisted.attr && "value" in persisted.attr); + +/** Chooses the stack's telemetry mode from persisted state rows. */ +export const telemetryModeFromState = (rows: { + catalogToken?: PersistedState; + analyticsToken?: PersistedState; + givenToken?: PersistedState; +}): TelemetryMode => { + if (isLiveResource(rows.catalogToken) || isLiveResource(rows.analyticsToken)) return "minted"; + if (isTelemetryTokenPersisted(rows.givenToken)) return "given"; + return "off"; +}; + +/** Reads Alchemy's `State` once to determine the stack's telemetry mode for `stage`. A state + * that is not there or cannot be read stops the deploy: read as "off", it would plan the delete + * of a stack's telemetry tokens, catalog, sinks and pipelines. */ +export const telemetryModeOf = (stage: string) => + Effect.gen(function* () { + const stateOption = yield* Effect.serviceOption(State); + if (Option.isNone(stateOption)) + return yield* Effect.die( + `The stack's state is not there to read, so the telemetry mode of ${stage} is not known. Nothing was changed.`, + ); + const state = yield* stateOption.value; + const [catalogToken, analyticsToken, givenToken] = yield* Effect.all([ + state.get({ stack: "mind", stage, fqn: "TelemetryCatalogToken" }), + state.get({ stack: "mind", stage, fqn: "TelemetryAnalyticsToken" }), + state.get({ stack: "mind", stage, fqn: "TelemetryToken" }), + ]); + return telemetryModeFromState({ catalogToken, analyticsToken, givenToken }); + }); + +/** Provider for `TelemetryToken`: it answers the value that the stack's state keeps. */ +export const TelemetryTokenProvider = () => + Provider.succeed(TelemetryToken, { + reconcile: ({ output }) => + output + ? Effect.succeed({ value: output.value }) + : Effect.die( + "This stack holds no telemetry token in its state, and a deploy takes no new one: a mind turns its telemetry tables on itself (onboarding/telemetry.md of /repos/onboarding).", + ), + // The token was created by the person in Cloudflare's dashboard, not by the deploy. + delete: () => Effect.void, + }); + +/** Attempts to delete a `Cloudflare.ApiToken.AccountApiToken`. When Cloudflare refuses for missing + * API-token write permission (and a read proves the credential is valid), logs the token name and + * dashboard URL so the owner can remove it manually and returns success. */ +export const deleteLegacyAccountApiToken = <E, R, E2, R2>( + remove: Effect.Effect<void, E, R>, + credentialWorks: Effect.Effect<unknown, E2, R2>, + token: { accountId: string; name: string; tokenId: string }, + say: (line: string) => void, +) => + remove.pipe( + Effect.catchIf(refusedForPermissionShape, (refused) => + credentialWorks.pipe( + Effect.flatMap(() => + Effect.sync(() => + say( + `API token ${token.name} (${token.tokenId}) stays in Cloudflare: this deploy credential lacks permission to delete API tokens. Delete it in Cloudflare's dashboard: https://dash.cloudflare.com/${token.accountId}/api-tokens`, + ), + ), + ), + Effect.catchCause(() => Effect.fail(refused)), + ), + ), + ); + +/** THE ANALYTICS TOKEN THAT A STACK MINTED UNTIL 22 NOV 2026: Account Analytics Read over the + * whole account, which nothing reads now. A refused delete of it fails the deploy: Alchemy keeps + * its state row (status `deleting`) and plans the delete again at the next deploy. Were it let go + * as the other tokens are, a token that reads the whole account would stay live with no trace in + * the stack's state. The deploy credential that minted it may delete it, so a refusal is not + * expected. Once a member deletes it in the dashboard, the next delete finds no token and + * succeeds. */ +const ANALYTICS_TOKEN = "TelemetryAnalyticsToken"; + +/** Deletes the analytics token (`ANALYTICS_TOKEN`), or fails with a line that names it and says how + * to delete it. */ +export const deleteAnalyticsToken = <E, R>( + remove: Effect.Effect<void, E, R>, + token: { accountId: string; name: string; tokenId: string }, + say: (line: string) => void, +) => + remove.pipe( + Effect.tapError((refused) => + Effect.sync(() => + say( + `API token ${token.name} (${token.tokenId}) reads the account's analytics and could not be deleted (${refusedForPermissionShape(refused) ? "this deploy credential lacks permission to delete API tokens" : wordsOf(refused)}). It stays in the stack's state, and this deploy fails. Delete it in Cloudflare's dashboard (https://dash.cloudflare.com/${token.accountId}/api-tokens), or deploy with a credential that may delete API tokens, then deploy again.`, + ), + ), + ), + ); + +/** Overrides Alchemy's `AccountApiTokenProvider` so deleting `AccountApiToken` resources succeeds + * even without `account_api_tokens` write scope, all but `ANALYTICS_TOKEN`. */ +export const AccountApiTokenDeleteFallbackProvider = () => + Provider.effect( + Cloudflare.ApiToken.AccountApiToken, + Effect.gen(function* () { + const base = yield* Cloudflare.ApiToken.AccountApiToken.Provider; + const credentials = yield* Credentials; + const httpClient = yield* HttpClient.HttpClient; + const wrapped: Provider.ProviderService<Cloudflare.ApiToken.AccountApiToken> = { + ...base, + delete: (input) => + input.id === ANALYTICS_TOKEN + ? deleteAnalyticsToken( + base.delete(input).pipe(noRetryOnPermissionRefusal), + input.output, + console.log, + ) + : deleteLegacyAccountApiToken( + base.delete(input).pipe(noRetryOnPermissionRefusal), + zones + .listZones({ account: { id: input.output.accountId }, perPage: 1 }) + .pipe( + Effect.provideService(Credentials, credentials), + Effect.provideService(HttpClient.HttpClient, httpClient), + ), + input.output, + console.log, + ), + }; + return wrapped; + }), + ).pipe(Layer.provide(Cloudflare.ApiToken.AccountApiTokenProvider())); + +/** WHETHER AN ERROR HAS THE SHAPE OF A REFUSAL FOR PERMISSION. Cloudflare answers 403 code 10000 + * "Authentication error" (mapped to `Unauthorized` or `Forbidden`) or code 10001 "Method not + * allowed for token" (`Forbidden`) for a valid token lacking permission. */ +const refusedForPermissionShape = (error: unknown) => + (Predicate.isTagged(error, "Unauthorized") && /^Authentication error$/i.test(wordsOf(error))) || + (Predicate.isTagged(error, "Forbidden") && + (/method not allowed for token/i.test(wordsOf(error)) || + /^Authentication error$/i.test(wordsOf(error)))); + +/** Retries transient Cloudflare errors (throttling, 5xx) with the SDK's default policy, but not a + * refusal for permission, so a deploy without API-token write fails fast instead of waiting + * about 24 s on retries. */ +const noRetryOnPermissionRefusal = Retry.policy((lastError) => { + const base = Retry.makeDefault(lastError); + return { + ...base, + while: (error) => !refusedForPermissionShape(error) && (base.while?.(error) ?? true), + }; +}); + +const wordsOf = (refused: unknown) => + z.object({ message: z.string() }).safeParse(refused).data?.message || "no reason given";
A core/alchemy/tsconfig.json
@@ -0,0 +1,6 @@ +{ + // The Alchemy script: a Node program. Each Worker package typechecks its own Worker. + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["node"] }, + "include": ["alchemy.run.ts", "src"] +}
A core/auth-worker/migrations/0000_users.sql
@@ -0,0 +1,21 @@ +-- THE AUTH WORKER'S PEOPLE (src/users.ts): copied from core/os's control plane +-- (core/os/src/control-plane/db/definitions.sql), its `users` and `identities` alone. Times are +-- epoch ms. + +-- email: trimmed and lower-cased. A user is never deleted. +create table users ( + id text primary key, + email text not null unique +); + +-- A sign-in method's stable subject, linked to a person once: one subject per provider per person. +-- provider: the method's issuer, such as https://os.iterate.com. added_at: null for one a sign-in +-- linked by its email, which is every one for now. +create table identities ( + provider text not null, + subject text not null, + user_id text not null references users (id), + added_at integer, + primary key (provider, subject), + unique (provider, user_id) +);
A core/auth-worker/migrations/0001_email_challenges.sql
@@ -0,0 +1,29 @@ +-- THE MAILED CODE'S CHALLENGES (src/email-sign-in.ts): one row per code asked for. The row is the +-- challenge while its code lives (`expires_at`, ten minutes; 0 once it is spent or ended), and the +-- record the sending limits count for an hour after (`created_at`). A try is spent in one statement +-- before the check (`tries < 5`), and every limit is counted inside the statement that adds a row. +-- Rows older than an hour are deleted when a new one is written. Times are epoch ms. +create table email_challenges ( + id text primary key, + -- the address as typed, trimmed and lower-cased: the one the code proves + email text not null, + -- the address without its `+tag`, which the per-address limits count + inbox text not null, + -- the requester's address (`cf-connecting-ip`), which the per-client cap counts; null when unknown + client text, + -- the SHA-256 of `<id>:<code>`: the id salts it + hash text not null, + tries integer not null default 0, + -- where the browser goes once signed in: a path on the issuer's origin + next text not null, + -- 1 when an `email` rule names the address + named integer not null, + -- 1 when a code was mailed + mailed integer not null, + created_at integer not null, + expires_at integer not null +); + +create index email_challenges_inbox on email_challenges (inbox, created_at); +create index email_challenges_client on email_challenges (client, created_at); +create index email_challenges_created on email_challenges (created_at);
A core/auth-worker/migrations/0002_members.sql
@@ -0,0 +1,10 @@ +-- THE MEMBERS A MEMBER ADDED (src/members.ts). A member is an address the stack config's +-- `login.allow` admits, or a row here; the config's members cannot be removed at run time, and an +-- empty table is a stack as the config alone says. Times are epoch ms. +create table members ( + -- trimmed and lower-cased; matched exactly, its `+tag` included + email text primary key, + -- the address of the member who added it + added_by text not null, + added_at integer not null +);
A core/auth-worker/migrations/0003_keys.sql
@@ -0,0 +1,37 @@ +-- THE KEYS AND THE STATEMENTS THEY SIGNED (src/keys.ts). Times are epoch ms. + +-- A key added at run time. Root keys are the stack config's (src/config.ts `keys`) and have no +-- row. A row is either a person's key (`user_id`: a passkey they added on /keys) or a service's +-- (`actor` and `paths`: a key a member allowed on /keys/enrol, such as the Cloud's). +-- id: the key's id, the SHA-256 of its public key (iterate/signed `keyIdOf`). public_key: +-- SubjectPublicKeyInfo DER, base64url. format: 'webauthn' or 'p256'. credential_id: the WebAuthn +-- credential's id, base64url, when it has one. paths: a service key's path prefixes, as a JSON +-- array. added_via: how it was added ('keys-page', 'enrol-page'). added_by: the member who added +-- it. A revoked key signs nothing from revoked_at on, and its row stays, so it is never added again. +create table keys ( + id text primary key, + user_id text references users (id), + actor text, + paths text, + public_key text not null, + format text not null, + credential_id text, + label text not null, + added_via text not null, + added_by text not null references users (id), + added_at integer not null, + revoked_at integer, + check ((user_id is null) <> (actor is null)), + check (actor is null or paths is not null) +); + +create index keys_by_user on keys (user_id); +create index keys_by_adder on keys (added_by); + +-- Each statement a key signed that `verify` took, by its hash (iterate/signed `statementHashOf`): +-- the insert that fails on a repeat is what makes a statement count once. A row goes once the +-- statement has expired, since an expired statement is refused anyway. +create table statements ( + hash text primary key, + expires integer not null +);
A core/auth-worker/migrations/0004_stack_key.sql
@@ -0,0 +1,9 @@ +-- THE STACK'S OWN KEY (src/stack-key.ts): one P-256 key pair, made on first use. id is always 1, so +-- two first uses insert one row between them. private_key: PKCS#8 DER, base64url. public_key: +-- SubjectPublicKeyInfo DER, base64url. key: its id (iterate/signed `keyIdOf`). +create table stack_key ( + id integer primary key check (id = 1), + key text not null, + public_key text not null, + private_key text not null +);
A core/auth-worker/migrations/0005_admissions.sql
@@ -0,0 +1,16 @@ +-- THE OPEN ENDPOINTS' ADMISSIONS (src/device/limits.ts): one row per device authorization or client +-- registration let through, which the limits count. Anyone on the internet may call both, so each is +-- counted per client address and for the whole stack, inside the statement that adds the row, and +-- two requests at once are counted one after the other. Rows older than the window, ten minutes, +-- are deleted when a new one is written. Times are epoch ms. +create table admissions ( + -- `device`: POST /oauth2/device_authorization; `registration`: POST /oauth2/register + kind text not null, + -- the requester's address (`cf-connecting-ip`); null when unknown, then counted for the stack alone + client text, + created_at integer not null +); + +-- At most 240 rows: 120 a kind, the stack's limit, within the window. The stack's count and the +-- deletion read them all. +create index admissions_client on admissions (kind, client, created_at);
A core/auth-worker/migrations/0006_passkey_sign_in.sql
@@ -0,0 +1,23 @@ +-- SIGNING IN WITH A PASSKEY, AND THE FIRST OWNER'S TICKET (src/passkey-sign-in.ts, +-- src/first-owner.ts). Times are epoch ms. + +-- A sign-in the page asked for. challenge: what the passkey must sign, the hash of a statement this +-- Worker made (iterate/signed `challengeOf`), so an answer counts for a challenge given here, once: +-- expires_at is set to 0 when it is answered. client: the requester's address (`cf-connecting-ip`), +-- null when unknown. The limits count these rows inside the statement that adds one; rows older +-- than ten minutes are deleted when a new one is written. +create table passkey_challenges ( + challenge text primary key, + client text, + created_at integer not null, + expires_at integer not null +); + +create index passkey_challenges_client on passkey_challenges (client, created_at); + +-- The first owner's ticket, used: the insert that fails on a repeat is what makes it count once. +-- hash: the SHA-256 of the ticket, in hex, as the Worker's FIRST_OWNER_TICKET variable holds it. +create table spent_tickets ( + hash text primary key, + spent_at integer not null +);
A core/auth-worker/migrations/0007_keys_by_credential.sql
@@ -0,0 +1,5 @@ +-- ONE ROW PER PASSKEY CREDENTIAL (src/passkey-sign-in.ts finds a passkey's key by its credential's +-- id, which the member's browser names when it is added). Without this, a member who learned +-- another's credential id could add a row that holds it, and that member's sign-in would find the +-- wrong key and be refused. +create unique index keys_by_credential on keys (credential_id) where credential_id is not null;
A core/auth-worker/migrations/0008_key_scope.sql
@@ -0,0 +1,7 @@ +-- WHAT A SERVICE'S KEY MAY LEND, AND WHEN IT LAST ASKED FOR A TOKEN (src/key-tokens.ts). +-- provide: the one capability name, `itx.<provide>`, that the key's token may lend to the mind +-- (`iterate provide --key`); null for a key that only adds events under its `paths`. A key that +-- only lends has `paths` '[]'. +-- last_used_at: when the key last got a token, epoch ms. `/keys` shows it. +alter table keys add column provide text; +alter table keys add column last_used_at integer;
A core/auth-worker/migrations/0009_blocked.sql
@@ -0,0 +1,11 @@ +-- THE PEOPLE AN OWNER BLOCKED (src/blocked.ts). A stack whose sign-in is open to anyone +-- (`login.methods.email.anyone`) has people who are not members: its apps' end users. A row here +-- refuses one of them: no code is mailed to the address, and no session or token of it is anyone's. +-- A member is never blocked: a member is removed. Times are epoch ms. +create table blocked ( + -- trimmed and lower-cased; matched exactly + email text primary key, + -- the address of the owner who blocked it + blocked_by text not null, + blocked_at integer not null +);
A core/auth-worker/migrations/0010_member_tickets.sql
@@ -0,0 +1,14 @@ +-- A MEMBER'S ONE-USE SIGN-IN LINK (src/members.ts makes one, src/first-owner.ts takes it). On a +-- stack with no mailed codes, a member an owner added has no way to a first passkey. An owner makes +-- a link for that member and passes it on. Only the hash is kept. Times are epoch ms. +create table member_tickets ( + -- the SHA-256 of the ticket, in hex + hash text primary key, + -- the member it signs in: trimmed and lower-cased + email text not null, + -- the address of the owner who made it + made_by text not null, + expires_at integer not null, + -- set by the one use; the update that finds it null is what makes it count once + spent_at integer +);
A core/auth-worker/migrations/0011_browser_sessions.sql
@@ -0,0 +1,21 @@ +-- A BROWSER'S SESSION AT THE ISSUER (src/cookies.ts `sessionCookie` makes one, `sessionOf` reads +-- it, src/sessions-page.ts lists and ends them). The session cookie holds the id: a cookie whose +-- row is gone, ended or expired is no session. Times are epoch ms. +create table browser_sessions ( + -- `session_<hex>` + id text primary key, + user_id text not null, + -- how it was opened: src/cookies.ts `SignInMethod`, never "cloudflare" + method text not null, + -- the id of the passkey that opened it, for the method "passkey": the session ends with the key + key_id text, + -- the browser's User-Agent at the sign-in, cut to 300 characters; "" when it sent none + user_agent text not null, + created_at integer not null, + -- written at most once in ten minutes + last_seen_at integer not null, + expires_at integer not null, + ended_at integer +); + +create index browser_sessions_by_user on browser_sessions (user_id, created_at);
A core/auth-worker/migrations/0012_cloudflare_people_by_subject.sql
@@ -0,0 +1,12 @@ +-- A PERSON WHOM ONLY CLOUDFLARE SIGNS IN KEEPS NO ADDRESS HERE (src/users.ts `linkBySubject`). +-- Cloudflare does not say that it checked the address it gives, so that address must not link a +-- later sign-in to this person. Such a person's row takes `cloudflare:<subject>` in `email`, the +-- key that the sign-in uses from now on, and keeps its id. A person with another way as well keeps +-- the address: that way checked it. +update users +set email = 'cloudflare:' || lower((select i.subject from identities i where i.user_id = users.id)) +where id in ( + select user_id from identities + group by user_id + having count(*) = 1 and min(provider) = 'cloudflare' +);
A core/auth-worker/migrations/0013_statement_drafts.sql
@@ -0,0 +1,17 @@ +-- A STATEMENT THAT WAITS FOR A MEMBER'S PASSKEY (src/statement-drafts.ts). An agent of the mind +-- proposes it; the link to its page carries only the id. The page shows these values, and the +-- press signs a statement made of them. Times are epoch ms. +create table statement_drafts ( + -- 128 random bits, base64url + id text primary key, + path text not null, + type text not null, + -- the payload as JSON text + payload text not null, + -- the context that asked: its own claim + asked_from text, + -- where the page goes once it is signed: a host of this mind + next text, + at integer not null, + expires integer not null +);
A core/auth-worker/migrations/0014_mind_melds.sql
@@ -0,0 +1,15 @@ +-- THE MINDS THIS MIND LETS IN (src/minds.ts): the copy of each mind's latest +-- `events.iterate.com/mind-meld/configured` rule, which a member's passkey signed on the context +-- `/minds/<domain>`. The event is the record; this row is its copy for the check of a statement. +-- domain: the other mind's, lowercase. append: JSON array of the context paths under which it may +-- add events; '[]' once the meld ended (the row stays, so an older rule sent again cannot start it +-- again). key: the one key id that counts, or null to follow the keys the mind publishes. +-- configured_at: the rule statement's `at`, epoch ms; a rule older than the row's is not taken. +-- configured_by: the user id of the member who signed it. +create table mind_melds ( + domain text primary key, + append text not null, + key text, + configured_at integer not null, + configured_by text not null +);
A core/auth-worker/migrations/0015_statement_draft_signer.sql
@@ -0,0 +1,3 @@ +-- The address of the one person whose passkey a draft takes (src/statement-drafts.ts), as the agent +-- named it. Null: any signer the intake takes. +alter table statement_drafts add column signer_email text;
A core/auth-worker/migrations/0016_outsider_keys.sql
@@ -0,0 +1,21 @@ +-- A PASSKEY THAT WAS ADDED WHILE ITS OWNER WAS NO MEMBER (src/keys-pages.ts sets it, src/keys.ts +-- reads it). Such a key never becomes a member's: not when a member adds the address, and not when +-- a deploy names it. It signs about its owner alone, at `/people/<address>`, and signs nobody in. +-- The session it opened and every grant of that session are no member's either. A member gets a +-- passkey by the way a new member takes: a mailed code or a member's link, and a new key, which +-- revokes this one. +-- 1: added by someone who was no member then. 0: every key from before this column, and every key +-- a member added. +alter table keys add column outsider integer not null default 0; + +-- THE STATEMENTS THAT A NON-MEMBER'S KEY SIGNED IN THE LAST HOUR (src/statements.ts counts them +-- inside the statement that adds one, and deletes the older rows). hash: the statement's +-- (iterate/signed `statementHashOf`), so the same statement sent again counts once. key: the id of +-- the key that signed it. at: epoch ms. +create table outsider_statements ( + hash text primary key, + key text not null, + at integer not null +); + +create index outsider_statements_by_key on outsider_statements (key, at);
A core/auth-worker/migrations/0017_identity_records.sql
@@ -0,0 +1,62 @@ +-- THE MIND'S IDENTITY LOG (src/identity.ts): every signed record of the mind's identity +-- (iterate/mind-identity) that this stack accepted, one row each. THESE ROWS ARE THE AUTHORITY: +-- a row decides which of two records is the next, whether the stack may sign, and what +-- `GET /.well-known/iterate` serves. The event `events.iterate.com/mind/identity-record-accepted` +-- on `/` is a copy of the row on the mind's own log, and the row is delivered there. A row's record is never changed and no row is deleted: a mind +-- that gets a new id keeps the rows of the id before. +create table identity_records ( + -- SHA-256 of the record's text, lowercase hex + hash text primary key not null, + -- the mind id: the hash of the log's genesis, the config's `mindId` when the row was written + mind text not null, + -- the hash of the record before it; null in a genesis + prev text, + -- 1 is the genesis + position integer not null check (position >= 1), + -- the exact text that was signed + record text not null, + -- JSON array of { key, sig }, as they came with the record + signatures text not null, + -- JSON array of the root keys whose signatures verified, as the event names them + signed_by text not null, + -- what the record takes in a published page, in bytes: its entry as JSON, and one comma + page_bytes integer not null check (page_bytes > 0), + -- epoch ms + accepted_at integer not null, + -- THE DELIVERY TO `/`: epoch ms at which the boundary said that the row's event is stored + -- there; null until then. The event has one key for ever, so it may be appended again. + delivered_at integer, + -- one record at each place of a log, and one record after each record + unique (mind, position), + unique (mind, prev), + -- a genesis is the first record, has no record before it, and its hash is the mind id + check ((position = 1) = (prev is null)), + check (position > 1 or hash = mind) +); +-- the rows that `/` does not hold yet: few, whatever the log's length +create index identity_records_undelivered on identity_records (mind, position) + where delivered_at is null; + +-- THE RECORDS THAT WERE REFUSED WITH AN EVENT (src/identity.ts): a record that a current root key +-- signed and that did not continue the log gets one `events.iterate.com/mind/identity-record-refused` +-- on `/`. This row is why it gets no second one, and it holds what the event says, so that the +-- same event is delivered until it is stored, whatever a later request sends. Every such record +-- is public once it is sent, so anyone can send it again. +create table identity_refusals ( + hash text primary key not null, + -- the mind id whose log refused it + mind text not null, + -- the check's reason and its sentence + reason text not null, + message text not null, + -- the envelope as it came with the request that was refused: the text and the JSON array of + -- { key, sig } + record text not null, + signatures text not null, + -- epoch ms + refused_at integer not null, + -- epoch ms at which the event was said to be stored on `/`; null until then + delivered_at integer +); +create index identity_refusals_undelivered on identity_refusals (refused_at) + where delivered_at is null;
A core/auth-worker/migrations/0018_stack_key_ml_dsa.sql
@@ -0,0 +1,13 @@ +-- THE STACK'S OWN KEY IS ML-DSA-65 (src/stack-key.ts): the working key that the mind's identity +-- lists for statements (iterate/mind-identity), made on first use. The P-256 key of 0004 goes +-- with its table: no record of an identity lists a P-256 key, so no mind signs with one, and no +-- clean mind was live with one. id is always 1, so two first uses insert one row between them. +-- key: its id (iterate/mind-identity `identityKeyIdOf`). public_key: the raw public key, 1952 +-- bytes. seed: the 32 bytes that the key is made from (WebCrypto `raw-seed`). Both base64url. +drop table stack_key; +create table stack_key ( + id integer primary key check (id = 1), + key text not null, + public_key text not null, + seed text not null +);
A core/auth-worker/migrations/0019_key_origin.sql
@@ -0,0 +1,4 @@ +-- THE iterate Cloud THAT PUBLISHED A KEY (src/keys-pages.ts writes it, `/keys` shows it). origin: +-- the `https:` origin whose `/.well-known/iterate-cloud` published the key when a member allowed +-- it on /keys/enrol, for a key with the actor `iterate-cloud`; null for every other key. +alter table keys add column origin text;
A core/auth-worker/migrations/0020_statement_draft_asked_by.sql
@@ -0,0 +1,4 @@ +-- Who asked for a draft (src/statement-drafts.ts), as the platform stamped the call that proposed +-- it: the JSON of iterate/workers `ProposedBy`. Null: the mind's own code asked, with nobody's +-- call behind it, or the draft is older than this column. +alter table statement_drafts add column asked_by text;
A core/auth-worker/migrations/0021_mind_melds_by_id.sql
@@ -0,0 +1,17 @@ +-- A MIND IS LET IN BY ITS ID (src/minds.ts). Additive: the Worker of before still selects and +-- upserts by `domain` on this table, so a rollback to an earlier version runs on it. +-- domain: from now on the hostname that the rule names (`name`), a label and where the log is +-- read. It stays the row's primary key: one row for each hostname. +-- mind: the id of the mind that this row lets in. A rule by id sets it. A row from before has +-- none until a statement uses it: then the id that the hostname's log proves is written here +-- (trust on first use, and the /minds page says so). +-- state: the identity state that this Worker last read for `mind` (iterate/mind-identity-log +-- `PublishedMind`, JSON): the next read goes on from its head, and takes only a log that +-- continues it. +-- pinned_at: when a row from before was pinned at first use, epoch ms; null for a rule by id. +-- refused: JSON { mind, at }: the last other id that `domain` was seen to serve, for the owner. +alter table mind_melds add column mind text; +alter table mind_melds add column state text; +alter table mind_melds add column pinned_at integer; +alter table mind_melds add column refused text; +create unique index mind_melds_mind on mind_melds (mind) where mind is not null;
A core/auth-worker/migrations/0022_page_event_days.sql
@@ -0,0 +1,9 @@ +-- THE DAY'S BUDGET OF THE PAGE RECORDS FROM OUTSIDE (src/page-events.ts `outsideReserved`): how +-- many records from anyone who is no member the mind took on one UTC day, at most 5,000. A batch +-- reserves its records in the one statement that adds them, so two batches at once are counted +-- one after the other. Rows of days before yesterday are deleted as a batch is counted. +create table page_event_days ( + -- the UTC day, `YYYY-MM-DD` + day text primary key, + records integer not null +);
A core/auth-worker/package.json
@@ -0,0 +1,21 @@ +{ + "name": "core-auth-worker", + "type": "module", + "scripts": { + "typecheck": "tsc --noEmit", + "test": "vitest run" + }, + "dependencies": { + "@cloudflare/workers-oauth-provider": "catalog:", + "iterate": "workspace:*", + "jose": "catalog:", + "oauth4webapi": "catalog:", + "zod": "catalog:" + }, + "devDependencies": { + "@cloudflare/workers-types": "catalog:", + "@types/node": "catalog:", + "typescript": "catalog:", + "vitest": "catalog:" + } +}
A core/auth-worker/src/access-list.test.ts
@@ -0,0 +1,202 @@ +import { expect, test, vi } from "vitest"; +import { clientsWithAccess, type Ends, endFields, endsOf, logoOriginsOf } from "./access-list.ts"; +import type { Env } from "./env.ts"; +import { configVars } from "./test-support.ts"; +import type { ClientWithAccess, SignIn } from "./oauth.ts"; + +test("a client is drawn once, with a summary, an all-N control, and each sign-in collapsed in details", () => { + const html = render([clientOf([codex, older])]); + const drawn = words(html); + expect(drawn.match(/Codex/g)).toHaveLength(1); + expect(drawn).toContain("Whole mind MCP goes to 127.0.0.1:53013 Latest 1 d ago"); + // one visible button ends all that the client holds, and the single sign-ins sit inside details + expect(drawn).toContain("[Revoke all 2 client=client-1]"); + expect(html).toContain(`<details class="access-details">`); + expect(drawn).toContain("2 sign-ins"); + expect(drawn).toContain("Used 1 d ago since 1 Nov ends 17 Nov if idle [Revoke signIn=grant-1]"); + expect(drawn).toContain("Used 1 d ago since 20 Oct ends 17 Nov if idle [Revoke signIn=grant-0]"); + expect(html).toContain( + `<time datetime="2026-11-10T12:00:00Z" title="2026-11-10 12:00 UTC">1 d ago</time>`, + ); +}); + +test("a client with one sign-in has that sign-in's button alone and no details disclosure", () => { + const html = render([clientOf([codex])]); + const drawn = words(html); + expect(html).toContain(`data-client="client-1" data-access="grant-1"`); + expect(html).not.toContain("<details"); + expect(drawn).toContain("[Revoke signIn=grant-1]"); + expect(drawn).not.toContain("Revoke all"); +}); + +test("each action control gets a full accessible label naming what it ends", () => { + const labels: string[] = []; + render( + [clientOf([codex, older])], + (ends, button, label) => { + labels.push(`${button} -> ${label}`); + return end(ends, button); + }, + "jo@example.net", + ); + expect(labels).toEqual([ + "Revoke -> Revoke Codex sign-in from 1 Nov of jo@example.net", + "Revoke -> Revoke Codex sign-in from 20 Oct of jo@example.net", + "Revoke all 2 -> Revoke all 2 sign-ins of Codex of jo@example.net", + ]); +}); + +test("a device's sign-in, a let-in and one of the mind's own pages each say what they are", () => { + const device = words(render([{ ...clientOf([codex]), name: "iterate CLI", device: true }])); + expect(device).toContain("Device sign-in"); + // where a device's code went is this stack's own page, which says nothing + expect(device).not.toContain("goes to"); + + const letInSoon = { + ...codex, + renews: false, + renewedAt: undefined, + until: Date.UTC(2026, 10, 11, 15, 0), + }; + const letInHtml = render([clientOf([letInSoon])]); + expect(words(letInHtml)).toContain("until in 3 h no renewal"); + expect(letInHtml).toContain(`title="2026-11-11 15:00 UTC"`); + + const letInLater = { ...letInSoon, until: Date.UTC(2026, 10, 15, 14, 30) }; + expect(words(render([clientOf([letInLater])]))).toContain("until 15 Nov, 14:30 UTC no renewal"); + + const browser: SignIn = { + ...codex, + clientName: "", + host: "https://guestbook.example.com", + resource: "https://guestbook.example.com", + scopes: ["identity"], + renews: false, + renewedAt: undefined, + endsAt: at("2026-11-12"), + }; + const page = words(render([{ ...clientOf([browser]), name: "Guestbook", host: browser.host }])); + expect(page).toContain("Guestbook Identity only guestbook.example.com This mind's page"); + expect(page).toContain("Signed in 1 Nov ends 12 Nov [Sign out signIn=grant-1]"); +}); + +test("an owner's list names the member, and a name that a client gave is written as text", () => { + const drawn = render( + [{ ...clientOf([codex]), name: '<img src=x onerror="alert(1)">' }], + end, + "jo@example.net", + ); + expect(drawn).not.toContain("<img src=x"); + expect(words(drawn)).toContain("of jo@example.net"); +}); + +test("a page allows a picture from a verified client's own domain alone", () => { + const verified = { + ...clientOf([codex]), + clientDomain: "app.example.org", + logoUri: "https://app.example.org/logo.png", + }; + // a logo with no verified domain, and one on another domain, are not shown + const claimed = { ...clientOf([codex]), logoUri: "https://app.example.org/logo.png" }; + const elsewhere = { ...verified, logoUri: "https://cdn.example.net/logo.png" }; + expect(logoOriginsOf([verified, claimed, elsewhere])).toBe("https://app.example.org"); + expect(logoOriginsOf([claimed, elsewhere])).toBeUndefined(); +}); + +test("one of the mind's own apps has its own name and icon, from its own host alone, and never a brand's mark", () => { + const app = { + ...clientOf([codex]), + name: "Guestbook", + host: "https://guestbook.example.com", + logoUri: "https://guestbook.example.com/icon.svg", + }; + const drawn = clientsWithAccess(env, [app], end); + expect(drawn).toContain( + `<div class="tile small" data-app-mark="icon"><img src="https://guestbook.example.com/icon.svg" alt="" referrerpolicy="no-referrer"></div>`, + ); + expect(words(drawn)).toContain("Guestbook"); + expect(logoOriginsOf([app])).toBe("https://guestbook.example.com"); + // an icon elsewhere is not the app's own: its initials, and no origin for the page to allow + const elsewhere = { ...app, logoUri: "https://cdn.example.net/icon.svg" }; + expect(clientsWithAccess(env, [elsewhere], end)).toContain( + `<div class="tile small" data-app-mark="initials">GU</div>`, + ); + expect(logoOriginsOf([elsewhere])).toBeUndefined(); + // an app of the mind that calls itself Codex is not OpenAI's + expect(clientsWithAccess(env, [{ ...app, name: "Codex", logoUri: undefined }], end)).toContain( + `<div class="tile small" data-app-mark="initials">CO</div>`, + ); +}); + +test("a form names one sign-in or all of one client, and a form that names neither ends nothing", () => { + const posted = (fields: Record<string, string>) => { + const form = new FormData(); + for (const [name, value] of Object.entries(fields)) form.set(name, value); + return endsOf(form); + }; + expect(posted({ signIn: "g1" })).toEqual({ signIn: "g1" }); + expect(posted({ client: "c1" })).toEqual({ client: "c1" }); + expect(posted({ other: "x" })).toBeNull(); + expect(endsOf(null)).toBeNull(); + expect(endFields({ client: 'c"1' })).toBe('<input type="hidden" name="client" value="c"1">'); +}); + +const NOW = Date.parse("2026-11-11T12:00:00Z"); +const at = (day: string) => Date.parse(`${day}T12:00:00Z`) / 1000; + +function render( + clients: ClientWithAccess[], + endControl: (ends: Ends, button: string, label: string) => string = end, + whose?: string, +) { + vi.useFakeTimers({ now: NOW, toFake: ["Date"] }); + try { + return clientsWithAccess(env, clients, endControl, whose); + } finally { + vi.useRealTimers(); + } +} +/** A form as the test reads it: its button's word and what it names. */ +const end = (ends: { signIn: string } | { client: string }, button: string) => + `[${button} ${"signIn" in ends ? `signIn=${ends.signIn}` : `client=${ends.client}`}]`; +/** The list's words, with its tags taken out and the numbered entities written as characters. */ +const words = (html: string) => + html + .replaceAll(/<[^>]+>/g, " ") + .replaceAll(/&#(\d+);/g, (_all, code) => String.fromCharCode(Number(code))) + .replaceAll(/\s+/g, " ") + .trim(); + +// the cast: the list reads the mind's config and no binding +const env = configVars() as unknown as Env; + +/** A Codex CLI's sign-in to the mind's MCP server, renewed nine days after it was made. */ +const codex: SignIn = { + id: "grant-1", + userId: "user_1", + clientId: "client-1", + clientName: "Codex", + resource: "https://iterate.example.com/mcp", + redirectUri: "http://127.0.0.1:53013/callback", + goesTo: "127.0.0.1:53013", + device: false, + scopes: ["iterate"], + createdAt: at("2026-11-01"), + endsAt: at("2026-11-17"), + renews: true, + renewedAt: at("2026-11-10"), +}; +const older: SignIn = { ...codex, id: "grant-0", createdAt: at("2026-10-20") }; + +/** The client that holds these sign-ins, as `sessionsByClientOf` groups them. */ +function clientOf(signIns: SignIn[]): ClientWithAccess { + const [newest] = signIns; + return { + clientId: newest!.clientId, + name: newest!.clientName, + redirectUri: newest!.redirectUri, + goesTo: newest!.goesTo, + device: newest!.device, + signIns, + }; +}
A core/auth-worker/src/access-list.ts
@@ -0,0 +1,273 @@ +// access-list.ts — WHO HOLDS ACCESS AS A PERSON, DRAWN: the list of ./oauth.ts +// `sessionsByClientOf`, which says what the list is and which pages show it. Each client is one +// scannable row with its mark, name, reach and recency; a client with several sign-ins keeps its +// "all N" button on the row and tucks the single sign-ins inside a `<details>`. +// +// A CLIENT SAYS ITS OWN NAME AND LOGO (./client-mark.ts). So a client also says where the access +// went: that is the one thing here a client cannot claim for another. +import { mindMcpUrlOf, mindProvideConnectResourceOf } from "iterate/mind-api"; +import { appTile } from "./asking-app.ts"; +import { clientTile, shownLogoOf } from "./client-mark.ts"; +import { configOf, type Env } from "./env.ts"; +import { type ClientWithAccess, mindHostResourceOf, type SignIn } from "./oauth.ts"; + +/** A form's hidden fields that name what its button ends: one sign-in, or all of one client. */ +export type Ends = { signIn: string } | { client: string }; + +/** The list. `end` makes the form that ends a sign-in or all of a client, with `button` as its + * visible words and `label` as its full accessible name; `whose` names the person on an owner's + * page. */ +export function clientsWithAccess( + env: Env, + clients: ClientWithAccess[], + end: (ends: Ends, button: string, label: string) => string, + whose?: string, +): string { + const now = Date.now(); + return clients.map((client) => clientRow(env, client, end, now, whose)).join(""); +} + +/** The origins that the list's pictures come from, for the page's `img-src`: each is a verified + * client's own logo on its own domain, or the icon of one of the mind's own apps on its own host. */ +export function logoOriginsOf(clients: ClientWithAccess[]): string | undefined { + const origins = new Set( + clients.flatMap((client) => { + if (client.host) return ownIconOf(client) ? [client.host] : []; + const logo = shownLogoOf(client); + return logo ? [logo.origin] : []; + }), + ); + return origins.size ? [...origins].join(" ") : undefined; +} + +/** What a posted form names to end, or null when it names nothing. */ +export function endsOf(form: FormData | null): Ends | null { + const [signIn, client] = [form?.get("signIn"), form?.get("client")]; + if (typeof signIn === "string" && signIn) return { signIn }; + return typeof client === "string" && client ? { client } : null; +} + +/** The hidden fields of a form that ends `ends`. */ +export const endFields = (ends: Ends) => + "signIn" in ends + ? `<input type="hidden" name="signIn" value="${text(ends.signIn)}">` + : `<input type="hidden" name="client" value="${text(ends.client)}">`; + +/** A `<time>` element with a compact label relative to `now` and the exact UTC minute in `title`. */ +export function pastTimeTag(atMs: number, now: number): string { + return timeTag(atMs, pastLabel(atMs, now)); +} + +function clientRow( + env: Env, + client: ClientWithAccess, + end: (ends: Ends, button: string, label: string) => string, + now: number, + whose?: string, +): string { + const name = nameOf(client); + const word = client.host ? "Sign out" : "Revoke"; + const ofWhom = whose ? ` of ${whose}` : ""; + const origin = clientOriginWords(client); + const summaries = client.signIns.map((signIn) => signInReachParts(env, client, signIn)); + const uniqueKeys = [...new Set(summaries.map((item) => item.key))]; + const sharedReach = uniqueKeys.length === 1 ? summaries[0]! : null; + + if (client.signIns.length === 1) { + const [only] = client.signIns; + const reach = summaries[0]!; + return `<li class="access" data-client="${text(client.clientId)}" data-access="${text(only!.id)}"> + ${tileOf(client)} + <div class="row-title"><strong>${text(name)}</strong>${whose ? ` <span class="muted">of ${text(whose)}</span>` : ""}</div> + <div class="row-meta"> + <div class="meta-line"><div class="meta-track">${metaLine(reach.badges, [reach.target, origin])}</div></div> + <div class="meta-line"><div class="meta-track">${metaItems(timesOf(only!, now))}</div></div> + </div> + ${end({ signIn: only!.id }, word, `${actionPhrase(word, name)}${ofWhom}`)} + </li>`; + } + + const latestMs = Math.max( + ...client.signIns.map((signIn) => (signIn.renewedAt ?? signIn.createdAt) * 1000), + ); + const summaryLine = sharedReach + ? metaLine(sharedReach.badges, [ + sharedReach.target, + origin, + `Latest ${pastTimeTag(latestMs, now)}`, + ]) + : metaItems([origin, `Latest ${pastTimeTag(latestMs, now)}`]); + const items = client.signIns + .map((signIn, index) => { + const reach = summaries[index]!; + const line = sharedReach + ? metaItems(timesOf(signIn, now)) + : metaLine(reach.badges, [reach.target, ...timesOf(signIn, now)]); + const started = pastLabel(signIn.createdAt * 1000, now); + return `<li data-access="${text(signIn.id)}"> + <span class="meta-line"><span class="meta-track">${line}</span></span> + ${end({ signIn: signIn.id }, word, `${actionPhrase(word, name)} sign-in from ${started}${ofWhom}`)} + </li>`; + }) + .join(""); + + return `<li class="access" data-client="${text(client.clientId)}"> + ${tileOf(client)} + <div class="row-title"><strong>${text(name)}</strong>${whose ? ` <span class="muted">of ${text(whose)}</span>` : ""}</div> + <div class="row-meta"> + <div class="meta-line"><div class="meta-track">${summaryLine}</div></div> + </div> + ${end({ client: client.clientId }, `${word} all ${client.signIns.length}`, `${word} all ${client.signIns.length} sign-ins of ${name}${ofWhom}`)} + <details class="access-details"> + <summary>${client.signIns.length} sign-ins</summary> + <ul class="access-sessions">${items}</ul> + </details> + </li>`; +} + +const metaItems = (parts: string[]) => + parts + .filter(Boolean) + .map((part) => `<span class="meta-item">${part}</span>`) + .join(" "); + +const metaLine = (badges: string, parts: string[]) => + [badges, metaItems(parts)].filter(Boolean).join(" "); + +const actionPhrase = (word: "Sign out" | "Revoke", name: string) => + word === "Sign out" ? `Sign out of ${name}` : `Revoke ${name}`; + +const text = (value: string) => + value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); + +const nameOf = (client: ClientWithAccess) => client.name || "An app"; + +/** The icon of one of the mind's own apps: its client's logo, which counts from the app's own + * origin alone. */ +const ownIconOf = (client: ClientWithAccess) => + client.host && + URL.canParse(client.logoUri || "") && + new URL(client.logoUri!).origin === client.host + ? client.logoUri! + : null; + +/** The client's mark. One of the mind's own apps has its own icon or its initials, as on the + * sign-in pages (./asking-app.ts), and never a built-in brand mark. Any other client has the + * mark of ./client-mark.ts. */ +const tileOf = (client: ClientWithAccess) => + client.host + ? appTile({ name: nameOf(client), icon: ownIconOf(client) }, { small: true }) + : clientTile( + { + name: nameOf(client), + redirectUri: client.redirectUri || "", + redirectHost: client.goesTo || "", + logoUri: client.logoUri, + clientDomain: client.clientDomain, + }, + { small: true }, + ); + +/** Where the client's access goes, or how it signed in. */ +function clientOriginWords(client: ClientWithAccess): string { + if (client.host) return "This mind's page"; + if (client.device) return "Device sign-in"; + return client.goesTo ? `goes to ${text(client.goesTo)}` : ""; +} + +const SCOPE_LABELS: Record<string, { label: string; strong: boolean }> = { + iterate: { label: "Whole mind", strong: true }, + identity: { label: "Identity only", strong: false }, +}; + +function signInReachParts(env: Env, client: ClientWithAccess, signIn: SignIn) { + const badges = signIn.scopes + .map((scope) => { + const known = SCOPE_LABELS[scope]; + if (!known) return `<span class="badge">${text(scope)}</span>`; + return `<span class="badge${known.strong ? " badge-strong" : ""}">${known.label}</span>`; + }) + .join(" "); + const rawTarget = reachTargetOf(env, signIn); + // A host app whose title is already its hostname needs no second copy of that hostname. + const target = client.host && rawTarget === nameOf(client) ? "" : text(rawTarget); + return { key: `${signIn.scopes.join(",")}|${rawTarget}`, badges, target }; +} + +/** The resource a sign-in's tokens reach, in short form. */ +function reachTargetOf(env: Env, signIn: SignIn): string { + const config = configOf(env); + const { resource } = signIn; + if (!resource) return "Mind & pages"; + if (resource === mindMcpUrlOf(config.controlPlaneHostname)) return "MCP"; + if (resource === mindProvideConnectResourceOf(config.controlPlaneHostname)) + return "Hands in this mind"; + const host = mindHostResourceOf(config, resource); + if (!host) return new URL(resource).pathname; + const { pathname } = new URL(resource); + return pathname.length > 1 ? `${new URL(host).host}${pathname}` : new URL(host).host; +} + +/** Compact lifecycle timestamps of one sign-in: most recent use first, creation, and expiry. */ +function timesOf(signIn: SignIn, now: number): string[] { + const createdMs = signIn.createdAt * 1000; + if (signIn.until) { + return [ + `Since ${pastTimeTag(createdMs, now)}`, + `until ${untilTimeTag(signIn.until, now)}`, + "no renewal", + ]; + } + if (!signIn.endsAt) return [`Since ${pastTimeTag(createdMs, now)}`]; + const endsMs = signIn.endsAt * 1000; + if (!signIn.renews) { + return [`Signed in ${pastTimeTag(createdMs, now)}`, `ends ${futureTimeTag(endsMs, now)}`]; + } + const parts = signIn.renewedAt + ? [`Used ${pastTimeTag(signIn.renewedAt * 1000, now)}`, `since ${pastTimeTag(createdMs, now)}`] + : [`Since ${pastTimeTag(createdMs, now)}`]; + parts.push(`ends ${futureTimeTag(endsMs, now)} if idle`); + return parts; +} + +const MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; + +function shortDate(atMs: number, now: number): string { + const date = new Date(atMs); + const day = date.getUTCDate(); + const month = MONTHS[date.getUTCMonth()]!; + const year = date.getUTCFullYear(); + return year === new Date(now).getUTCFullYear() ? `${day} ${month}` : `${day} ${month} ${year}`; +} + +function pastLabel(atMs: number, now: number): string { + const diff = now - atMs; + if (diff >= 0 && diff < 60_000) return "just now"; + if (diff >= 60_000 && diff < 3_600_000) return `${Math.floor(diff / 60_000)} m ago`; + if (diff >= 3_600_000 && diff < 86_400_000) return `${Math.floor(diff / 3_600_000)} h ago`; + if (diff >= 86_400_000 && diff < 7 * 86_400_000) return `${Math.floor(diff / 86_400_000)} d ago`; + return shortDate(atMs, now); +} + +function futureLabel(atMs: number, now: number): string { + const diff = atMs - now; + if (diff > 0 && diff < 60_000) return "in <1 m"; + if (diff >= 60_000 && diff < 3_600_000) return `in ${Math.ceil(diff / 60_000)} m`; + if (diff >= 3_600_000 && diff < 86_400_000) return `in ${Math.round(diff / 3_600_000)} h`; + return shortDate(atMs, now); +} + +function untilTimeTag(untilMs: number, now: number): string { + const diff = untilMs - now; + if (diff > 0 && diff < 86_400_000) return timeTag(untilMs, futureLabel(untilMs, now)); + const clock = new Date(untilMs).toISOString().slice(11, 16); + return timeTag(untilMs, `${shortDate(untilMs, now)}, ${clock} UTC`); +} + +const futureTimeTag = (atMs: number, now: number) => timeTag(atMs, futureLabel(atMs, now)); + +function timeTag(atMs: number, label: string): string { + const iso = new Date(atMs).toISOString().replace(".000Z", "Z"); + const utc = `${new Date(atMs).toISOString().slice(0, 16).replace("T", " ")} UTC`; + return `<time datetime="${iso}" title="${utc}">${text(label)}</time>`; +}
A core/auth-worker/src/access-sign-in.test.ts
@@ -0,0 +1,277 @@ +// What a token of Cloudflare Access opens (./access-sign-in.ts), through the Worker's own router +// and SQL: for an owner with no passkey yet the one session that adds the first passkey, and for +// anything else nothing, with words that say what to do. The team's keys are read where the team +// publishes them: `fetch` answers that one address with this file's own key. +import { exportJWK, generateKeyPair, type JWTPayload, SignJWT } from "jose"; +import { expect, test, vi } from "vitest"; +import type { Env } from "./env.ts"; +import { authResponse } from "./http.ts"; +import { sqliteStack } from "./test-support.ts"; + +const ISSUER = "https://iterate.example.com"; +const TEAM = "https://team.cloudflareaccess.com"; +const KEY_ID = "the-teams-key"; + +const team = await generateKeyPair("RS256"); +// a key that is not the team's, which names the team's key +const stranger = await generateKeyPair("RS256"); +const teamKeySet = { keys: [{ ...(await exportJWK(team.publicKey)), kid: KEY_ID, alg: "RS256" }] }; + +test("a token for an owner with no passkey yet opens the session that adds the first passkey, and nothing else", async () => { + const { env, db } = sqliteStack(); + const answer = await ask(env, "/sign-in/access", await tokenOf()); + expect({ status: answer.status, location: answer.headers.get("location") }).toEqual({ + status: 303, + location: `/keys/first?next=${encodeURIComponent("https://onboarding.example.com/")}`, + }); + // the row's kind is this proof's own (./enrolment.ts `Proof`) + expect(db.prepare("select method, key_id from browser_sessions").all()).toEqual([ + { method: "cloudflare-access", key_id: null }, + ]); + const cookie = sessionCookieOf(answer); + const form = await ask(env, "/keys/first", null, cookie); + expect(await form.text()).toContain(`<button type="submit">Add a passkey</button>`); + // to every other page the browser is signed out + const keys = await ask(env, "/keys", null, cookie); + expect(keys.headers.get("location")).toBe(`${ISSUER}/sign-in?next=%2Fkeys`); +}); + +test("the sign-in goes on to the `next` it was given, when that is an explicit address of the mind's own; bare control-plane root falls back to onboarding", async () => { + const { env } = sqliteStack(); + const locationFor = async (next: string) => + ( + await ask(env, `/sign-in/access?${new URLSearchParams({ next })}`, await tokenOf()) + ).headers.get("location"); + expect([ + await locationFor("https://dash.example.com/agents"), + await locationFor("/oauth2/auth?client_id=onboarding"), + await locationFor("/"), + await locationFor("https://iterate.example.com/"), + await locationFor("https://elsewhere.example.net/"), + ]).toEqual([ + `/keys/first?next=${encodeURIComponent("https://dash.example.com/agents")}`, + `/keys/first?next=${encodeURIComponent("https://iterate.example.com/oauth2/auth?client_id=onboarding")}`, + `/keys/first?next=${encodeURIComponent("https://onboarding.example.com/")}`, + `/keys/first?next=${encodeURIComponent("https://onboarding.example.com/")}`, + `/keys/first?next=${encodeURIComponent("https://onboarding.example.com/")}`, + ]); +}); + +test("new owner path from /sign-in (no next) through Cloudflare Access lands on the onboarding wizard, never the control-plane root", async () => { + const { env } = sqliteStack(); + const signInHtml = await (await ask(env, "/sign-in", null)).text(); + const match = + /<form method="get" action="(\/sign-in\/access)" class="stack">\s*<input type="hidden" name="(next)" value="([^"]+)">/.exec( + signInHtml, + ); + expect(match?.slice(1)).toEqual(["/sign-in/access", "next", "/"]); + const accessAnswer = await ask(env, "/sign-in/access?next=%2F", await tokenOf()); + expect({ + status: accessAnswer.status, + location: accessAnswer.headers.get("location"), + }).toEqual({ + status: 303, + location: `/keys/first?next=${encodeURIComponent("https://onboarding.example.com/")}`, + }); +}); + +test.for([ + { + passkey: "has a passkey", + removedAt: null, + words: + "owner@example.net has a passkey for iterate.example.com, so nothing else signs it in. Sign in with the passkey.", + }, + { + passkey: "had a passkey, which was removed", + removedAt: 1, + words: + "owner@example.net had a passkey for iterate.example.com, so Cloudflare's proof of the address signs it in no more. An owner with no passkey left gets back in by the recovery command, which whoever holds this mind's Cloudflare account runs.", + }, +])( + "an owner who $passkey is refused, with words that say what to do", + async ({ removedAt, words }) => { + const { env, db } = sqliteStack(); + db.exec("insert into users (id, email) values ('user_owner', 'owner@example.net')"); + db.prepare( + `insert into keys (id, user_id, public_key, format, label, added_via, added_by, added_at, revoked_at) + values ('a-passkey', 'user_owner', 'a-public-key', 'webauthn', 'A phone', 'keys-page', 'user_owner', 0, ?)`, + ).run(removedAt); + expect(await refusalOf(env, await tokenOf())).toEqual({ status: 403, words, session: "" }); + }, +); + +test.for<{ name: string; token: () => Promise<string> }>([ + { + name: "a token for another application of the team", + token: () => tokenOf({ aud: ["another-applications-audience-tag"] }), + }, + { + name: "a token of another team", + token: () => tokenOf({ iss: "https://another-team.cloudflareaccess.com" }), + }, + { + name: "a token of the team's own session, not of an application", + token: () => tokenOf({ type: "org" }), + }, + { + name: "a token that is not valid yet", + token: () => tokenOf({ nbf: Math.floor(Date.now() / 1000) + 600 }), + }, + { name: "a token with no end", token: () => tokenOf({ exp: undefined }) }, + { + name: "a token with no email: a service token's", + token: () => tokenOf({ email: undefined, common_name: "a-service-token" }), + }, + { + name: "a token that another key signed under the team's key id", + token: () => tokenOf({}, stranger.privateKey), + }, + { + name: "a token with a changed byte", + token: async () => { + const [header, payload, signature] = (await tokenOf()).split("."); + const changed = payload!.replace(/.$/, (last) => (last === "A" ? "B" : "A")); + return [header, changed, signature].join("."); + }, + }, + { + name: "a token signed with a shared secret, not with the team's key", + token: () => + new SignJWT(claimsOf({})) + .setProtectedHeader({ alg: "HS256", kid: KEY_ID }) + .sign(new TextEncoder().encode("a secret that anyone may know, of 32 bytes")), + }, + { name: "text that is no token", token: async () => "not.a.token" }, +])("$name is no proof that Cloudflare Access made for this mind", async ({ token }) => { + const { env, db } = sqliteStack(); + expect(await refusalOf(env, await token())).toEqual({ + status: 403, + words: + "This is no proof of an email address that Cloudflare Access made for iterate.example.com. Sign in again.", + session: "", + }); + expect(db.prepare("select count(*) as sessions from browser_sessions").get()).toEqual({ + sessions: 0, + }); +}); + +test.for<{ name: string; token: () => Promise<string | null>; words: string }>([ + { + name: "no token", + token: async () => null, + words: + "Cloudflare Access sent no proof of an email address with this request, so it signs nobody in. Sign in with your passkey.", + }, + { + name: "a token that is over", + token: () => tokenOf({ exp: Math.floor(Date.now() / 1000) - 60 }), + words: "Cloudflare's proof of your email address is over. Sign in again.", + }, + { + name: "a token for an address that is no owner's", + token: () => tokenOf({ email: "member@example.net" }), + words: + "member@example.net is not an owner of iterate.example.com, and Cloudflare Access signs in an owner alone. Sign in with your passkey.", + }, + { + // an added member is no owner: an owner's sign-in link is that member's way in + name: "a token for an added member's address", + token: () => tokenOf({ email: "added@example.net" }), + words: + "added@example.net is not an owner of iterate.example.com, and Cloudflare Access signs in an owner alone. Sign in with your passkey.", + }, + { + name: "a token for an owner's address with a tag", + token: () => tokenOf({ email: "owner+tag@example.net" }), + words: + "owner+tag@example.net is not an owner of iterate.example.com, and Cloudflare Access signs in an owner alone. Sign in with your passkey.", + }, +])("$name is refused, and the page says what to do", async ({ token, words }) => { + const { env, db } = sqliteStack(); + db.exec( + "insert into members (email, added_by, added_at) values ('added@example.net', 'owner@example.net', 0)", + ); + expect(await refusalOf(env, await token())).toEqual({ status: 403, words, session: "" }); + expect(db.prepare("select count(*) as sessions from browser_sessions").get()).toEqual({ + sessions: 0, + }); +}); + +test.for([ + { name: "the sign-in page", path: "/sign-in", method: "GET" }, + { name: "the first passkey's page", path: "/keys/first", method: "GET" }, + { name: "a path under the application's", path: "/sign-in/access/", method: "GET" }, + { name: "a POST to the application's path", path: "/sign-in/access", method: "POST" }, +])("a good token on $name opens nothing: it counts on one path alone", async ({ path, method }) => { + const { env, db } = sqliteStack(); + const answer = await ask(env, path, await tokenOf(), "", method); + expect(answer).not.toMatchObject({ status: 303 }); + expect(sessionCookieOf(answer)).toBe(""); + expect(db.prepare("select count(*) as sessions from browser_sessions").get()).toEqual({ + sessions: 0, + }); +}); + +test("the sign-in page has an owner's way to Cloudflare Access, with where the sign-in goes on", async () => { + const page = await ask(sqliteStack().env, "/sign-in?next=%2Fkeys", null); + expect(await page.text()).toMatch( + /<form method="get" action="\/sign-in\/access" class="stack">\s*<input type="hidden" name="next" value="\/keys">\s*<button type="submit">Set up your first passkey<\/button>/, + ); +}); + +/** What Cloudflare Access puts in an application's token for a person's sign-in, with `over` in + * place of its claims: an `undefined` leaves a claim out. */ +function claimsOf(over: JWTPayload): JWTPayload { + const now = Math.floor(Date.now() / 1000); + return { + aud: ["the-audience-tag-of-the-owners-application"], + email: "owner@example.net", + exp: now + 900, + iat: now, + nbf: now, + iss: TEAM, + type: "app", + sub: "a-person-of-the-team", + ...over, + }; +} + +const tokenOf = (over: JWTPayload = {}, key = team.privateKey) => + new SignJWT(claimsOf(over)).setProtectedHeader({ alg: "RS256", kid: KEY_ID }).sign(key); + +/** One request to the Worker, with `token` as Cloudflare Access sends it on. The team's keys are + * at the one address that the team publishes them at. */ +function ask(env: Env, path: string, token: string | null, cookie = "", method = "GET") { + vi.stubGlobal("fetch", async (address: string | URL) => { + expect(String(address)).toBe(`${TEAM}/cdn-cgi/access/certs`); + return Response.json(teamKeySet); + }); + const headers = new Headers({ cookie }); + if (token) headers.set("cf-access-jwt-assertion", token); + return authResponse( + new Request(`${ISSUER}${path}`, { method, headers }), + env, + // the cast: these pages hand the runtime nothing to keep alive + {} as ExecutionContext, + ); +} + +const sessionCookieOf = (answer: Response) => + answer.headers + .getSetCookie() + .map((cookie) => cookie.split(";")[0]!) + .find((cookie) => cookie.startsWith("__Host-iterate-auth-session=")) || ""; + +/** The refusal's page for `token` on the application's path: its words, and no session. */ +async function refusalOf(env: Env, token: string | null) { + const answer = await ask(env, "/sign-in/access", token); + const html = (await answer.text()).replaceAll(/&#(\d+);/g, (_all, code) => + String.fromCharCode(Number(code)), + ); + return { + status: answer.status, + words: html.match(/<h1>You can't continue<\/h1><p>([^<]*)<\/p>/)?.[1], + session: sessionCookieOf(answer), + }; +}
A core/auth-worker/src/access-sign-in.ts
@@ -0,0 +1,87 @@ +// access-sign-in.ts — CLOUDFLARE ACCESS PROVES AN OWNER'S ADDRESS. The stack puts one Access +// application on this one path of the control plane (core/alchemy/src/stack.ts), whose policy +// names the mind's owners alone. Cloudflare asks a visitor there for an address, mails a +// six-digit code from its own domain and, after the code, sends the request on with a token that +// it signed: the header `cf-access-jwt-assertion` +// (https://developers.cloudflare.com/cloudflare-one/access-controls/applications/http-apps/authorization-cookie/validating-json/). +// +// GET /sign-in/access the token names an owner: the one session that may add the first +// passkey (./enrolment.ts), then that page +// +// THE SIGNATURE IS THE GUARANTEE, NOT THE EDGE: the Worker checks the token itself, against the +// keys that the account's team publishes, so a request that reached it some other way proves +// nothing. The header counts on this path alone. It is the one proof of an address that the mind +// takes for an owner, and ./enrolment.ts decides what it opens: nothing for an owner who has, or +// had, a passkey. Access is for owners only: an added member gets in by an owner's link, and an +// app's own people by the mind's own mailed code (./email-sign-in.ts), so none of them takes a +// seat of the account's team. +import { createRemoteJWKSet, errors, jwtVerify } from "jose"; +import { z } from "zod"; +import { enrolmentCookie, FIRST_PASSKEY_PATH } from "./enrolment.ts"; +import { configOf, type Env, explicitFirstPasskeyNext, onboardingOf } from "./env.ts"; +import { errorPage } from "./pages.ts"; +import { signInHref } from "./sign-in.ts"; + +/** What the Worker reads of a token's claims, beyond those that jose checks. `type` is `app` for + * a token of an application; a person's sign-in names an `email`, a service token's none. */ +const AccessClaims = z.object({ type: z.literal("app"), email: z.email().toLowerCase() }); + +export async function accessSignInResponse(env: Env, request: Request) { + const url = new URL(request.url); + if (url.pathname !== "/sign-in/access" || request.method !== "GET") return null; + const config = configOf(env); + const mind = config.controlPlaneHostname; + const next = explicitFirstPasskeyNext(url.searchParams.get("next"), env) || onboardingOf(env); + const refusal = (outcome: string, words: string) => { + console.info({ event: "auth.cloudflare-access-proof", outcome }); + return errorPage(words, 403, undefined, [{ href: signInHref(next), label: "Sign in" }]); + }; + const token = request.headers.get("cf-access-jwt-assertion"); + if (!token) + return refusal( + "no token", + "Cloudflare Access sent no proof of an email address with this request, so it signs nobody in. Sign in with your passkey.", + ); + const team = `https://${config.cloudflareAccessTeamDomain}`; + // jose checks the signature, and `exp` and `nbf`. What it refuses is a token's fault, or the + // team's keys that could not be read: its words go to the log. + const claims = await jwtVerify(token, teamKeysOf(team), { + algorithms: ["RS256"], + issuer: team, + audience: config.cloudflareAccessAudienceTag, + requiredClaims: ["exp"], + }).then( + ({ payload }) => AccessClaims.safeParse(payload), + (error: unknown) => (error instanceof errors.JOSEError ? error : Promise.reject(error)), + ); + if (claims instanceof errors.JWTExpired) + return refusal("expired", "Cloudflare's proof of your email address is over. Sign in again."); + if (claims instanceof errors.JOSEError || !claims.success) + return refusal( + claims instanceof errors.JOSEError ? claims.message : "no token of a person's sign-in", + `This is no proof of an email address that Cloudflare Access made for ${mind}. Sign in again.`, + ); + const opened = await enrolmentCookie(env, request, claims.data.email, "cloudflare-access"); + // an address that is no owner's, or an owner who has or had a passkey: the page says which + if ("refused" in opened) return refusal("no owner with no passkey yet", opened.refused); + console.info({ event: "auth.cloudflare-access-proof", outcome: "proven" }); + return opened.facts.on( + new Response(null, { + status: 303, + headers: { + location: `${FIRST_PASSKEY_PATH}?${new URLSearchParams({ next })}`, + "set-cookie": opened.setCookie, + "cache-control": "no-store", + }, + }), + ); +} + +// One reader of the team's keys for an isolate. jose keeps the keys for ten minutes, and reads +// them again sooner when a token names a key that is not among them, at most once in 30 seconds. +const teamKeys = new Map<string, ReturnType<typeof createRemoteJWKSet>>(); +function teamKeysOf(team: string) { + const known = teamKeys.get(team) || createRemoteJWKSet(new URL(`${team}/cdn-cgi/access/certs`)); + teamKeys.set(team, known); + return known; +}
A core/auth-worker/src/account-facts.ts
@@ -0,0 +1,167 @@ +import { type Facts, withFacts } from "iterate/facts"; +import type { Envelope } from "iterate/signed"; +import { z } from "zod"; + +/** `session`: the browser's session it opened (./cookies.ts `sessionCookie`). */ +const session = z.string().min(1); +const SignedIn = z.union([ + z.object({ method: z.literal("passkey"), key: z.string().min(1), session, at: z.number() }), + // a proof that opens the session that may add a first passkey (./enrolment.ts `Proof`) + z.object({ + method: z.enum(["cloudflare-access", "member-link", "recovery-link"]), + session, + at: z.number(), + }), + // a mailed code that proved the address of a person who is no member (./email-sign-in.ts) + z.object({ method: z.literal("email"), session, at: z.number() }), + // another mind vouched that this person is its member (./mind-sign-in.ts): that mind's id and + // hostname. No session row: the cookie is the session (./cookies.ts `mindSessionCookie`) + z.object({ + method: z.literal("mind"), + mind: z.string().min(1), + hostname: z.string().min(1), + at: z.number(), + }), +]); +/** This mind vouched for its member to another mind (./vouch.ts): that mind's id and hostname. */ +const SignInVouched = z.object({ + mind: z.string().min(1), + hostname: z.string().min(1), + at: z.number(), +}); +/** A new guest (./guest-sign-in.ts): the name they typed, and the host of the app that let them + * come. Once for each guest: the sessions a guest earns later write nothing. */ +const GuestSignedIn = z.object({ + userId: z.string().min(1), + name: z.string().min(1), + app: z.string().min(1), + at: z.number(), +}); +/** A guest was not let in. "rate": the stack's bound on new guests is reached; "session-rate": + * its bound on guests' sessions; "blocked": an owner blocked this guest. At most one for each + * reason in ten minutes, however many were refused. */ +const GuestRefused = z.object({ + reason: z.enum(["rate", "session-rate", "blocked"]), + app: z.string().min(1), + at: z.number(), +}); +/** A browser's session ended: at sign-out, on /sessions, or with its person's removal. */ +const SessionEnded = z.object({ session, at: z.number() }); +const ConsentApproved = z.object({ + clientId: z.string().min(1), + clientName: z.string(), + minds: z.null(), + scopes: z.array(z.string()), +}); +const GrantEnded = z.object({ grantId: z.string().min(1) }); +/** The key that signed a change which lets more act (./signed-change.ts), and what it signed. */ +const SignedBy = z.object({ + signer: z.object({ + principal: z.object({ actor: z.string(), email: z.string() }), + key: z.string(), + label: z.string(), + }), + signed: z.custom<Envelope>(), +}); +const KeyAdded = z.union([ + // `signer` and `signed`: on each passkey but a person's first + SignedBy.partial().extend({ + key: z.string().min(1), + label: z.string(), + format: z.literal("webauthn"), + at: z.number(), + }), + z.object({ + key: z.string().min(1), + label: z.string(), + format: z.literal("p256"), + at: z.number(), + actor: z.string(), + paths: z.array(z.string()), + /** The capability the key's token may lend, `itx.<provide>`, when it has one. */ + provide: z.string().optional(), + /** The iterate Cloud's origin that published the key, for the actor `iterate-cloud`. */ + cloud: z.string().optional(), + addedBy: z.string(), + }), +]); +const KeyRemoved = z.object({ + key: z.string().min(1), + label: z.string(), + actor: z.string().optional(), + at: z.number(), + /** The owner's user id, when an owner removed a member's key on /members. */ + removedBy: z.string().optional(), +}); +const MemberRemoved = z.object({ email: z.string().min(1) }); +const PersonBlocked = z.object({ email: z.string().min(1) }); +const MemberLinkMade = z.object({ email: z.string().min(1), expires: z.number() }); +const MemberAdded = SignedBy.extend({ email: z.string().min(1) }); +/** A device's request that a member's passkey signed to continue (./device/page.ts), as the page + * showed it. The grant itself is `consent-approved`, and for a let-in `let-in-approved`. */ +const DeviceConfirmed = SignedBy.extend({ + userCode: z.string().min(1), + clientId: z.string().min(1), + clientName: z.string(), + resource: z.string(), + letIn: z.object({ seconds: z.number().int(), reason: z.string() }).optional(), +}); +const LetInApproved = z.object({ + grantId: z.string().min(1), + clientId: z.string().min(1), + clientName: z.string(), + reason: z.string(), + until: z.number().int().positive(), // epoch ms + signer: z.object({ actor: z.string(), key: z.string() }).optional(), +}); + +export type AccountFact = ( + | { type: "events.iterate.com/account/signed-in"; payload: z.infer<typeof SignedIn> } + | { + type: "events.iterate.com/account/consent-approved"; + payload: z.infer<typeof ConsentApproved>; + } + | { type: "events.iterate.com/account/grant-ended"; payload: z.infer<typeof GrantEnded> } + | { type: "events.iterate.com/account/session-ended"; payload: z.infer<typeof SessionEnded> } + | { type: "events.iterate.com/account/member-added"; payload: z.infer<typeof MemberAdded> } + | { type: "events.iterate.com/account/member-removed"; payload: z.infer<typeof MemberRemoved> } + | { + type: "events.iterate.com/account/member-link-made"; + payload: z.infer<typeof MemberLinkMade>; + } + | { type: "events.iterate.com/account/person-blocked"; payload: z.infer<typeof PersonBlocked> } + | { type: "events.iterate.com/account/person-unblocked"; payload: z.infer<typeof PersonBlocked> } + | { type: "events.iterate.com/account/let-in-approved"; payload: z.infer<typeof LetInApproved> } + | { + type: "events.iterate.com/account/device-confirmed"; + payload: z.infer<typeof DeviceConfirmed>; + } + | { type: "events.iterate.com/account/key-added"; payload: z.infer<typeof KeyAdded> } + | { type: "events.iterate.com/account/key-removed"; payload: z.infer<typeof KeyRemoved> } + | { + type: "events.iterate.com/account/guest-signed-in"; + payload: z.infer<typeof GuestSignedIn>; + } + | { type: "events.iterate.com/account/guest-refused"; payload: z.infer<typeof GuestRefused> } + | { + type: "events.iterate.com/account/sign-in-vouched"; + payload: z.infer<typeof SignInVouched>; + } +) & { idempotencyKey?: string }; + +// A record for the mind, never the authority: members and live grants are this Worker's D1 and KV. +export class AccountFacts { + readonly #facts: Facts = []; + + add(userId: string, fact: AccountFact) { + this.#facts.push({ path: `/users/${userId}`, events: [fact] }); + } + + addToMind(fact: AccountFact) { + this.#facts.push({ path: "/", events: [fact] }); + } + + on(response: Response): Response { + return withFacts(response, this.#facts); + } +}
A core/auth-worker/src/asking-app.test.ts
@@ -0,0 +1,569 @@ +// The app of the mind that a sign-in is for: which requests name one, what an app says of itself, +// and what the sign-in pages then show. +import type { SignInMethod } from "iterate/principal"; +import { expect, test, vi } from "vitest"; +import { appOf, appTile, askingAppOf, saidIn, signInOf } from "./asking-app.ts"; +import { emailSignInResponse } from "./email-sign-in.ts"; +import type { Env } from "./env.ts"; +import { hostCallbackOf, hostClientOf, oauthHelpers } from "./oauth.ts"; +import { appSignIn, chooserPage, consentPage, signInPage } from "./pages.ts"; +import { configVars } from "./test-support.ts"; + +const MIND = "iterate.example.com"; +// the mind's one zone, where its apps' hosts are +const DOMAIN = "example.com"; +const HOST = `guestbook.${DOMAIN}`; +const ORIGIN = `https://${HOST}`; +const DESCRIPTION = `${ORIGIN}/.well-known/iterate-app`; +// how the people of an app sign in when the app names no method: for anyone, and for members. A +// member signs in with a passkey and nothing else, at an app for members as at the control plane. +const FOR_ANYONE = ["email", "passkey"]; +const FOR_MEMBERS = ["passkey"]; + +test("an app is read from a sign-in's request only when the stack holds all three of its parts", async () => { + const stack = stackWith({ [HOST]: { name: "Guestbook", icon: `${ORIGIN}/icon.svg` } }); + const client = await hostClientOf(stack.env, HOST); + const next = (change: Record<string, string> = {}) => + `/oauth2/auth?${new URLSearchParams({ + response_type: "code", + client_id: client, + redirect_uri: hostCallbackOf(ORIGIN), + resource: ORIGIN, + scope: "identity", + state: "s", + ...change, + })}`; + // the request that the host's own page makes + expect(await askingAppOf(stack.env, next())).toEqual({ + host: HOST, + origin: ORIGIN, + name: "Guestbook", + icon: `${ORIGIN}/icon.svg`, + members: false, + signIn: FOR_ANYONE, + }); + // a path on the host is the host, as the authorization endpoint reads it + expect(await askingAppOf(stack.env, next({ resource: `${ORIGIN}/mcp` }))).toMatchObject({ + host: HOST, + }); + // one part that is another's, and the page is the mind's own + for (const forged of [ + next({ client_id: "another-client" }), + next({ redirect_uri: "https://elsewhere.test/callback" }), + next({ redirect_uri: `https://docs.${DOMAIN}/.iterate/callback` }), + next({ resource: "https://guestbook.elsewhere.test" }), + next({ resource: `https://${MIND}` }), + // a host of the mind that never asked for a sign-in has no client + next({ + resource: `https://docs.${DOMAIN}`, + redirect_uri: hostCallbackOf(`https://docs.${DOMAIN}`), + }), + next().replace("/oauth2/auth", "/keys"), + `https://elsewhere.test${next()}`, + "/", + ]) + expect(await askingAppOf(stack.env, forged)).toBeNull(); +}); + +const NOTHING = { name: null, icon: null, members: false, signIn: FOR_ANYONE }; + +test.for([ + { + name: "its name, and its icon as a path on its own origin", + description: { name: "Guestbook", icon: "/icon.svg" }, + said: { name: "Guestbook", icon: `${ORIGIN}/icon.svg` }, + }, + { + name: "a path that names another host is no icon, and the name still counts", + description: { name: "Guestbook", icon: "//elsewhere.test/logo.png" }, + said: { name: "Guestbook" }, + }, + { + name: "a backslash names another host as a slash does", + description: { name: "Guestbook", icon: "/\\elsewhere.test/logo.png" }, + said: { name: "Guestbook" }, + }, + { + name: "a name is one line of sixty characters", + description: { name: ` Guest\nbook ${"x".repeat(80)}` }, + said: { name: `Guest book ${"x".repeat(49)}` }, + }, + { + name: "an app for the mind's members says so, and its people sign in by a passkey alone", + description: { name: "Dash", for: "members" }, + said: { name: "Dash", members: true, signIn: FOR_MEMBERS }, + }, + { + name: "an app names its sign-in methods, in its order", + description: { name: "Guestbook", signIn: ["passkey", "email"] }, + said: { name: "Guestbook", signIn: ["passkey", "email"] }, + }, + { + name: "an app that names the passkey alone", + description: { name: "Guestbook", signIn: ["passkey"] }, + said: { name: "Guestbook", signIn: ["passkey"] }, + }, + { + // taken as it is written: the app's own code decides + name: "an app for members that names the mailed code first", + description: { name: "Dash", for: "members", signIn: ["email", "passkey"] }, + said: { name: "Dash", members: true, signIn: ["email", "passkey"] }, + }, + { + name: "a method named twice is named once", + description: { name: "Guestbook", signIn: ["email", "email"] }, + said: { name: "Guestbook", signIn: ["email"] }, + }, + { + name: "what a browser's manifest would say is passed over", + description: { name: "Guestbook", short_name: "Book", icons: [{ src: "/other.svg" }] }, + said: { name: "Guestbook" }, + }, + // a text that is no description says nothing at all: the app is its host, for anyone + { + name: "a method that this issuer does not know", + description: { name: "G", signIn: ["email", "google"] }, + said: {}, + }, + { name: "an empty list of methods", description: { name: "G", signIn: [] }, said: {} }, + { name: "methods that are no list", description: { name: "G", signIn: "email" }, said: {} }, + { + name: "any other word than 'members'", + description: { name: "Dash", for: "everyone" }, + said: {}, + }, + { + name: "an icon that is no path", + description: { name: "G", icon: "https://elsewhere.test/logo.png" }, + said: {}, + }, + { name: "no name", description: { icon: "/icon.svg", signIn: ["passkey"] }, said: {} }, + { name: "a name that is no text", description: { name: 7 }, said: {} }, + { name: "not an object", description: ["Guestbook"], said: {} }, +])("what an app's description says: $name", ({ description, said }) => { + expect(saidIn(JSON.stringify(description), DESCRIPTION)).toEqual({ ...NOTHING, ...said }); +}); + +test("a description that is no JSON, is empty or is too long says nothing", () => { + for (const text of ["", "<!doctype html>", `{"name":"${"x".repeat(20_000)}"}`]) + expect(saidIn(text, DESCRIPTION)).toEqual(NOTHING); +}); + +test("the description is read at its well-known path once in five minutes, with no redirect followed, and the host's own client then holds the app's name and icon", async () => { + const stack = stackWith({}); + const client = await hostClientOf(stack.env, HOST); + using web = answers({ name: "Guestbook", icon: "/icon.svg", signIn: ["passkey"] }); + const before = Date.now(); + const app = await appOf(stack.env, ORIGIN); + expect(app).toEqual({ + host: HOST, + origin: ORIGIN, + name: "Guestbook", + icon: `${ORIGIN}/icon.svg`, + members: false, + signIn: ["passkey"], + }); + expect(await appOf(stack.env, ORIGIN)).toEqual(app); + // the one address that is asked: no web app manifest is read + expect(web).toMatchObject({ asked: [[DESCRIPTION, "manual"]] }); + expect(stack.askedAgainIn(HOST, before)).toBe("5 minutes"); + // five minutes later it is asked again, and no sooner + stack.due(HOST); + await appOf(stack.env, ORIGIN); + expect(web.asked).toHaveLength(2); + // the OAuth client that the host signs in with is that app now, for any list of clients + expect(await oauthHelpers(stack.env, ORIGIN).lookupClient(client)).toMatchObject({ + clientName: "Guestbook", + logoUri: `${ORIGIN}/icon.svg`, + }); +}); + +test.for([ + { name: "a 503", answer: () => new Response("Unavailable\n", { status: 503 }) }, + { + name: "no answer", + answer: () => { + throw new TypeError("fetch failed"); + }, + }, + { + name: "an answer that breaks off", + answer: () => + new Response(new ReadableStream({ start: (stream) => stream.error(new Error("cut")) })), + }, +])( + "an app that does not answer ($name) is still what it last said, and is asked again after a minute", + async ({ answer }) => { + const stack = stackWith({}); + const client = await hostClientOf(stack.env, HOST); + { + using _web = answers({ name: "Guestbook", icon: "/icon.svg", for: "members" }); + await appOf(stack.env, ORIGIN); + } + // five minutes later the app is asked again, and it is down + stack.due(HOST); + const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async () => answer()); + using _down = { [Symbol.dispose]: () => spy.mockRestore() }; + const before = Date.now(); + expect(await appOf(stack.env, ORIGIN)).toEqual({ + host: HOST, + origin: ORIGIN, + name: "Guestbook", + icon: `${ORIGIN}/icon.svg`, + members: true, + signIn: FOR_MEMBERS, + }); + expect(stack.askedAgainIn(HOST, before)).toBe("1 minute"); + // and the client that the list of sign-ins reads still names the app + expect(await oauthHelpers(stack.env, ORIGIN).lookupClient(client)).toMatchObject({ + clientName: "Guestbook", + logoUri: `${ORIGIN}/icon.svg`, + }); + }, +); + +test("an app that answers with no description any more has said so: it is its host again, for anyone", async () => { + const stack = stackWith({}); + const client = await hostClientOf(stack.env, HOST); + { + using _web = answers({ name: "Guestbook", icon: "/icon.svg", signIn: ["passkey"] }); + await appOf(stack.env, ORIGIN); + } + stack.due(HOST); + using _web = answers(null); + expect(await appOf(stack.env, ORIGIN)).toEqual({ + host: HOST, + origin: ORIGIN, + name: HOST, + icon: null, + members: false, + signIn: FOR_ANYONE, + }); + expect(await oauthHelpers(stack.env, ORIGIN).lookupClient(client)).toMatchObject({ + clientName: HOST, + }); +}); + +test("an app that says nothing, or whose host does not answer, is its host and its initials, and that is kept too", async () => { + const stack = stackWith({}); + using web = answers(null); + const app = (await appOf(stack.env, ORIGIN))!; + expect(app).toEqual({ + host: HOST, + origin: ORIGIN, + name: HOST, + icon: null, + members: false, + signIn: FOR_ANYONE, + }); + expect(appTile(app)).toBe(`<div class="tile" data-app-mark="initials">GU</div>`); + await appOf(stack.env, ORIGIN); + expect(web.asked).toHaveLength(1); +}); + +test("a hostname that the stack holds nothing of is counted before it is asked: past the count it is not asked, and nothing is kept", async () => { + const stack = stackWith({}); + using web = answers({ name: "Guestbook" }); + stack.admits(false); + expect(await appOf(stack.env, ORIGIN)).toBeNull(); + expect(await signInOf(stack.env, `/oauth2/auth?resource=${ORIGIN}`)).toBeNull(); + expect(web).toMatchObject({ asked: [] }); + // a host with a client of its own is an app that the stack knows: it is asked whatever the count + stack.admits(true); + await hostClientOf(stack.env, HOST); + stack.admits(false); + expect(await appOf(stack.env, ORIGIN)).toMatchObject({ name: "Guestbook" }); +}); + +test("the methods of a sign-in are those of the app that its authorization is for, whichever client asks; the app is named for its own sign-in alone", async () => { + const stack = stackWith({ + [HOST]: { name: "Guestbook", icon: null, signIn: ["passkey"] }, + }); + const client = await hostClientOf(stack.env, HOST); + const own = `/oauth2/auth?${new URLSearchParams({ client_id: client, redirect_uri: hostCallbackOf(ORIGIN), resource: ORIGIN })}`; + expect(await signInOf(stack.env, own)).toMatchObject({ + app: { name: "Guestbook" }, + methods: ["passkey"], + }); + // an MCP client that signs a person in to the app: its own client and callback, the app's server + const mcp = `/oauth2/auth?${new URLSearchParams({ client_id: "an-mcp-client", redirect_uri: "http://127.0.0.1:4100/callback", resource: `${ORIGIN}/mcp` })}`; + expect(await signInOf(stack.env, mcp)).toEqual({ app: null, methods: ["passkey"] }); + // the control plane's own sign-in, and one for the mind's API or its MCP server + for (const next of [ + "/", + "/keys", + `/oauth2/auth?resource=https://${MIND}/mcp`, + "https://elsewhere.test/", + ]) + expect(await signInOf(stack.env, next), next).toEqual({ app: null, methods: FOR_MEMBERS }); +}); + +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 () => { + const stack = stackWith({ [HOST]: { name: "Guestbook", icon: `${ORIGIN}/icon.svg` } }); + const client = await hostClientOf(stack.env, HOST); + const next = `/oauth2/auth?${new URLSearchParams({ client_id: client, redirect_uri: hostCallbackOf(ORIGIN), resource: ORIGIN })}`; + const answer = await emailSignInResponse( + stack.env, + new Request(`https://${MIND}/sign-in/email?${new URLSearchParams({ next })}`), + ); + const html = await answer!.text(); + expect(html).toContain(`<title>Sign in to Guestbook</title>`); + // the app's icon is the card's one mark: no pair, and no mark of iterate's beside it. The + // heading is the app's own name, and the line under it the host, which no app chooses. + expect(html).toContain( + `<main class="centered"><div class="tile" data-app-mark="icon"><img src="${ORIGIN}/icon.svg" alt="" referrerpolicy="no-referrer"></div><h1>Sign in to Guestbook</h1><p class="muted center">${HOST}</p>`, + ); + expect(html).not.toMatch(/class="asks"|class="mark"|class="about"|is an app of/); + // the mind's own line of who gets a code is not on an app's page + expect(html).not.toContain("Anyone can sign in"); + // the one image the page may load is on the app's own origin + expect(answer!.headers.get("content-security-policy")).toContain(`img-src data: ${ORIGIN}`); + // a sign-in for the mind itself has no mailed code: its address page leads to its sign-in page + const plain = await emailSignInResponse( + stack.env, + new Request(`https://${MIND}/sign-in/email?next=%2Fkeys`), + ); + expect({ status: plain!.status, location: plain!.headers.get("location") }).toEqual({ + status: 303, + location: "/sign-in?next=%2Fkeys", + }); +}); + +test("the four pages of an app's sign-in agree: each shows the app's icon and its host, and none says the mind's own line", async () => { + const stack = stackWith({ [HOST]: { name: "Guestbook", icon: `${ORIGIN}/icon.svg` } }); + const client = await hostClientOf(stack.env, HOST); + const next = `/oauth2/auth?${new URLSearchParams({ client_id: client, redirect_uri: hostCallbackOf(ORIGIN), resource: ORIGIN })}`; + const app = { + host: HOST, + origin: ORIGIN, + name: "Guestbook", + icon: `${ORIGIN}/icon.svg`, + members: false, + signIn: ["email", "passkey"] as SignInMethod[], + }; + stack.challenge.next = next; + const mailed = (path: string, headers?: HeadersInit) => + emailSignInResponse(stack.env, new Request(`https://${MIND}${path}`, { headers })); + const pages = { + address: await mailed(`/sign-in/email?${new URLSearchParams({ next })}`), + code: await mailed("/sign-in/email/code", { cookie: "__Host-iterate-auth-code=abc" }), + passkey: signInPage({ + mind: MIND, + next, + app, + offersEmail: true, + offersGuest: false, + asksAtOpen: false, + noPasskeyYet: false, + }), + chooser: chooserPage({ mind: MIND, email: "guest@example.net", here: next, app }), + }; + for (const [name, answer] of Object.entries(pages)) { + const html = await answer!.text(); + const page = `the ${name} page`; + expect(html, page).toContain( + `<div class="tile" data-app-mark="icon"><img src="${ORIGIN}/icon.svg"`, + ); + expect(html, page).toContain( + name === "code" + ? "<h1>Enter your code</h1>" + : `<h1>Sign in to Guestbook</h1><p class="muted center">${HOST}</p>`, + ); + expect(html, page).not.toMatch(/class="about"|is an app of/); + // the mind's own words for its own sign-in are not on an app's page + expect(html, page).not.toContain(`Sign in to ${MIND}`); + expect(html, page).not.toContain("Anyone can sign in"); + expect(answer!.headers.get("content-security-policy"), page).toContain( + `img-src data: ${ORIGIN}`, + ); + } + // the code's page: one sentence over the field, which names the host; what to do when no code + // comes is under the button, with the way back + const code = await (await mailed("/sign-in/email/code", { + cookie: "__Host-iterate-auth-code=abc", + }))!.text(); + expect(code).toContain( + `If <strong>guest@example.net</strong> may sign in to <strong>${HOST}</strong>, a code is on its way. It expires in 10 minutes.`, + ); + expect( + code.indexOf("No code after a minute? Check the spam folder, or <a href="), + ).toBeGreaterThan(code.indexOf('<button type="submit">Sign in</button>')); + expect(code).toContain( + '<input class="code" name="code" inputmode="numeric" autocomplete="one-time-code" autofocus required>', + ); + // an outside client's sign-in to the app is no page of the app's: the code's page is the mind's + // own, with the mind's line of what a code gives + stack.challenge.next = `/oauth2/auth?${new URLSearchParams({ client_id: "an-mcp-client", redirect_uri: "http://127.0.0.1:4100/callback", resource: `${ORIGIN}/mcp` })}`; + const own = await (await mailed("/sign-in/email/code", { + cookie: "__Host-iterate-auth-code=abc", + }))!.text(); + expect(own).toContain( + `<p class="muted">A code signs you in to the apps of ${MIND}, never to the mind itself. Members sign in with a passkey.</p>`, + ); + expect(own).toContain("may sign in here, a code is on its way."); + expect(own).not.toContain(`class="about"`); +}); + +test("an app for members says in one quiet line that it works as the person; an app for anyone says nothing of itself", () => { + const dash = { + host: `dash.${DOMAIN}`, + origin: `https://dash.${DOMAIN}`, + name: "Dash", + icon: null, + members: true, + signIn: ["passkey"] as SignInMethod[], + }; + expect(appSignIn(dash)).toMatchObject({ + heading: `<h1>Sign in to Dash</h1><p class="muted center">dash.${DOMAIN}</p>`, + about: `<p class="muted" data-for-members>It works as you: it can read and change everything that you can.</p>`, + }); + expect(appSignIn({ ...dash, members: false })).toMatchObject({ about: "" }); +}); + +test("the address page of an app for members that names the mailed code, as the app's own description makes it", async () => { + const origin = `https://dash.${DOMAIN}`; + const stack = stackWith({ + [`dash.${DOMAIN}`]: { + name: "Dash", + icon: `${origin}/icon.svg`, + members: true, + signIn: ["passkey", "email"], + }, + }); + const client = await hostClientOf(stack.env, `dash.${DOMAIN}`); + const next = `/oauth2/auth?${new URLSearchParams({ client_id: client, redirect_uri: hostCallbackOf(origin), resource: origin })}`; + const answer = await emailSignInResponse( + stack.env, + new Request(`https://${MIND}/sign-in/email?${new URLSearchParams({ next })}`), + ); + const html = await answer!.text(); + expect(html).toContain(`<h1>Sign in to Dash</h1><p class="muted center">dash.${DOMAIN}</p>`); + expect(html).toContain("It works as you: it can read and change everything that you can."); + expect(html).not.toContain("Anyone can sign in"); +}); + +test("the passkey's page, the chooser and a consent for the app's host name the host, and a host is text", async () => { + const app = { + host: HOST, + origin: ORIGIN, + name: HOST, + icon: null, + members: false, + signIn: ["email", "passkey"] as SignInMethod[], + }; + const passkey = await signInPage({ + mind: MIND, + next: "/", + app: { ...app, name: "<b>Guestbook</b>", host: `<b>${HOST}</b>` }, + offersEmail: true, + offersGuest: false, + asksAtOpen: false, + noPasskeyYet: false, + }).text(); + // an app's name and its host are text + expect(passkey).toContain( + `<h1>Sign in to <b>Guestbook</b></h1><p class="muted center"><b>${HOST}</b></p>`, + ); + expect(passkey).not.toMatch(/<b>/); + // an app with no icon has no tile of initials: iterate's mark is the card's one + expect(passkey).toContain(`<main class="centered"><div class="mark"`); + expect(passkey).not.toContain("data-app-mark"); + const guestbook = app; + const chooser = await chooserPage({ + mind: MIND, + email: "guest@example.net", + here: "/oauth2/auth?client_id=c", + app: guestbook, + }).text(); + expect(chooser).toContain(`<h1>Sign in to ${HOST}</h1>`); + expect(chooser).toContain(`<button type="submit">Continue as guest@example.net</button>`); + // without an app, the chooser is the mind's own, as a member sees it + const own = await chooserPage({ mind: MIND, email: "m@example.net", here: "/x" }).text(); + expect(own).toContain(`<button type="submit">Continue as m@example.net</button>`); + expect(own).not.toContain(`class="about"`); + const consent = await consentPage({ + details: { + clientName: "Notes", + redirectUri: "https://notes.example.org/callback", + redirectHost: "notes.example.org", + redirectIsLoopback: false, + } as never, + handle: "handle", + email: "guest@example.net", + mind: MIND, + resource: "its API", + host: HOST, + here: "/oauth2/auth?client_id=c", + headers: new Headers(), + }).text(); + expect(consent).toContain(`<h1>Notes wants to use ${HOST} as you</h1>`); + expect(consent).not.toContain("is an app of"); +}); + +/** A stack with an in-memory store, which already holds what the named hosts' apps say, as heard + * a moment ago. */ +function stackWith( + said: Record< + string, + { name: string | null; icon: string | null; members?: boolean; signIn?: SignInMethod[] } + >, +) { + const keyOf = (host: string) => `iterate-app-description:${host}`; + const kv = new Map<string, string>( + Object.entries(said).map(([host, value]) => [ + keyOf(host), + JSON.stringify({ + members: false, + signIn: FOR_ANYONE, + ...value, + askAfter: Date.now() + 5 * 60_000, + }), + ]), + ); + // whether the count of new hostnames admits one more (./device/limits.ts `admitted`) + let admits = true; + const keptOf = (host: string) => JSON.parse(kv.get(keyOf(host))!) as { askAfter: number }; + // the one mailed code that waits, as the code's page reads it + const challenge = { email: "guest@example.net", next: "/" }; + const env = { + ...configVars(), + OAUTH_KV: { + get: async (key: string, type?: unknown) => { + const kept = kv.get(key); + return kept && type ? JSON.parse(kept) : kept || null; + }, + put: async (key: string, value: string) => void kv.set(key, value), + }, + DB: { + prepare: (sql: string) => ({ + first: async () => ({ id: "test-member-passkey" }), + bind: (...bound: unknown[]) => ({ sql, bound, first: async () => challenge }), + }), + // the admission of a new host client, or of a hostname that is asked about first + batch: async () => [{}, { results: admits ? [{ admitted: 1 }] : [] }], + }, + } as unknown as Env; + return { + env, + challenge, + admits: (more: boolean) => void (admits = more), + /** The time has come to ask `host`'s app again. */ + due: (host: string) => kv.set(keyOf(host), JSON.stringify({ ...keptOf(host), askAfter: 0 })), + /** How long after `since` the app is asked again, in whole minutes. */ + askedAgainIn(host: string, since: number) { + const minutes = Math.round((keptOf(host).askAfter - since) / 60_000); + return `${minutes} minute${minutes === 1 ? "" : "s"}`; + }, + }; +} + +/** The web for one test: every fetch answers `description` as JSON (null: a 404), and is + * recorded. */ +function answers(description: object | null) { + const asked: [string, string | undefined][] = []; + const spy = vi.spyOn(globalThis, "fetch").mockImplementation(async (input, init) => { + asked.push([String(input), init?.redirect]); + return description ? Response.json(description) : new Response("Not found\n", { status: 404 }); + }); + return { asked, [Symbol.dispose]: () => spy.mockRestore() }; +}
A core/auth-worker/src/asking-app.ts
@@ -0,0 +1,248 @@ +// asking-app.ts — THE APP OF THIS MIND THAT A SIGN-IN IS FOR. A page of an app's host +// (a hostname of one of the mind's zones) that asks who is there sends the browser to this issuer with an +// authorization request of the host's own: its resource is the host, its redirect is the host's +// own callback, and its client is the one this stack made for the host (./oauth.ts +// `hostClientOf`). The sign-in pages then say which app the person signs in to. +// +// WHAT IS TRUSTED. `next`, the request that a sign-in goes on to, is a query that anyone can +// write. So the app is NAMED from it only when its three parts agree with what this stack holds: +// the test by which the authorization endpoint completes a host's own sign-in with no consent +// page. A link that passes it is the link that the host's own page makes. +// +// WHAT THE APP SAYS OF ITSELF, in the document that its own code answers at +// `/.well-known/iterate-app` on its own host (iterate/app-description; iterate/sdk +// `serveAppDescription`): its name, its icon, whether it is for the mind's members alone, and +// how its people sign in: +// +// { "name": "Guestbook", "icon": "/icon.svg", "signIn": ["email", "passkey"] } +// +// This Worker reads it over the public internet, as it reads an outside client's document, follows +// no redirect, and asks again after five minutes. An icon counts only from the app's own origin, +// so the page's policy allows that one origin. An app that says nothing is shown by its host and +// its initials. An app that DOES NOT ANSWER (no answer in two seconds, or a 5xx) has said nothing +// new: it is still what it last said, and it is asked again after a minute. +// +// "For members" changes the page's words and the default of `signIn`, and nothing else: who may +// come is the guard in the app's own code (the mind's worker.ts), which this Worker does not +// read. +// +// HOW THE APP'S PEOPLE SIGN IN (`signIn`) is the one part that this Worker enforces: the +// authorization endpoint gives a code for the app's host only to a session whose method the app +// names, or to a passkey's (./authorize.ts, `appTakes`), and the sign-in pages offer those +// 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. +// +// 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 type { SignInMethod } from "iterate/principal"; +import { admitted } from "./device/limits.ts"; +import { configOf, type Env, issuerOf } from "./env.ts"; +import { + AUTHORIZE_ENDPOINT, + hostCallbackOf, + keptHostClientOf, + knownResourceOf, + mindHostResourceOf, + oauthHelpers, +} from "./oauth.ts"; + +export type AskingApp = { + /** The app's hostname, in one of the mind's zones. */ + host: string; + origin: string; + /** What the app calls itself, or its host when it says nothing. */ + name: string; + /** Its icon, on its own origin, when it names one. */ + icon: string | null; + /** The app says that it is for the mind's members alone. */ + members: boolean; + /** 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[]; +}; + +const text = (value: string) => + value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); + +/** HOW A PERSON SIGNS IN TO THE CONTROL PLANE ITSELF, and for a client of the mind's API or its + * MCP server: a member's passkey, and nothing else. The mailed code is for the people of the + * mind's apps, and opens no way into the mind (./email-sign-in.ts). */ +const CONTROL_PLANE_SIGN_IN: SignInMethod[] = ["passkey"]; + +/** THE SIGN-IN THAT `next` GOES ON TO (a path of this issuer), as its pages show it: the methods + * that they offer, in order, and the app that they name. An authorization for a mind hostname + * takes the methods of that hostname's app, whichever client asks, since the authorization + * endpoint holds the session to the same list; the pages name the app only for its own sign-in + * (`askingAppOf`). Anything else is the control plane's own sign-in. Null: too many hostnames + * that the stack holds nothing of were asked about just now (`appOf`). */ +export async function signInOf( + env: Env, + next: string, +): Promise<{ app: AskingApp | null; methods: SignInMethod[] } | null> { + const authorization = hostAuthorizationIn(env, next); + if (!authorization) return { app: null, methods: CONTROL_PLANE_SIGN_IN }; + const app = await appOf(env, authorization.origin); + if (!app) return null; + return { app: (await isOwnSignIn(env, authorization)) ? app : null, methods: app.signIn }; +} + +/** The app whose own sign-in `next` goes on to (a path of this issuer), or null: for any other + * request, and for one whose parts this stack does not hold. */ +export async function askingAppOf(env: Env, next: string): Promise<AskingApp | null> { + const authorization = hostAuthorizationIn(env, next); + if (!authorization || !(await isOwnSignIn(env, authorization))) return null; + return appOf(env, authorization.origin); +} + +/** WHETHER AN APP TAKES A SESSION THAT `method` OPENED, for a code for the app's host: a + * passkey's counts at every app, and any other when the app names its method. */ +export const appTakes = (app: Pick<AskingApp, "signIn">, method: SignInMethod) => + method === "passkey" || app.signIn.includes(method); + +/** `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) { + const issuer = issuerOf(env); + if (!URL.canParse(next, issuer)) return null; + const url = new URL(next, issuer); + if (url.origin !== issuer || url.pathname !== AUTHORIZE_ENDPOINT) return null; + const asked = url.searchParams.get("resource"); + const origin = asked && mindHostResourceOf(configOf(env), knownResourceOf(env, asked)); + return origin ? { origin, parameters: url.searchParams } : null; +} + +/** Whether an authorization for a mind hostname is that host's own sign-in: its code goes to + * the host's own callback, and its client is the one this stack made for the host. */ +async function isOwnSignIn( + env: Env, + { origin, parameters }: { origin: string; parameters: URLSearchParams }, +) { + if (parameters.get("redirect_uri") !== hostCallbackOf(origin)) return false; + const client = await keptHostClientOf(env, new URL(origin).host); + return Boolean(client) && client === parameters.get("client_id"); +} + +/** A HOST OF THIS MIND AS AN APP: `origin` is one that `mindHostResourceOf` let through. Anyone + * can ask about any hostname of the mind's zones, in the `next` of a sign-in page, so a hostname + * that the stack holds nothing of (no description, no client of its own) is counted as a new + * host client is (./oauth.ts `hostClientOf`): null when too many were asked about just now. */ +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"); + if ( + !kept && + !(await keptHostClientOf(env, host)) && + !(await admitted(env, "host-client", new Request(origin))) + ) + return null; + if (!kept || kept.askAfter <= Date.now()) { + const document = `${origin}${APP_DESCRIPTION_PATH}`; + const heard = await fetch(document, { + headers: { accept: "application/json" }, + redirect: "manual", + signal: AbortSignal.timeout(2000), + }) + // an answer of the app: its description's text, which is empty for an app that has none + // (a 404, a sign-in). Null: the app did not answer, or its answer broke off. + .then(async (answer) => { + if (answer.status >= 500) return null; + return { description: answer.status === 200 ? await answer.text() : "" }; + }) + .catch(() => null); + const last = kept || NOTHING; + kept = heard + ? // "nothing" is kept too: an app with no description is not asked at each page + { ...saidIn(heard.description, document), askAfter: Date.now() + 5 * 60_000 } + : // it did not answer: it is what it last said, and is asked again after a minute + { ...last, askAfter: Date.now() + 60_000 }; + // The row goes a day after it was last written: an app that is asked about is written again + // within five minutes, and a hostname that nobody asks about any more leaves no row. + await env.OAUTH_KV.put(key, JSON.stringify(kept), { expirationTtl: 24 * 3600 }); + if (heard) await keepOnClient(env, origin, { name: kept.name || host, icon: kept.icon }); + } + return { + host, + origin, + name: kept.name || host, + icon: kept.icon, + members: kept.members, + signIn: kept.signIn, + }; +} + +/** What an app said of itself (`saidIn`), and when to ask it again. */ +type Kept = ReturnType<typeof saidIn> & { askAfter: number }; + +/** The host's own client says what the app says: written when it says something else. */ +async function keepOnClient(env: Env, origin: string, said: { name: string; icon: string | null }) { + const clientId = await keptHostClientOf(env, new URL(origin).host); + if (!clientId) return; + const helpers = oauthHelpers(env, origin); + const client = await helpers.lookupClient(clientId); + if (!client || (client.clientName === said.name && (client.logoUri || null) === said.icon)) + return; + await helpers.updateClient(clientId, { clientName: said.name, logoUri: said.icon || undefined }); +} + +/** An app that says nothing: it is shown by its host, and it is for anyone, whose people sign in + * by the mailed code first. */ +const NOTHING: { + name: string | null; + icon: string | null; + members: boolean; + signIn: SignInMethod[]; +} = { name: null, icon: null, members: false, signIn: ["email", "passkey"] }; + +/** WHAT THE TEXT OF AN APP'S DESCRIPTION SAYS (iterate/app-description `AppDescription`): a name + * of at most sixty characters, its icon when that is on the description's own origin, over + * https, whether the app is for members, and how its people sign in: the list it names, as it is + * written, or the passkey alone for an app for members (a member signs in with nothing else), + * and email then passkey for any other. A text that is no `AppDescription` says nothing: one + * that names a method this issuer does not know is such a text, so no app is held to a list that + * it did not write. */ +export function saidIn(descriptionText: string, descriptionUrl: string): typeof NOTHING { + if (!descriptionText || descriptionText.length > 20_000) return NOTHING; + let json: unknown; + try { + json = JSON.parse(descriptionText); + } catch { + return NOTHING; + } + const parsed = AppDescription.safeParse(json); + if (!parsed.success) return NOTHING; + const name = parsed.data.name + // a name is one line of text + .replace(/[\p{Cc}\p{Cf}]/gu, " ") + .trim() + .slice(0, 60); + const { origin } = new URL(descriptionUrl); + const icon = parsed.data.icon ? new URL(parsed.data.icon, descriptionUrl) : null; + const members = parsed.data.for === "members"; + return { + name: name || null, + // a path that begins `//` names another host: an icon is the app's own origin's alone + icon: icon?.protocol === "https:" && icon.origin === origin ? icon.href : null, + members, + signIn: [ + ...new Set<SignInMethod>(parsed.data.signIn || (members ? ["passkey"] : NOTHING.signIn)), + ], + }; +} + +/** The app's tile (plain-page.css `.tile`): its icon, or its initials. Never a built-in mark of + * ./client-mark.ts: an app of a mind that calls itself "Codex" is not OpenAI's. `small` is for a + * row of a list. */ +export function appTile( + app: Pick<AskingApp, "name" | "icon">, + { small = false }: { small?: boolean } = {}, +): string { + const tile = small ? "tile small" : "tile"; + if (app.icon) + return `<div class="${tile}" data-app-mark="icon"><img src="${text(app.icon)}" alt="" referrerpolicy="no-referrer"></div>`; + const initials = [...app.name.replace(/[^\p{L}\p{N}]/gu, "")].slice(0, 2).join(""); + return `<div class="${tile}" data-app-mark="initials">${text(initials.toUpperCase() || "?")}</div>`; +}
A core/auth-worker/src/authorize.ts
@@ -0,0 +1,447 @@ +import { + type AuthRequest, + AuthorizationError, + authorizationErrorRedirect, + CimdFetchError, +} from "@cloudflare/workers-oauth-provider"; +import { cookieValueOf } from "iterate/lib"; +import { mindMcpUrlOf, mindProvideConnectResourceOf } from "iterate/mind-api"; +import { AccountFacts } from "./account-facts.ts"; +import { appOf, appTakes, askingAppOf } from "./asking-app.ts"; +import { + clearGuestCookie, + clearMindCookie, + clearMindFreshCookie, + clearSessionCookie, + endThisSession, + guestCookie, + guestOf, + MIND_FRESH_COOKIE, + mindFreshOf, + mindSessionOf, + type PersonSession, + personSessionOf, +} from "./cookies.ts"; +import { configOf, type Env, issuerOf } from "./env.ts"; +import { + type GrantProps, + grantedScopes, + hostCallbackOf, + oauthHelpers, + type SignInMetadata, + mindHostResourceOf, +} from "./oauth.ts"; +import { isMemberSession } from "./members.ts"; +import { chooserPage, consentPage, errorPage, notMemberPage } from "./pages.ts"; +import { signInHref } from "./sign-in.ts"; +import { admitted, TOO_MANY } from "./device/limits.ts"; +import { GUEST_SESSIONS_PER_TEN_MINUTES, guestRefusal } from "./guest-sign-in.ts"; +import { mindPersonName } from "./mind-sign-in.ts"; +import { CALLBACK_PATH as DEVICE_CALLBACK_PATH } from "./device/protocol.ts"; +import { deviceStore } from "./device/store.ts"; + +export async function authorizeResponse(env: Env, request: Request) { + const answer = await authorizeAnswer(env, request); + // a mind sign-in's fresh mark answers this authorization or none (./cookies.ts `mindFreshCookie`) + if (!cookieValueOf(request.headers.get("cookie"), MIND_FRESH_COOKIE)) return answer; + const headers = new Headers(answer.headers); + headers.append("set-cookie", clearMindFreshCookie); + return new Response(answer.body, { + status: answer.status, + statusText: answer.statusText, + headers, + }); +} + +async function authorizeAnswer(env: Env, request: Request) { + try { + return request.method === "POST" ? await decide(env, request) : await describe(env, request); + } catch (error) { + // A redirect back to the client only once the library validated the client and its redirect. + if (error instanceof AuthorizationError && error.redirectTo) + return Response.redirect(error.redirectTo, 302); + if (error instanceof AuthorizationError) return errorPage(error.description, 400); + if (error instanceof CimdFetchError) + return errorPage( + "We could not load this app's description, so we can't tell who it is.", + 400, + ); + throw error; + } +} + +async function describe(env: Env, request: Request) { + const config = configOf(env); + const hostResource = mindHostResourceOf( + config, + new URL(request.url).searchParams.get("resource"), + ); + const helpers = oauthHelpers(env, hostResource); + const parsed = await helpers.parseAuthRequest(request); + // PKCE with S256 for every client: the library requires it of a public client, and a client + // that holds a secret is held to it here too. + if (parsed.codeChallengeMethod !== "S256" || !parsed.codeChallenge) + return Response.redirect( + authorizationErrorRedirect(parsed, "invalid_request", "PKCE with S256 is required."), + 302, + ); + const scope = grantedScopes(parsed.scope, Boolean(hostResource)); + if (!scope) + return Response.redirect( + authorizationErrorRedirect( + parsed, + "invalid_scope", + hostResource + ? "A mind hostname grants only `identity`." + : "The mind's API and MCP server grant only `iterate`.", + ), + 302, + ); + const authRequest = { ...parsed, scope }; + const { prompt, here } = promptOf(new URL(request.url)); + // a hostname's own sign-in: the code goes to ingress on that host alone, and is not a consent + const hostSignIn = hostResource && authRequest.redirectUri === hostCallbackOf(hostResource); + // Anyone signed in: a mind hostname takes a person who is no member (`grantRefusal`). A guest's + // cookie counts only where nobody is signed in, for a host's own sign-in whose app names guests + // (`guestAt`). + const session: SignedIn | null = + (await personSessionOf(env, request)) || + (hostSignIn + ? (await guestAt(env, hostResource, request)) || + (await mindPersonAt(env, hostResource, request)) + : null); + const guest = session?.method === "guest"; + // a member of another mind, as a guest: a cookie of their own, with no session row + const cookieOnly = guest || session?.method === "mind"; + const signIn = `${issuerOf(env)}${signInHref(here)}`; + if (!session) return Response.redirect(signIn, 302); + // AN APP NAMES HOW ITS PEOPLE SIGN IN, and this endpoint holds every code for the app's host to + // it, whichever client asks. A session that the app does not take is no session here: the + // person goes to the sign-in for this request, which offers the app's methods alone. + const taken = hostResource ? await hostTakes(env, hostResource, session) : true; + if (taken === null) return errorPage(TOO_MANY, 429); + if (!taken) return Response.redirect(signIn, 302); + // A MIND SIGN-IN THAT JUST COMPLETED for this host is the answer to its `select_account`, once: + // the person signed out here, then signed in with their mind (./cookies.ts `mindFreshCookie`). + const answered = + prompt === "select_account" && + hostSignIn && + session.method === "mind" && + (await freshAnswers(env, request, session.userId, new URL(hostResource).host)); + const asked = answered ? null : prompt; + // OpenID Connect's `prompt`. `login`: sign in again, whoever is signed in. `select_account`: say + // who is signed in and offer another account. Either comes back here without it. A guest's + // cookie ends for either: the name form is the page that says who they are, and its answer is + // a new guest. A member of another mind's cookie ends too: their mind is asked again. + if (asked === "login" || (asked && cookieOnly)) { + const facts = new AccountFacts(); + if (!cookieOnly) await endThisSession(env, request, facts); + return facts.on( + new Response(null, { + status: 302, + headers: { + location: signIn, + "set-cookie": guest + ? clearGuestCookie + : cookieOnly + ? clearMindCookie + : clearSessionCookie, + "cache-control": "no-store", + }, + }), + ); + } + if (asked === "select_account") + return chooserPage({ + mind: config.controlPlaneHostname, + 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 + // the mind's own + app: (await isMemberSession(env, session)) ? null : await askingAppOf(env, here), + signedOutOf: hostSignIn ? new URL(hostResource).host : undefined, + }); + const refused = await grantRefusal(env, session, hostResource, here); + if (refused) return refused; + // A GUEST'S NEXT 15 MINUTES on this host (./guest-sign-in.ts): counted for the whole stack, + // since anyone can be a guest, and for this guest, so that one cookie cannot use up the stack's + // number and stop every other guest's renewal. The cookie is set again, so it ends 30 days + // after the browser last came. + if (hostSignIn && guest) { + if ( + !(await admitted( + env, + "guest-session", + request, + GUEST_SESSIONS_PER_TEN_MINUTES, + session.userId, + )) + ) + return guestRefusal("session-rate", new URL(hostResource).host); + const { redirectTo } = await complete(env, session, authRequest, hostResource); + return new Response(null, { + status: 302, + headers: { + location: redirectTo, + "set-cookie": await guestCookie(env, { + id: session.userId, + key: session.email, + name: session.name || "", + }), + "cache-control": "no-store", + }, + }); + } + // a hostname's own sign-in: the code goes to ingress on that host alone, and is not a consent + if (hostSignIn) { + const { redirectTo } = await complete(env, session, authRequest, hostResource); + return Response.redirect(redirectTo, 302); + } + // describe first: a failed lookup leaves nothing in KV + const details = await helpers.describeConsent(authRequest); + const consent = await helpers.beginConsent(authRequest); + return consentPage({ + details, + handle: consent.handle, + email: session.email, + mind: config.controlPlaneHostname, + resource: resourceInWords(env, authRequest.resource), + host: hostResource ? new URL(hostResource).host : undefined, + here, + headers: consent.headers, + }); +} + +/** An authorization request's `prompt` (a space-separated list; `login` wins), and the request + * without it, as a path of the issuer: where a sign-in or the chooser goes on. */ +export function promptOf(url: URL): { prompt: "login" | "select_account" | null; here: string } { + const asked = (url.searchParams.get("prompt") || "").split(" "); + const rest = new URL(url); + rest.searchParams.delete("prompt"); + return { + prompt: asked.includes("login") + ? "login" + : asked.includes("select_account") + ? "select_account" + : null, + here: rest.pathname + rest.search, + }; +} + +async function decide(env: Env, request: Request) { + // the session's cookie approves a grant, so the form must come from this page + if (request.headers.get("origin") !== issuerOf(env)) + return errorPage("Approve this from its own page.", 403); + const form = await request.formData().catch(() => null); + const handle = form?.get("handle"); + if (typeof handle !== "string") return errorPage("This form is incomplete. Start again.", 400); + const session = await personSessionOf(env, request); + if (!session) return errorPage("You are signed out. Go back to the app and start again.", 401); + const helpers = oauthHelpers(env); + if (form?.get("decision") !== "allow") { + const denied = await helpers.denyConsent(request, handle); + denied.headers.set("cache-control", "no-store"); + return new Response(null, { status: 302, headers: denied.headers }); + } + const approved = await helpers.approveConsent(request, handle); + // the resource is the one the consent was begun with, kept by the library: the form names none + const hostResource = mindHostResourceOf(configOf(env), approved.request.resource); + const refused = await grantRefusal(env, session, hostResource, "/"); + if (refused) return refused; + // the session may be another than the one that the consent page was shown to + if (hostResource && !(await hostTakes(env, hostResource, session))) + return errorPage("This app does not take the way you signed in. Start again from the app."); + const client = await helpers.lookupClient(approved.request.clientId); + return approve(env, session, approved.request, client, approved.headers); +} + +/** WHO A GRANT IS FOR: a person's session at the issuer, or a guest or a member of another mind, + * who have no session row (./guest-sign-in.ts, ./mind-sign-in.ts). `name`: the name a guest + * typed, or the other mind's hostname, which the grant keeps. `mind`: the mind that vouched, and + * `until` when that cookie ends (epoch ms), which the grant keeps as its deadline. */ +type SignedIn = Pick<PersonSession, "userId" | "email" | "method"> & { + name?: string; + mind?: { id: string; hostname: string; userId: string }; + until?: number; +}; + +/** THE MEMBER OF ANOTHER MIND THIS BROWSER IS, for the own sign-in of the host at `hostResource`, + * or null: the host's app names "mind". Read here alone, as the guest's cookie is. */ +async function mindPersonAt( + env: Env, + hostResource: string, + request: Request, +): Promise<SignedIn | null> { + const app = await appOf(env, hostResource); + if (!app?.signIn.includes("mind")) return null; + const person = await mindSessionOf(env, request); + if (!person) return null; + return { + userId: person.userId, + email: person.email, + method: "mind", + name: mindPersonName(person.mind.hostname), + mind: person.mind, + until: person.expiresAt, + }; +} + +/** THE GUEST THIS BROWSER IS, for the own sign-in of the host at `hostResource`, or null: the + * host's app names guests, and no owner blocked this guest. Read here alone, so the cookie gives + * no reach by itself. */ +async function guestAt(env: Env, hostResource: string, request: Request): Promise<SignedIn | null> { + const app = await appOf(env, hostResource); + if (!app?.signIn.includes("guest")) return null; + const guest = await guestOf(env, request); + return guest && !guest.blocked + ? { userId: guest.userId, email: guest.email, method: "guest", name: guest.name } + : null; +} + +/** Whether this browser's fresh mind sign-in (./cookies.ts `mindFreshCookie`) is the one of + * `userId` for the app at `host`, taken now for the first time. */ +async function freshAnswers(env: Env, request: Request, userId: string, host: string) { + const fresh = await mindFreshOf(env, request); + if (!fresh || fresh.user !== userId || fresh.app !== host) return false; + // once: a repeat cannot insert (the statements' table, as ./mind-sign-in.ts takes a vouch) + const [, inserted] = await env.DB.batch([ + env.DB.prepare(`delete from statements where expires <= ?1`).bind(Date.now()), + env.DB.prepare( + `insert into statements (hash, expires) values (?1, ?2) on conflict do nothing`, + ).bind(`mind-fresh:${fresh.jti}`, fresh.exp * 1000), + ]); + return Boolean(inserted?.meta.changes); +} + +/** Whether the app at `hostResource` takes `session` (./asking-app.ts `appTakes`). Null: the + * app could not be asked, since too many new hostnames were asked about just now. */ +async function hostTakes(env: Env, hostResource: string, session: SignedIn) { + const app = await appOf(env, hostResource); + return app && appTakes(app, session.method); +} + +/** WHY A SESSION GETS NO GRANT, or null. A mind hostname takes the identity of anyone signed in, + * a person who is no member too: an app there has users of its own, and says how they sign in + * (`hostTakes`). The mind's API, its MCP server and the right to hand in a mind that runs + * elsewhere take a member's session alone, which is a passkey's (./members.ts + * `isMemberSession`). A grant keeps how its session's person signed in (./oauth.ts + * `GrantProps`). */ +async function grantRefusal( + env: Env, + session: SignedIn, + hostResource: string | null, + here: string, +) { + if (hostResource || (await isMemberSession(env, session))) return null; + return notMemberPage({ mind: configOf(env).controlPlaneHostname, email: session.email, here }); +} + +/** What a grant keeps of its client: the name and the logo that the client gave. */ +type AskingClient = { clientName?: string; logoUri?: string } | null; + +async function complete( + env: Env, + session: SignedIn, + authRequest: AuthRequest, + hostResource: string | null, + client?: AskingClient, +) { + const clientName = client?.clientName; + // a device's request: its code goes to this stack's own device callback + const letIn = + authRequest.redirectUri === `${issuerOf(env)}${DEVICE_CALLBACK_PATH}` + ? (await deviceStore(env.OAUTH_KV).byKey(authRequest.state))?.letIn + : undefined; + const props: GrantProps = { + userId: session.userId, + email: session.email, + method: session.method, + name: session.name, + ...(session.mind && { mind: session.mind, deadline: session.until }), + // a rule to remove, with its unmarked case (./oauth.ts `GrantProps.standingByMethod`) + standingByMethod: true, + ...(letIn && { + deadline: Date.now() + letIn.seconds * 1000, + letIn: { + reason: letIn.reason, + clientName: clientName || authRequest.clientId, + ...(letIn.signer && { signer: { actor: letIn.signer.actor, key: letIn.signer.key } }), + }, + }), + }; + const { redirectTo } = await oauthHelpers(env, hostResource).completeAuthorization({ + request: authRequest, + userId: session.userId, + // what /keys shows of this sign-in (./oauth.ts `signInsOf`) + metadata: { + clientName: clientName || authRequest.clientId, + method: session.method, + resource: authRequest.resource, + logoUri: client?.logoUri, + until: props.deadline, + } satisfies SignInMetadata, + scope: authRequest.scope, + revokeExistingGrants: false, + props, + }); + return { redirectTo, grantId: grantIdOf(redirectTo), props }; +} + +async function approve( + env: Env, + session: PersonSession, + authRequest: AuthRequest, + client: AskingClient, + headers: Headers, +) { + const clientName = client?.clientName; + const hostResource = mindHostResourceOf(configOf(env), authRequest.resource); + const { redirectTo, grantId, props } = await complete( + env, + session, + authRequest, + hostResource, + client, + ); + const facts = new AccountFacts(); + facts.add(session.userId, { + type: "events.iterate.com/account/consent-approved", + payload: { + clientId: authRequest.clientId, + clientName: clientName || authRequest.clientId, + minds: null, + scopes: authRequest.scope, + }, + idempotencyKey: `account/consent-approved/${grantId}`, + }); + if (props.letIn && props.deadline) + facts.add(session.userId, { + type: "events.iterate.com/account/let-in-approved", + payload: { + grantId, + clientId: authRequest.clientId, + clientName: props.letIn.clientName, + reason: props.letIn.reason, + until: props.deadline, + signer: props.letIn.signer, + }, + idempotencyKey: `account/let-in-approved/${grantId}`, + }); + headers.set("location", redirectTo); + headers.set("cache-control", "no-store"); + return facts.on(new Response(null, { status: 302, headers })); +} + +function resourceInWords(env: Env, resource: string | undefined) { + const config = configOf(env); + if (resource === mindProvideConnectResourceOf(config.controlPlaneHostname)) + return "the right to hand in the mind, as the computer that runs it: it receives every request and all mail"; + return resource === mindMcpUrlOf(config.controlPlaneHostname) ? "its MCP server" : "its API"; +} + +// The library's codes are `<userId>:<grantId>:<secret>`. +function grantIdOf(redirectTo: string) { + const grantId = new URL(redirectTo).searchParams.get("code")?.split(":")[1]; + if (!grantId) throw new Error("The authorization code names no grant."); + return grantId; +}
A core/auth-worker/src/blocked.test.ts
@@ -0,0 +1,29 @@ +import { expect, test } from "vitest"; +import { isBlocked } from "./blocked.ts"; +import type { Env } from "./env.ts"; + +test("a blocked address is blocked with any +tag too, and a block of one tag is of that tag alone", async () => { + const env = stack(["abuser@example.net", "other+spam@example.net"]); + // the same mailbox under another name: the block of the address holds + expect(await isBlocked(env, "abuser@example.net")).toBe(true); + expect(await isBlocked(env, "Abuser+1@Example.net ")).toBe(true); + expect(await isBlocked(env, "abuser+anything.at-all@example.net")).toBe(true); + // a block that names a tag is of that tag: the mailbox's plain address stays free + expect(await isBlocked(env, "other+spam@example.net")).toBe(true); + expect(await isBlocked(env, "other@example.net")).toBe(false); + expect(await isBlocked(env, "other+else@example.net")).toBe(false); + expect(await isBlocked(env, "someone@example.net")).toBe(false); +}); + +/** A stack whose block list holds `blocked`: the one statement `isBlocked` runs, and no more of D1. */ +function stack(blocked: string[]) { + const prepare = (sql: string) => ({ + bind: (...values: unknown[]) => ({ + first: async () => { + if (!sql.startsWith("select 1 from blocked where")) throw new Error(`not expected: ${sql}`); + return blocked.some((email) => values.includes(email)) ? { 1: 1 } : null; + }, + }), + }); + return { DB: { prepare } } as unknown as Env; +}
A core/auth-worker/src/blocked.ts
@@ -0,0 +1,24 @@ +// blocked.ts — THE PEOPLE AN OWNER BLOCKED (migrations/0009_blocked.sql). An owner blocks and +// unblocks on /members (./members.ts). Whoever is blocked gets no mailed code, and a session or a +// token of theirs is nobody's from the next request on. +import type { Env } from "./env.ts"; + +export type Blocked = { email: string; blockedBy: string }; + +/** Whether an owner blocked `email`, or the address it is a `+tag` of: `a+1@x` reaches the mailbox + * of `a@x`, so a block of `a@x` holds for it (./email-sign-in.ts counts its codes the same way). A + * block that names a tag is of that tag alone. */ +export async function isBlocked(env: Env, email: string): Promise<boolean> { + const exact = email.trim().toLowerCase(); + const row = await env.DB.prepare("select 1 from blocked where email = ?1 or email = ?2") + .bind(exact, exact.replace(/\+[^@]*@/, "@")) + .first(); + return Boolean(row); +} + +export async function blockedOf(env: Env): Promise<Blocked[]> { + const { results } = await env.DB.prepare( + "select email, blocked_by as blockedBy from blocked order by blocked_at", + ).all<Blocked>(); + return results; +}
A core/auth-worker/src/browser-sessions-fake.ts
@@ -0,0 +1,85 @@ +// THE `browser_sessions` TABLE IN MEMORY, for the units whose D1 is a stand-in that matches SQL +// (./cookies.ts writes and reads it). It answers the statements of ./cookies.ts about a passkey's +// sessions, and nothing else: `statementOf` is null for any other SQL, so a test's own stand-in +// answers that. A session of another kind is tested on SQLite (./test-support.ts). +type Row = { + id: string; + user_id: string; + key_id: string; + user_agent: string; + created_at: number; + last_seen_at: number; + expires_at: number; + ended_at: number | null; +}; + +export function browserSessionsFake( + keyLive: (key: string, userId: string) => boolean = () => true, +) { + const rows = new Map<string, Row>(); + const live = (row: Row, now: number) => + row.ended_at === null && row.expires_at > now && keyLive(row.key_id, row.user_id); + const statementOf = (sql: string, bound: unknown[]) => { + if (!sql.includes("browser_sessions")) return null; + const answer = (): unknown[] => { + const [a, b, c, d, e, f] = bound as [string, string, string, string, number, number]; + if (sql.trimStart().startsWith("insert")) { + rows.set(a, { + id: a, + user_id: b, + key_id: c, + user_agent: d, + created_at: e, + last_seen_at: e, + expires_at: f, + ended_at: null, + }); + return []; + } + if (sql.trimStart().startsWith("delete")) return []; + if (sql.includes("set last_seen_at")) { + const row = rows.get(a); + if (row && row.last_seen_at < (bound[2] as number)) row.last_seen_at = bound[1] as number; + return []; + } + if (sql.includes("set ended_at")) { + const now = bound[1] as number; + const ended = [...rows.values()].filter( + (row) => + row.user_id === a && + row.ended_at === null && + row.expires_at > now && + (!sql.includes("and id = ?3") || row.id === bound[2]) && + (!sql.includes("and id != ?3") || row.id !== bound[2]), + ); + for (const row of ended) row.ended_at = now; + return ended.map(({ id }) => ({ id })); + } + if (sql.includes("where s.id = ?1")) { + const row = rows.get(a); + return row && row.user_id === b && live(row, bound[2] as number) + ? [{ method: "passkey", last_seen_at: row.last_seen_at }] + : []; + } + if (sql.includes("where s.user_id = ?1")) + return [...rows.values()] + .filter((row) => row.user_id === a && live(row, bound[1] as number)) + .sort((x, y) => y.created_at - x.created_at) + .map((row) => ({ + id: row.id, + method: "passkey", + userAgent: row.user_agent, + createdAt: row.created_at, + lastSeenAt: row.last_seen_at, + })); + throw new Error(`not expected: ${sql}`); + }; + return { + first: async () => answer()[0] ?? null, + all: async () => ({ results: answer() }), + run: async () => ({ meta: { changes: answer().length } }), + results: () => ({ results: answer() }), + }; + }; + return { rows, statementOf }; +}
A core/auth-worker/src/client-mark.test.ts
@@ -0,0 +1,84 @@ +// Which built-in mark a client gets, and the tile a page draws for it. +import { expect, test } from "vitest"; +import { clientTile, knownMarkOf } from "./client-mark.ts"; + +const loopback = { redirectUri: "http://127.0.0.1:1455/callback", redirectHost: "127.0.0.1:1455" }; + +test.for([ + // by its verified domain: Codex's client ID is a document on chatgpt.com + { mark: "openai", name: "An app", clientDomain: "chatgpt.com", ...loopback }, + { mark: "openai", name: "An app", clientDomain: "platform.openai.com", ...loopback }, + { mark: "claude", name: "An app", clientDomain: "claude.ai", ...loopback }, + // by where its access goes + { + mark: "openai", + name: "An app", + redirectUri: "https://chatgpt.com/connector_platform_oauth_redirect", + redirectHost: "chatgpt.com", + }, + { + mark: "claude", + name: "An app", + redirectUri: "https://claude.ai/api/mcp/auth_callback", + redirectHost: "claude.ai", + }, + { mark: "cursor", name: "An app", redirectUri: "cursor://x/callback", redirectHost: "" }, + { mark: "zed", name: "An app", redirectUri: "zed://oauth/callback", redirectHost: "" }, + { mark: "windsurf", name: "An app", redirectUri: "windsurf://x/callback", redirectHost: "" }, + // by the name it gives, as a device does + { mark: "openai", name: "Codex", ...loopback }, + { mark: "openai", name: "codex-mcp-client", ...loopback }, + { mark: "openai", name: "ChatGPT", ...loopback }, + { mark: "openai", name: "OpenAI Codex", ...loopback }, + { mark: "claude", name: "Claude Code", ...loopback }, + { mark: "cursor", name: "Cursor", ...loopback }, + { mark: "zed", name: "Zed", ...loopback }, + { mark: "windsurf", name: "Windsurf", ...loopback }, + { mark: "gemini", name: "Gemini CLI MCP Client", ...loopback }, + { mark: "gemini", name: "Google Gemini", ...loopback }, + { mark: "opencode", name: "opencode", ...loopback }, + // a fact outweighs a name: a client of chatgpt.com that calls itself Claude is OpenAI's + { mark: "openai", name: "Claude Code", clientDomain: "chatgpt.com", ...loopback }, + // a name counts at its start, as a whole word + { mark: null, name: "Not Codex", ...loopback }, + { mark: null, name: "My ChatGPT helper", ...loopback }, + { mark: null, name: "Codexa", ...loopback }, + { mark: null, name: "Zedd", ...loopback }, + // a host that only ends like a known one is another host + { + mark: null, + name: "An app", + redirectUri: "https://notchatgpt.com/x", + redirectHost: "notchatgpt.com", + }, + { mark: null, name: "An app", clientDomain: "chatgpt.com.example.org", ...loopback }, + // no free mark: its initials + { + mark: null, + name: "Visual Studio Code", + redirectUri: "https://vscode.dev/redirect", + redirectHost: "vscode.dev", + }, +] as const)("the mark of $name ($clientDomain, $redirectHost) is $mark", ({ mark, ...client }) => { + expect(knownMarkOf(client)).toBe(mark); +}); + +test("a tile is the mark in one svg, small for a row of a list, and never an outside image for a known client", () => { + const codex = { + name: "Codex", + clientDomain: "chatgpt.com", + logoUri: "https://chatgpt.com/logo.png", + ...loopback, + }; + const tile = clientTile(codex); + expect(tile).toMatch( + /^<div class="tile" data-client-mark="known" data-client="openai"><svg viewBox="[0-9. ]+" xmlns="http:\/\/www.w3.org\/2000\/svg" fill="currentColor"><path d="M[^"<>]+"\/><\/svg><\/div>$/, + ); + expect(tile).not.toContain("<img"); + expect(clientTile(codex, { small: true })).toBe( + tile.replace(`class="tile"`, `class="tile small"`), + ); + expect(clientTile({ name: "Notes", ...loopback }, { small: true })).toBe( + `<div class="tile small" data-client-mark="initials">NO</div>`, + ); +});
A core/auth-worker/src/client-mark.ts
@@ -0,0 +1,133 @@ +// client-mark.ts — WHO ASKS, AS A PICTURE: the tile beside the mind's own mark on the consent page +// and on a device's sign-in. A person reads "Claude Code" faster from its mark than from its name. +// +// A CLIENT SAYS ITS OWN NAME AND LOGO, so a picture proves nothing: the page's words say whether +// the name is verified, and where the access goes. That is why this file is careful about which +// picture it shows: +// a built-in mark for a client we know, by the host its access goes to, or by its name +// the client's logo only for a client whose domain is verified (its client ID is a document on +// that domain), and only from that domain, over https +// its initials for everybody else +// The marks are Simple Icons' (https://simpleicons.org, CC0), each in its brand's colour, or in +// the page's own colour where the brand's is black. Simple Icons has none for OpenAI: its mark +// here is the blossom as OpenAI draws it (the path of https://developers.openai.com/favicon.svg), +// in one colour and with no wordmark, and it names OpenAI's own clients and nothing else. Visual +// Studio Code has no free mark, so it shows its initials. +// +// The list of a person's sign-ins (/sessions, and an owner's /members) draws the same tile, small: +// clientTile(client, { small: true }) + +const text = (value: string) => + value.replace(/[&<>"']/g, (character) => `&#${character.charCodeAt(0)};`); + +const MARKS = { + claude: { + fill: "#D97757", + path: "m4.7144 15.9555 4.7174-2.6471.079-.2307-.079-.1275h-.2307l-.7893-.0486-2.6956-.0729-2.3375-.0971-2.2646-.1214-.5707-.1215-.5343-.7042.0546-.3522.4797-.3218.686.0608 1.5179.1032 2.2767.1578 1.6514.0972 2.4468.255h.3886l.0546-.1579-.1336-.0971-.1032-.0972L6.973 9.8356l-2.55-1.6879-1.3356-.9714-.7225-.4918-.3643-.4614-.1578-1.0078.6557-.7225.8803.0607.2246.0607.8925.686 1.9064 1.4754 2.4893 1.8336.3643.3035.1457-.1032.0182-.0728-.164-.2733-1.3539-2.4467-1.445-2.4893-.6435-1.032-.17-.6194c-.0607-.255-.1032-.4674-.1032-.7285L6.287.1335 6.6997 0l.9957.1336.419.3642.6192 1.4147 1.0018 2.2282 1.5543 3.0296.4553.8985.2429.8318.091.255h.1579v-.1457l.1275-1.706.2368-2.0947.2307-2.6957.0789-.7589.3764-.9107.7468-.4918.5828.2793.4797.686-.0668.4433-.2853 1.8517-.5586 2.9021-.3643 1.9429h.2125l.2429-.2429.9835-1.3053 1.6514-2.0643.7286-.8196.85-.9046.5464-.4311h1.0321l.759 1.1293-.34 1.1657-1.0625 1.3478-.8804 1.1414-1.2628 1.7-.7893 1.36.0729.1093.1882-.0183 2.8535-.607 1.5421-.2794 1.8396-.3157.8318.3886.091.3946-.3278.8075-1.967.4857-2.3072.4614-3.4364.8136-.0425.0304.0486.0607 1.5482.1457.6618.0364h1.621l3.0175.2247.7892.522.4736.6376-.079.4857-1.2142.6193-1.6393-.3886-3.825-.9107-1.3113-.3279h-.1822v.1093l1.0929 1.0686 2.0035 1.8092 2.5075 2.3314.1275.5768-.3218.4554-.34-.0486-2.2039-1.6575-.85-.7468-1.9246-1.621h-.1275v.17l.4432.6496 2.3436 3.5214.1214 1.0807-.17.3521-.6071.2125-.6679-.1214-1.3721-1.9246L14.38 17.959l-1.1414-1.9428-.1397.079-.674 7.2552-.3156.3703-.7286.2793-.6071-.4614-.3218-.7468.3218-1.4753.3886-1.9246.3157-1.53.2853-1.9004.17-.6314-.0121-.0425-.1397.0182-1.4328 1.9672-2.1796 2.9446-1.7243 1.8456-.4128.164-.7164-.3704.0667-.6618.4008-.5889 2.386-3.0357 1.4389-1.882.929-1.0868-.0062-.1579h-.0546l-6.3385 4.1164-1.1293.1457-.4857-.4554.0608-.7467.2307-.2429 1.9064-1.3114Z", + }, + cursor: { + fill: "currentColor", + path: "M11.503.131 1.891 5.678a.84.84 0 0 0-.42.726v11.188c0 .3.162.575.42.724l9.609 5.55a1 1 0 0 0 .998 0l9.61-5.55a.84.84 0 0 0 .42-.724V6.404a.84.84 0 0 0-.42-.726L12.497.131a1.01 1.01 0 0 0-.996 0M2.657 6.338h18.55c.263 0 .43.287.297.515L12.23 22.918c-.062.107-.229.064-.229-.06V12.335a.59.59 0 0 0-.295-.51l-9.11-5.257c-.109-.063-.064-.23.061-.23", + }, + openai: { + fill: "currentColor", + // the blossom alone: the box it fills in OpenAI's drawing, which has a disc around it + box: "4 3.93 15.5 15.5", + path: "M9.94494 9.59163V8.13227C9.94494 8.00935 9.99105 7.91713 10.0985 7.85575L13.0327 6.16599C13.4321 5.93558 13.9083 5.8281 14.3998 5.8281C16.2432 5.8281 17.4108 7.25677 17.4108 8.77751C17.4108 8.885 17.4108 9.00792 17.3953 9.13083L14.3537 7.34884C14.1694 7.24135 13.985 7.24135 13.8007 7.34884L9.94494 9.59163ZM16.7963 15.2755V11.7883C16.7963 11.5732 16.704 11.4196 16.5197 11.3121L12.664 9.0693L13.9236 8.34725C14.0311 8.28587 14.1234 8.28587 14.2308 8.34725L17.165 10.037C18.0099 10.5287 18.5782 11.5732 18.5782 12.587C18.5782 13.7544 17.887 14.8298 16.7963 15.2753V15.2755ZM9.03861 12.2031L7.77896 11.4658C7.67146 11.4045 7.62535 11.3122 7.62535 11.1893V7.8098C7.62535 6.16613 8.88501 4.92176 10.5902 4.92176C11.2354 4.92176 11.8344 5.13689 12.3415 5.52089L9.31526 7.27218C9.13097 7.37968 9.03875 7.53328 9.03875 7.74841V12.2033L9.03861 12.2031ZM11.75 13.77L9.94494 12.7562V10.6056L11.75 9.59178L13.5549 10.6056V12.7562L11.75 13.77ZM12.9098 18.44C12.2645 18.44 11.6655 18.2249 11.1585 17.8409L14.1847 16.0896C14.369 15.9821 14.4612 15.8285 14.4612 15.6134V11.1585L15.7363 11.8958C15.8438 11.9572 15.8899 12.0494 15.8899 12.1723V15.5519C15.8899 17.1955 14.6148 18.44 12.9098 18.44ZM9.26901 15.0144L6.33486 13.3246C5.4899 12.833 4.92161 11.7885 4.92161 10.7746C4.92161 9.59177 5.62824 8.53183 6.71886 8.0863V11.5887C6.71886 11.8039 6.81109 11.9575 6.99538 12.065L10.8359 14.2923L9.57621 15.0144C9.46872 15.0758 9.37649 15.0758 9.26901 15.0144ZM9.10013 17.5337C7.36426 17.5337 6.08919 16.2279 6.08919 14.6149C6.08919 14.492 6.1046 14.3691 6.11988 14.2462L9.1461 15.9975C9.33039 16.105 9.51483 16.105 9.69912 15.9975L13.5549 13.7702V15.2295C13.5549 15.3524 13.5088 15.4446 13.4013 15.506L10.4671 17.1958C10.0677 17.4262 9.59148 17.5337 9.09999 17.5337H9.10013ZM12.9098 19.3616C14.7685 19.3616 16.32 18.0406 16.6735 16.2893C18.3939 15.8438 19.5 14.2308 19.5 12.5872C19.5 11.5118 19.0391 10.4673 18.2096 9.71454C18.2864 9.39192 18.3326 9.0693 18.3326 8.74682C18.3326 6.55014 16.5505 4.90634 14.4921 4.90634C14.0774 4.90634 13.6779 4.96772 13.2785 5.10605C12.5872 4.43011 11.6347 4 10.5902 4C8.7314 4 7.17996 5.32103 6.8265 7.07232C5.10605 7.51786 4 9.13083 4 10.7745C4 11.8498 4.4608 12.8944 5.29035 13.6471C5.21354 13.9697 5.16743 14.2923 5.16743 14.6148C5.16743 16.8114 6.94941 18.4552 9.00792 18.4552C9.42261 18.4552 9.82204 18.3939 10.2215 18.2556C10.9127 18.9315 11.8651 19.3616 12.9098 19.3616Z", + }, + zed: { + fill: "#084CCF", + path: "M2.25 1.5a.75.75 0 0 0-.75.75v16.5H0V2.25A2.25 2.25 0 0 1 2.25 0h20.095c1.002 0 1.504 1.212.795 1.92L10.764 14.298h3.486V12.75h1.5v1.922a1.125 1.125 0 0 1-1.125 1.125H9.264l-2.578 2.578h11.689V9h1.5v9.375a1.5 1.5 0 0 1-1.5 1.5H5.185L2.562 22.5H21.75a.75.75 0 0 0 .75-.75V5.25H24v16.5A2.25 2.25 0 0 1 21.75 24H1.655C.653 24 .151 22.788.86 22.08L13.19 9.75H9.75v1.5h-1.5V9.375A1.125 1.125 0 0 1 9.375 8.25h5.314l2.625-2.625H5.625V15h-1.5V5.625a1.5 1.5 0 0 1 1.5-1.5h13.19L21.438 1.5z", + }, + windsurf: { + fill: "currentColor", + path: "M23.55 5.067c-1.2038-.002-2.1806.973-2.1806 2.1765v4.8676c0 .972-.8035 1.7594-1.7597 1.7594-.568 0-1.1352-.286-1.4718-.7659l-4.9713-7.1003c-.4125-.5896-1.0837-.941-1.8103-.941-1.1334 0-2.1533.9635-2.1533 2.153v4.8957c0 .972-.7969 1.7594-1.7596 1.7594-.57 0-1.1363-.286-1.4728-.7658L.4076 5.1598C.2822 4.9798 0 5.0688 0 5.2882v4.2452c0 .2147.0656.4228.1884.599l5.4748 7.8183c.3234.462.8006.8052 1.3509.9298 1.3771.313 2.6446-.747 2.6446-2.0977v-4.893c0-.972.7875-1.7593 1.7596-1.7593h.003a1.798 1.798 0 0 1 1.4718.7658l4.9723 7.0994c.4135.5905 1.05.941 1.8093.941 1.1587 0 2.1515-.9645 2.1515-2.153v-4.8948c0-.972.7875-1.7594 1.7596-1.7594h.194a.22.22 0 0 0 .2204-.2202v-4.622a.22.22 0 0 0-.2203-.2203Z", + }, + gemini: { + fill: "#8E75B2", + path: "M11.04 19.32Q12 21.51 12 24q0-2.49.93-4.68.96-2.19 2.58-3.81t3.81-2.55Q21.51 12 24 12q-2.49 0-4.68-.93a12.3 12.3 0 0 1-3.81-2.58 12.3 12.3 0 0 1-2.58-3.81Q12 2.49 12 0q0 2.49-.96 4.68-.93 2.19-2.55 3.81a12.3 12.3 0 0 1-3.81 2.58Q2.49 12 0 12q2.49 0 4.68.96 2.19.93 3.81 2.55t2.55 3.81", + }, + opencode: { + fill: "currentColor", + path: "M22 24H2V0h20zM17 4.8H7v14.4h10z", + }, +}; + +/** The mark that a word stands for: the scheme of a client's own redirect, or the first word of + * the name it gives. */ +const MARK_BY_WORD: Record<string, keyof typeof MARKS> = { + claude: "claude", + cursor: "cursor", + codex: "openai", + chatgpt: "openai", + openai: "openai", + zed: "zed", + windsurf: "windsurf", + "google gemini": "gemini", + gemini: "gemini", + opencode: "opencode", +}; + +/** The built-in mark of a client we know, and which one. First by what a client cannot claim for + * another: its verified domain, and where its access goes. Else by the name it gives, at the + * name's start alone, so "Not Codex" and "My ChatGPT helper" get initials. */ +export function knownMarkOf(client: { + name: string; + redirectUri: string; + redirectHost: string; + clientDomain?: string; +}): keyof typeof MARKS | null { + const host = client.redirectHost.toLowerCase(); + const domain = (client.clientDomain || "").toLowerCase(); + const anthropic = /(^|\.)claude\.(ai|com)$/; + const openai = /(^|\.)(chatgpt\.com|openai\.com)$/; + if (anthropic.test(domain) || anthropic.test(host)) return "claude"; + if (openai.test(domain) || openai.test(host)) return "openai"; + const scheme = /^(cursor|zed|windsurf):/i.exec(client.redirectUri)?.[1]?.toLowerCase(); + if (scheme) return MARK_BY_WORD[scheme] ?? null; + const named = + /^(claude|cursor|codex|chatgpt|openai|zed|windsurf|google gemini|gemini|opencode)\b/i + .exec(client.name.trim())?.[1] + ?.toLowerCase(); + return (named && MARK_BY_WORD[named]) || null; +} + +/** The client's own logo, when it may be shown: the client's domain is verified, and the logo is + * on that domain (or under it), over https. Its origin is what the page's policy must allow. */ +export function shownLogoOf(client: { logoUri?: string; clientDomain?: string }) { + if (!client.logoUri || !client.clientDomain) return null; + let logo: URL; + try { + logo = new URL(client.logoUri); + } catch { + return null; + } + const domain = client.clientDomain.toLowerCase(); + const onDomain = logo.hostname === domain || logo.hostname.endsWith(`.${domain}`); + if (logo.protocol !== "https:" || !onDomain || logo.username || logo.password) return null; + return { href: logo.href, origin: logo.origin }; +} + +/** The client's tile, as HTML for a plain page (plain-page.css `.tile`): the size of the mind's + * own mark beside it, or `small` for a row of a list. */ +export function clientTile( + client: { + name: string; + redirectUri: string; + redirectHost: string; + logoUri?: string; + clientDomain?: string; + }, + { small = false }: { small?: boolean } = {}, +): string { + const tile = small ? "tile small" : "tile"; + const known = knownMarkOf(client); + if (known) + return `<div class="${tile}" data-client-mark="known" data-client="${known}"><svg viewBox="${"box" in MARKS[known] ? MARKS[known].box : "0 0 24 24"}" xmlns="http://www.w3.org/2000/svg" fill="${MARKS[known].fill}"><path d="${MARKS[known].path}"/></svg></div>`; + const logo = shownLogoOf(client); + if (logo) + return `<div class="${tile}" data-client-mark="logo"><img src="${text(logo.href)}" alt="" referrerpolicy="no-referrer"></div>`; + // the first two letters or digits of the name + const initials = [...client.name.replace(/[^\p{L}\p{N}]/gu, "")].slice(0, 2).join(""); + return `<div class="${tile}" data-client-mark="initials">${text(initials.toUpperCase() || "?")}</div>`; +}
A core/auth-worker/src/cloud-key.ts
@@ -0,0 +1,45 @@ +// cloud-key.ts — WHETHER AN iterate Cloud PUBLISHES A KEY: the one check behind the name +// `iterate-cloud` on `/keys/enrol` (./key-rules.ts `CLOUD_ACTOR`). The link names the Cloud's +// origin, and this Worker reads `<origin>/.well-known/iterate-cloud` itself, at the consent page +// and again at the member's press. The secrets Worker reads the same document for the Cloud's +// clients (core/secrets-worker cloud-client.ts); this reads its two other fields, `actor` and +// `publicKey`, and nothing else of it. +import { deadlineIn, jsonOf, textWithin } from "iterate/mind-identity-log"; +import { z } from "zod"; +import { CLOUD_ACTOR } from "./key-rules.ts"; + +const CLOUD_DOCUMENT_PATH = "/.well-known/iterate-cloud"; +/** The Cloud's whole document, its clients' facts with it, is a few KiB. */ +const DOCUMENT_MAX_BYTES = 256 * 1024; +/** A consent page waits this long for the Cloud, at most. */ +const DOCUMENT_READ_MS = 5000; + +const CloudDocument = z.object({ actor: z.literal(CLOUD_ACTOR), publicKey: z.string().min(1) }); + +/** WHY `publicKey` IS NOT THE KEY THAT THE CLOUD AT `cloud` PUBLISHES, in a member's words, or + * null when it is. `cloud` is an `https:` origin (./key-rules.ts `cloudOriginOf`). A redirect is + * no answer: the key must be the one that this origin itself gives. */ +export async function cloudKeyRefusal(cloud: string, publicKey: string): Promise<string | null> { + const host = new URL(cloud).host; + const deadline = deadlineIn(DOCUMENT_READ_MS); + const body = await fetch(`${cloud}${CLOUD_DOCUMENT_PATH}`, { + headers: { accept: "application/json" }, + redirect: "manual", + signal: AbortSignal.timeout(DOCUMENT_READ_MS), + }) + .then((answer) => + answer.status === 200 ? textWithin(answer, DOCUMENT_MAX_BYTES, deadline.expiry) : null, + ) + .catch(() => null) + .finally(deadline.clear); + const document = body ? CloudDocument.safeParse(jsonOf(body)) : null; + if (!document?.success) { + console.info({ event: "auth.cloud-key-refused", cloud, answered: false }); + return `${host} did not answer with an iterate Cloud's key at ${cloud}${CLOUD_DOCUMENT_PATH}, so this mind cannot check the key in this link. Nothing was added. Try again later.`; + } + if (document.data.publicKey !== publicKey) { + console.info({ event: "auth.cloud-key-refused", cloud, answered: true }); + return `${host} publishes another key than the one in this link, so this is not its key. Nothing was added.`; + } + return null; +}
A core/auth-worker/src/config.test.ts
@@ -0,0 +1,94 @@ +import { inspect } from "node:util"; +import { expect, test } from "vitest"; +import { atMindsZone, authConfigOf, isOwner, tokenAudiencesOf } from "./config.ts"; +import { configVars } from "./test-support.ts"; + +test("the config is the shared one and the Worker's own signing key", () => { + const config = authConfigOf(configVars()); + expect(config).toMatchObject({ + controlPlaneHostname: "iterate.example.com", + zones: ["example.com"], + ownerEmails: ["owner@example.net"], + topology: "full-cloudflare", + }); + expect(config.signingKey.exposeSecret()).toBe("a signing key for a test, never a real one"); +}); + +test("a config with no signing key is refused, and the refusal names the variable", () => { + const { ITERATE } = configVars(); + expect(() => authConfigOf({ ITERATE })).toThrow("ITERATE__SIGNING_KEY"); +}); + +test("the config names the team and the application of Cloudflare Access, and one without them is refused", () => { + const vars = configVars(); + expect(authConfigOf(vars)).toMatchObject({ + cloudflareAccessTeamDomain: "team.cloudflareaccess.com", + cloudflareAccessAudienceTag: "the-audience-tag-of-the-owners-application", + }); + const { cloudflareAccessTeamDomain: _, ...withoutTeam } = JSON.parse(vars.ITERATE); + expect(() => authConfigOf({ ...vars, ITERATE: JSON.stringify(withoutTeam) })).toThrow( + "ITERATE__CLOUDFLARE_ACCESS_TEAM_DOMAIN", + ); + const { cloudflareAccessAudienceTag: __, ...withoutTag } = JSON.parse(vars.ITERATE); + expect(() => authConfigOf({ ...vars, ITERATE: JSON.stringify(withoutTag) })).toThrow( + "ITERATE__CLOUDFLARE_ACCESS_AUDIENCE_TAG", + ); +}); + +test("a dump of the config prints REDACTED where the signing key is", () => { + const config = authConfigOf(configVars()); + for (const dump of [JSON.stringify(config), inspect(config), `${config.signingKey}`]) { + expect(dump).not.toContain("a signing key for a test"); + expect(dump).toMatch(/redacted/i); + } +}); + +test.for([ + ["at a zone", "owner@example.com"], + ["under a zone", "owner@mail.example.com"], + ["at the second zone", "owner@second.example"], +])("an owner's address %s of the mind is refused: the mind receives its mail", ([, email]) => { + const vars = configVars({ zones: ["example.com", "second.example"], ownerEmails: [email!] }); + expect(() => authConfigOf(vars)).toThrow(/ITERATE__OWNER_EMAILS.*is at a zone of the mind/); +}); + +test("an address is the mind's own at any of its zones, and nowhere else", () => { + const config = { zones: ["example.com", "second.example"] }; + expect( + [ + "agent@example.com", + "Agent@Sub.Second.Example ", + // another domain that only ends with the same letters + "jo@notexample.com", + "jo@example.net", + ].map((email) => atMindsZone(config, email)), + ).toEqual([true, true, false, false]); +}); + +test("an owner is an address the config names, and no other", () => { + const config = { ownerEmails: ["owner@example.net"] }; + expect([ + isOwner(config, "owner@example.net"), + isOwner(config, " Owner@Example.net"), + isOwner(config, "owner+tag@example.net"), + isOwner(config, "other@example.net"), + ]).toEqual([true, true, false, false]); +}); + +test("the token audiences are the API and the MCP server, and the external mind's address when it runs outside the stack", () => { + const controlPlaneHostname = "iterate.example.com"; + expect(tokenAudiencesOf({ controlPlaneHostname, topology: "full-cloudflare" })).toEqual([ + "https://iterate.example.com/api", + "https://iterate.example.com/mcp", + ]); + expect( + tokenAudiencesOf({ + controlPlaneHostname, + topology: "external-mind-connects-into-cloudflare-boundary", + }), + ).toEqual([ + "https://iterate.example.com/api", + "https://iterate.example.com/mcp", + "https://iterate.example.com/api/provide-connect", + ]); +});
A core/auth-worker/src/config.ts
@@ -0,0 +1,56 @@ +// config.ts — WHAT THE AUTH WORKER IS TOLD: the config that every Worker of the mind gets +// (iterate/mind-config), and its own key. Its owners are `ownerEmails`, the resources it issues +// tokens for follow from the control-plane hostname and the topology, and every hostname of every zone +// is the mind's own. Pure: ./env.ts reads it out of the Worker's variables. +import { fieldNameOf, redacted } from "iterate/app-config"; +import { mindApiUrlOf, mindMcpUrlOf, mindProvideConnectResourceOf } from "iterate/mind-api"; +import { Hostname, type MindConfig, mindConfigOf, zoneOfMailAddress } from "iterate/mind-config"; +import { z } from "zod"; + +const ownFields = { + signingKey: redacted(z.string().min(1)), + /** The domain of the account's Zero Trust team, `<name>.cloudflareaccess.com`: the issuer of + * the tokens that prove an owner's address (./access-sign-in.ts), where its keys are read. */ + cloudflareAccessTeamDomain: Hostname, + /** The audience tag of the stack's one Access application, on the control plane's + * `/sign-in/access`: a token of the team for any other application proves nothing here. */ + cloudflareAccessAudienceTag: z.string().min(1), +}; + +/** The Worker's config out of its variables: `ITERATE`, with the two facts of Cloudflare Access + * that are this Worker's own, and the secret `ITERATE__SIGNING_KEY`, which signs the session + * cookies (./cookies.ts) and a key's tokens (./key-tokens.ts). Throws + * naming the field that is wrong. An owner's address at a zone of the mind is refused: the mind + * receives that address's mail, so the mind's code, which may be hostile, could sign in as that + * owner. */ +export function authConfigOf(env: object) { + const config = mindConfigOf(env, ownFields); + const own = config.ownerEmails.find((email) => atMindsZone(config, email)); + if (own) + throw new Error( + `${fieldNameOf(["ownerEmails"], { prefix: "ITERATE" })}: ${own} is at a zone of the mind, which receives that address's mail, so the mind could sign in as that owner`, + ); + return config; +} + +/** Whether `email` is at a zone of the mind or under one. Every mailbox there is the mind's, + * whose code may be hostile: the mind receives the sign-in code mailed to that address. */ +export const atMindsZone = (config: Pick<MindConfig, "zones">, email: string) => + zoneOfMailAddress(config, email.trim()) !== null; + +/** An owner is a member the config names: the people a deploy lets in, so the only ones who let + * another member in again. */ +export const isOwner = (config: Pick<MindConfig, "ownerEmails">, email: string) => + config.ownerEmails.includes(email.trim().toLowerCase()); + +/** THE AUDIENCES OF THE TOKENS THIS WORKER ISSUES TO MEMBERS (RFC 8707 resources), each a + * canonical URI: the mind's API and its MCP server, and the address an external mind connects in + * at, when the mind runs outside the stack. Besides them, any hostname of the mind is an audience + * for anyone signed in (./oauth.ts `mindHostResourceOf`). A request for any other is refused. */ +export const tokenAudiencesOf = (config: Pick<MindConfig, "controlPlaneHostname" | "topology">) => [ + mindApiUrlOf(config.controlPlaneHostname), + mindMcpUrlOf(config.controlPlaneHostname), + ...(config.topology === "external-mind-connects-into-cloudflare-boundary" + ? [mindProvideConnectResourceOf(config.controlPlaneHostname)] + : []), +];
A core/auth-worker/src/cookies.ts
@@ -0,0 +1,546 @@ +import { waitUntil } from "cloudflare:workers"; +import { cookieValueOf } from "iterate/lib"; +import type { SignInMethod } from "iterate/principal"; +import { jwtVerify, SignJWT } from "jose"; +import { z } from "zod"; +import type { AccountFacts } from "./account-facts.ts"; +import { isBlocked } from "./blocked.ts"; +import { configOf, type Env, issuerOf } from "./env.ts"; + +// A browser's session at the issuer is a row of `browser_sessions` (../migrations/0011), and its +// cookie holds the row's id. It ends at expiry, at sign-out, on /sessions (./sessions-page.ts), +// or for everyone when the config's signing key changes. The row's `method` says which of three +// kinds it is. The first two are a person's session, and their word is the person's sign-in +// method (iterate/principal `SignInMethod`), which the session, its grants, their tokens and the +// person that the boundary stamps all carry: +// +// a passkey's ("passkey") a member's session, which ends with the passkey that opened +// it. Membership is checked again on every use. `sessionOf` answers it. +// a mailed code's ("email") a mailed code proved the address of a person who was no +// member (./email-sign-in.ts). An app of the mind with users of its own +// takes it, when the app names "email". It is never a member's, whatever +// its address becomes: only `personSessionOf` answers it, for the few +// pages that take anyone. +// to add a first passkey (./enrolment.ts; its `method` is the proof's, never a sign-in method) +// neither reader here answers it, so no page and no RPC that asks who is +// signed in takes it for a person. +const SESSION_COOKIE = "__Host-iterate-auth-session"; +const SESSION_SECONDS = 30 * 24 * 3600; +/** The cookie's token is for this use alone: a token this key signed for another (a key's token, + * ./key-tokens.ts) is no session. */ +const AUDIENCE = "session"; +/** `last_seen_at` is written at most this often: a D1 write on every request would cost. */ +const SEEN_EVERY_MS = 10 * 60_000; +/** A passkey's ended or expired row stays this long, then the user's next sign-in deletes it. */ +const KEPT_MS = 30 * 24 * 3600_000; + +/** WHICH OF A PERSON'S SESSIONS AND SIGN-INS ARE MEANT: all of them, or those alone that a mailed + * code opened (the `method` of a session and of a grant). A session that a mailed code opened + * lists and ends its own kind alone on /sessions (`reachOf`): its address may be a member's by + * now, and mail must not reach what a passkey opened. */ +export type Reach = "all" | Exclude<SignInMethod, "passkey">; + +/** What `session` manages of its person: a passkey's, everything. */ +export const reachOf = (session: PersonSession): Reach => + session.method === "passkey" ? "all" : session.method; + +const within = (reach: Reach, column: string) => + reach === "all" ? "" : `and ${column} = '${reach}'`; + +/** A member's session at the issuer, which a passkey opened. `id` is its row's. */ +export type Session = { id: string; userId: string; email: string }; + +/** A session of anyone signed in, and how they signed in. A passkey's acts as a member while its + * address is a member's (./members.ts `isMemberSession`). A mailed code's is no member's. */ +export type PersonSession = Session & { + method: SignInMethod; + /** When the session's row expires, in epoch milliseconds. */ + expiresAt: number; +}; + +/** A NEW SESSION OF A PASSKEY: its row, and the cookie that holds the row's id. `key` is the id + * of the passkey that opened it: the session ends with the key. `request` is the sign-in's, for + * its User-Agent. */ +export async function sessionCookie( + env: Env, + request: Request, + user: { id: string; email: string }, + key: string, +): Promise<{ setCookie: string; session: string }> { + const session = newSessionId(); + const now = Date.now(); + await env.DB.batch([ + env.DB.prepare( + `delete from browser_sessions + where user_id = ?1 and coalesce(ended_at, expires_at) < ?2`, + ).bind(user.id, now - KEPT_MS), + env.DB.prepare( + `insert into browser_sessions + (id, user_id, method, key_id, user_agent, created_at, last_seen_at, expires_at) + values (?1, ?2, 'passkey', ?3, ?4, ?5, ?5, ?6)`, + ).bind(session, user.id, key, userAgentOf(request), now, now + SESSION_SECONDS * 1000), + ]); + return { setCookie: await cookieOf(env, user, session, SESSION_SECONDS), session }; +} + +/** A NEW SESSION OF A PERSON WHO IS NO MEMBER, whose address a mailed code proved: its row, whose + * method is "email", and the cookie that holds the row's id. */ +export async function emailSessionCookie( + env: Env, + request: Request, + user: { id: string; email: string }, +): Promise<{ setCookie: string; session: string }> { + const session = newSessionId(); + const now = Date.now(); + await env.DB.prepare( + `insert into browser_sessions + (id, user_id, method, key_id, user_agent, created_at, last_seen_at, expires_at) + values (?1, ?2, 'email', null, ?3, ?4, ?4, ?5)`, + ) + .bind(session, user.id, userAgentOf(request), now, now + SESSION_SECONDS * 1000) + .run(); + return { setCookie: await cookieOf(env, user, session, SESSION_SECONDS), session }; +} + +/** REMOVES THE SESSIONS THAT ARE NO PASSKEY'S AND ARE OVER: ended, or expired. One statement for + * the batch that sweeps the mailed codes (./email-sign-in.ts), which runs before any such session + * is made, so their rows never outgrow the codes that were asked for. A passkey's rows are kept + * for `KEPT_MS` and go at that person's next sign-in (`sessionCookie`). */ +export const sessionsOverRemoved = (env: Env, now: number) => + env.DB.prepare( + "delete from browser_sessions where method != 'passkey' and coalesce(ended_at, expires_at) <= ?1", + ).bind(now); + +export const newSessionId = () => `session_${crypto.randomUUID().replaceAll("-", "")}`; + +/** The browser's User-Agent as a session's row keeps it. */ +export const userAgentOf = (request: Request) => + (request.headers.get("user-agent") || "").slice(0, 300); + +/** The `Set-Cookie` of the session `session` of `user`, which lasts `seconds`. */ +export async function cookieOf( + env: Env, + user: { id: string; email: string }, + session: string, + seconds: number, +) { + const token = await new SignJWT({ email: user.email, session }) + .setProtectedHeader({ alg: "HS256" }) + .setIssuer(issuerOf(env)) + .setAudience(AUDIENCE) + .setSubject(user.id) + .setIssuedAt() + .setExpirationTime(`${seconds}s`) + .sign(keyOf(env)); + return cookie(SESSION_COOKIE, token, seconds); +} + +/** What the request's session cookie says, when this Worker signed it: the row's id and whose it + * is. It is no session yet: its row says whether it is live, and of which kind. */ +export async function cookieClaimsOf( + env: Env, + request: Request, +): Promise<{ session: string; userId: string; email: string } | null> { + const token = cookieValueOf(request.headers.get("cookie"), SESSION_COOKIE); + if (!token) return null; + // every bad cookie is no cookie: why it failed is never said + const claims = await jwtVerify(token, keyOf(env), { + issuer: issuerOf(env), + audience: AUDIENCE, + algorithms: ["HS256"], + }).then( + ({ payload }) => payload, + () => null, + ); + const email = z.string().safeParse(claims?.email); + const session = z.string().min(1).safeParse(claims?.session); + if (!claims?.sub || !email.success || !session.success) return null; + return { session: session.data, userId: claims.sub, email: email.data }; +} + +/** THE BROWSER'S SESSION, OF ANYONE SIGNED IN: its cookie, and a row that is not ended and not + * expired, of a passkey whose key is not removed (a lost device holds a passkey and its session: + * to remove the one must end the other), or of a person who was no member. One read. For a page + * that takes a person who is no member: every other page asks `sessionOf`. */ +export async function personSessionOf(env: Env, request: Request): Promise<PersonSession | null> { + const claims = await cookieClaimsOf(env, request); + if (!claims) return null; + const now = Date.now(); + const row = await env.DB.prepare( + `select s.method, s.last_seen_at, s.expires_at from browser_sessions s + where s.id = ?1 and s.user_id = ?2 and s.ended_at is null and s.expires_at > ?3 + and ${LIVE_PERSON_SESSION}`, + ) + .bind(claims.session, claims.userId, now) + .first<{ method: SignInMethod; last_seen_at: number; expires_at: number }>(); + if (!row) return null; + if (row.last_seen_at < now - SEEN_EVERY_MS) waitUntil(seen(env, claims.session, now)); + return { + id: claims.session, + userId: claims.userId, + email: claims.email, + method: row.method, + expiresAt: row.expires_at, + }; +} + +/** As SQL over a row `s` of `browser_sessions`: the row is a person's session, a mailed code's + * or a passkey's whose key is not removed. So a row that answers it has a `SignInMethod` for + * its `method`, and a session that may add a first passkey (./enrolment.ts) never answers. A + * passkey that was added while its owner was no member opens no session (../migrations/0016, + * ./passkey-sign-in.ts): a row of one is nobody's. */ +const LIVE_PERSON_SESSION = `(s.method = 'email' or (s.method = 'passkey' and exists + (select 1 from keys k + where k.id = s.key_id and k.user_id = s.user_id and k.revoked_at is null + and k.outsider = 0)))`; + +/** THE BROWSER'S SESSION OF A PASSKEY, the one kind that can be a member's: what every page of + * the control plane asks, but the few that take anyone (`personSessionOf`). */ +export async function sessionOf(env: Env, request: Request): Promise<Session | null> { + const session = await personSessionOf(env, request); + return session?.method === "passkey" ? session : null; +} + +/** The conditional write: of two requests at once, one writes. */ +async function seen(env: Env, session: string, now: number) { + await env.DB.prepare( + "update browser_sessions set last_seen_at = ?2 where id = ?1 and last_seen_at < ?3", + ) + .bind(session, now, now - SEEN_EVERY_MS) + .run() + .catch((error: unknown) => + console.warn({ event: "auth.session-seen-failed", message: String(error) }), + ); +} + +/** Which of a person's sessions to end: one, every one but this browser's, or every one. */ +export type SessionsEnded = { session: string } | { allBut: string } | "all"; + +/** ENDS THIS BROWSER'S ROW AS ITS COOKIE IS CLEARED: the session the request's cookie holds, of + * either kind. Clearing the cookie must not wait on D1: a failure to end the row is logged, and + * the caller still answers with the cleared cookie. The row then ends at its own expiry, or on + * /sessions. */ +export async function endThisSession(env: Env, request: Request, facts: AccountFacts) { + try { + const claims = await cookieClaimsOf(env, request); + if (claims) await endSessions(env, claims.userId, "all", { session: claims.session }, facts); + } catch (error) { + console.warn({ event: "auth.session-end-failed", message: String(error) }); + } +} + +/** ENDS SESSIONS OF ONE PERSON, each with a fact. A session that is not that person's, that is + * not within `reach`, or that ended already, ends nothing. Answers the ids it ended. */ +export async function endSessions( + env: Env, + userId: string, + reach: Reach, + which: SessionsEnded, + facts: AccountFacts, +): Promise<string[]> { + const now = Date.now(); + const [condition, bound] = + which === "all" + ? ["", []] + : "session" in which + ? ["and id = ?3", [which.session]] + : ["and id != ?3", [which.allBut]]; + const { results } = await env.DB.prepare( + `update browser_sessions set ended_at = ?2 + where user_id = ?1 and ended_at is null and expires_at > ?2 ${condition} + ${within(reach, "method")} + returning id`, + ) + .bind(userId, now, ...bound) + .all<{ id: string }>(); + for (const { id } of results) + facts.add(userId, { + type: "events.iterate.com/account/session-ended", + payload: { session: id, at: now }, + idempotencyKey: `account/session-ended/${id}`, + }); + return results.map(({ id }) => id); +} + +/** A person's live sessions, newest first, as /sessions lists them. `method`: as on + * `PersonSession`. */ +export type SessionRow = { + id: string; + method: SignInMethod; + userAgent: string; + createdAt: number; + lastSeenAt: number; +}; + +export async function liveSessionsOf( + env: Env, + userId: string, + reach: Reach, +): Promise<SessionRow[]> { + const { results } = await env.DB.prepare( + `select s.id, s.method, s.user_agent as userAgent, s.created_at as createdAt, + s.last_seen_at as lastSeenAt + from browser_sessions s + where s.user_id = ?1 and s.ended_at is null and s.expires_at > ?2 + and ${LIVE_PERSON_SESSION} + ${within(reach, "s.method")} + order by s.created_at desc`, + ) + .bind(userId, Date.now()) + .all<SessionRow>(); + return results; +} + +export const clearSessionCookie = cookie(SESSION_COOKIE, "", 0); + +// A GUEST'S COOKIE (./guest-sign-in.ts) is kept apart from the session's, and proves nothing: the +// authorization endpoint alone reads it (./authorize.ts), for a host's own sign-in whose app names +// guests. It holds no row: the user id, the key of the guest's row and the name they typed, signed. +// It outlives a guest's 15 minutes on an app's host (./oauth.ts), so that a browser that comes back +// is the same guest and is asked for no name again: 30 days from the browser's last visit. +const GUEST_COOKIE = "__Host-iterate-auth-guest-session"; +const GUEST_SECONDS = 30 * 24 * 3600; +/** The name form's own cookie: the `next` it goes on to and the form's state, for ten minutes. */ +const GUEST_FORM_COOKIE = "__Host-iterate-auth-guest-form"; +const GUEST_FORM_SECONDS = 10 * 60; + +/** The key of a guest's row in `users.email`: no address, so no proof of an address reaches it. */ +export const GUEST_KEY_PREFIX = "guest:"; + +/** A guest's cookie, set again at each session it earns on an app's host. */ +export async function guestCookie(env: Env, guest: { id: string; key: string; name: string }) { + const token = await signed(env, "guest-session", { key: guest.key, name: guest.name }) + .setSubject(guest.id) + .setExpirationTime(`${GUEST_SECONDS}s`) + .sign(keyOf(env)); + return cookie(GUEST_COOKIE, token, GUEST_SECONDS); +} + +/** THE GUEST THIS BROWSER IS, or null; `blocked` when an owner blocked them (./members.ts). The + * token's audience is this cookie's own: a session's token under this name is no guest. */ +export async function guestOf( + env: Env, + request: Request, +): Promise<{ userId: string; email: string; name: string; blocked: boolean } | null> { + const claims = await claimsOf(env, request, GUEST_COOKIE, "guest-session"); + const key = z.string().startsWith(GUEST_KEY_PREFIX).safeParse(claims?.key); + const name = z.string().min(1).safeParse(claims?.name); + if (!claims?.sub || !key.success || !name.success) return null; + return { + userId: claims.sub, + email: key.data, + name: name.data, + blocked: await isBlocked(env, key.data), + }; +} + +/** The name form's cookie: the browser that was shown the form, and where it goes on. */ +export async function guestFormCookie(env: Env, form: { next: string; state: string }) { + const token = await signed(env, "guest-form", form) + .setExpirationTime(`${GUEST_FORM_SECONDS}s`) + .sign(keyOf(env)); + return cookie(GUEST_FORM_COOKIE, token, GUEST_FORM_SECONDS); +} + +export async function guestFormOf(env: Env, request: Request) { + const form = z + .object({ next: z.string(), state: z.string().min(1) }) + .safeParse(await claimsOf(env, request, GUEST_FORM_COOKIE, "guest-form")); + if (!form.success) return null; + return form.data; +} + +export const clearGuestFormCookie = cookie(GUEST_FORM_COOKIE, "", 0); +export const clearGuestCookie = cookie(GUEST_COOKIE, "", 0); + +// A MEMBER OF ANOTHER MIND (./mind-sign-in.ts) has a cookie like a guest's: no row, and read by the +// authorization endpoint alone, for a host's own sign-in whose app names "mind". It holds the user +// id, the key of the row, and the mind that vouched: its id, its hostname and the person's user +// id there. It lasts 24 hours from the vouch and is never set again, so a member whom that mind +// removes keeps this mind's session for 24 hours at most; then their mind is asked again. +const MIND_COOKIE = "__Host-iterate-auth-mind-session"; +const MIND_SESSION_SECONDS = 24 * 3600; +/** The sign-in's own cookie, between `POST /sign-in/mind` and the return from the person's mind: + * the browser that started it, and what it waits for. The return is a POST from the other mind's + * page, a cross-site request, so the cookie is `SameSite=None`: a Lax one is not sent with it. + * Its path is the sign-in's alone, so no other request carries it, and with a path it cannot have + * the `__Host-` prefix: `__Secure-`, with no Domain, is host-only too. */ +const MIND_FORM_COOKIE = "__Secure-iterate-auth-mind-form"; +const MIND_FORM_SECONDS = 10 * 60; +export const MIND_FORM_PATH = "/sign-in/mind"; + +/** The key of a member of another mind's row in `users.email`: `mind:<that mind's id>:<their user + * id there>`. No address, so no proof of an address reaches it, and it is nobody's member. */ +export const MIND_KEY_PREFIX = "mind:"; + +/** Whom another mind vouched for: that mind and the person's user id there. */ +export type Vouched = { id: string; hostname: string; userId: string }; + +/** The cookie of a member of another mind, set once at the vouch. */ +export async function mindSessionCookie( + env: Env, + person: { id: string; key: string; mind: Vouched }, +) { + const { mind } = person; + const token = await signed(env, "mind-session", { + key: person.key, + mind: mind.id, + hostname: mind.hostname, + user: mind.userId, + }) + .setSubject(person.id) + .setExpirationTime(`${MIND_SESSION_SECONDS}s`) + .sign(keyOf(env)); + return cookie(MIND_COOKIE, token, MIND_SESSION_SECONDS); +} + +/** THE MEMBER OF ANOTHER MIND THIS BROWSER IS, or null; `expiresAt` in epoch milliseconds, the + * end that no visit moves. */ +export async function mindSessionOf( + env: Env, + request: Request, +): Promise<{ userId: string; email: string; mind: Vouched; expiresAt: number } | null> { + const claims = await claimsOf(env, request, MIND_COOKIE, "mind-session"); + const parsed = z + .object({ + sub: z.string().startsWith("user_"), + key: z.string().startsWith(MIND_KEY_PREFIX), + mind: z.string().min(1), + hostname: z.string().min(1), + user: z.string().min(1), + exp: z.number(), + }) + .safeParse(claims); + if (!parsed.success) return null; + const { sub, key, mind, hostname, user, exp } = parsed.data; + return { + userId: sub, + email: key, + mind: { id: mind, hostname, userId: user }, + expiresAt: exp * 1000, + }; +} + +/** What a sign-in by another mind waits for (./mind-sign-in.ts). */ +export type MindForm = { + next: string; + /** The host of the app the sign-in is for; a form from before it was kept has none. */ + app?: string; + hostname: string; + mind: string; + state: string; + nonce: string; +}; + +export async function mindFormCookie(env: Env, form: MindForm) { + const token = await signed(env, "mind-form", form) + .setExpirationTime(`${MIND_FORM_SECONDS}s`) + .sign(keyOf(env)); + return mindFormCookieOf(token, MIND_FORM_SECONDS); +} + +export async function mindFormOf(env: Env, request: Request): Promise<MindForm | null> { + const form = z + .object({ + next: z.string().min(1), + app: z.string().min(1).optional(), + hostname: z.string().min(1), + mind: z.string().min(1), + state: z.string().min(1), + nonce: z.string().min(1), + }) + .safeParse(await claimsOf(env, request, MIND_FORM_COOKIE, "mind-form")); + if (!form.success) return null; + return form.data; +} + +const mindFormCookieOf = (value: string, maxAgeSeconds: number) => + `${MIND_FORM_COOKIE}=${value}; HttpOnly; Secure; SameSite=None; Path=${MIND_FORM_PATH}; Max-Age=${maxAgeSeconds}`; + +export const clearMindFormCookie = mindFormCookieOf("", 0); + +// A MEMBER'S INTENT TO OPEN AN APP OF ANOTHER MIND (./vouch.ts `/sign-in/open`): set by this mind's +// own page, for one use and two minutes, so that a vouch to a mind that this mind lets in goes on +// with no press only when the member began it here. Any other site's link to the vouch gets the +// Continue page. +const VOUCH_INTENT_COOKIE = "__Host-iterate-auth-vouch-intent"; +const VOUCH_INTENT_SECONDS = 120; + +export async function vouchIntentCookie(env: Env, intent: { app: string; user: string }) { + const token = await signed(env, "vouch-intent", intent) + .setExpirationTime(`${VOUCH_INTENT_SECONDS}s`) + .sign(keyOf(env)); + return cookie(VOUCH_INTENT_COOKIE, token, VOUCH_INTENT_SECONDS); +} + +export async function vouchIntentOf(env: Env, request: Request) { + const intent = z + .object({ app: z.string().min(1), user: z.string().min(1) }) + .safeParse(await claimsOf(env, request, VOUCH_INTENT_COOKIE, "vouch-intent")); + if (!intent.success) return null; + return intent.data; +} + +export const clearVouchIntentCookie = cookie(VOUCH_INTENT_COOKIE, "", 0); +export const clearMindCookie = cookie(MIND_COOKIE, "", 0); + +// A MIND SIGN-IN THAT JUST COMPLETED (./mind-sign-in.ts): set at the return, for the person it +// made and the app it was for, for 30 seconds: the return goes on to the app, whose guard asks +// the authorization endpoint at once. There it answers that host's `prompt=select_account` once +// (./authorize.ts): a host that the person signed out of asks who they are, and they just said. +// Any authorization clears it, and its `jti` is taken once (`statements`), so it answers one +// prompt at most. +export const MIND_FRESH_COOKIE = "__Host-iterate-auth-mind-fresh"; +const MIND_FRESH_SECONDS = 30; + +export async function mindFreshCookie(env: Env, fresh: { user: string; app: string }) { + const token = await signed(env, "mind-fresh", fresh) + .setJti(crypto.randomUUID()) + .setExpirationTime(`${MIND_FRESH_SECONDS}s`) + .sign(keyOf(env)); + return cookie(MIND_FRESH_COOKIE, token, MIND_FRESH_SECONDS); +} + +export async function mindFreshOf(env: Env, request: Request) { + const fresh = z + .object({ + user: z.string().min(1), + app: z.string().min(1), + jti: z.string().min(1), + exp: z.number(), + }) + .safeParse(await claimsOf(env, request, MIND_FRESH_COOKIE, "mind-fresh")); + return fresh.success ? fresh.data : null; +} + +export const clearMindFreshCookie = cookie(MIND_FRESH_COOKIE, "", 0); + +const signed = (env: Env, audience: string, claims: Record<string, string>) => + new SignJWT(claims) + .setProtectedHeader({ alg: "HS256" }) + .setIssuer(issuerOf(env)) + .setAudience(audience) + .setIssuedAt(); + +/** What the cookie `name` holds, when this Worker signed it for `audience`; every bad cookie is + * no cookie. */ +async function claimsOf(env: Env, request: Request, name: string, audience: string) { + const token = cookieValueOf(request.headers.get("cookie"), name); + if (!token) return null; + return jwtVerify(token, keyOf(env), { + issuer: issuerOf(env), + audience, + algorithms: ["HS256"], + }).then( + ({ payload }) => payload, + () => null, + ); +} + +// `__Host-` binds each cookie to this origin over https. `SameSite=Lax` because a client's link to +// the authorization endpoint is a cross-site navigation. +function cookie(name: string, value: string, maxAgeSeconds: number) { + return `${name}=${value}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAgeSeconds}`; +} + +const keyOf = (env: Env) => new TextEncoder().encode(configOf(env).signingKey.exposeSecret());
A core/auth-worker/src/device/callback.ts
@@ -0,0 +1,79 @@ +import { AccountFacts } from "../account-facts.ts"; +import { sessionOf } from "../cookies.ts"; +import { type Env, issuerOf } from "../env.ts"; +import { oauthHelpers } from "../oauth.ts"; +import { VERIFICATION_PATH } from "./protocol.ts"; +import { type DeviceRequest, deviceStore } from "./store.ts"; + +export async function deviceCallbackResponse(env: Env, request: Request) { + const url = new URL(request.url); + const facts = new AccountFacts(); + const store = deviceStore(env.OAUTH_KV); + const key = url.searchParams.get("state") || ""; + const device = + url.searchParams.get("iss") === issuerOf(env) && /^[\w-]{43}$/.test(key) + ? await store.byKey(key) + : null; + const outcome = (to: "approved" | "declined" | "failed") => + facts.on( + new Response(null, { + status: 303, + headers: { + location: `${VERIFICATION_PATH}?${new URLSearchParams({ outcome: to, ...(device?.letIn && { kind: "let-in" }) })}`, + "cache-control": "no-store", + }, + }), + ); + const code = url.searchParams.get("code"); + const codeGrant = code ? grantOfCode(code) : null; + if (codeGrant && device?.grant?.grantId === codeGrant.grantId) return outcome("approved"); + const person = (await sessionOf(env, request))?.userId || null; + const ownGrant = codeGrant && codeGrant.userId === person ? codeGrant : null; + const refusal = callbackRefusal(device, person, !code || Boolean(ownGrant)); + if (!device || refusal) { + // A grant is ended only for a device this person confirmed: a code's ids are its text, which + // anyone can put in a link, so a bare GET here must not end a grant of the person who opens it. + if (ownGrant && device?.confirmedBy === person) await endGrant(env, ownGrant, facts); + console.warn({ event: "device-login.callback-refused", reason: refusal }); + return outcome("failed"); + } + // past the refusals, no code is the consent's refusal + if (!code || !ownGrant) { + const error = url.searchParams.get("error") || "access_denied"; + const description = url.searchParams.get("error_description") || "The person declined."; + await store.put(key, { ...device, status: "ended", error, description }); + console.info({ event: "device-login.denied", clientId: device.clientId, error }); + return outcome(error === "access_denied" ? "declined" : "failed"); + } + await store.put(key, { ...device, status: "approved", code, grant: ownGrant }); + console.info({ event: "device-login.approved", clientId: device.clientId }); + return outcome("approved"); +} + +function callbackRefusal(device: DeviceRequest | null, person: string | null, codeIsOwn: boolean) { + if (!device) return "unknown"; + if (device.expiresAt <= Date.now()) return "expired"; + if (device.status !== "confirmed") return "not-confirmed"; + if (!person || device.confirmedBy !== person) return "other-session"; + if (!codeIsOwn) return "other-grant"; + return null; +} + +// The library's codes are `<userId>:<grantId>:<secret>`. +function grantOfCode(code: string) { + const [userId, grantId, secret] = code.split(":"); + return userId && grantId && secret ? { userId, grantId } : null; +} + +export async function endGrant( + env: Env, + grant: { userId: string; grantId: string }, + facts: AccountFacts, +) { + await oauthHelpers(env).revokeGrant(grant.grantId, grant.userId); + facts.add(grant.userId, { + type: "events.iterate.com/account/grant-ended", + payload: { grantId: grant.grantId }, + idempotencyKey: `account/grant-ended/${grant.grantId}`, + }); +}
A core/auth-worker/src/device/limits.test.ts
@@ -0,0 +1,63 @@ +// The limits on what a caller may make the stack store, counted per client: no caller is exempt, +// also one whose request names no address, and the mind's own requests count as one client. +import { DatabaseSync } from "node:sqlite"; +import { expect, test } from "vitest"; +import type { Env } from "../env.ts"; +import { admitted } from "./limits.ts"; + +test("a caller with no address is one client, held at 20 in the window, and leaves the stack's limit to others", async () => { + const env = envWithAdmissions(); + const answers: boolean[] = []; + for (let n = 0; n < 25; n += 1) + answers.push(await admitted(env, "device", new Request("https://iterate.example.com/"))); + expect(answers.filter(Boolean)).toHaveLength(20); + expect(answers.slice(20)).toEqual([false, false, false, false, false]); + // a visitor with an address of their own still gets in + expect(await admitted(env, "device", from("203.0.113.7"))).toBe(true); +}); + +test("the mind's own requests share the boundary's one address, and so one client's limit", async () => { + const env = envWithAdmissions(); + const answers: boolean[] = []; + for (let n = 0; n < 130; n += 1) answers.push(await admitted(env, "device", from("192.0.0.8"))); + // 20, not the stack's 120: the members' sign-ins keep the rest + expect(answers.filter(Boolean)).toHaveLength(20); + expect(await admitted(env, "device", from("203.0.113.7"))).toBe(true); +}); + +test("the stack's limit of 120 in the window still holds for many clients together", async () => { + const env = envWithAdmissions(); + const answers: boolean[] = []; + for (let n = 0; n < 125; n += 1) + answers.push(await admitted(env, "registration", from(`198.51.100.${n}`))); + expect(answers.filter(Boolean)).toHaveLength(120); +}); + +test("a host's client is asked for with no client, and the stack's limit alone holds it", async () => { + const env = envWithAdmissions(); + const answers: boolean[] = []; + for (let n = 0; n < 125; n += 1) + answers.push(await admitted(env, "host-client", new Request("https://blog.example.com/"))); + expect(answers.filter(Boolean)).toHaveLength(120); +}); + +const from = (address: string) => + new Request("https://iterate.example.com/", { headers: { "cf-connecting-ip": address } }); + +/** An `Env` whose `DB` is SQLite in memory with the table of migrations/0005_admissions.sql, and + * of D1's surface the three members `admitted` uses. */ +function envWithAdmissions() { + const db = new DatabaseSync(":memory:"); + db.exec("create table admissions (kind text not null, client text, created_at integer not null)"); + const prepare = (sql: string) => ({ + bind: (...values: (string | number | null)[]) => ({ + run: () => ({ results: db.prepare(sql).all(...values) }), + }), + }); + const DB = { + prepare, + batch: async (statements: { run(): unknown }[]) => statements.map((one) => one.run()), + }; + // the three members of D1 that the code under test calls, of the binding's many + return { DB } as unknown as Env; +}
A core/auth-worker/src/device/limits.ts
@@ -0,0 +1,55 @@ +import type { Env } from "../env.ts"; + +const WINDOW_MS = 10 * 60_000; + +// Per kind, per window: 20 a client (6 a guest for a guest's sessions), 120 the stack (or the +// stack's own number for its guests), which bounds what a stranger with many addresses can make +// it store. One statement, so two at once cannot both pass. ?1 kind, ?2 client, ?3 now, ?4 the +// stack's bound, ?5 the client's bound. +const ADMIT = `insert into admissions (kind, client, created_at) +select ?1, ?2, ?3 +where (?2 is null or (select count(*) from admissions + where kind = ?1 and client = ?2 and created_at > ?3 - ${WINDOW_MS}) + < ?5) + and (select count(*) from admissions where kind = ?1 and created_at > ?3 - ${WINDOW_MS}) + < ?4 +returning 1 as admitted`; + +/** The window that every bound here counts in, as a number that names it: two refusals in one + * window are one event (./guest-sign-in.ts). */ +export const admissionWindowOf = (now: number) => Math.floor(now / WINDOW_MS); + +/** The client a limit counts a request for: the address the edge names, or the mind's own + * requests' one address, which the boundary sets (core/boundary-worker `own-request.ts`). A + * request with no address at all is counted too, all such as one client: no caller is exempt from + * the per-client limit, or it could use up the stack's and stop the members' sign-ins. */ +export function clientOf(request: Request): string { + return request.headers.get("cf-connecting-ip") || "no-address"; +} + +/** `host-client` is asked with no client: the boundary asks for a visitor it does not name, so + * the stack's own count holds it. `guest-session` is counted for `guest`, the guest's user id, + * and never for an address: the guests of one office come from one address. One guest gets 6 in + * the window: a session lasts 15 minutes, on each host the guest has open. `stackBound`: the + * stack's bound for its guests, from its config; 120 for every other kind. */ +export async function admitted( + env: Env, + kind: "device" | "registration" | "host-client" | "guest" | "guest-session" | "mind", + request: Request, + stackBound = 120, + guest?: string, +) { + const now = Date.now(); + const client = + kind === "guest-session" ? guest || null : kind === "host-client" ? null : clientOf(request); + const [, added] = await env.DB.batch([ + env.DB.prepare("delete from admissions where created_at <= ?1").bind(now - WINDOW_MS), + env.DB.prepare(ADMIT).bind(kind, client, now, stackBound, kind === "guest-session" ? 6 : 20), + ]); + const allowed = Boolean(added?.results[0]); + if (!allowed) console.warn({ event: "auth.admission-refused", kind }); + return allowed; +} + +export const TOO_MANY = + "Too many sign-ins were started here just now. Wait ten minutes, then try again.";
A core/auth-worker/src/device/page.test.ts
@@ -0,0 +1,355 @@ +import { decodeFacts, FACTS_HEADER } from "iterate/facts"; +import { base64url, keyIdOf, signedP256, statementText } from "iterate/signed"; +import { expect, test } from "vitest"; +import { browserSessionsFake } from "../browser-sessions-fake.ts"; +import { sessionCookie } from "../cookies.ts"; +import type { Env } from "../env.ts"; +import { configVars, keyRows, stackKeyPair } from "../test-support.ts"; +import { DEVICE_CONFIRMED, devicePageResponse, pressPayloadOf } from "./page.ts"; +import { requesterOf } from "./start.ts"; +import { type DeviceRequest, deviceStore } from "./store.ts"; + +test("the page asks for the passkey and says what it will sign", async () => { + const stack = await stackOf(); + const page = await stack.get(); + expect(page.text).toContain('<button type="submit" data-continue>Continue with passkey</button>'); + expect(page.text).toContain("Your passkey signs this request."); + // the request as the page shows it, for the page's script to sign + expect(page.text).toContain(`"userCode":"${CODE}"`); + expect(page.text).toContain('"clientId":"client-1"'); +}); + +test("a device's sign-in shows its name as its own claim, what it wants, that it gets everything as the member, and the code", async () => { + const stack = await stackOf(); + const { text } = await stack.get(); + expect(text).toContain( + `<div><dt>Device</dt><dd><strong>the laptop</strong><span class="note">The name is the device's own claim.</span></dd></div>`, + ); + expect(text).toMatch( + /<dt>Asked <details class="help">.*?<\/details><\/dt><dd>\d+ seconds ago, from London, GB<\/dd>/, + ); + expect(text).toContain("<div><dt>It wants</dt><dd>the mind's API</dd></div>"); + expect(text).toContain( + `<div><dt>It gets</dt><dd>everything in this mind, as <strong>owner@example.net</strong><span class="note">It can read and change all of it.</span></dd></div>`, + ); + expect(text).toContain( + `<div><dt>Code</dt><dd><strong>${CODE}</strong><span class="note">Continue only if you started this sign-in yourself and the device shows this code.</span></dd></div>`, + ); +}); + +test("a let-in shows its reason as the asker's word, how long with no renewal, and who asks: a claim, or the key that proved it", async () => { + const stack = await stackOf({ + device: { ...DEVICE, letIn: { seconds: 3600, reason: "to fix the build" } }, + }); + const { text } = await stack.get(); + expect(text).toContain( + `<div><dt>Who asks</dt><dd><strong>the laptop</strong><span class="note">The name is its own claim: nothing proves who asks. Continue only if you know where this request comes from.</span></dd></div>`, + ); + expect(text).toContain( + `<div><dt>Its reason <details class="help"><summary aria-label="About Its reason">?</summary><p>The asker wrote this. Nobody checked it.</p></details></dt><dd><blockquote>to fix the build</blockquote></dd></div>`, + ); + expect(text).toContain( + `<div><dt>It gets</dt><dd>everything in this mind, as <strong>owner@example.net</strong><span class="note">It can read and change all of it.</span></dd></div>`, + ); + expect(text).toContain( + `<div><dt>For</dt><dd>60 minutes from your approval<span class="note">It cannot renew this.</span></dd></div>`, + ); + expect(text).toContain( + `<div><dt>Code</dt><dd><strong>${CODE}</strong><span class="note">Continue only if you expected this request.</span></dd></div>`, + ); + const signer = { actor: "cli-bridge", label: "The bridge", key: "p".repeat(43) }; + await stack.start({ ...DEVICE, letIn: { seconds: 7200, reason: "to fix the build", signer } }); + const proved = (await stack.get()).text; + expect(proved).toContain( + `<div><dt>Who asks</dt><dd><strong>The bridge</strong><span class="note">It proved who it is with the key this mind trusts for cli-bridge (pppppppp).</span></dd></div>`, + ); + expect(proved).toContain("<dt>For</dt><dd>2 hours from your approval"); +}); + +test.for([ + ["the Continue of a page whose script did not run", { action: "" }], + ["a form that says confirm with no statement", { action: "confirm" }], + ["a statement that is no statement", { action: "confirm", signed: "{}" }], +])("%s signs in no device, and the request waits on", async ([, fields]) => { + const stack = await stackOf(); + const answer = await stack.post(fields as Record<string, string>); + expect(answer).toMatchObject({ status: 403 }); + expect(answer.text).toContain("To continue takes a press of your passkey"); + expect(await stack.request()).toMatchObject({ status: "pending" }); +}); + +test("only this member's statement of this request continues it", async () => { + const stack = await stackOf(); + const asked = pressPayloadOf(CODE, DEVICE); + const refusals = [ + // another device's code, another client, and a smaller thing than was asked + [await stack.owner.signed(DEVICE_CONFIRMED, { ...asked, userCode: "BCDF-GHJK" }), "another"], + [await stack.owner.signed(DEVICE_CONFIRMED, { ...asked, clientId: "client-2" }), "another"], + [await stack.owner.signed(DEVICE_CONFIRMED, { userCode: CODE }), "for another request"], + // another member's passkey is no press of this member's + [await stack.other.signed(DEVICE_CONFIRMED, asked), "signed by another person"], + // a statement of another kind, such as the one that adds a key + [await stack.owner.signed("events.iterate.com/account/key-added", asked), "is not"], + ] as const; + for (const [signed, why] of refusals) { + const answer = await stack.post({ action: "confirm", signed }); + expect(answer).toMatchObject({ status: 403 }); + expect(answer.text).toContain(why); + } + expect(await stack.request()).toMatchObject({ status: "pending" }); + + const answer = await stack.post({ + action: "confirm", + signed: await stack.owner.signed(DEVICE_CONFIRMED, asked), + }); + expect(answer).toMatchObject({ status: 303 }); + expect(answer.location).toMatch(/^\/oauth2\/auth\?/); + expect(await stack.request()).toMatchObject({ status: "confirmed", confirmedBy: "user_owner" }); + // the account's record of the press: what was signed, and by which key + expect(answer.facts).toMatchObject([ + { + path: "/users/user_owner", + events: [ + { + type: DEVICE_CONFIRMED, + payload: { ...asked, signer: { principal: { email: "owner@example.net" } } }, + }, + ], + }, + ]); +}); + +test("a statement counts once, and Decline takes no passkey", async () => { + const stack = await stackOf(); + const signed = await stack.owner.signed(DEVICE_CONFIRMED, pressPayloadOf(CODE, DEVICE)); + expect(await stack.post({ action: "confirm", signed })).toMatchObject({ status: 303 }); + // the same statement for the same request again: it was used + await stack.start(DEVICE); + expect(await stack.post({ action: "confirm", signed })).toMatchObject({ status: 403 }); + + expect(await stack.post({ action: "decline" })).toMatchObject({ + status: 303, + location: "/oauth2/device?outcome=declined", + }); + expect(await stack.request()).toMatchObject({ status: "ended", error: "access_denied" }); +}); + +test.for([ + ["approved", "This code was used: the device is signed in. You can close this page."], + ["redeemed", "This code was used: the device is signed in. You can close this page."], +] as const)( + "a code that was %s says so when its page opens again, with no form and no alert", + async ([status, words]) => { + const stack = await stackOf(); + await stack.start({ ...DEVICE, status, confirmedBy: "user_owner" }); + const page = await stack.get(); + expect({ + status: page.status, + said: page.text.includes(`<p>${words}</p>`), + form: page.text.includes("<form"), + alert: page.text.includes('<p role="alert"'), + }).toEqual({ status: 200, said: true, form: false, alert: false }); + // a let-in's code says it in its own words + await stack.start({ ...DEVICE, status, letIn: { seconds: 3600, reason: "a test" } }); + expect((await stack.get()).text).toContain( + "<p>This code was used: it is let in. You can close this page.</p>", + ); + }, +); + +test("a code that is unknown, or that ran out unused, keeps the form and its words", async () => { + const stack = await stackOf(); + const unknown = await stack.get("BCDF-GHJK"); + const words = "No device is waiting for this code. It may have expired."; + expect({ status: unknown.status, said: unknown.text.includes(words) }).toEqual({ + status: 400, + said: true, + }); + expect(unknown.text).toContain('<input name="user_code" value="BCDF-GHJK"'); + await stack.start({ ...DEVICE, expiresAt: Date.now() - 1 }); + expect((await stack.get()).text).toContain(words); +}); + +test("a let-in's statement names how long and why, and one for a plain sign-in lets nothing in", async () => { + const letIn = { ...DEVICE, letIn: { seconds: 3600, reason: "to fix the build" } }; + const stack = await stackOf({ device: letIn }); + expect((await stack.get()).text).toContain( + '"letIn":{"seconds":3600,"reason":"to fix the build"}', + ); + const plain = await stack.owner.signed(DEVICE_CONFIRMED, pressPayloadOf(CODE, DEVICE)); + expect(await stack.post({ action: "confirm", signed: plain })).toMatchObject({ status: 403 }); + const longer = await stack.owner.signed(DEVICE_CONFIRMED, { + ...pressPayloadOf(CODE, letIn), + letIn: { seconds: 86400, reason: "to fix the build" }, + }); + expect(await stack.post({ action: "confirm", signed: longer })).toMatchObject({ status: 403 }); + const signed = await stack.owner.signed(DEVICE_CONFIRMED, pressPayloadOf(CODE, letIn)); + expect(await stack.post({ action: "confirm", signed })).toMatchObject({ status: 303 }); +}); + +test("a let-in that another mind signed is headed by the mind's verified hostname, never by the label it gave its own key", async () => { + const signer = { + principal: { actor: "e".repeat(64), kind: "mind" as const, hostname: "peer.example.net" }, + key: "p".repeat(43), + label: "owner@example.net's passkey, trust me", + member: false, + }; + const asked = requesterOf(signer); + expect(asked).toEqual({ + actor: "e".repeat(64), + label: `peer.example.net (${"e".repeat(12)}…)`, + key: signer.key, + }); + // a person's or a service's key keeps the label that a member gave it + expect(requesterOf({ ...signer, principal: { actor: "cli-bridge" } })).toMatchObject({ + label: "owner@example.net's passkey, trust me", + }); + const stack = await stackOf({ + device: { ...DEVICE, letIn: { seconds: 3600, reason: "to fix the build", signer: asked } }, + }); + const { text } = await stack.get(); + expect(text).toContain(`<h1>Let peer.example.net (${"e".repeat(12)}…) in?</h1>`); + expect(text).not.toContain("trust me"); +}); + +const MIND = "iterate.example.com"; +const ISSUER = `https://${MIND}`; +const CODE = "WDJB-MJHT"; +const KEY = "k".repeat(43); +const DEVICE: DeviceRequest = { + status: "pending", + clientId: "client-1", + clientName: "the laptop", + resource: `${ISSUER}/api`, + requestedFrom: { city: "London", country: "GB" }, + createdAt: Date.now(), + expiresAt: Date.now() + 300_000, +}; +const P256 = { name: "ECDSA", namedCurve: "P-256" } as const; + +async function keyPair() { + const pair = (await crypto.subtle.generateKey(P256, true, ["sign", "verify"])) as CryptoKeyPair; + const exported = async (format: "spki" | "pkcs8", key: CryptoKey) => + base64url(new Uint8Array((await crypto.subtle.exportKey(format, key)) as ArrayBuffer)); + const publicKey = await exported("spki", pair.publicKey); + return { + key: await keyIdOf(publicKey), + publicKey, + pkcs8: await exported("pkcs8", pair.privateKey), + privateKey: pair.privateKey, + }; +} + +/** A stack with an owner who is signed in with a passkey, another member, and one device that + * waits. Of D1 and KV, what the device page and a statement's check read and write. */ +async function stackOf({ device = DEVICE } = {}) { + const [ownerKey, otherKey, stackKey] = [await keyPair(), await keyPair(), await stackKeyPair()]; + const seen = new Set<unknown>(); + const sessions = browserSessionsFake(); + // each person's key stands in for their passkey: a statement it signs is theirs + const keys = await keyRows([ + { actor: "owner-key", email: "owner@example.net", publicKey: ownerKey.publicKey, label: "O" }, + { actor: "other-key", email: "other@example.org", publicKey: otherKey.publicKey, label: "X" }, + ]); + const prepare = (sql: string, bound: unknown[] = []) => ({ + bind: (...values: unknown[]) => prepare(sql, values), + first: async () => { + const session = sessions.statementOf(sql, bound); + if (session) return session.first(); + if (sql.includes("from keys k left join users u")) return keys(bound[0]); + if (sql.includes("from stack_key")) return stackKey.row; + if (sql.includes("from members where email")) return { 1: 1 }; + throw new Error(`not expected: ${sql}`); + }, + counted: () => { + const session = sessions.statementOf(sql, bound); + if (session) return session.results(); + if (sql.startsWith("delete from statements")) return { meta: { changes: 0 } }; + if (!sql.startsWith("insert into statements")) throw new Error(`not expected: ${sql}`); + const fresh = !seen.has(bound[0]); + seen.add(bound[0]); + return { meta: { changes: fresh ? 1 : 0 } }; + }, + }); + const kept = new Map<string, string>(); + const env = { + ...configVars(), + DB: { + prepare, + batch: async (statements: ReturnType<typeof prepare>[]) => + statements.map((statement) => statement.counted()), + }, + OAUTH_KV: { + get: async (key: string) => 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 + } as unknown as Env; + const store = deviceStore(env.OAUTH_KV); + const start = async (request: DeviceRequest) => { + kept.clear(); + await store.start(KEY, CODE, request); + }; + await start(device); + const cookie = ( + await sessionCookie( + env, + new Request(ISSUER), + { id: "user_owner", email: "owner@example.net" }, + "key-1", + ) + ).setCookie.split(";")[0]!; + const member = (pair: Awaited<ReturnType<typeof keyPair>>) => ({ + signed: async (type: string, payload: Record<string, unknown>) => { + const now = Date.now(); + const statement = statementText({ + mind: MIND, + path: "/", + type, + payload, + at: now, + expires: now + 60_000, + }); + return JSON.stringify(await signedP256(statement, pair.privateKey, pair.key)); + }, + }); + const answered = async (answer: Response) => ({ + status: answer.status, + location: answer.headers.get("location"), + facts: answer.headers.has(FACTS_HEADER) ? decodeFacts(answer.headers.get(FACTS_HEADER)!) : [], + // the page writes a quote as a numbered entity + text: (await answer.text()).replaceAll(/&#(\d+);/g, (_all, code) => + String.fromCharCode(Number(code)), + ), + }); + return { + owner: member(ownerKey), + other: member(otherKey), + start, + /** The device's request as the store holds it now. */ + request: () => store.byKey(KEY), + get: async (userCode = CODE) => + answered( + await devicePageResponse( + env, + new Request(`${ISSUER}/oauth2/device?user_code=${userCode}`, { headers: { cookie } }), + ), + ), + /** The page's own form, posted by the owner's session. */ + post: async (fields: Record<string, string>) => + answered( + await devicePageResponse( + env, + new Request(`${ISSUER}/oauth2/device`, { + method: "POST", + headers: { + cookie, + origin: ISSUER, + "content-type": "application/x-www-form-urlencoded", + }, + body: new URLSearchParams({ user_code: CODE, ...fields }), + }), + ), + ), + }; +}
A core/auth-worker/src/device/page.ts
@@ -0,0 +1,270 @@ +import { jsonEqual } from "iterate/lib"; +import { mindMcpUrlOf, mindProvideConnectResourceOf } from "iterate/mind-api"; +import { AccountFacts } from "../account-facts.ts"; +import { sessionOf } from "../cookies.ts"; +import { configOf, type Env, issuerOf } from "../env.ts"; +import { isMember } from "../members.ts"; +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 { signInHref } from "../sign-in.ts"; +import { CALLBACK_PATH, normalizeUserCode, VERIFICATION_PATH } from "./protocol.ts"; +import { type DeviceRequest, deviceStore } from "./store.ts"; + +const OUTCOMES = { + approved: "The device is signed in. You can close this page.", + declined: "You declined. The device is not signed in.", + failed: "This sign-in did not finish. Start it again on the device.", +} as const; +/** A code that a member approved, opened again (a reload, the browser's back, an in-app browser + * that opens the link once more): its row stays, `approved` or `redeemed`, until a minute after + * the code's own end (./store.ts), and says so in place of "no device is waiting". */ +const USED = { + device: "This code was used: the device is signed in. You can close this page.", + letIn: "This code was used: it is let in. You can close this page.", +} as const; +const LET_IN_OUTCOMES = { + approved: "You let it in, for the time it asked. You can close this page.", + declined: "You declined. It is not let in.", + failed: "This did not finish. It is not let in, and it must ask again.", +} as const; + +/** WHAT A MEMBER'S PASSKEY SIGNS TO CONTINUE. "Sign in a device" and "Let … in" give a device, or + * an agent somewhere else, a token for the whole mind as the member who continues. So Continue is + * a statement that one of the member's passkeys signs, with the member checked (a PIN, a + * fingerprint or a face), as allowing a key is (../keys-pages.ts): a stolen session signs in no + * device. Its fact is the account's own record of the press. */ +export const DEVICE_CONFIRMED = "events.iterate.com/account/device-confirmed"; + +/** THE REQUEST AS THE PAGE SHOWS IT, which is what the passkey signs: this code, this device, what + * it reaches, and for a let-in how long and why. A statement for another request continues + * nothing. */ +export const pressPayloadOf = (userCode: string, device: DeviceRequest) => ({ + userCode, + clientId: device.clientId, + clientName: device.clientName, + resource: device.resource, + ...(device.letIn && { letIn: { seconds: device.letIn.seconds, reason: device.letIn.reason } }), +}); + +export async function devicePageResponse(env: Env, request: Request) { + const url = new URL(request.url); + const outcome = url.searchParams.get("outcome"); + if (request.method === "GET" && outcome && outcome in OUTCOMES) { + const letIn = url.searchParams.get("kind") === "let-in"; + const title = letIn ? "Let in" : "Device sign-in"; + const words = (letIn ? LET_IN_OUTCOMES : OUTCOMES)[outcome as keyof typeof OUTCOMES]; + return page({ title, body: `<h1>${title}</h1><p>${text(words)}</p>` }); + } + if (request.method === "POST" && request.headers.get("origin") !== issuerOf(env)) + return errorPage("Confirm this device from its own page.", 403); + const form = request.method === "POST" ? await request.formData().catch(() => null) : null; + const typed = String(form?.get("user_code") ?? url.searchParams.get("user_code") ?? ""); + const session = await sessionOf(env, request); + const here = typed + ? `${VERIFICATION_PATH}?${new URLSearchParams({ user_code: typed })}` + : VERIFICATION_PATH; + if (!session) return seeOther(signInHref(here)); + const mind = configOf(env).controlPlaneHostname; + if (!(await isMember(env, session.email))) return notMemberPage({ mind, email: session.email }); + if (!typed) return enter(mind); + const userCode = normalizeUserCode(typed); + if (!userCode) return enter(mind, typed, "A code is eight letters, like WDJB-MJHT."); + const store = deviceStore(env.OAUTH_KV); + const found = await store.byUserCode(userCode); + const device = found?.request; + if (device?.status === "approved" || device?.status === "redeemed") { + const title = device.letIn ? "Let in" : "Device sign-in"; + const words = device.letIn ? USED.letIn : USED.device; + return page({ title, body: `<h1>${title}</h1><p>${text(words)}</p>` }); + } + const waits = + device && + device.expiresAt > Date.now() && + (device.status === "pending" || + (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); + + // Only Decline declines: Continue with no signature (a page whose script did not run) says + // what it takes, and the request waits on. + if (form?.get("action") === "decline") { + await store.put(found.key, { + ...device, + status: "ended", + error: "access_denied", + description: "The person declined this sign-in.", + }); + console.info({ event: "device-login.denied", clientId: device.clientId }); + return seeOther(`${VERIFICATION_PATH}?outcome=declined${device.letIn ? "&kind=let-in" : ""}`); + } + // The session alone, or a page that posts this form for the member, continues nothing. + const press = await signedChangeBy(env, form?.get("signed"), DEVICE_CONFIRMED, session.email); + const refused = + "refused" in press + ? `${press.refused}. To continue takes a press of your passkey.` + : jsonEqual(press.payload, pressPayloadOf(userCode, device)) + ? 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}`); + const facts = new AccountFacts(); + facts.add(session.userId, { + type: DEVICE_CONFIRMED, + payload: { ...pressPayloadOf(userCode, device), ...signerOf(press) }, + idempotencyKey: `account/device-confirmed/${found.key}`, + }); + await store.put(found.key, { ...device, status: "confirmed", confirmedBy: session.userId }); + console.info({ event: "device-login.confirmed", clientId: device.clientId }); + // `state` and the PKCE challenge are both the store's key (./start.ts) + const authorize = new URLSearchParams({ + response_type: "code", + client_id: device.clientId, + redirect_uri: `${issuerOf(env)}${CALLBACK_PATH}`, + scope: "iterate", + state: found.key, + code_challenge: found.key, + code_challenge_method: "S256", + resource: device.resource, + }); + return facts.on(seeOther(`/oauth2/auth?${authorize}`)); +} + +function enter(mind: string, typed = "", error?: string) { + return page({ + title: `Sign in a device to ${mind}`, + status: error ? 400 : 200, + body: `<h1>Sign in a device to ${text(mind)}</h1> + <p class="muted">Enter the code the device shows.</p> + ${error ? `<p role="alert">${text(error)}</p>` : ""} + <form method="get" class="stack"> + <label>Code <input name="user_code" value="${text(typed)}" autocomplete="off" autocapitalize="characters" spellcheck="false"></label> + <button type="submit">Next</button> + </form>`, + }); +} + +/** Who asks, as the consent page shows it (../client-mark.ts): a device gives a name alone, so its + * tile is a known client's mark by that name, or its initials. The page's words say that the + * 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) { + const mind = configOf(env).controlPlaneHostname; + const where = [device.requestedFrom.city, device.requestedFrom.country] + .filter(Boolean) + .join(", "); + const ago = Math.max(0, Math.round((Date.now() - device.createdAt) / 1000)); + // Continue has no value of its own: the page's script signs, sets `action` and posts. Decline + // comes first in the form, so its own value is the one the server reads. + const form = `${error ? `<p role="alert">${text(error)}</p>` : ""} + <form method="post" class="actions" data-press="${text(JSON.stringify(pressPayloadOf(userCode, device)))}"> + <input type="hidden" name="user_code" value="${text(userCode)}"> + <button type="submit" name="action" value="decline" class="secondary">Decline</button> + <button type="submit" data-continue>Continue with passkey</button> + <input type="hidden" name="action" value="" data-action><input type="hidden" name="signed" value=""> + </form> + <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 = { + status: error ? 403 : 200, + script: `${signScript(mind)}${PRESS_SCRIPT}`, + }; + const note = (words: string) => `<span class="note">${text(words)}</span>`; + const reach = { + label: "It gets", + value: `everything in this mind, as <strong>${text(email)}</strong>${note("It can read and change all of it.")}`, + }; + if (device.letIn) { + const { signer } = device.letIn; + const name = signer ? signer.label : device.clientName; + const proof = signer + ? `It proved who it is with the key this mind trusts for ${signer.actor} (${signer.key.slice(0, 8)}).` + : "The name is its own claim: nothing proves who asks. Continue only if you know where this request comes from."; + return page({ + ...shown, + title: `Let ${name} in?`, + asker: deviceTile(name), + body: `<h1>Let ${text(name)} in?</h1> + ${factsTable([ + { label: "Who asks", value: `<strong>${text(name)}</strong>${note(proof)}` }, + { + label: "Its reason", + value: `<blockquote>${text(device.letIn.reason)}</blockquote>`, + help: "The asker wrote this. Nobody checked it.", + }, + { label: "Mind", value: text(mind) }, + reach, + { + label: "For", + value: `${text(durationInWords(device.letIn.seconds))} from your approval${note("It cannot renew this.")}`, + }, + { + label: "Code", + value: `<strong>${text(userCode)}</strong>${note("Continue only if you expected this request.")}`, + }, + ])} + ${form}`, + }); + } + return page({ + ...shown, + title: `Sign in ${device.clientName}?`, + asker: deviceTile(device.clientName), + body: `<h1>Sign in a device to ${text(mind)}?</h1> + ${factsTable([ + { + label: "Device", + value: `<strong>${text(device.clientName)}</strong>${note("The name is the device's own claim.")}`, + }, + { + label: "Asked", + value: text(`${ago} seconds ago${where ? `, from ${where}` : ""}`), + help: "The place is where the request came from, by its network address.", + }, + { label: "It wants", value: text(resourceInWords(env, device.resource)) }, + reach, + { + label: "Code", + value: `<strong>${text(userCode)}</strong>${note("Continue only if you started this sign-in yourself and the device shows this code.")}`, + }, + ])} + ${form}`, + }); +} + +// Continue is a statement one of the person's passkeys signs, of the request as the page says it. +// Decline posts the form as it is. +const PRESS_SCRIPT = ` +const form = document.querySelector("form[data-press]"); +const status = document.getElementById("status"); +form.addEventListener("submit", async (event) => { + if (!event.submitter?.hasAttribute("data-continue") || form.signed.value) return; + event.preventDefault(); + try { + statusSay(status, "Waiting for your passkey…"); + form.signed.value = JSON.stringify(await signedStatement({ type: "${DEVICE_CONFIRMED}", payload: JSON.parse(form.dataset.press) })); + // by its mark, not by its name: the Decline button has the same name + form.querySelector("[data-action]").value = "confirm"; + form.submit(); + } catch (error) { + statusFailed(status, error, "The device is not signed in."); + } +});`; + +function durationInWords(seconds: number) { + const minutes = Math.round(seconds / 60); + return minutes < 120 ? `${minutes} minutes` : `${Math.round(minutes / 60)} hours`; +} + +function resourceInWords(env: Env, resource: string) { + const config = configOf(env); + if (resource === mindMcpUrlOf(config.controlPlaneHostname)) return "the mind's MCP server"; + if (resource === mindProvideConnectResourceOf(config.controlPlaneHostname)) + return "to run the mind from that computer"; + return "the mind's API"; +} + +const seeOther = (location: string) => + new Response(null, { status: 303, headers: { location, "cache-control": "no-store" } });
A core/auth-worker/src/device/poll.ts
@@ -0,0 +1,86 @@ +import { calculatePKCECodeChallenge } from "oauth4webapi"; +import { AccountFacts } from "../account-facts.ts"; +import { type Env, issuerOf } from "../env.ts"; +import { TOKEN_ENDPOINT, tokenEndpointResponse } from "../oauth.ts"; +import { endGrant } from "./callback.ts"; +import { + CALLBACK_PATH, + DEVICE_CODE_GRANT, + DevicePollForm, + formOf, + oauthError, + POLL_INTERVAL_SECONDS, +} from "./protocol.ts"; +import { refused } from "./start.ts"; +import { deviceStore } from "./store.ts"; + +export async function devicePollResponse(env: Env, request: Request, ctx: ExecutionContext) { + const fields = await formOf(request.clone()); + if (fields.grant_type !== DEVICE_CODE_GRANT) return null; + const form = DevicePollForm.safeParse(fields); + if (!form.success) return refused("invalid_request", "device_code and client_id are required"); + const store = deviceStore(env.OAUTH_KV); + const key = await calculatePKCECodeChallenge(form.data.device_code); + const device = await store.byKey(key); + if (!device || device.clientId !== form.data.client_id) + return refused("invalid_grant", "Unknown device code"); + // a second short of the interval, so a poll's own lateness never reads as too early + if (await store.polledWithin(key, POLL_INTERVAL_SECONDS - 1)) + return oauthError("slow_down", "Poll less often: add five seconds to the interval."); + + const facts = new AccountFacts(); + const end = async (event: string, error: string, description: string) => { + if (device.grant) await endGrant(env, device.grant, facts); + await store.put(key, { ...device, status: "ended", code: undefined, error, description }); + console.info({ event, clientId: device.clientId }); + return facts.on(oauthError(error, description)); + }; + if (device.status === "ended") + return oauthError(device.error || "access_denied", device.description || "Ended."); + if (device.status === "redeemed") + return end( + "device-login.failed", + "invalid_grant", + "This sign-in was approved, but its tokens never reached the device, so it was ended. Run the sign-in again.", + ); + // An approval is redeemed even just past the code's five minutes, within the row's minute of + // grace (./store.ts): a KV read in the device's location may see it up to a minute late. + const approved = device.status === "approved" && device.code; + if (!approved && device.expiresAt <= Date.now()) + return end( + "device-login.expired", + "expired_token", + "The code expired before the sign-in finished.", + ); + if (!approved) return oauthError("authorization_pending", "The person has not answered yet."); + + // Marked first, so no later poll gets tokens. KV has no compare-and-set: two polls at once may + // both reach the exchange, and the library's single-use code refuses the second. + await store.put(key, { ...device, status: "redeemed", code: undefined }); + const exchange = new URLSearchParams({ + grant_type: "authorization_code", + code: approved, + client_id: device.clientId, + redirect_uri: `${issuerOf(env)}${CALLBACK_PATH}`, + code_verifier: form.data.device_code, + resource: device.resource, + }); + const answer = await tokenEndpointResponse( + env, + new Request(`${issuerOf(env)}${TOKEN_ENDPOINT}`, { method: "POST", body: exchange }), + ctx, + ); + console.info({ + event: answer.ok ? "device-login.redeemed" : "device-login.failed", + clientId: device.clientId, + status: answer.status, + }); + // A refused exchange stays `redeemed`, so the next poll ends it and its grant: KV takes one write + // a second for a key. + if (!answer.ok || !device.letIn) return answer; + // Nobody may renew being let in, so the library's refresh token is dropped. + const { refresh_token: _dropped, ...tokens } = (await answer.json()) as Record<string, unknown>; + const headers = new Headers(answer.headers); + headers.delete("content-length"); + return Response.json(tokens, { status: answer.status, headers }); +}
A core/auth-worker/src/device/protocol.ts
@@ -0,0 +1,87 @@ +import { z } from "zod"; + +export const DEVICE_AUTHORIZATION_PATH = "/oauth2/device_authorization"; +export const VERIFICATION_PATH = "/oauth2/device"; +export const CALLBACK_PATH = "/oauth2/device/callback"; +export const DEVICE_CODE_GRANT = "urn:ietf:params:oauth:grant-type:device_code"; + +// RFC 8628 §5.4's advice against a code someone else sent. The CLI waits no longer. +export const DEVICE_CODE_SECONDS = 300; +// RFC 8628 §3.2's default. +export const POLL_INTERVAL_SECONDS = 5; + +// RFC 8628 §6.1's example alphabet; eight letters are 34.6 bits. Bytes below 240 only: 240 is a +// multiple of 20, so the letters are uniform. +export function newUserCode() { + let letters = ""; + while (letters.length < 8) + for (const byte of crypto.getRandomValues(new Uint8Array(16))) + if (byte < 240 && letters.length < 8) letters += "BCDFGHJKLMNPQRSTVWXZ"[byte % 20]; + return `${letters.slice(0, 4)}-${letters.slice(4)}`; +} + +// Any character but case, spaces and dashes is refused, never dropped: a typo is not another code. +export function normalizeUserCode(typed: string): string | null { + const letters = typed.toUpperCase().replace(/[\s-]/g, ""); + if (!/^[BCDFGHJKLMNPQRSTVWXZ]{8}$/.test(letters)) return null; + return `${letters.slice(0, 4)}-${letters.slice(4)}`; +} + +export const DeviceRegistration = z.object({ + client_name: z.string().trim().min(1).max(200).optional(), + token_endpoint_auth_method: z.literal("none"), + grant_types: z.array(z.string()).refine((grants) => grants.includes(DEVICE_CODE_GRANT)), +}); + +// The library refuses a token with less than a minute left, and the exchange comes after the approval. +export const LET_IN_MIN_SECONDS = 300; +export const LET_IN_MAX_SECONDS = 86400; +export const LET_IN_WAIT_SECONDS = 3600; + +export const DeviceAuthorizationForm = z + .object({ + client_id: z.string().min(1), + scope: z.string().default("iterate"), + resource: z.string().min(1), + access_seconds: z.coerce + .number() + .int() + .min(LET_IN_MIN_SECONDS) + .max(LET_IN_MAX_SECONDS) + .optional(), + reason: z.string().trim().min(1).max(300).optional(), + signed: z.string().min(1).max(16384).optional(), + }) + .refine((form) => !form.access_seconds === !form.reason && (!form.signed || !!form.reason)); + +// Shown with the request, never appended. +export const LET_IN_STATEMENT_TYPE = "events.iterate.com/cloud/let-in-request-signed"; + +export const DevicePollForm = z.object({ + grant_type: z.literal(DEVICE_CODE_GRANT), + device_code: z.string().min(1).max(256), + client_id: z.string().min(1), +}); + +// Read as bytes: workerd logs a warning for `.text()` on a form. +export async function formOf(request: Request) { + return Object.fromEntries( + new URLSearchParams(new TextDecoder().decode(await request.arrayBuffer())), + ); +} + +export function oauthError(error: string, description: string, status = 400) { + return Response.json( + { error, error_description: description }, + { status, headers: { "cache-control": "no-store" } }, + ); +} + +export const RequestedFrom = z + .object({ city: z.string().optional(), country: z.string().optional() }) + .catch({}); + +export async function sha256Hex(text: string) { + const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(text)); + return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, "0")).join(""); +}
A core/auth-worker/src/device/start.ts
@@ -0,0 +1,220 @@ +import { CimdFetchError } from "@cloudflare/workers-oauth-provider"; +import { calculatePKCECodeChallenge, generateRandomCodeVerifier } from "oauth4webapi"; +import type { Verified } from "iterate/workers"; +import { tokenAudiencesOf } from "../config.ts"; +import { configOf, type Env, issuerOf } from "../env.ts"; +import { personKeyRefusal, verifiedStatement } from "../keys.ts"; +import { authorizationServer, oauthHelpers } from "../oauth.ts"; +import { + CALLBACK_PATH, + DEVICE_AUTHORIZATION_PATH, + DEVICE_CODE_GRANT, + DEVICE_CODE_SECONDS, + DeviceAuthorizationForm, + DeviceRegistration, + formOf, + LET_IN_MAX_SECONDS, + LET_IN_STATEMENT_TYPE, + LET_IN_MIN_SECONDS, + LET_IN_WAIT_SECONDS, + newUserCode, + oauthError, + POLL_INTERVAL_SECONDS, + RequestedFrom, + VERIFICATION_PATH, +} from "./protocol.ts"; +import { admitted, TOO_MANY } from "./limits.ts"; +import { type DeviceRequest, deviceStore } from "./store.ts"; + +export async function metadataResponse(env: Env, request: Request, ctx: ExecutionContext) { + const answer = await authorizationServer(env).fetch(request, env, ctx); + if (!answer.ok) return answer; + const metadata = (await answer.json()) as Record<string, unknown>; + const grants = Array.isArray(metadata.grant_types_supported) + ? metadata.grant_types_supported + : []; + const headers = new Headers(answer.headers); + headers.delete("content-length"); + return Response.json( + { + ...metadata, + device_authorization_endpoint: `${issuerOf(env)}${DEVICE_AUTHORIZATION_PATH}`, + grant_types_supported: [...grants, DEVICE_CODE_GRANT], + }, + { headers }, + ); +} + +// The library has no device grant, so a device redeems through its code exchange, which needs a +// redirect URI and PKCE: this registers a public client whose one redirect is the device callback. +export async function deviceRegistrationResponse( + env: Env, + request: Request, + ctx: ExecutionContext, +) { + const body: unknown = await request + .clone() + .json() + .catch(() => null); + const asked = DeviceRegistration.safeParse(body); + if (!asked.success) return null; + const registration = await authorizationServer(env).fetch( + new Request(request.url, { + method: "POST", + // the registration's limit counts this address (../oauth.ts) + headers: { + "content-type": "application/json", + "cf-connecting-ip": request.headers.get("cf-connecting-ip") || "", + }, + body: JSON.stringify({ + client_name: asked.data.client_name || "a device", + redirect_uris: [`${issuerOf(env)}${CALLBACK_PATH}`], + token_endpoint_auth_method: "none", + grant_types: ["authorization_code", "refresh_token"], + response_types: ["code"], + }), + }), + env, + ctx, + ); + if (!registration.ok) return registration; + const registered = (await registration.json()) as Record<string, unknown>; + console.info({ event: "device-login.client-registered", clientId: registered.client_id }); + return Response.json( + { ...registered, grant_types: [DEVICE_CODE_GRANT, "refresh_token"] }, + { status: registration.status, headers: { "cache-control": "no-store" } }, + ); +} + +export async function deviceAuthorizationResponse(env: Env, request: Request) { + const form = DeviceAuthorizationForm.safeParse(await formOf(request)); + if (!form.success) + return refused( + "invalid_request", + `client_id and resource are required. To be let in, send access_seconds (a whole number from ${LET_IN_MIN_SECONDS} to ${LET_IN_MAX_SECONDS}) and a reason (1 to 300 characters), both or neither; signed only with them.`, + ); + const { client_id: clientId, resource, access_seconds: seconds, reason, signed } = form.data; + if (form.data.scope.split(" ").some((scope) => scope && scope !== "iterate")) + return refused("invalid_scope", "The device sign-in grants the iterate scope alone."); + if (!tokenAudiencesOf(configOf(env)).includes(resource)) + return refused( + "invalid_target", + "The device sign-in is for the mind's API, its MCP server, or the right to hand in the mind.", + ); + const callback = `${issuerOf(env)}${CALLBACK_PATH}`; + const client = await oauthHelpers(env) + .lookupClient(clientId) + .catch((error: unknown) => { + if (error instanceof CimdFetchError) return null; + throw error; + }); + if (!client) return refused("invalid_client", "Unknown client", 401); + if (client.tokenEndpointAuthMethod !== "none" || !client.redirectUris.includes(callback)) + return refused("unauthorized_client", "Register this client for the device grant first."); + let letIn: DeviceRequest["letIn"]; + if (seconds && reason) { + const signer = signed + ? await signerOf(env, signed, { client: clientId, seconds, reason }) + : null; + if (signer && "refused" in signer) return refused("invalid_request", signer.refused); + letIn = { seconds, reason, signer: signer || undefined }; + } + const waitSeconds = letIn ? LET_IN_WAIT_SECONDS : DEVICE_CODE_SECONDS; + // not `slow_down`: the iterate CLI reads that only on a poll of the token endpoint + if (!(await admitted(env, "device", request))) + return refused("temporarily_unavailable", TOO_MANY, 429); + + // The device code is the PKCE verifier and its S256 challenge the store's key: only the device, + // which holds the code, can name the row or redeem it. + const deviceCode = generateRandomCodeVerifier(); + const key = await calculatePKCECodeChallenge(deviceCode); + const now = Date.now(); + const requestedFrom = RequestedFrom.parse(request.cf ?? {}); + // three taken codes in a row mean the store answers wrongly, not chance + for (let attempt = 0; attempt < 3; attempt++) { + const userCode = newUserCode(); + const stored = await deviceStore(env.OAUTH_KV).start(key, userCode, { + status: "pending", + clientId, + clientName: client.clientName || clientId, + resource, + requestedFrom, + createdAt: now, + expiresAt: now + waitSeconds * 1000, + letIn, + }); + if (!stored) continue; + console.info({ + event: "device-login.started", + clientId, + country: requestedFrom.country, + letIn: Boolean(letIn), + signer: letIn?.signer?.actor, + }); + const verificationUri = `${issuerOf(env)}${VERIFICATION_PATH}`; + return Response.json( + { + device_code: deviceCode, + user_code: userCode, + verification_uri: verificationUri, + verification_uri_complete: `${verificationUri}?${new URLSearchParams({ user_code: userCode })}`, + expires_in: waitSeconds, + interval: POLL_INTERVAL_SECONDS, + }, + { headers: { "cache-control": "no-store" } }, + ); + } + throw new Error("Three fresh user codes were all taken."); +} + +// The payload must be exactly what is asked, so a statement cannot be moved to another client, +// time or reason. The key's paths do not matter: nothing is appended. +async function signerOf( + env: Env, + signed: string, + asked: { client: string; seconds: number; reason: string }, +) { + let value: unknown; + try { + value = JSON.parse(signed); + } catch { + return { refused: "signed is not JSON" }; + } + const verified = await verifiedStatement(env, value); + if ("refused" in verified) return verified; + const { type, payload = {} } = verified.statement; + if (type !== LET_IN_STATEMENT_TYPE) + return { refused: `the statement is not ${LET_IN_STATEMENT_TYPE}` }; + if ( + Object.keys(payload).length !== 3 || + payload.client !== asked.client || + payload.seconds !== asked.seconds || + payload.reason !== asked.reason + ) + return { refused: "the statement's payload is not { client, seconds, reason } as asked" }; + // the page says "the key this mind trusts": a removed member's key is not one + const notThisPerson = personKeyRefusal(verified.signer); + if (notThisPerson) return { refused: notThisPerson }; + return requesterOf(verified.signer); +} + +/** WHO ASKS, as the approval page names it (./page.ts): a person's or a service's key by its + * label, which a member gave it when the key was added; ANOTHER MIND BY ITS ID (`actor`) AND ITS + * HOSTNAME (the label), which its identity log proves (../minds.ts). A mind's working key carries + * a label that the mind wrote itself, so that label never names who asks. */ +export function requesterOf(signer: Exclude<Verified, { refused: string }>["signer"]) { + const { principal, label, key } = signer; + return { + actor: principal.actor, + label: + principal.kind === "mind" + ? `${principal.hostname || principal.actor} (${principal.actor.slice(0, 12)}…)` + : label, + key, + }; +} + +export function refused(error: string, description: string, status = 400) { + console.warn({ event: "oauth.refusal", category: "device-login", code: error }); + return oauthError(error, description, status); +}
A core/auth-worker/src/device/store.ts
@@ -0,0 +1,79 @@ +import { z } from "zod"; +import { RequestedFrom, sha256Hex } from "./protocol.ts"; + +// KV keys, each expiring with its request: `device:<S256 challenge of the device code>`, +// `device-user:<SHA-256 of the user code>` → that key, and `device-poll:<key>`, apart from the +// request so a poll never overwrites an approval written meanwhile. +export const DeviceRequest = z.object({ + // pending → confirmed → approved → redeemed, or → ended with the error its next poll answers + status: z.enum(["pending", "confirmed", "approved", "redeemed", "ended"]), + clientId: z.string(), + clientName: z.string(), + resource: z.string(), + requestedFrom: RequestedFrom, + createdAt: z.number(), // epoch ms + expiresAt: z.number(), + // the only person whose consent counts + confirmedBy: z.string().optional(), + code: z.string().optional(), + grant: z.object({ userId: z.string(), grantId: z.string() }).optional(), + error: z.string().optional(), + description: z.string().optional(), + letIn: z + .object({ + seconds: z.number().int(), + reason: z.string(), + signer: z.object({ actor: z.string(), label: z.string(), key: z.string() }).optional(), + }) + .optional(), +}); +export type DeviceRequest = z.infer<typeof DeviceRequest>; + +// A row outlives its code, so a late poll reads `expired_token`. KV refuses an expiry under 60 s away. +const ROW_GRACE_SECONDS = 60; +const expirationOf = (request: DeviceRequest) => + Math.max( + Math.ceil(request.expiresAt / 1000) + ROW_GRACE_SECONDS, + Math.ceil(Date.now() / 1000) + ROW_GRACE_SECONDS, + ); + +export function deviceStore(kv: KVNamespace) { + const userKey = async (userCode: string) => `device-user:${await sha256Hex(userCode)}`; + const store = { + async start(key: string, userCode: string, request: DeviceRequest) { + const byUser = await userKey(userCode); + if (await kv.get(byUser)) return false; + await store.put(key, request); + await kv.put(byUser, key, { expiration: expirationOf(request) }); + return true; + }, + + async byKey(key: string): Promise<DeviceRequest | null> { + const value = await kv.get(`device:${key}`); + return value ? DeviceRequest.parse(JSON.parse(value)) : null; + }, + + async byUserCode(userCode: string) { + const key = await kv.get(await userKey(userCode)); + const request = key ? await store.byKey(key) : null; + return key && request ? { key, request } : null; + }, + + async put(key: string, request: DeviceRequest) { + await kv.put(`device:${key}`, JSON.stringify(request), { + expiration: expirationOf(request), + }); + }, + + // Only a poll in time is written: KV takes one write a second for a key. + async polledWithin(key: string, seconds: number) { + const last = Number(await kv.get(`device-poll:${key}`)); + if (last > Date.now() - seconds * 1000) return true; + await kv.put(`device-poll:${key}`, String(Date.now()), { + expirationTtl: ROW_GRACE_SECONDS, + }); + return false; + }, + }; + return store; +}
A core/auth-worker/src/email-sign-in.ts
@@ -0,0 +1,412 @@ +// email-sign-in.ts — THE MAILED CODE, the sign-in method "email": six digits, mailed through +// Cloudflare Email Sending, that prove an address. The mail comes from where the person is +// (`mailCode`): `sign-in@<the zone of the app's hostname>` under the app's name for an app's own +// sign-in, and `sign-in@<the zone of the control-plane hostname>` for an outside client's sign-in +// to an app. IT IS FOR THE PEOPLE OF THE MIND'S APPS, AND OPENS NO WAY INTO THE MIND. What the +// proof opens depends on whose address it is as the code is typed: +// +// a person who is no member a session that is no member's (./cookies.ts `emailSessionCookie`): +// an app of the mind with users of its own takes it, when it names +// "email" +// a member, with a passkey nothing, and the words say what signs that member in +// 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 +// +// 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 +// plane's own sign-in, the address page leads back to the sign-in page, and no code is mailed in +// its name. +// +// ANYONE MAY ASK FOR A CODE, so that the mind's apps have users of their own. The limits keep the +// mind's zone from being a way to mail the world (`INSERT_CHALLENGE`). Every address is answered +// alike and a member's address is mailed its code too, so the pages say nothing of who is a +// member: a member reads the refusal only after the right code, which proves the mailbox. +import { waitUntil } from "cloudflare:workers"; +import { cookieValueOf, reportIssue } from "iterate/lib"; +import { zoneOf } from "iterate/mind-config"; +import { z } from "zod"; +import { AccountFacts } from "./account-facts.ts"; +import { type AskingApp, askingAppOf, signInOf } from "./asking-app.ts"; +import { isBlocked } from "./blocked.ts"; +import { isOwner } from "./config.ts"; +import { emailSessionCookie, MIND_FORM_PATH, sessionsOverRemoved } from "./cookies.ts"; +import { sha256Hex } from "./device/protocol.ts"; +import { clientOf, TOO_MANY } from "./device/limits.ts"; +import { passkeysOf } from "./enrolment.ts"; +import { configOf, dashOf, type Env, issuerOf } from "./env.ts"; +import { honouredNext } from "./key-rules.ts"; +import { appSignIn, errorPage, page, passkeySignIn, text } from "./pages.ts"; +import { isMember } from "./members.ts"; +import { signInHref } from "./sign-in.ts"; +import { userOf } from "./users.ts"; + +const EMAIL_SIGN_IN_PATH = "/sign-in/email"; +const CODE_PATH = `${EMAIL_SIGN_IN_PATH}/code`; +const COOKIE = "__Host-iterate-auth-code"; +const LIFETIME_SECONDS = 10 * 60; +const TRIES = 5; +const MINUTE = 60_000; +const HOUR = 60 * MINUTE; + +type Challenge = { + email: string; + hash: string; + tries: number; + next: string; + /** 1 when the code was mailed. */ + mailed: number; +}; + +/** How many codes an hour the whole mind mails to addresses that are no member's. A member's + * address is one that somebody named, and its code is no part of the count: a member always + * gets the mail whose code leads to the words of what signs them in. Any other address is one + * that anyone can type. */ +export const NON_MEMBER_CODES_AN_HOUR = 20; +/** How many codes an hour one mailbox gets from all clients together: what keeps an inbox from a + * flood. One client address also gets one a minute for one mailbox. */ +export const CODES_AN_HOUR_FOR_A_MAILBOX = 5; +/** How many codes one client address may ask for in ten minutes, mailed or not. */ +const CHALLENGES_IN_TEN_MINUTES_FOR_A_CLIENT = 20; +/** How many challenges the whole mind holds that are not over yet, mailed or not, as the passkey's + * challenges are capped (./passkey-sign-in.ts): what a stranger with many addresses can make + * the mind store. A row is kept an hour, so the table holds six times this at most. */ +export const LIVE_CHALLENGES = 120; +/** The longest `next` a challenge keeps. A longer one is not kept: the person goes on to the + * mind's front page. */ +const NEXT_MAX_CHARACTERS = 2048; + +// One statement, so two requests at once are counted one after the other. ?1 id, ?2 email, ?3 +// inbox, ?4 client, ?5 hash, ?6 next, ?7 named (a member's address), ?8 mailable, ?9 now, ?10 +// expires at. +// +// WHETHER THE CODE IS MAILED: never to an address that is not mailable; never past a mailbox's +// limits; always to a member's; to any other while the mind is under its cap for the hour. +// THE LIMITS OF A MAILBOX (`inbox`: the address without its `+tag`) count the codes MAILED to it: +// one a minute for each asking client, and `CODES_AN_HOUR_FOR_A_MAILBOX` from all of them. A +// request that mails nothing, such as one for `owner+tag@…` past the cap, spends none of them. +// A CHALLENGE THAT IS NOT MAILED IS MADE ALL THE SAME, for every reason alike, so the answer is +// the same for every address: it says nothing of whether the address is a member's, or of its +// mailbox's limits. Only the limits that hold for every address (a client's, the mind's live +// challenges) refuse the request. +const INSERT_CHALLENGE = `with code as (select + case + when ?8 = 0 then 0 + when exists (select 1 from email_challenges + where inbox = ?3 and client = ?4 and mailed = 1 and created_at > ?9 - ${MINUTE}) + then 0 + when (select count(*) from email_challenges + where inbox = ?3 and mailed = 1 and created_at > ?9 - ${HOUR}) + >= ${CODES_AN_HOUR_FOR_A_MAILBOX} + then 0 + when ?7 = 1 then 1 + when (select count(*) from email_challenges + where named = 0 and mailed = 1 and created_at > ?9 - ${HOUR}) < ${NON_MEMBER_CODES_AN_HOUR} + then 1 + else 0 + end as mailed) +insert into email_challenges + (id, email, inbox, client, hash, next, named, mailed, created_at, expires_at) +select ?1, ?2, ?3, ?4, ?5, ?6, ?7, code.mailed, ?9, ?10 from code +where (select count(*) from email_challenges + where client = ?4 and created_at > ?9 - ${10 * MINUTE}) < ${CHALLENGES_IN_TEN_MINUTES_FOR_A_CLIENT} + and (select count(*) from email_challenges where expires_at > ?9) < ${LIVE_CHALLENGES} +returning mailed`; + +// RFC 2606 and 6761 names are never mailed (a bounce costs the sender's reputation), but get a +// challenge all the same, so a check can walk the pages. +const reservedDomain = /@(example\.(com|net|org)|[^@]+\.(test|example|invalid|localhost))$/i; + +export async function emailSignInResponse(env: Env, request: Request) { + const { pathname } = new URL(request.url); + if (pathname !== EMAIL_SIGN_IN_PATH && pathname !== CODE_PATH) return null; + if (request.method === "POST" && request.headers.get("origin") !== issuerOf(env)) + return errorPage("Send this from its own page.", 403); + if (pathname === CODE_PATH) + return request.method === "POST" ? finish(env, request) : codePage(env, request); + if (request.method === "POST") return start(env, request); + const next = new URL(request.url).searchParams.get("next") || "/"; + const signIn = await signInOf(env, next); + if (!signIn) return errorPage(TOO_MANY, 429); + return signIn.methods.includes("email") ? emailAddressPage(env, next, signIn) : toSignIn(next); +} + +/** The way back for a sign-in that does not name "email": its own sign-in page. */ +const toSignIn = (next: string) => + new Response(null, { + status: 303, + headers: { location: signInHref(next), "cache-control": "no-store" }, + }); + +/** The mind's own line above a form: what a code gives. It is on the page of an outside client's + * sign-in to an app, which is headed with the mind's name. An app's own page leaves it out: its + * words are the mind's, not the app's. */ +function ruleAbove(env: Env, asking: object | null) { + if (asking) return ""; + const mind = text(configOf(env).controlPlaneHostname); + return `<p class="muted">A code signs you in to the apps of ${mind}, never to the mind itself. Members sign in with a passkey.</p>`; +} + +/** What the pages need of the sign-in that a code is for (./asking-app.ts `signInOf`). */ +type SignIn = NonNullable<Awaited<ReturnType<typeof signInOf>>>; + +/** THE ADDRESS PAGE: the form that asks for a code, and below it the passkey. A passkey counts at + * every app, whatever methods the app names, so a member can always use theirs here. It is `/sign-in/email`, and it is the sign-in page itself for a sign-in whose + * first method is "email" (./http.ts). `signIn` is the one that `next` goes on to. */ +export function emailAddressPage( + env: Env, + next: string, + signIn: SignIn, + error?: string, + typed = "", +) { + const mind = configOf(env).controlPlaneHostname; + const passkey = passkeySignIn(next, { alone: false, asksAtOpen: false }); + // a sign-in that an app of this mind started says which app, on each of its pages + const asking = signIn.app ? appSignIn(signIn.app) : null; + return page({ + title: asking?.title || `Sign in to ${mind}`, + mark: asking?.mark, + centered: true, + imageOrigin: asking?.imageOrigin, + status: error ? 400 : 200, + body: `${asking?.heading || `<h1>Sign in to ${text(mind)}</h1>`} + <p class="muted">Enter your email. We send you a code to sign in with.</p> + ${ruleAbove(env, asking)} + ${error ? `<p role="alert">${text(error)}</p>` : ""} + <form method="post" action="${EMAIL_SIGN_IN_PATH}" class="stack"> + <input type="hidden" name="next" value="${text(next)}"> + <label>Email <input type="email" name="email" value="${text(typed)}" autocomplete="email" placeholder="you@example.com" required></label> + <button type="submit">Send a code</button> + </form> + ${passkey.body}${signIn.app && signIn.methods.includes("mind") ? mindWay(next) : ""}${asking?.about || ""}`, + script: passkey.script, + }); +} + +/** 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)}"> + <button type="submit" class="secondary">Sign in with your mind</button> + </form>`; + +async function start(env: Env, request: Request) { + const form = await request.formData().catch(() => null); + // where the person goes on once signed in: an address of the mind's own, kept whole as it was + // checked, else the mind's Dash + const asked = honouredNext(String(form?.get("next") || ""), configOf(env)); + const next = asked && asked.length <= NEXT_MAX_CHARACTERS ? asked : dashOf(env); + const signIn = await signInOf(env, next); + if (!signIn) return errorPage(TOO_MANY, 429); + if (!signIn.methods.includes("email")) return toSignIn(next); + const typed = String(form?.get("email") || ""); + 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."); + const id = crypto.randomUUID(); + const code = String(crypto.getRandomValues(new Uint32Array(1))[0]! % 1_000_000).padStart(6, "0"); + // both are read for every address alike, so the answer's time says nothing + const [named, blocked] = await Promise.all([isMember(env, email), isBlocked(env, email)]); + // someone an owner blocked gets the same page as anyone, and no mail; a member is never blocked + const mailable = !reservedDomain.test(email) && (named || !blocked); + const now = Date.now(); + const [, , added] = await env.DB.batch<{ mailed: number }>([ + env.DB.prepare("delete from email_challenges where created_at <= ?1").bind(now - HOUR), + sessionsOverRemoved(env, now), + env.DB.prepare(INSERT_CHALLENGE).bind( + id, + email, + email.replace(/\+[^@]*@/, "@"), + clientOf(request), + await sha256Hex(`${id}:${code}`), + next, + named ? 1 : 0, + mailable ? 1 : 0, + now, + now + LIFETIME_SECONDS * 1000, + ), + ]); + const row = added?.results[0]; + if (!row) return again("Codes were asked for just now. Wait ten minutes, then try again."); + // after the answer, so every address is answered alike and in the same time + if (row.mailed) waitUntil(mailCode(env, email, code, signIn.app)); + else console.info({ event: "email-sign-in.not-mailed" }); + return new Response(null, { + status: 303, + headers: { + location: CODE_PATH, + "set-cookie": cookie(id, LIFETIME_SECONDS), + "cache-control": "no-store", + }, + }); +} + +/** THE MAIL COMES FROM WHERE THE PERSON IS. `app` is the app whose own sign-in the code is for: + * the sender is `sign-in@<the zone of the app's hostname>`, and the app's name is the sender's + * name and in the subject, so a mind with two zones mails an app's people from the zone that + * they are on. With no app, an outside client's sign-in to an app (an MCP client's): + * `sign-in@<the zone of the control-plane hostname>`, under the control-plane hostname. The stack + * lets this Worker send as `sign-in@<zone>` for every zone of the mind (core/alchemy). */ +async function mailCode(env: Env, email: string, code: string, app: AskingApp | null) { + const config = configOf(env); + const name = app?.name || config.controlPlaneHostname; + // an app's own name is the app's choice: the mail also says the hostname, which is not + const where = app && app.name !== app.host ? `${app.name} (${app.host})` : name; + try { + const { messageId } = await env.SEND_EMAIL.send({ + from: { email: `sign-in@${zoneOf(config, app?.host || config.controlPlaneHostname)}`, name }, + to: [email], + subject: `Your sign-in code for ${name}`, + text: `${code}\n\nEnter this code to sign in to ${where}. It expires in 10 minutes.\n\nIf you did not try to sign in, ignore this email.\n`, + }); + console.info({ event: "email-sign-in.sent", messageId }); + } catch (error) { + reportIssue("email-sign-in.send-failed", error); + } +} + +async function codePage(env: Env, request: Request, error?: string, status = 200) { + const id = cookieValueOf(request.headers.get("cookie"), COOKIE); + const challenge = id + ? await env.DB.prepare( + "select email, next from email_challenges where id = ?1 and tries < ?2 and expires_at > ?3", + ) + .bind(id, TRIES, Date.now()) + .first<Pick<Challenge, "email" | "next">>() + : null; + if (!challenge) return restart(); + // the code is for the app that the sign-in started from, and the page still says which + const app = await askingAppOf(env, challenge.next); + const asking = app && { ...appSignIn(app, { heading: "Enter your code" }), app }; + // ONE SENTENCE OVER THE FIELD: whose code, for which sign-in, and how long it lasts. What to do + // when no code comes is under the button, with the way back. + const where = asking ? `sign in to <strong>${text(asking.app.host)}</strong>` : "sign in here"; + return page({ + title: "Enter your code", + mark: asking?.mark, + centered: true, + imageOrigin: asking?.imageOrigin, + status, + body: `${asking?.heading || "<h1>Enter your code</h1>"} + <p class="muted">If <strong>${text(challenge.email)}</strong> may ${where}, a code is on its way. It expires in 10 minutes.</p> + ${ruleAbove(env, asking)} + ${error ? `<p role="alert">${text(error)}</p>` : ""} + <form method="post" action="${CODE_PATH}" class="stack"> + <label>Code <input class="code" name="code" inputmode="numeric" autocomplete="one-time-code" autofocus required></label> + <button type="submit">Sign in</button> + </form> + <p class="muted">No code after a minute? Check the spam folder, or <a href="${text(`${EMAIL_SIGN_IN_PATH}?${new URLSearchParams({ next: challenge.next })}`)}">use another email or send a new code</a>.</p>${asking?.about || ""}`, + }); +} + +async function finish(env: Env, request: Request) { + const id = cookieValueOf(request.headers.get("cookie"), COOKIE); + const form = await request.formData().catch(() => null); + const entered = String(form?.get("code") || "").replace(/\D/g, ""); + // the try is spent before the check, in one statement: no other request sees it unspent + const challenge = id + ? await env.DB.prepare( + "update email_challenges set tries = tries + 1 where id = ?1 and tries < ?2 and expires_at > ?3 returning email, hash, tries, next, mailed", + ) + .bind(id, TRIES, Date.now()) + .first<Challenge>() + : null; + if (!id || !challenge) return restart(); + // A challenge that was not mailed has no code that anyone was given: no entry is right for it, + // and its page answers as for a wrong one. + const right = + entered.length === 6 && + (await sha256Hex(`${id}:${entered}`)) === challenge.hash && + challenge.mailed === 1; + if (!right) { + if (challenge.tries >= TRIES) + return errorPage( + "Too many tries. Ask for a new code.", + 400, + new Headers({ "set-cookie": cookie("", 0) }), + [ + { + href: `${EMAIL_SIGN_IN_PATH}?${new URLSearchParams({ next: challenge.next })}`, + label: "Send a new code", + }, + ], + ); + const left = TRIES - challenge.tries; + return codePage( + env, + request, + `That code is not right. ${left} ${left === 1 ? "try" : "tries"} left.`, + 400, + ); + } + // spent once: of two right answers at once, one signs in + const spent = await env.DB.prepare( + "update email_challenges set expires_at = 0 where id = ?1 and expires_at > ?2 returning id", + ) + .bind(id, Date.now()) + .first(); + if (!spent) return restart(); + // A code proves an address, and no more: it opens no way into the mind. A member's address, as + // the code is typed, gets the words of what does sign that member in, and no session. + if (await isMember(env, challenge.email)) { + const refused = await memberRefusal(env, challenge.email, challenge.next); + console.info({ event: "auth.sign-in-refused", method: "email" }); + return errorPage(refused.words, 403, new Headers({ "set-cookie": cookie("", 0) }), [ + refused.link, + ]); + } + const user = await userOf(env.DB, challenge.email); + const { setCookie, session } = await emailSessionCookie(env, request, user); + console.info({ event: "auth.signed-in", method: "email", userId: user.id }); + const facts = new AccountFacts(); + facts.add(user.id, { + type: "events.iterate.com/account/signed-in", + payload: { method: "email", session, at: Date.now() }, + }); + // The session's cookie, the code's own cookie cleared, and on to where the sign-in was for: the + // address that was checked when the code was asked for. + const headers = new Headers({ location: challenge.next, "cache-control": "no-store" }); + headers.append("set-cookie", setCookie); + headers.append("set-cookie", cookie("", 0)); + return facts.on(new Response(null, { status: 303, headers })); +} + +/** WHY A RIGHT CODE SIGNS IN NO MEMBER, in words that say what does, and the link under them. + * Mail must not open the mind: a member signs in with a passkey, and the first one is added after + * a proof that ./enrolment.ts takes. `next` is where the sign-in was for. */ +async function memberRefusal(env: Env, email: string, next: string) { + const config = configOf(env); + const mind = config.controlPlaneHostname; + const owner = isOwner(config, email); + const passkeys = await passkeysOf(env, email); + const words = { + held: `${email} has a passkey for ${mind}, so nothing else signs it in. Sign in with the passkey.`, + removed: owner + ? `${email} had a passkey for ${mind}, so a code by email signs it in no more. An owner with no passkey left gets back in by the recovery command, which whoever holds this mind's Cloudflare account runs.` + : `${email} had a passkey for ${mind}, so a code by email signs it in no more. Ask an owner of the mind for a sign-in link.`, + none: owner + ? `${email} is an owner of ${mind}, and a code by email signs in no member. Prove your email address with Cloudflare, and then add a passkey.` + : `${email} is a member of ${mind}, and a code by email signs in no member. Ask an owner of the mind for a sign-in link, and then add a passkey.`, + }[passkeys]; + // an owner with no passkey yet goes on to Cloudflare Access; anyone else, back to the sign-in + const link = + owner && passkeys === "none" + ? { + href: `/sign-in/access?${new URLSearchParams({ next })}`, + label: "Prove your email address with Cloudflare", + } + : { href: signInHref(next), label: "Sign in" }; + return { words, link }; +} + +const restart = () => + new Response(null, { + status: 303, + headers: { + location: EMAIL_SIGN_IN_PATH, + "set-cookie": cookie("", 0), + "cache-control": "no-store", + }, + }); + +const cookie = (id: string, maxAgeSeconds: number) => + `${COOKIE}=${id}; HttpOnly; Secure; SameSite=Lax; Path=/; Max-Age=${maxAgeSeconds}`;
A core/auth-worker/src/enrolment.test.ts
@@ -0,0 +1,1419 @@ +// What a proof of an address is good for, through the Worker's own router and SQL: the first +// passkey of a member (./enrolment.ts) by an owner's link and the recovery command's link, each +// to the address the browser ends at (Cloudflare Access, an owner's proof, is +// ./access-sign-in.test.ts); and the mailed code (./email-sign-in.ts), which gives a person who +// is no member a session that an app of the mind takes and the mind itself does not, and gives a +// member nothing. Then what an app names (./asking-app.ts): the sign-in methods that the issuer +// holds its host to, the form that its sign-in page opens on, and the zone and the name that its +// code is mailed from. +import { decodeFacts, FACTS_HEADER } from "iterate/facts"; +import { base64url, challengeOf, keyIdOf, signedP256, statementText } from "iterate/signed"; +import { calculatePKCECodeChallenge, generateRandomCodeVerifier } from "oauth4webapi"; +import { expect, test, vi } from "vitest"; +import { sha256Hex } from "./device/protocol.ts"; +import { liveSessionsOf } from "./cookies.ts"; +import { + CODES_AN_HOUR_FOR_A_MAILBOX, + LIVE_CHALLENGES, + NON_MEMBER_CODES_AN_HOUR, +} from "./email-sign-in.ts"; +import { passkeysOf as passkeysRead, RECOVERY_COMMAND } from "./enrolment.ts"; +import type { Env } from "./env.ts"; +import { authResponse } from "./http.ts"; +import { hostCallbackOf, hostClientOf, oauthHelpers, sessionsByClientOf } from "./oauth.ts"; +import { Auth } from "./rpc.ts"; +import { sqliteStack } from "./test-support.ts"; +import { userOf } from "./users.ts"; +import { whoIs } from "./who-is.ts"; + +const ISSUER = "https://iterate.example.com"; +const ZONES = ["example.com", "second.example"]; +// no reserved name (RFC 2606): a code is mailed, to the test's own mail binding +const OWNER = "ada@adas-mail.dev"; +const MEMBER = "bo@bos-mail.dev"; +const GUEST = "eve@eves-mail.dev"; +// an app that says nothing of itself: it is for anyone, whose people sign in by a mailed code +const GUESTBOOK = "https://guestbook.example.com"; +const MIND = "iterate.example.com"; + +// A MAILED CODE IS FOR THE PEOPLE OF THE MIND'S APPS: a person who is no member gets a session +// that is no member's, and with it the app's host. +test("a mailed code gives a person who is no member a session that is no member's, which adds no passkey, and the app that the sign-in was for takes it", async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + const guest = await codeRedeemed(stack, GUEST, next); + expect({ + status: guest.status, + location: guest.location, + person: await personOf(stack.env, guest.cookie), + mayAddAPasskey: (await formOf(stack.env, guest.cookie)).challenge !== null, + }).toEqual({ + status: 303, + location: next, + person: { + userId: expect.stringMatching(/^user_/), + email: GUEST, + member: false, + method: "email", + // when the browser's session ends, in Unix seconds: a session of the API ends no later + expiresAt: expect.any(Number), + }, + mayAddAPasskey: false, + }); + // the browser goes on to the app's own authorization request, which gives a code for its host + const on = await ask(stack.env, guest.location.slice(ISSUER.length), { cookie: guest.cookie }); + expect(on.headers.get("location")).toMatch( + /^https:\/\/guestbook\.example\.com\/\.iterate\/callback\?code=/, + ); +}); + +// A MAILED CODE NEVER OPENS A WAY INTO THE MIND. A member's address is mailed its code as any +// address is, so the pages tell a stranger nothing; the right code, which proves the mailbox, is +// answered with what does sign that member in. +test.for([ + { + who: "an owner who never had a passkey", + email: OWNER, + passkey: "none", + words: `${OWNER} is an owner of ${MIND}, and a code by email signs in no member. Prove your email address with Cloudflare, and then add a passkey.`, + way: "Prove your email address with Cloudflare", + }, + { + who: "an added member who never had a passkey", + email: MEMBER, + passkey: "none", + words: `${MEMBER} is a member of ${MIND}, and a code by email signs in no member. Ask an owner of the mind for a sign-in link, and then add a passkey.`, + way: "Sign in", + }, + { + who: "an owner who has a passkey", + email: OWNER, + passkey: "held", + words: `${OWNER} has a passkey for ${MIND}, so nothing else signs it in. Sign in with the passkey.`, + way: "Sign in", + }, + { + who: "an added member who has a passkey", + email: MEMBER, + passkey: "held", + words: `${MEMBER} has a passkey for ${MIND}, so nothing else signs it in. Sign in with the passkey.`, + way: "Sign in", + }, + { + who: "an owner whose passkey is gone", + email: OWNER, + passkey: "removed", + words: `${OWNER} had a passkey for ${MIND}, so a code by email signs it in no more. An owner with no passkey left gets back in by the recovery command, which whoever holds this mind's Cloudflare account runs.`, + way: "Sign in", + }, + { + who: "an added member whose passkey is gone", + email: MEMBER, + passkey: "removed", + words: `${MEMBER} had a passkey for ${MIND}, so a code by email signs it in no more. Ask an owner of the mind for a sign-in link.`, + way: "Sign in", + }, +])( + "the right code of $who is refused, opens no session, and the page says what to do instead", + async ({ email, passkey, words, way }) => { + const stack = stackOf(); + if (passkey !== "none") await passkeyAdded(stack, email); + if (passkey === "removed") stack.db.exec("update keys set revoked_at = 1"); + const next = await appSignIn(stack.env); + // the sessions that are not over: a request for a code removes those that are (./cookies.ts) + const sessions = () => + stack.db.prepare("select count(*) as n from browser_sessions where ended_at is null").get()! + .n; + const before = sessions(); + // the code is mailed to the member's address: `codeMailed` reads it from that mail + const refused = await codeRedeemed(stack, email, next); + expect(refused).toMatchObject({ status: 403, location: "", cookie: "" }); + expect(refused.text).toContain(`<p>${words}</p>`); + // the one link under the words: for an owner with no passkey yet, on to Cloudflare Access + const href = way === "Sign in" ? "/sign-in" : "/sign-in/access"; + expect(refused.text).toContain( + `<p><a href="${href}?${new URLSearchParams({ next })}">${way}</a></p>`, + ); + expect(sessions()).toBe(before); + }, +); + +test("a session of a person who is no member reaches /sessions and sign-out, and no other page of the control plane", async () => { + const stack = stackOf(); + const { cookie } = await codeRedeemed(stack, GUEST); + expect(cookie).not.toBe(""); + expect(await statusOf(stack.env, "/sessions", cookie)).toBe(200); + expect(await statusOf(stack.env, "/keys.json", cookie)).toBe(401); + expect(await locationOf(stack.env, "/keys", cookie)).toBe(`${ISSUER}/sign-in?next=%2Fkeys`); + expect(await locationOf(stack.env, "/members", cookie)).toBe("/sign-in?next=%2Fmembers"); + expect(await locationOf(stack.env, "/minds", cookie)).toBe("/sign-in?next=%2Fminds"); + expect(await locationOf(stack.env, "/self-test", cookie)).toBe( + `${ISSUER}/sign-in?next=%2Fself-test`, + ); + expect(await locationOf(stack.env, "/oauth2/device?user_code=WDJB-MJHT", cookie)).toMatch( + /^\/sign-in\?/, + ); + expect(await firstPasskeyAdded(stack.env, cookie)).toMatchObject({ status: 403 }); + // `/` says who is signed in, and that the address is no member + expect(await statusOf(stack.env, "/", cookie)).toBe(403); + const out = await ask(stack.env, "/sign-out", { method: "POST", cookie, body: new FormData() }); + expect(out).toMatchObject({ status: 303 }); + expect(await personOf(stack.env, cookie)).toBeNull(); +}); + +test("a person who is no member gets a token for an app's host, which says so, and no grant for the mind's API: also once the address is a member's", async () => { + const stack = stackOf(); + const { cookie } = await codeRedeemed(stack, GUEST); + const host = "https://guestbook.example.com"; + const api = `${ISSUER}/api`; + // the app's host signs its visitor in: the code goes to the host's own callback, with no consent + const verifier = generateRandomCodeVerifier(); + const authorize = async (fields: Record<string, string>) => + ask( + stack.env, + `/oauth2/auth?${new URLSearchParams({ + response_type: "code", + code_challenge: await calculatePKCECodeChallenge(verifier), + code_challenge_method: "S256", + state: "a-state", + ...fields, + })}`, + { cookie }, + ); + const redirectUri = hostCallbackOf(host); + const clientId = await hostClientOf(stack.env, new URL(host).host); + const signedIn = await authorize({ + client_id: clientId, + redirect_uri: redirectUri, + resource: host, + scope: "identity", + }); + const back = new URL(signedIn.headers.get("location")!); + expect(back.origin + back.pathname).toBe(redirectUri); + const answer = await ask(stack.env, "/oauth2/token", { + method: "POST", + body: new URLSearchParams({ + grant_type: "authorization_code", + code: back.searchParams.get("code")!, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: verifier, + resource: host, + }), + }); + const { access_token: token } = (await answer.json()) as { access_token: string }; + expect(await whoIs(stack.env, token, host)).toMatchObject({ + principal: { email: GUEST }, + member: false, + }); + + // the mind's API takes a member alone: the request gets a refusal's page, and no code + const app = await oauthHelpers(stack.env).createClient({ + redirectUris: ["http://127.0.0.1:7777/callback"], + tokenEndpointAuthMethod: "none", + grantTypes: ["authorization_code", "refresh_token"], + responseTypes: ["code"], + }); + const forApi = () => + authorize({ + client_id: app.clientId, + redirect_uri: "http://127.0.0.1:7777/callback", + resource: api, + scope: "iterate", + }); + const refused = await forApi(); + expect(refused).toMatchObject({ status: 403 }); + expect(await refused.text()).toContain("is not a member of iterate.example.com"); + + // An owner adds the address as a member. What mail proved is no member's all the same: the + // session, the host's token and a new request for the API. + stack.db + .prepare("insert into members (email, added_by, added_at) values (?, ?, 0)") + .run(GUEST, OWNER); + expect(await personOf(stack.env, cookie)).toMatchObject({ email: GUEST, member: false }); + expect(await whoIs(stack.env, token, host)).toMatchObject({ member: false }); + expect(await forApi()).toMatchObject({ status: 403 }); +}); + +test(`the whole mind mails ${NON_MEMBER_CODES_AN_HOUR} codes an hour to addresses that are no member's, and a member's code is no part of that`, async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + // each request from a client address of its own: one client's own limit is another test's + let clients = 0; + const asked = async (email: string) => { + const before = stack.mailed.length; + const answer = await ask(stack.env, "/sign-in/email", { + method: "POST", + headers: { "cf-connecting-ip": `192.0.2.${(clients += 1)}` }, + body: new URLSearchParams({ email, next }), + }); + return { status: answer.status, mailed: stack.mailed.length - before }; + }; + for (let n = 1; n <= NON_MEMBER_CODES_AN_HOUR; n += 1) + expect(await asked(`guest-${n}@guests-mail.dev`)).toEqual({ status: 303, mailed: 1 }); + // past the cap: the same answer, and no mail + expect(await asked("guest-too-many@guests-mail.dev")).toEqual({ status: 303, mailed: 0 }); + // An address with a tag is no member's, though its mailbox is the owner's. Past the cap it + // mails nothing, so it spends none of the owner's own codes. + const tagged = OWNER.replace("@", "+tag@"); + for (const email of [tagged, tagged, tagged, tagged, tagged, tagged]) + expect(await asked(email)).toEqual({ status: 303, mailed: 0 }); + expect(await asked(OWNER)).toEqual({ status: 303, mailed: 1 }); + expect(await asked(MEMBER)).toEqual({ status: 303, mailed: 1 }); + // an hour on, the mind mails strangers again + stack.db.exec("update email_challenges set created_at = created_at - 3600000"); + expect(await asked("guest-an-hour-on@guests-mail.dev")).toEqual({ status: 303, mailed: 1 }); +}); + +test("one client address asks for twenty codes in ten minutes, and no more", async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + const asked = async (n: number) => + ( + await ask(stack.env, "/sign-in/email", { + method: "POST", + headers: { "cf-connecting-ip": "192.0.2.1" }, + body: new URLSearchParams({ email: `guest-${n}@guests-mail.dev`, next }), + }) + ).status; + const statuses = []; + for (let n = 1; n <= 21; n += 1) statuses.push(await asked(n)); + expect(statuses).toEqual([...Array(20).fill(303), 400]); +}); + +test(`a mailbox gets one code a minute from one client, and ${CODES_AN_HOUR_FOR_A_MAILBOX} an hour from all: past either, the same answer and no mail`, async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + let clients = 0; + const asked = async (client = `192.0.2.${(clients += 1)}`) => { + const before = stack.mailed.length; + const answer = await ask(stack.env, "/sign-in/email", { + method: "POST", + headers: { "cf-connecting-ip": client }, + body: new URLSearchParams({ email: OWNER, next }), + }); + return { status: answer.status, mailed: stack.mailed.length - before }; + }; + expect(await asked("192.0.2.200")).toEqual({ status: 303, mailed: 1 }); + // within the minute the same client gets no second mail, and another client does + expect(await asked("192.0.2.200")).toEqual({ status: 303, mailed: 0 }); + for (let n = 2; n <= CODES_AN_HOUR_FOR_A_MAILBOX; n += 1) + expect(await asked()).toEqual({ status: 303, mailed: 1 }); + expect(await asked()).toEqual({ status: 303, mailed: 0 }); + stack.db.exec("update email_challenges set created_at = created_at - 3600000"); + expect(await asked()).toEqual({ status: 303, mailed: 1 }); +}); + +// THE ADDRESS PAGE TELLS A STRANGER NOTHING: with the mind's codes for strangers spent and a +// member's mailbox at its limit, a member's address and a stranger's get the same answer +test("past the strangers' cap and a member's mailbox limit, a member's address and a stranger's are answered alike", async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + let clients = 0; + const asked = async (email: string) => { + const before = stack.mailed.length; + const answer = await ask(stack.env, "/sign-in/email", { + method: "POST", + headers: { "cf-connecting-ip": `198.51.100.${(clients += 1)}` }, + body: new URLSearchParams({ email, next }), + }); + return { + status: answer.status, + location: answer.headers.get("location"), + mailed: stack.mailed.length - before, + }; + }; + for (let n = 1; n <= NON_MEMBER_CODES_AN_HOUR; n += 1) await asked(`guest-${n}@guests-mail.dev`); + for (let n = 1; n <= CODES_AN_HOUR_FOR_A_MAILBOX; n += 1) await asked(MEMBER); + const [member, stranger] = [await asked(MEMBER), await asked("someone@guests-mail.dev")]; + expect(member).toEqual(stranger); + expect(member).toMatchObject({ status: 303, mailed: 0 }); +}); + +test(`the whole mind holds ${LIVE_CHALLENGES} challenges that are not over, whoever asks`, async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + let clients = 0; + const asked = async () => + ( + await ask(stack.env, "/sign-in/email", { + method: "POST", + headers: { "cf-connecting-ip": `198.51.100.${(clients += 1)}` }, + body: new URLSearchParams({ email: `guest-${clients}@guests-mail.dev`, next }), + }) + ).status; + for (let n = 1; n <= LIVE_CHALLENGES; n += 1) expect(await asked()).toBe(303); + expect(await asked()).toBe(400); + // the challenges end after their ten minutes, and the mind takes new ones + stack.db.exec("update email_challenges set expires_at = expires_at - 600000"); + expect(await asked()).toBe(303); +}); + +test("a challenge that was not mailed takes no code, not the right one either", async () => { + const stack = stackOf(); + const mailed = await codeMailed(stack, GUEST); + stack.db.exec("update email_challenges set mailed = 0"); + const answer = await redeem(stack.env, mailed); + expect(answer).toMatchObject({ status: 400, cookie: "" }); + expect(answer.text).toContain("That code is not right. 4 tries left."); +}); + +test("a code that went out while the address was no member's signs nobody in once the address is a member's", async () => { + const stack = stackOf(); + const mailed = await codeMailed(stack, GUEST); + stack.db + .prepare("insert into members (email, added_by, added_at) values (?, ?, 0)") + .run(GUEST, OWNER); + const redeemed = await redeem(stack.env, mailed); + expect(redeemed).toMatchObject({ status: 403, cookie: "" }); + expect(redeemed.text).toContain( + `${GUEST} is a member of ${MIND}, and a code by email signs in no member.`, + ); + expect(stack.db.prepare("select count(*) as n from browser_sessions").get()).toEqual({ n: 0 }); +}); + +// THE CONTROL PLANE'S OWN SIGN-IN HAS NO MAILED CODE: the address page and the request for a code +// lead back to its sign-in page, and nothing is mailed or kept. So do an empty `next` and a `next` +// that is too long to keep, both of which go on to the mind's Dash. +test.for([ + { name: "the control plane's own page", next: "/keys" }, + { name: "the mind's API, for an outside client", next: "/oauth2/auth?client_id=c" }, + { name: "no next at all", next: "" }, + { name: "a hostname of the mind that is no authorization request", next: `${GUESTBOOK}/notes` }, + { name: "a next that is too long to keep", next: `${GUESTBOOK}/${"n".repeat(3000)}` }, +])( + "/sign-in/email mails no code for a sign-in with no asking app: $name", + async ({ name, next }) => { + const stack = stackOf(); + const page = await ask(stack.env, `/sign-in/email?${new URLSearchParams({ next })}`); + const posted = await ask(stack.env, "/sign-in/email", { + method: "POST", + body: new URLSearchParams({ email: OWNER, next }), + }); + for (const answer of [page, posted]) { + expect(answer).toMatchObject({ status: 303 }); + expect(answer.headers.get("location")).toMatch(/^\/sign-in\?next=/); + expect(answer.headers.getSetCookie()).toEqual([]); + } + // the page keeps the `next` it was given; a request keeps the address that was checked + expect(page.headers.get("location")).toBe( + `/sign-in?${new URLSearchParams({ next: next || "/" })}`, + ); + if (name === "no next at all" || name.includes("too long")) + expect(posted.headers.get("location")).toBe( + `/sign-in?${new URLSearchParams({ next: "https://dash.example.com/" })}`, + ); + expect(stack).toMatchObject({ mailed: [] }); + expect(stack.db.prepare("select count(*) as n from email_challenges").get()).toEqual({ n: 0 }); + }, +); + +test("a session that a mailed code opened for a person who was no member lists and ends its own kind alone, once the address is a member's with a passkey", async () => { + const stack = stackOf(); + const host = "https://guestbook.example.com"; + const before = await codeRedeemed(stack, GUEST); + const beforeOnPhone = await codeRedeemed(stack, GUEST); + await hostSignedIn(stack.env, before.cookie, host); + // an owner adds the address, and the person adds a passkey and signs in to the same app + stack.db + .prepare("insert into members (email, added_by, added_at) values (?, ?, 0)") + .run(GUEST, OWNER); + const member = await passkeyAdded(stack, GUEST); + await hostSignedIn(stack.env, member.cookie, host); + const { userId } = (await personOf(stack.env, member.cookie))!; + const held = async () => ({ + browsers: (await liveSessionsOf(stack.env, userId, "all")).map(({ method }) => method), + grants: (await sessionsByClientOf(stack.env, userId, "all")) + .flatMap(({ signIns }) => signIns.map(({ id }) => grantMethods.get(id))) + .toSorted(), + }); + // how the person of each grant signed in, as its metadata keeps it + const grantMethods = new Map( + (await oauthHelpers(stack.env).listUserGrants(userId)).items.map((grant) => [ + grant.id, + (grant.metadata as { method: string }).method, + ]), + ); + expect(await held()).toEqual({ + browsers: ["passkey", "email", "email"], + grants: ["email", "passkey"], + }); + + // the old session's page shows its own kind, and nothing that the passkey opened + const page = await (await ask(stack.env, "/sessions", { cookie: before.cookie })).text(); + expect(page.match(/data-session="/g)).toHaveLength(2); + expect(page).toContain("Email code"); + expect(page).not.toContain("Passkey"); + expect(page.match(/name="signIn"/g)).toHaveLength(1); + + // and its forms end its own kind alone: the other mailed session, and its own grant + const post = (fields: Record<string, string>) => + ask(stack.env, "/sessions", { + method: "POST", + cookie: before.cookie, + body: new URLSearchParams(fields), + }); + await post({ others: "1" }); + await post({ client: await hostClientOf(stack.env, new URL(host).host) }); + expect(await held()).toEqual({ browsers: ["passkey", "email"], grants: ["passkey"] }); + expect(await personOf(stack.env, beforeOnPhone.cookie)).toBeNull(); + + // the passkey's session ends everything of the person + await ask(stack.env, "/sessions", { + method: "POST", + cookie: member.cookie, + body: new URLSearchParams({ others: "1" }), + }); + expect(await held()).toMatchObject({ browsers: ["passkey"] }); +}); + +test("the sessions that are no passkey's are removed once they are over, as a code is asked for", async () => { + const stack = stackOf(); + const guest = await codeRedeemed(stack, GUEST); + const member = await passkeyAdded(stack, MEMBER); + const rows = () => stack.db.prepare("select method from browser_sessions order by method").all(); + // the member's enrolment session ended as the passkey was added: it is over, and still a row + expect(rows()).toEqual([{ method: "email" }, { method: "member-link" }, { method: "passkey" }]); + await codeMailed(stack, "another-guest@guests-mail.dev"); + expect(rows()).toEqual([{ method: "email" }, { method: "passkey" }]); + // expired: the guest's goes, and the passkey's, which its own sign-in removes, stays + stack.db.exec("update browser_sessions set expires_at = 1"); + await codeMailed(stack, "one-more-guest@guests-mail.dev"); + expect(rows()).toEqual([{ method: "passkey" }]); + expect([guest.cookie, member.cookie].every(Boolean)).toBe(true); +}); + +test("an address that an owner blocked is no longer blocked once an owner adds it as a member", async () => { + const stack = stackOf(); + const owner = await ownerWithKey(stack); + stack.db + .prepare("insert into blocked (email, blocked_by, blocked_at) values (?, ?, 0)") + .run(GUEST, OWNER); + const answer = await ask(stack.env, "/members", { + method: "POST", + headers: { accept: "application/json", "content-type": "application/json" }, + body: await owner.signed("events.iterate.com/account/member-added", { email: GUEST }), + }); + expect(answer).toMatchObject({ status: 200 }); + expect(stack.db.prepare("select email from blocked").all()).toEqual([]); + expect( + decodeFacts(answer.headers.get(FACTS_HEADER)!).flatMap(({ events }) => + events.map(({ type, payload }) => ({ type, email: (payload as { email: string }).email })), + ), + ).toEqual([ + { type: "events.iterate.com/account/person-unblocked", email: GUEST }, + { type: "events.iterate.com/account/member-added", email: GUEST }, + ]); +}); + +test("a code for a tagged address of a mailbox that was mailed just now waits, as the mailbox's own would", async () => { + const stack = stackOf(); + const next = await appSignIn(stack.env); + const post = (email: string) => + ask(stack.env, "/sign-in/email", { + method: "POST", + body: new URLSearchParams({ email, next }), + }); + expect(await post(OWNER)).toMatchObject({ status: 303 }); + expect(await post(OWNER.replace("@", "+tag@"))).toMatchObject({ status: 303 }); + expect(stack.mailed).toHaveLength(1); +}); + +// A PASSKEY OF AN ADDRESS THAT IS NO MEMBER'S, from before ../migrations/0016: its `outsider` +// reads 0. It never signs in, and never bars a member's first passkey, also once an owner adds +// the address. +test("a passkey that an address held while it was no member's never signs in and never bars its first passkey as a member", async () => { + const stack = stackOf(); + // the control: an owner's key of the same shape signs in, and with no `next` goes on to the Dash + const ownerKey = await passkeyOfRow(stack, OWNER); + expect(await passkeySignedIn(stack.env, ownerKey)).toMatchObject({ + status: 200, + next: "https://dash.example.com/", + }); + expect(await passkeySignedIn(stack.env, ownerKey, "/keys")).toMatchObject({ + status: 200, + next: "https://iterate.example.com/keys", + }); + const old = await passkeyOfRow(stack, GUEST); + expect(await passkeySignedIn(stack.env, old)).toMatchObject({ status: 403 }); + const owner = await ownerWithKey(stack); + const added = await ask(stack.env, "/members", { + method: "POST", + headers: { accept: "application/json", "content-type": "application/json" }, + body: await owner.signed("events.iterate.com/account/member-added", { email: GUEST }), + }); + expect(added).toMatchObject({ status: 200 }); + // a member now, and the key is still no member's + expect( + stack.db.prepare("select outsider, revoked_at from keys where id = ?").get(old.id), + ).toEqual({ outsider: 1, revoked_at: null }); + expect(await passkeySignedIn(stack.env, old)).toMatchObject({ status: 403 }); + expect(await passkeysRead(stack.env, GUEST)).toBe("none"); + // the owner's link opens the member's first passkey, which revokes the old one + expect(await passkeyAdded(stack, GUEST)).toMatchObject({ status: 200 }); + expect( + stack.db.prepare("select revoked_at is not null as revoked from keys where id = ?").get(old.id), + ).toEqual({ revoked: 1 }); +}); + +// THE THREE PROOFS THAT OPEN THE SESSION WHICH ADDS A FIRST PASSKEY are Cloudflare Access +// (./access-sign-in.test.ts), an owner's link and the recovery command's link. +test.for([ + { proof: "an owner's link", who: "an added member", email: MEMBER, method: "member-link" }, + { proof: "the recovery command's link", who: "an owner", email: OWNER, method: "recovery-link" }, +])( + "$proof signs in $who who has no passkey, to add the first one and nothing else", + async ({ email, method }) => { + const stack = stackOf(); + const opened = await enrolling(stack, email); + expect(opened).toMatchObject({ status: 200 }); + expect(stack.db.prepare("select method, key_id from browser_sessions").all()).toEqual([ + { method, key_id: null }, + ]); + // the session reaches the first passkey's page, and is nobody anywhere else + const { cookie } = opened; + expect(await formOf(stack.env, cookie)).toMatchObject({ + heading: "Add your passkey to iterate.example.com", + html: expect.stringContaining( + "A passkey is required to continue — there is no password or email sign-in, and this step cannot be skipped.", + ), + }); + expect(await statusOf(stack.env, "/keys.json", cookie)).toBe(401); + expect(await locationOf(stack.env, "/keys", cookie)).toBe(`${ISSUER}/sign-in?next=%2Fkeys`); + expect(await locationOf(stack.env, "/members", cookie)).toBe("/sign-in?next=%2Fmembers"); + expect(await locationOf(stack.env, "/sessions", cookie)).toBe("/sign-in?next=%2Fsessions"); + expect(await personOf(stack.env, cookie)).toBeNull(); + + const added = await firstPasskeyAdded(stack.env, cookie); + expect(added).toMatchObject({ status: 200, next: "https://onboarding.example.com/" }); + // the answer's cookie is the passkey's own session, a member's + expect(await statusOf(stack.env, "/keys.json", added.cookie)).toBe(200); + expect(await personOf(stack.env, added.cookie)).toMatchObject({ email, member: true }); + // and the session that the link opened is over + expect(await personOf(stack.env, cookie)).toBeNull(); + expect(await firstPasskeyAdded(stack.env, cookie)).toMatchObject({ status: 403 }); + }, +); + +test("a link names whose it is: the recovery command's signs in no added member, an owner's link no owner, and neither a person who is no member", async () => { + const stack = stackOf(); + const spent = async (email: string, madeBy: string) => + (await linkSpent(stack.env, await linkFor(stack, email, madeBy))).status; + expect({ + recoveryForAnAddedMember: await spent(MEMBER, RECOVERY_COMMAND), + ownersLinkForAnOwner: await spent(OWNER, OWNER), + recoveryForNoMember: await spent(GUEST, RECOVERY_COMMAND), + ownersLinkForNoMember: await spent(GUEST, OWNER), + }).toEqual({ + recoveryForAnAddedMember: 403, + ownersLinkForAnOwner: 403, + recoveryForNoMember: 403, + ownersLinkForNoMember: 403, + }); + expect(stack.db.prepare("select count(*) as n from browser_sessions").get()).toEqual({ n: 0 }); +}); + +test("a session of a proof that this Worker does not take adds no passkey", async () => { + const stack = stackOf(); + const { cookie } = await enrolling(stack, MEMBER); + expect(await formOf(stack.env, cookie)).toMatchObject({ challenge: expect.any(String) }); + const form = await formOf(stack.env, cookie); + // the row's method is no proof of ./enrolment.ts: a mailed code's, by a name of its own + stack.db.exec("update browser_sessions set method = 'member-email'"); + expect(await formOf(stack.env, cookie)).toMatchObject({ challenge: null }); + expect(await firstPasskeyAdded(stack.env, cookie, { challenge: form.challenge! })).toMatchObject({ + status: 403, + }); + expect(passkeysOf(stack, MEMBER)).toBe(0); +}); + +test("the members page says how a new member gets in: by the sign-in link that an owner makes there, and by no mailed code", async () => { + const stack = stackOf(); + const pageOf = async (email: string) => + ( + await ( + await ask(stack.env, "/members", { cookie: (await passkeyAdded(stack, email)).cookie }) + ).text() + ).replaceAll(/\s+/g, " "); + const [owners, members] = [await pageOf(OWNER), await pageOf(MEMBER)]; + expect(owners).toContain( + `Then make the new member a <a href="#link">sign-in link</a>, to set up a passkey of their own.`, + ); + expect(owners).toContain( + `<h2 id="link">A sign-in link for a member</h2> <p>For a new member, or one whose keys you removed. It works once, within 24 hours, to add a passkey.`, + ); + // a member who is no owner makes no link, and reads who does + expect(members).toContain( + "Then an owner makes the new member a sign-in link on this page, to set up a passkey of their own.", + ); + expect(members).not.toContain(`id="link"`); + for (const page of [owners, members]) + expect(page).not.toMatch(/sign-in\/email|signs in once with a code|get a code by email/); +}); + +test("the page of a link that is over says to ask for a new one, and offers no email address", async () => { + const stack = stackOf(); + const html = await (await ask(stack.env, "/keys/first")).text(); + expect(html).toContain("<p>This link was used, or its 24 hours are over.</p>"); + expect(html).toContain( + `<p>Ask for a new one. If you have a passkey here, <a href="/sign-in?next=https%3A%2F%2Fonboarding.example.com%2F">sign in</a>.</p>`, + ); + expect(html).not.toMatch(/email/i); +}); + +test("a member whose passkeys an owner removed comes back by an owner's link, and adds a passkey with it", async () => { + const stack = stackOf(); + await passkeyAdded(stack, MEMBER); + stack.db.exec("update keys set revoked_at = 1"); + const { cookie, status } = await linkSpent(stack.env, await linkFor(stack, MEMBER, OWNER)); + expect(status).toBe(200); + expect(await firstPasskeyAdded(stack.env, cookie)).toMatchObject({ status: 200 }); + expect(passkeysOf(stack, MEMBER)).toBe(1); +}); + +test("the first passkey ends every session that could add one: a second browser's is over, and reads nothing", async () => { + const stack = stackOf(); + const first = await enrolling(stack, OWNER); + const second = await enrolling(stack, OWNER); + // both browsers hold a session that may add the first passkey + expect(await formOf(stack.env, second.cookie)).toMatchObject({ challenge: expect.any(String) }); + const stale = await formOf(stack.env, second.cookie); + + const added = await firstPasskeyAdded(stack.env, first.cookie); + expect(sessionsEndedIn(added.facts)).toHaveLength(2); + expect( + stack.db.prepare("select count(*) as n from browser_sessions where ended_at is null").get(), + ).toEqual({ n: 1 }); + + // the second browser: no form, no passkey of its own, no key's id, no person + expect(await formOf(stack.env, second.cookie)).toMatchObject({ challenge: null }); + expect( + await firstPasskeyAdded(stack.env, second.cookie, { challenge: stale.challenge! }), + ).toMatchObject({ status: 403 }); + expect(await statusOf(stack.env, "/keys.json", second.cookie)).toBe(401); + expect(await personOf(stack.env, second.cookie)).toBeNull(); + expect(passkeysOf(stack, OWNER)).toBe(1); +}); + +test("a link that was made before the first passkey and is opened after it opens no session", async () => { + const stack = stackOf(); + const first = await enrolling(stack, MEMBER); + const late = await linkFor(stack, MEMBER, OWNER); + await firstPasskeyAdded(stack.env, first.cookie); + expect(await linkSpent(stack.env, late)).toMatchObject({ status: 403, cookie: "" }); + expect( + stack.db.prepare("select count(*) as n from browser_sessions where ended_at is null").get(), + ).toEqual({ n: 1 }); +}); + +test.for(["one after the other", "at once"])( + "of two sessions that opened the first passkey's page, one adds a passkey: %s", + async (when) => { + const stack = stackOf(); + const sessions = [await enrolling(stack, OWNER), await enrolling(stack, OWNER)]; + const forms = await Promise.all(sessions.map(({ cookie }) => formOf(stack.env, cookie))); + const add = (n: number) => + firstPasskeyAdded(stack.env, sessions[n]!.cookie, { challenge: forms[n]!.challenge! }); + const answers = + when === "at once" ? await Promise.all([add(0), add(1)]) : [await add(0), await add(1)]; + expect({ + added: answers.filter(({ status }) => status === 200).length, + passkeys: passkeysOf(stack, OWNER), + }).toEqual({ added: 1, passkeys: 1 }); + }, +); + +test("an owner's link signs in no person who is an owner by the time it is opened, or by the time the passkey is recorded", async () => { + const stack = stackOf(); + const promoted = stack.envOf({ ownerEmails: [OWNER, MEMBER] }); + // opened after the deploy that made the member an owner + expect(await linkSpent(promoted, await linkFor(stack, MEMBER, OWNER))).toMatchObject({ + status: 403, + cookie: "", + }); + // opened before it: the session is over once the person is an owner + const before = await linkSpent(stack.env, await linkFor(stack, MEMBER, OWNER)); + const form = await formOf(stack.env, before.cookie); + expect(form).toMatchObject({ challenge: expect.any(String) }); + expect(await formOf(promoted, before.cookie)).toMatchObject({ challenge: null }); + expect( + await firstPasskeyAdded(promoted, before.cookie, { challenge: form.challenge! }), + ).toMatchObject({ status: 403 }); + expect(passkeysOf(stack, MEMBER)).toBe(0); +}); + +test("a link that the recovery command made signs in an owner with no passkey left, and no owner who has one", async () => { + const stack = stackOf(); + await passkeyAdded(stack, OWNER); + // the owner still has the passkey: the link opens nothing + expect(await linkSpent(stack.env, await linkFor(stack, OWNER, RECOVERY_COMMAND))).toMatchObject({ + status: 403, + }); + stack.db.exec("update keys set revoked_at = 1"); + const { cookie, status } = await linkSpent( + stack.env, + await linkFor(stack, OWNER, RECOVERY_COMMAND), + ); + expect(status).toBe(200); + expect(await firstPasskeyAdded(stack.env, cookie)).toMatchObject({ status: 200 }); + // a link is spent once + const ticket = await linkFor(stack, OWNER, RECOVERY_COMMAND); + stack.db.exec("update keys set revoked_at = 1"); + expect(await linkSpent(stack.env, ticket)).toMatchObject({ status: 200 }); + expect(await linkSpent(stack.env, ticket)).toMatchObject({ status: 403 }); +}); + +// From the `next` that the first passkey's page was given to the address the page's script +// assigns once the passkey is added. A target is the whole `https:` URL that was checked, on a +// hostname of the mind, or the mind's front page. +test.for([ + { + next: "https://shop.second.example/cart?item=1", + ends: "https://shop.second.example/cart?item=1", + }, + { next: "/keys/enrol?actor=a", ends: "https://iterate.example.com/keys/enrol?actor=a" }, + { + next: "/oauth2/auth?client_id=c&state=a+b", + ends: "https://iterate.example.com/oauth2/auth?client_id=c&state=a+b", + }, + // a network-path reference names a host: it is that host, or nothing + { next: "//shop.second.example/a", ends: "https://shop.second.example/a" }, + { next: "//evil.example/", ends: "https://onboarding.example.com/" }, + // a path that begins with two slashes stays a path of this origin, written whole + { + next: "https://iterate.example.com//evil.example/a", + ends: "https://iterate.example.com//evil.example/a", + }, + { next: "/\\evil.example/", ends: "https://onboarding.example.com/" }, + { next: "https://evil.example/", ends: "https://onboarding.example.com/" }, + { next: "http://shop.second.example/", ends: "https://onboarding.example.com/" }, + { next: "blob:https://iterate.example.com/a-page", ends: "https://onboarding.example.com/" }, + { next: "javascript:alert(1)", ends: "https://onboarding.example.com/" }, + { next: "/", ends: "https://onboarding.example.com/" }, + { next: "https://iterate.example.com/", ends: "https://onboarding.example.com/" }, + { next: "", ends: "https://onboarding.example.com/" }, +])( + "after the first passkey, the browser that came with next $next ends at $ends", + async ({ next, ends }) => { + const stack = stackOf(); + const { cookie } = await enrolling(stack, MEMBER); + // the form keeps the address that was checked, and none for a `next` that is not the mind's + const form = await formOf(stack.env, cookie, `/keys/first?${new URLSearchParams({ next })}`); + expect(form).toMatchObject({ next: ends === "https://onboarding.example.com/" ? "" : ends }); + const added = await firstPasskeyAdded(stack.env, cookie, { + challenge: form.challenge!, + next: form.next, + }); + expect(added).toMatchObject({ next: ends }); + }, +); + +test("a passkey's name is the person's to give: a default with none, and a refusal for one that is no short text", async () => { + const names = async (label: unknown) => { + const stack = stackOf(); + const { cookie } = await enrolling(stack, OWNER); + const { status } = await firstPasskeyAdded(stack.env, cookie, { label }); + return { + status, + kept: stack.db + .prepare("select label from keys") + .all() + .map((row) => row.label), + }; + }; + const byDay = expect.stringMatching(/^Passkey, \d{4}-\d{2}-\d{2}$/); + expect(await names(undefined)).toEqual({ status: 200, kept: [byDay] }); + expect(await names(" ")).toEqual({ status: 200, kept: [byDay] }); + expect(await names(" A phone ")).toEqual({ status: 200, kept: ["A phone"] }); + expect(await names("n".repeat(101))).toEqual({ status: 400, kept: [] }); + expect(await names(7)).toEqual({ status: 400, kept: [] }); +}); + +// AN APP NAMES HOW ITS PEOPLE SIGN IN (iterate/app-description `signIn`), and the issuer holds +// every code for the app's host to the list, whichever client asks for it. +test("a mailed code's session at an app that names the passkey alone goes to that app's sign-in page, from the app's own page and from an MCP client alike; a passkey's session passes at every app", async () => { + const stack = stackOf(); + const ledger = "https://ledger.example.com"; + const letters = "https://letters.second.example"; + stack.described.set("ledger.example.com", { name: "Ledger", signIn: ["passkey"] }); + stack.described.set("letters.second.example", { name: "Letters", signIn: ["email"] }); + const guest = (await codeRedeemed(stack, GUEST)).cookie; + const member = await passkeyAdded(stack, MEMBER); + const mcp = await oauthHelpers(stack.env).createClient({ + clientName: "An MCP client", + redirectUris: [MCP_CALLBACK], + tokenEndpointAuthMethod: "none", + grantTypes: ["authorization_code", "refresh_token"], + responseTypes: ["code"], + }); + const ends = async (cookie: string, host: string) => ({ + own: (await authorized(stack.env, cookie, host)).ends, + mcp: (await authorized(stack.env, cookie, host, mcp.clientId)).ends, + }); + expect({ + // the app names the passkey alone: mail does not sign its people in + guestAtLedger: await ends(guest, ledger), + memberAtLedger: await ends(member.cookie, ledger), + // the app names the mailed code alone: a passkey's session counts all the same + guestAtLetters: await ends(guest, letters), + memberAtLetters: await ends(member.cookie, letters), + // an app that says nothing takes both + guestAtAnother: await ends(guest, "https://another.example.com"), + }).toEqual({ + guestAtLedger: { own: "the sign-in page", mcp: "the sign-in page" }, + memberAtLedger: { own: "a code for the host", mcp: "the consent page" }, + guestAtLetters: { own: "a code for the host", mcp: "the consent page" }, + memberAtLetters: { own: "a code for the host", mcp: "the consent page" }, + guestAtAnother: { own: "a code for the host", mcp: "the consent page" }, + }); + + // The sign-in page that the person is sent to is the app's: it offers the passkey, and no + // mailed code. An MCP client's page is the mind's own, with the app's methods. + const refused = await authorized(stack.env, guest, ledger); + const page = await (await ask(stack.env, refused.location.slice(ISSUER.length))).text(); + expect(page).toContain( + `<h1>Sign in to Ledger</h1><p class="muted center">ledger.example.com</p>`, + ); + expect(page).toContain(`<button type="submit">Sign in with a passkey</button>`); + expect(page).not.toMatch(/sign-in\/email|type="email"/); + const fromMcp = await authorized(stack.env, guest, ledger, mcp.clientId); + const mcpPage = await (await ask(stack.env, fromMcp.location.slice(ISSUER.length))).text(); + expect(mcpPage).toContain("<h1>Sign in to iterate.example.com</h1>"); + expect(mcpPage).not.toMatch(/sign-in\/email|type="email"/); + + // no code is mailed in the name of an app that does not name "email": the address page and + // the request for a code both lead back to the app's sign-in page + const next = new URL(refused.location).searchParams.get("next")!; + const before = stack.mailed.length; + for (const answer of [ + await ask(stack.env, `/sign-in/email?${new URLSearchParams({ next })}`), + await ask(stack.env, "/sign-in/email", { + method: "POST", + body: new URLSearchParams({ email: GUEST, next: `${ISSUER}${next}` }), + }), + ]) { + expect(answer).toMatchObject({ status: 303 }); + expect(answer.headers.get("location")).toMatch(/^\/sign-in\?next=/); + } + expect(stack.mailed).toHaveLength(before); +}); + +test("a consent that a session of another method approves gives no code for an app that does not take that method", async () => { + const stack = stackOf(); + const letters = "https://letters.second.example"; + const guest = (await codeRedeemed(stack, GUEST)).cookie; + const mcp = await oauthHelpers(stack.env).createClient({ + clientName: "An MCP client", + redirectUris: [MCP_CALLBACK], + tokenEndpointAuthMethod: "none", + grantTypes: ["authorization_code", "refresh_token"], + responseTypes: ["code"], + }); + // the app took the mailed code when the consent page was shown, and names the passkey alone now + const consent = await authorized(stack.env, guest, letters, mcp.clientId); + expect(consent).toMatchObject({ ends: "the consent page" }); + stack.described.set("letters.second.example", { name: "Letters", signIn: ["passkey"] }); + stack.db.exec("delete from admissions"); + // the description is asked for again + await stack.env.OAUTH_KV.delete("iterate-app-description:letters.second.example"); + const approved = await ask(stack.env, "/oauth2/auth", { + method: "POST", + cookie: [guest, consent.cookie].join("; "), + body: new URLSearchParams({ handle: consent.handle, decision: "allow" }), + }); + expect(approved).toMatchObject({ status: 403 }); + expect(approved.headers.get("location")).toBeNull(); +}); + +// THE SIGN-IN PAGE OPENS ON THE FIRST METHOD that the app names, and offers the others below. +test.for([ + { + name: "the mailed code first, then the passkey: the default of an app for anyone", + says: { name: "Guestbook" }, + opensOn: "email", + below: "passkey", + }, + { + // a passkey counts at every app, so it is offered below the form whatever the app names + name: "the mailed code alone", + says: { name: "Guestbook", signIn: ["email"] }, + opensOn: "email", + below: "passkey", + }, + { + name: "the passkey alone: the default of an app for members", + says: { name: "Guestbook", for: "members" }, + opensOn: "passkey", + below: null, + }, + { + name: "the passkey alone, as the app names it", + says: { name: "Guestbook", signIn: ["passkey"] }, + opensOn: "passkey", + below: null, + }, + { + name: "the passkey first, then the mailed code, as the app names them", + says: { name: "Guestbook", signIn: ["passkey", "email"] }, + opensOn: "passkey", + below: "email", + }, + { + // the description is taken as it is written: the app's own code decides + name: "an app for members that names the mailed code first", + says: { name: "Guestbook", for: "members", signIn: ["email", "passkey"] }, + opensOn: "email", + below: "passkey", + }, +])("an app's sign-in page, $name", async ({ says, opensOn, below }) => { + const stack = stackOf(); + // a mind where somebody has a passkey: with none yet, an app for members opens on the first one + stack.db.exec("insert into users (id, email) values ('user_owner', 'owner@example.net')"); + stack.db.exec( + `insert into keys (id, user_id, public_key, format, label, added_via, added_by, added_at) + values ('a-passkey', 'user_owner', 'a-public-key', 'webauthn', 'A phone', 'keys-page', 'user_owner', 0)`, + ); + const host = "https://guestbook.second.example"; + stack.described.set("guestbook.second.example", says); + const { location } = await authorized(stack.env, "", host); + const html = await (await ask(stack.env, location.slice(ISSUER.length))).text(); + // the app's name, and under it the host that the person came from + expect(html).toContain( + `<h1>Sign in to Guestbook</h1><p class="muted center">guestbook.second.example</p>`, + ); + const emailForm = + /<form method="post" action="\/sign-in\/email" class="stack">[^]*<input type="email" name="email"/; + const passkeyMain = `<button type="submit">Sign in with a passkey</button>`; + const passkeyBelow = `<p class="or">or</p>`; + const emailBelow = `<button type="submit" class="secondary">Sign in with your email address</button>`; + expect({ + emailForm: emailForm.test(html), + // the passkey's prompt as the page opens + asksForPasskeyAtOpen: html.includes("\nsignIn(false);"), + passkeyMain: html.includes(passkeyMain), + passkeyBelow: html.includes(passkeyBelow), + emailBelow: html.includes(emailBelow), + }).toEqual({ + emailForm: opensOn === "email", + asksForPasskeyAtOpen: opensOn === "passkey", + passkeyMain: opensOn === "passkey", + passkeyBelow: opensOn === "email" && below === "passkey", + emailBelow: opensOn === "passkey" && below === "email", + }); +}); + +// THE MAIL COMES FROM WHERE THE PERSON IS: the zone of the app's hostname, under the app's name. +test("the code of an app in the mind's second zone is mailed from that zone, with the app's name as the sender's name and in the subject; the control plane's own comes from the zone of the control-plane hostname", async () => { + const stack = stackOf(); + const host = "https://guestbook.second.example"; + stack.described.set("guestbook.second.example", { name: "Guestbook", icon: "/icon.svg" }); + const { location } = await authorized(stack.env, "", host); + const next = `${ISSUER}${new URL(location).searchParams.get("next")!}`; + await codeMailed(stack, GUEST, next); + expect(stack.mailed.at(-1)).toMatchObject({ + from: { email: "sign-in@second.example", name: "Guestbook" }, + to: [GUEST], + subject: "Your sign-in code for Guestbook", + text: expect.stringContaining("to sign in to Guestbook (guestbook.second.example)."), + }); + // an app that says nothing is named by its hostname, from its hostname's zone + const plain = await authorized(stack.env, "", "https://plain.second.example"); + await codeMailed(stack, GUEST, `${ISSUER}${new URL(plain.location).searchParams.get("next")!}`); + expect(stack.mailed.at(-1)).toMatchObject({ + from: { email: "sign-in@second.example", name: "plain.second.example" }, + subject: "Your sign-in code for plain.second.example", + text: expect.stringContaining("to sign in to plain.second.example."), + }); + // An outside client's sign-in to the app (an MCP client's) is no page of the app's: the mail is + // the mind's own, from the zone of the control-plane hostname. + const mcp = await oauthHelpers(stack.env).createClient({ + clientName: "An MCP client", + redirectUris: [MCP_CALLBACK], + tokenEndpointAuthMethod: "none", + grantTypes: ["authorization_code", "refresh_token"], + responseTypes: ["code"], + }); + const fromMcp = await authorized(stack.env, "", host, mcp.clientId); + await codeMailed(stack, GUEST, `${ISSUER}${new URL(fromMcp.location).searchParams.get("next")!}`); + expect(stack.mailed.at(-1)).toMatchObject({ + from: { email: "sign-in@example.com", name: "iterate.example.com" }, + subject: "Your sign-in code for iterate.example.com", + }); +}); + +/** A mind with two zones, one owner and one member whom the owner added, and the web that its + * issuer reads for this test. `described` is what the mind's apps say of themselves, by + * hostname, as each answers at `/.well-known/iterate-app` (iterate/app-description). A hostname + * that is not there says nothing, as an app with no description: it is for anyone, and its + * people sign in by a mailed code first. Vitest restores the web after the test. */ +function stackOf() { + const stack = sqliteStack({ zones: ZONES, ownerEmails: [OWNER] }); + stack.db + .prepare("insert into members (email, added_by, added_at) values (?, ?, 0)") + .run(MEMBER, OWNER); + const described = new Map<string, object>(); + vi.spyOn(globalThis, "fetch").mockImplementation(async (input) => { + const said = described.get(new URL(String(input)).hostname); + return said ? Response.json(said) : new Response("Not found\n", { status: 404 }); + }); + return { ...stack, described }; +} +type Stack = ReturnType<typeof stackOf>; + +const ask = (env: Env, path: string, init: RequestInit & { cookie?: string } = {}) => + authResponse( + new Request(`${ISSUER}${path}`, { + ...init, + headers: { origin: ISSUER, cookie: init.cookie || "", ...init.headers }, + }), + env, + // the cast: the pages hand the runtime nothing to keep alive in these flows + {} as ExecutionContext, + ); + +const cookieOf = (answer: Response, name: string) => + answer.headers + .getSetCookie() + .map((cookie) => cookie.split(";")[0]!) + .find((cookie) => cookie.startsWith(`${name}=`) && !cookie.endsWith("=")) || ""; + +/** THE `next` OF AN APP'S OWN SIGN-IN: the authorization request that a page of the app's host + * makes, as an address of the issuer. A sign-in page mails a code only for such a request, of + * an app that names "email". */ +async function appSignIn(env: Env, host = GUESTBOOK) { + const { location } = await authorized(env, "", host); + return `${ISSUER}${new URL(location).searchParams.get("next")!}`; +} + +/** A code asked for `email` on the mailed code's page, as it left in the mail. `next`: the + * sign-in that the code is for; with none, the guestbook's own. */ +async function codeMailed(stack: Stack, email: string, next?: string) { + // a second code for one mailbox waits a minute: the earlier ones are an hour old here + stack.db.exec("update email_challenges set created_at = created_at - 3600000"); + const answer = await ask(stack.env, "/sign-in/email", { + method: "POST", + body: new URLSearchParams({ email, next: next || (await appSignIn(stack.env)) }), + }); + expect(answer).toMatchObject({ status: 303 }); + const mail = stack.mailed.at(-1)!; + expect(mail).toMatchObject({ to: [email] }); + return { cookie: cookieOf(answer, "__Host-iterate-auth-code"), code: mail.text.slice(0, 6) }; +} + +/** The answer to a code typed on its page: where it sends the browser, and the session's cookie + * when it opened one. */ +async function redeem(env: Env, { cookie, code }: { cookie: string; code: string }) { + const answer = await ask(env, "/sign-in/email/code", { + method: "POST", + cookie, + body: new URLSearchParams({ code }), + }); + return { + status: answer.status, + location: answer.headers.get("location") || "", + cookie: cookieOf(answer, "__Host-iterate-auth-session"), + // the page writes an apostrophe as a numbered entity + text: (await answer.text()).replaceAll(/&#(\d+);/g, (_all, code) => + String.fromCharCode(Number(code)), + ), + }; +} + +const codeRedeemed = async (stack: Stack, email: string, next?: string) => + redeem(stack.env, await codeMailed(stack, email, next)); + +/** A SESSION THAT MAY ADD THE FIRST PASSKEY, opened by a link: an owner's link for an added + * member, and the recovery command's for an owner. */ +const enrolling = async (stack: Stack, email: string) => + linkSpent(stack.env, await linkFor(stack, email, email === OWNER ? RECOVERY_COMMAND : OWNER)); + +/** The member of `email` with a first passkey, added through such a session: the passkey's own + * session. */ +const passkeyAdded = async (stack: Stack, email: string) => + firstPasskeyAdded(stack.env, (await enrolling(stack, email)).cookie); + +/** The browser of `cookie` signed in to an app of the mind at `host`: the code goes to the host's + * own callback, with no consent, and is exchanged for the host's token. */ +async function hostSignedIn(env: Env, cookie: string, host: string) { + const verifier = generateRandomCodeVerifier(); + const redirectUri = hostCallbackOf(host); + const clientId = await hostClientOf(env, new URL(host).host); + const signedIn = await ask( + env, + `/oauth2/auth?${new URLSearchParams({ + response_type: "code", + code_challenge: await calculatePKCECodeChallenge(verifier), + code_challenge_method: "S256", + state: "a-state", + client_id: clientId, + redirect_uri: redirectUri, + resource: host, + scope: "identity", + })}`, + { cookie }, + ); + const answer = await ask(env, "/oauth2/token", { + method: "POST", + body: new URLSearchParams({ + grant_type: "authorization_code", + code: new URL(signedIn.headers.get("location")!).searchParams.get("code")!, + redirect_uri: redirectUri, + client_id: clientId, + code_verifier: verifier, + resource: host, + }), + }); + expect(answer).toMatchObject({ status: 200 }); +} + +/** Where an outside client's code goes: an MCP client on the person's own computer. */ +const MCP_CALLBACK = "http://127.0.0.1:4100/callback"; + +/** WHERE AN AUTHORIZATION FOR AN APP'S HOST ENDS for the browser of `cookie` ("": signed out). + * With no `client` it is the host's own sign-in, whose code goes to the host's own callback with + * no consent; with one, that client asks for the app's MCP server, as an MCP client does. */ +async function authorized(env: Env, cookie: string, host: string, client?: string) { + const redirectUri = client ? MCP_CALLBACK : hostCallbackOf(host); + const answer = await ask( + env, + `/oauth2/auth?${new URLSearchParams({ + response_type: "code", + code_challenge: await calculatePKCECodeChallenge(generateRandomCodeVerifier()), + code_challenge_method: "S256", + state: "a-state", + client_id: client || (await hostClientOf(env, new URL(host).host)), + redirect_uri: redirectUri, + resource: client ? `${host}/mcp` : host, + scope: "identity", + })}`, + { cookie }, + ); + const location = answer.headers.get("location") || ""; + const html = location ? "" : await answer.text(); + return { + ends: location.startsWith(`${ISSUER}/sign-in?`) + ? "the sign-in page" + : location.startsWith(`${redirectUri}?code=`) + ? "a code for the host" + : html.includes(`wants to use ${new URL(host).host} as you`) + ? "the consent page" + : `${answer.status} ${location}`, + location, + // a consent's handle and the cookie that binds it, for the approval + handle: /name="handle" value="([^"]+)"/.exec(html)?.[1] || "", + cookie: answer.headers + .getSetCookie() + .map((set) => set.split(";")[0]!) + .join("; "), + }; +} + +/** The stack's owner with a P-256 key of their own on /keys, and a statement that the key signs + * as the body of a request. */ +async function ownerWithKey(stack: Stack) { + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + const publicKey = base64url( + new Uint8Array((await crypto.subtle.exportKey("spki", pair.publicKey)) as ArrayBuffer), + ); + const key = await keyIdOf(publicKey); + const user = await userOf(stack.env.DB, OWNER); + stack.db + .prepare( + `insert into keys (id, user_id, public_key, format, label, added_via, added_by, added_at) + values (?, ?, ?, 'p256', 'a key', 'keys-page', ?, 0)`, + ) + .run(key, user.id, publicKey, user.id); + return { + signed: async (type: string, payload: Record<string, unknown>) => { + const now = Date.now(); + const statement = statementText({ + mind: "iterate.example.com", + path: "/", + type, + payload, + at: now, + expires: now + 60_000, + }); + return JSON.stringify(await signedP256(statement, pair.privateKey, key)); + }, + }; +} + +/** A sign-in link's ticket for `email`, as `madeBy` wrote its row: an owner's address, or the + * recovery command. */ +async function linkFor(stack: Stack, email: string, madeBy: string) { + const ticket = `ticket-${crypto.randomUUID()}`; + stack.db + .prepare("insert into member_tickets (hash, email, made_by, expires_at) values (?, ?, ?, ?)") + .run(await sha256Hex(ticket), email, madeBy, Date.now() + 3_600_000); + return ticket; +} + +async function linkSpent(env: Env, ticket: string) { + const answer = await ask(env, "/keys/first/link", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ticket }), + }); + return { status: answer.status, cookie: cookieOf(answer, "__Host-iterate-auth-session") }; +} + +/** The first passkey's page as this browser gets it: its form's challenge and `next`, or a null + * challenge for a browser that has no session for it. */ +async function formOf(env: Env, cookie: string, path = "/keys/first") { + const html = await (await ask(env, path, { cookie })).text(); + const attribute = (name: string) => + html + .match(new RegExp(`data-${name}="([^"]*)"`))?.[1] + ?.replace(/&#(\d+);/g, (_all, code) => String.fromCharCode(Number(code))); + return { + heading: html.match(/<h1>([^<]*)<\/h1>/)?.[1], + html, + challenge: attribute("challenge") ?? null, + next: attribute("next") ?? "", + }; +} + +/** The answer to a new P-256 passkey posted as the page's script posts it. `challenge`: one read + * from the page before; else the page is asked for one now. */ +async function firstPasskeyAdded( + env: Env, + cookie: string, + sent: { challenge?: string; next?: string; label?: unknown } = {}, +) { + const challenge = sent.challenge || (await formOf(env, cookie)).challenge || "no-challenge"; + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + const spki = new Uint8Array( + (await crypto.subtle.exportKey("spki", pair.publicKey)) as ArrayBuffer, + ); + const clientData = { type: "webauthn.create", origin: ISSUER, challenge }; + const answer = await ask(env, "/keys/first", { + method: "POST", + cookie, + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + label: sent.label, + next: sent.next, + publicKey: base64url(spki), + credentialId: base64url(crypto.getRandomValues(new Uint8Array(16))), + clientDataJSON: base64url(new TextEncoder().encode(JSON.stringify(clientData))), + }), + }); + const body = (await answer.json()) as { next?: string }; + return { + status: answer.status, + next: body.next, + cookie: cookieOf(answer, "__Host-iterate-auth-session"), + facts: answer.headers.has(FACTS_HEADER) ? decodeFacts(answer.headers.get(FACTS_HEADER)!) : [], + }; +} + +const sessionsEndedIn = (facts: ReturnType<typeof decodeFacts>) => + facts.flatMap(({ events }) => + events.filter(({ type }) => type === "events.iterate.com/account/session-ended"), + ); + +const statusOf = async (env: Env, path: string, cookie: string) => + (await ask(env, path, { cookie })).status; + +const locationOf = async (env: Env, path: string, cookie: string) => + (await ask(env, path, { cookie })).headers.get("location"); + +/** Who the stack's other Workers are told this browser is (./rpc.ts `browserSession`). */ +function personOf(env: Env, cookie: string) { + // the cast: the entrypoint's `env` is the runtime's to set, and this call reads no `ctx` + const auth = Object.assign(new (Auth as unknown as new () => Auth)(), { env }); + return auth.browserSession(cookie); +} + +const passkeysOf = (stack: Stack, email: string) => + stack.db + .prepare( + `select count(*) as n from keys k join users u on u.id = k.user_id + where u.email = ? and k.format = 'webauthn' and k.revoked_at is null`, + ) + .get(email)!.n; + +/** A passkey row of `email` as the old stack wrote it before ../migrations/0016: `outsider` 0. */ +async function passkeyOfRow(stack: Stack, email: string) { + const pair = (await crypto.subtle.generateKey({ name: "ECDSA", namedCurve: "P-256" }, true, [ + "sign", + "verify", + ])) as CryptoKeyPair; + const publicKey = base64url( + new Uint8Array((await crypto.subtle.exportKey("spki", pair.publicKey)) as ArrayBuffer), + ); + const user = await userOf(stack.env.DB, email); + const id = await keyIdOf(publicKey); + const credentialId = `credential-of-${email}`; + stack.db + .prepare( + `insert into keys (id, user_id, public_key, format, credential_id, label, added_via, added_by, added_at) + values (?, ?, ?, 'webauthn', ?, 'a passkey', 'keys-page', ?, 0)`, + ) + .run(id, user.id, publicKey, credentialId, user.id); + return { id, credentialId, privateKey: pair.privateKey }; +} + +/** The passkey sign-in of ./passkey-sign-in.ts, as a browser's authenticator answers it. */ +async function passkeySignedIn( + env: Env, + passkey: { credentialId: string; privateKey: CryptoKey }, + next?: string, +) { + const asked = await ask(env, "/sign-in/passkey/challenge", { method: "POST" }); + const { statement } = (await asked.json()) as { statement: string }; + const encoder = new TextEncoder(); + const clientDataJSON = encoder.encode( + JSON.stringify({ + type: "webauthn.get", + challenge: await challengeOf(statement), + origin: ISSUER, + }), + ); + const rpIdHash = new Uint8Array( + await crypto.subtle.digest("SHA-256", encoder.encode(new URL(ISSUER).hostname)), + ); + // user present and user verified + const authenticatorData = new Uint8Array([...rpIdHash, 0x05, 0, 0, 0, 1]); + const clientDataHash = new Uint8Array(await crypto.subtle.digest("SHA-256", clientDataJSON)); + const raw = new Uint8Array( + await crypto.subtle.sign( + { name: "ECDSA", hash: "SHA-256" }, + passkey.privateKey, + new Uint8Array([...authenticatorData, ...clientDataHash]), + ), + ); + const integer = (half: Uint8Array) => { + let at = 0; + while (at < half.length - 1 && half[at] === 0) at++; + const bytes = half.subarray(at); + const positive = bytes[0]! & 0x80 ? [0, ...bytes] : [...bytes]; + return [0x02, positive.length, ...positive]; + }; + const body = [...integer(raw.subarray(0, 32)), ...integer(raw.subarray(32))]; + const answer = await ask(env, "/sign-in/passkey", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + statement, + credentialId: passkey.credentialId, + sig: base64url(new Uint8Array([0x30, body.length, ...body])), + authenticatorData: base64url(authenticatorData), + clientDataJSON: base64url(clientDataJSON), + next, + }), + }); + const parsed = (await answer.json()) as { next?: string }; + return { + status: answer.status, + cookie: cookieOf(answer, "__Host-iterate-auth-session"), + next: parsed.next, + }; +}
A core/auth-worker/src/enrolment.ts
@@ -0,0 +1,451 @@ +// enrolment.ts — THE FIRST PASSKEY, and the one session that may add it. Whoever holds a member's +// mailbox must not hold the mind, so exactly three proofs open such a session, each good for that +// one thing, once (`proofRefusal` decides): +// +// Cloudflare Access (./access-sign-in.ts; the proof "cloudflare-access") proves the address of +// an owner who has NEVER had a passkey: a removed passkey counts as had. So +// whoever holds an owner's mailbox gets in only by adding a passkey before +// the owner does, as the mind is made. +// an owner's link (./members.ts `memberLink`; "member-link") opens one for a member who is no +// owner and has no passkey now: a new member, or one whose keys an owner +// removed. +// a recovery link ("recovery-link") is a link that the recovery command made, which whoever +// holds the mind's Cloudflare account runs: for an owner who has no passkey +// left. +// +// THE MIND'S OWN MAILED CODE IS NONE OF THEM (./email-sign-in.ts): it is for the people of the +// mind's apps, who are no members, and opens no way into the mind. +// +// Such a session is a row of `browser_sessions` whose `method` is the proof's (`Proof`), which +// is never a sign-in method (iterate/principal `SignInMethod`). No reader of ./cookies.ts answers +// it, so to every other page and to the stack's other Workers its browser is signed out. It +// reaches this page and the POST that records the first passkey, and sign-out (./sign-in.ts). The +// write that records the passkey holds the same condition as the session's making, in its own +// statement, and ends every such session of the person. +// +// GET /keys/first the form, for a browser with such a session; else the page a link +// opens, which spends the ticket in the link's fragment and loads again +// POST /keys/first records the first passkey, and answers the passkey's own session +// POST /keys/first/link spends a link's ticket +import { base64url, fromBase64url, keyIdOf } from "iterate/signed"; +import { z } from "zod"; +import { AccountFacts } from "./account-facts.ts"; +import { isOwner } from "./config.ts"; +import { cookieClaimsOf, cookieOf, newSessionId, sessionCookie, userAgentOf } from "./cookies.ts"; +import { sha256Hex } from "./device/protocol.ts"; +import { configOf, type Env, explicitFirstPasskeyNext, issuerOf, onboardingOf } from "./env.ts"; +import { outsiderKeysRevoked, outsiderKeysRevokedFacts } from "./keys-pages.ts"; +import { isMember } from "./members.ts"; +import { page, text } from "./pages.ts"; +import { SIGN_HELPERS } from "./signed-change.ts"; +import { stackKeyOf } from "./stack-key.ts"; +import { userOf } from "./users.ts"; + +export const FIRST_PASSKEY_PATH = "/keys/first"; +const LINK_PATH = `${FIRST_PASSKEY_PATH}/link`; + +/** How long such a session lasts, and a link before it is spent. */ +export const ENROLMENT_MS = 24 * 3600_000; + +/** `member_tickets.made_by` of a link that the recovery command made. An owner's link has the + * owner's address there, which is never this word. */ +export const RECOVERY_COMMAND = "recovery-command"; + +/** What proved the address: the session's `method`. */ +const Proof = z.enum(["cloudflare-access", "member-link", "recovery-link"]); +type Proof = z.infer<typeof Proof>; +/** The same, as SQL: the rows of `browser_sessions` that are this module's. A row of another + * method is a passkey's session or a mailed code's (./cookies.ts), and adds no passkey. */ +const PROOF_METHODS = `(${Proof.options.map((proof) => `'${proof}'`).join(", ")})`; + +const CHALLENGE_SECONDS = 5 * 60; +const CHALLENGE_KEY_PREFIX = "iterate-first-passkey-challenge:"; + +/** THE PASSKEY THAT BARS A PROOF, as SQL over the `keys` rows of the user `user` (a column or a + * parameter): for Cloudflare Access any passkey the person ever had, for a link one that is not + * removed. `proof` is the SQL of the session's method. One text, so the session's making and the + * passkey's write hold the same condition, each in its own statement. A passkey that was added + * while its owner was no member is none (../migrations/0016): whoever added it would otherwise + * lock the member out, and the member's first passkey revokes it. */ +const barringPasskey = (user: string, proof: string) => + `select 1 from keys k where k.user_id = ${user} and k.format = 'webauthn' and k.outsider = 0 + and (${proof} = 'cloudflare-access' or k.revoked_at is null)`; + +/** WHO MAY ENROL: why a proof opens no session, in words for the person, or null. The one + * decision for the session's making and for its reading. Each refusal says the one way that is + * left, and never one the server forbids. */ +async function proofRefusal(env: Env, email: string, proof: Proof): Promise<string | null> { + const config = configOf(env); + const mind = config.controlPlaneHostname; + // WHOSE ADDRESS A PROOF IS FOR. The policy of Cloudflare Access names the owners alone, and the + // recovery command is an owner's way back. An owner's link is for an added member: no owner + // makes a way in as another owner. + const owner = isOwner(config, email); + if (owner && proof === "member-link") + return `${email} is an owner of ${mind}. An owner's link signs in no owner.`; + if (!owner && proof === "cloudflare-access") + return `${email} is not an owner of ${mind}, and Cloudflare Access signs in an owner alone. Sign in with your passkey.`; + if (!owner && proof === "recovery-link") + return `${email} is not an owner of ${mind}, and the recovery command's link signs in an owner alone.`; + if (!(await isMember(env, email))) return `${email} is not a member of ${mind}.`; + const passkeys = await passkeysOf(env, email); + if (passkeys === "held") + return `${email} has a passkey for ${mind}, so nothing else signs it in. Sign in with the passkey.`; + if (passkeys === "removed" && proof === "cloudflare-access") + return `${email} had a passkey for ${mind}, so Cloudflare's proof of the address signs it in no more. An owner with no passkey left gets back in by the recovery command, which whoever holds this mind's Cloudflare account runs.`; + return null; +} + +/** THE PASSKEYS OF AN ADDRESS, as a refusal reads them: "none" that the person ever had, one that + * is "held" now, or "removed", each of them. An outsider's passkey counts as none + * (`barringPasskey`). */ +export async function passkeysOf(env: Env, email: string): Promise<"none" | "held" | "removed"> { + const had = await env.DB.prepare( + `select count(*) as ever, count(k.revoked_at) as removed from keys k + where k.format = 'webauthn' and k.outsider = 0 + and k.user_id = (select id from users where email = ?1)`, + ) + .bind(email) + .first<{ ever: number; removed: number }>(); + if (!had?.ever) return "none"; + return had.ever > had.removed ? "held" : "removed"; +} + +/** A NEW SESSION THAT MAY ADD THE FIRST PASSKEY, for the person of `email`, or the refusal's + * words. One statement makes the row only while no passkey bars the proof, so a proof redeemed + * while another browser records the passkey leaves no session. */ +export async function enrolmentCookie( + env: Env, + request: Request, + email: string, + proof: Proof, +): Promise<{ setCookie: string; facts: AccountFacts } | { refused: string }> { + const refused = await proofRefusal(env, email, proof); + if (refused) return { refused }; + const user = await userOf(env.DB, email); + const session = newSessionId(); + const now = Date.now(); + const made = await env.DB.prepare( + `insert into browser_sessions + (id, user_id, method, key_id, user_agent, created_at, last_seen_at, expires_at) + select ?1, ?2, ?3, null, ?4, ?5, ?5, ?6 + where not exists (${barringPasskey("?2", "?3")}) + returning id`, + ) + .bind(session, user.id, proof, userAgentOf(request), now, now + ENROLMENT_MS) + .first(); + // a passkey was recorded since the check above: the words for it are that check's + if (!made) + return { refused: (await proofRefusal(env, email, proof)) || "Sign in with the passkey." }; + console.info({ event: "auth.signed-in", method: proof, userId: user.id }); + const facts = new AccountFacts(); + facts.add(user.id, { + type: "events.iterate.com/account/signed-in", + payload: { method: proof, session, at: now }, + }); + return { setCookie: await cookieOf(env, user, session, ENROLMENT_MS / 1000), facts }; +} + +/** THE BROWSER'S SESSION THAT MAY ADD THE FIRST PASSKEY, or null: its cookie, a row that is not + * ended and not expired, and a person whom its proof would still let enrol now (`proofRefusal`): + * a deploy may have changed who is an owner, and a passkey may have been added since. */ +async function enrolmentOf(env: Env, request: Request) { + const claims = await cookieClaimsOf(env, request); + if (!claims) return null; + const row = await env.DB.prepare( + `select s.method from browser_sessions s + where s.id = ?1 and s.user_id = ?2 and s.method in ${PROOF_METHODS} + and s.ended_at is null and s.expires_at > ?3`, + ) + .bind(claims.session, claims.userId, Date.now()) + .first<{ method: string }>(); + const proof = Proof.safeParse(row?.method); + if (!proof.success || (await proofRefusal(env, claims.email, proof.data))) return null; + return { id: claims.session, userId: claims.userId, email: claims.email }; +} + +export async function firstPasskeyResponse(env: Env, request: Request): Promise<Response | null> { + const url = new URL(request.url); + const get = request.method === "GET" || request.method === "HEAD"; + const post = request.method === "POST"; + if ( + !(url.pathname === FIRST_PASSKEY_PATH && (get || post)) && + !(url.pathname === LINK_PATH && post) + ) + return null; + // the page's own script alone + if (post && request.headers.get("origin") !== issuerOf(env)) + return json({ error: "use this site's own page" }, 403); + if (url.pathname === LINK_PATH) return linkSpent(env, request); + const session = await enrolmentOf(env, request); + if (post) + return session + ? firstPasskeyAdded(env, request, session) + : json({ error: "This sign-in is over. Sign in again." }, 403); + const next = explicitFirstPasskeyNext(url.searchParams.get("next"), env); + return session ? formPage(env, session, next) : linkPage(env, next); +} + +async function formPage(env: Env, session: { userId: string; email: string }, next: string | null) { + const mind = configOf(env).controlPlaneHostname; + const challenge = base64url(crypto.getRandomValues(new Uint8Array(32))); + await env.OAUTH_KV.put(`${CHALLENGE_KEY_PREFIX}${challenge}`, session.userId, { + expirationTtl: CHALLENGE_SECONDS, + }); + // The person came for one thing, so the page is that one thing: that a passkey is required + // (no skip), why, what the browser asks next, and the button. + return page({ + title: `Add your passkey to ${mind}`, + body: `<h1>Add your passkey to ${text(mind)}</h1> + <p>A passkey is required to continue — there is no password or email sign-in, and this step cannot be skipped.</p> + <p class="muted">It is how you sign in here and approve what your agents ask for. Your browser asks for your fingerprint, your face, a PIN or a security key.</p> + <form id="add" class="stack" data-challenge="${text(challenge)}" data-user="${text(session.userId)}" data-email="${text(session.email)}" data-rp="${text(mind)}" data-next="${text(next || "")}"> + <button type="submit">Add a passkey</button> + <details><summary>Name it (optional)</summary><input name="label" maxlength="100" size="28" aria-label="Name" placeholder="such as YubiKey"></details> + <p id="status" class="muted" role="status"></p> + </form>`, + script: `${SIGN_HELPERS}${FORM_SCRIPT}`, + }); +} + +// No credential is excluded: the person has no passkey here that counts, and one that was removed +// may be made again on the device that held it. The answer names where the browser goes on. +const FORM_SCRIPT = ` +const form = document.getElementById("add"); +const status = document.getElementById("status"); +// A link opened in a browser that holds such a session already, perhaps another person's: the +// link's ticket is spent, and the page loads again for the person the link names. +if (location.hash.length > 1) + fetch("${LINK_PATH}", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify({ ticket: location.hash.slice(1) }) }).then((answer) => { + history.replaceState(null, "", location.pathname + location.search); + if (answer.ok) location.reload(); + }); +form.addEventListener("submit", async (event) => { + event.preventDefault(); + const { challenge, user, email, rp, next } = form.dataset; + try { + statusSay(status, "Waiting for your new passkey…"); + // With no name typed the passkey is named after the device, where the browser says which, + // and the day: the press never waits for a name. + const day = new Date().toISOString().slice(0, 10); + const typed = form.label.value.trim(); + const device = navigator.userAgentData && navigator.userAgentData.platform ? navigator.userAgentData.platform + " passkey" : "Passkey"; + const credential = await navigator.credentials.create({ publicKey: { + rp: { id: rp, name: rp }, + // The name is what a password manager lists the passkey under: its name here, this host and + // the day, so that a person's passkeys are told apart there. The address is the displayName. + user: { id: enc.encode(user), name: [typed || device, rp, day].join(" · "), displayName: email }, + challenge: unb64u(challenge), + pubKeyCredParams: [{ type: "public-key", alg: -7 }], + authenticatorSelection: { residentKey: "required", userVerification: "preferred" }, + attestation: "none", + } }); + const body = { label: typed || device + ", " + day, publicKey: b64u(credential.response.getPublicKey()), credentialId: credential.id, clientDataJSON: b64u(credential.response.clientDataJSON), next }; + const response = await fetch("${FIRST_PASSKEY_PATH}", { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) }); + const answer = await response.json(); + if (!response.ok) throw new Error(answer.error); + // said before the next page loads: "Waiting for your new passkey…" would stand there meanwhile + statusSay(status, "Your passkey is added. One moment…"); + location.assign(answer.next); + } catch (error) { + statusFailed(status, error, "The passkey was not added."); + } +});`; + +const FirstPasskey = z.object({ + /** A name is the person's to give or to leave out: with none, the key is named after the day. */ + label: z.string().max(100).optional(), + publicKey: z.string(), + credentialId: z.string(), + clientDataJSON: z.string(), + next: z.string().optional(), +}); +const ClientData = z.object({ type: z.string(), origin: z.string(), challenge: z.string() }); + +async function firstPasskeyAdded( + env: Env, + request: Request, + session: { id: string; userId: string; email: string }, +): Promise<Response> { + const input = FirstPasskey.safeParse(await request.json().catch(() => null)); + const clientData = ClientData.safeParse( + input.success ? clientDataOf(input.data.clientDataJSON) : null, + ); + if (!input.success || !clientData.success) + return json( + { + error: + "Send the passkey's public key, credential id and client data as JSON, and a name of at most 100 characters if you name it.", + }, + 400, + ); + if (clientData.data.type !== "webauthn.create" || clientData.data.origin !== issuerOf(env)) + return json({ error: "This is not a passkey made on this page." }, 403); + const challengeKey = `${CHALLENGE_KEY_PREFIX}${clientData.data.challenge}`; + if ((await env.OAUTH_KV.get(challengeKey)) !== session.userId) + return json({ error: "This page expired. Reload it and try again." }, 403); + await env.OAUTH_KV.delete(challengeKey); + const { publicKey, credentialId } = input.data; + const key = await passkeyIdOf(env, publicKey); + if (!key) return json({ error: "This passkey's key is not a P-256 key." }, 400); + const at = Date.now(); + const label = input.data.label?.trim() || `Passkey, ${new Date(at).toISOString().slice(0, 10)}`; + // One transaction. The passkey is recorded only while this session is live and no passkey bars + // its proof: of two browsers at once, one records a passkey. Then every session of this person + // that may add a first passkey ends, this one and any other browser's. + const [added, ended, revoked] = await env.DB.batch<{ id: string; label: string }>([ + env.DB.prepare( + `insert into keys + (id, user_id, public_key, format, credential_id, label, added_via, added_by, added_at) + select ?1, ?2, ?3, 'webauthn', ?4, ?5, 'keys-page', ?2, ?6 + where exists (select 1 from browser_sessions s + where s.id = ?7 and s.user_id = ?2 and s.method in ${PROOF_METHODS} + and s.ended_at is null and s.expires_at > ?6 + and not exists (${barringPasskey("?2", "s.method")})) + on conflict do nothing`, + ).bind(key, session.userId, publicKey, credentialId, label, at, session.id), + env.DB.prepare( + `update browser_sessions set ended_at = ?2 + where user_id = ?1 and method in ${PROOF_METHODS} and ended_at is null + and exists (select 1 from keys k where k.user_id = ?1 and k.format = 'webauthn' + and k.revoked_at is null and k.outsider = 0) + returning id`, + ).bind(session.userId, at), + // the passkeys from before the address was a member's end with it, in the same transaction + outsiderKeysRevoked(env, session.userId, key, at), + ]); + if (!added?.meta.changes) + return json({ error: "This sign-in is over: you have a passkey now. Sign in with it." }, 409); + const facts = new AccountFacts(); + outsiderKeysRevokedFacts(facts, session.userId, at, revoked?.results || []); + facts.add(session.userId, { + type: "events.iterate.com/account/key-added", + payload: { key, label, format: "webauthn", at }, + idempotencyKey: `account/key-added:${key}`, + }); + for (const { id } of ended?.results || []) + facts.add(session.userId, { + type: "events.iterate.com/account/session-ended", + payload: { session: id, at }, + idempotencyKey: `account/session-ended/${id}`, + }); + // the passkey was made in this browser, so this browser's session is that passkey's now + const user = { id: session.userId, email: session.email }; + const made = await sessionCookie(env, request, user, key); + facts.add(session.userId, { + type: "events.iterate.com/account/signed-in", + payload: { method: "passkey", key, session: made.session, at }, + }); + console.info({ event: "auth.first-passkey-added", userId: session.userId }); + return facts.on( + Response.json( + // where the browser goes on: the `next` the page was given, checked again here, else the + // mind's onboarding wizard + { + key, + label, + next: explicitFirstPasskeyNext(input.data.next || null, env) || onboardingOf(env), + }, + { headers: { "set-cookie": made.setCookie, "cache-control": "no-store" } }, + ), + ); +} + +/** What a browser says of the passkey it made, or null for text that is no base64url of JSON. */ +function clientDataOf(clientDataJSON: string): unknown { + try { + return JSON.parse(new TextDecoder().decode(fromBase64url(clientDataJSON))); + } catch { + return null; + } +} + +/** The id of a P-256 public key that may be a person's passkey, or null: for another kind of key, + * and for the stack's own. */ +async function passkeyIdOf(env: Env, publicKey: string): Promise<string | null> { + try { + await crypto.subtle.importKey( + "spki", + fromBase64url(publicKey), + { name: "ECDSA", namedCurve: "P-256" }, + false, + ["verify"], + ); + } catch { + return null; + } + const key = await keyIdOf(publicKey); + if (key === (await stackKeyOf(env)).key) return null; + return key; +} + +/** A LINK'S TICKET, SPENT BY THIS CALL: an owner's (./members.ts `memberLink`), or the recovery + * command's. It signs in the person it names, once, within its day. */ +async function linkSpent(env: Env, request: Request): Promise<Response> { + const body = z.object({ ticket: z.string() }).safeParse(await request.json().catch(() => null)); + const row = body.success + ? await env.DB.prepare( + `update member_tickets set spent_at = ?2 + where hash = ?1 and spent_at is null and expires_at > ?2 + returning email, made_by as madeBy`, + ) + .bind(await sha256Hex(body.data.ticket), Date.now()) + .first<{ email: string; madeBy: string }>() + : null; + const opened = row + ? await enrolmentCookie( + env, + request, + row.email, + row.madeBy === RECOVERY_COMMAND ? "recovery-link" : "member-link", + ) + : { refused: "no such link, or used before, or over" }; + if ("refused" in opened) { + console.info({ event: "auth.sign-in-link-refused", reason: opened.refused }); + // every refusal alike: which of them it was is said to the log alone + return json({ error: "used before, or over" }, 403); + } + return opened.facts.on(json({}, 200, new Headers({ "set-cookie": opened.setCookie }))); +} + +function linkPage(env: Env, next: string | null) { + const mind = configOf(env).controlPlaneHostname; + const signIn = `/sign-in?${new URLSearchParams({ next: next || onboardingOf(env) })}`; + return page({ + title: `Add your passkey to ${mind}`, + body: `<h1>Add your passkey to ${text(mind)}</h1> + <p id="status" class="muted" role="status">Signing you in…</p> + <div id="over" hidden> + <p>This link was used, or its 24 hours are over.</p> + <p>Ask for a new one. If you have a passkey here, <a href="${text(signIn)}">sign in</a>.</p> + </div>`, + script: LINK_SCRIPT, + }); +} + +// The ticket is in the fragment, which no server and no log sees. It leaves the address bar once +// the Worker answered, so a reload after a failed connection sends it again. Spent, the page +// loads again, as the form. +const LINK_SCRIPT = ` +const ticket = location.hash.slice(1); +const status = document.getElementById("status"); +const answered = (ok) => { + history.replaceState(null, "", location.pathname + location.search); + if (ok) return location.reload(); + status.hidden = true; + document.getElementById("over").hidden = false; +}; +if (!ticket) answered(false); +else fetch("${LINK_PATH}", { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ ticket }), +}).then( + (answer) => answered(answer.ok), + () => { statusRefused(status, "This site could not be reached. Reload the page to try again."); }, +);`; + +function json(body: unknown, status = 200, headers = new Headers()) { + headers.set("cache-control", "no-store"); + return Response.json(body, { status, headers }); +}
A core/auth-worker/src/env.ts
@@ -0,0 +1,62 @@ +// env.ts — THE AUTH WORKER'S BINDINGS, as the stack declares them (core/alchemy), and its config. +// The boundary and the secrets Worker call it; it calls no other Worker. What it reads of the +// world it reads over the public internet: an outside client's document, and the description of +// an app of the mind (./asking-app.ts). +import { controlPlaneOriginOf, zoneOf } from "iterate/mind-config"; +import { authConfigOf } from "./config.ts"; +import { honouredNext } from "./key-rules.ts"; + +// THE BINDINGS are declared on `Cloudflare.Env`, which the OAuth library's types default to, as +// `wrangler types` declares them. `Env` is the same type by name. +declare global { + namespace Cloudflare { + interface Env { + /** JSON: the config that every Worker of the mind gets (iterate/mind-config). */ + ITERATE: string; + /** Generated by the stack and bound as a secret: the config's `signingKey` (./config.ts). + * Never returned or logged. */ + ITERATE__SIGNING_KEY: string; + /** The people (./users.ts): `users` and `identities`, from ../migrations. */ + DB: D1Database; + /** The OAuth library's store: clients, grants, tokens, consent handles. Its name is the one + * the library reads. */ + OAUTH_KV: KVNamespace; + /** Cloudflare Email Sending: how a mailed sign-in code leaves (./email-sign-in.ts). */ + SEND_EMAIL: SendEmail; + } + } +} + +export type Env = Cloudflare.Env; + +/** The Worker's config, which `mindConfigOf` parses once for each `env` object: every request of + * an isolate gets the same one. */ +export const configOf = (env: Env) => authConfigOf(env); + +/** The issuer's origin, `https://<controlPlaneHostname>`, where every page and endpoint of this Worker + * is. The boundary sends it every request there that is not for the API, the MCP server or the + * secret pages. */ +export const issuerOf = (env: Env) => controlPlaneOriginOf(configOf(env)); + +/** The mind's Dash (`https://dash.<zone>/`), where the control-plane root and returning sign-ins + * with no `next` URL go. A control plane at `dash.<zone>` itself falls back to the sessions page + * (./http.ts). */ +export function dashOf(env: Env) { + const config = configOf(env); + return `https://dash.${zoneOf(config, config.controlPlaneHostname)}/`; +} + +/** The mind's onboarding wizard (`https://onboarding.<zone>/`), where a new person continues setup + * after adding their first passkey when no explicit `next` URL was passed. */ +export function onboardingOf(env: Env) { + const config = configOf(env); + return `https://onboarding.${zoneOf(config, config.controlPlaneHostname)}/`; +} + +/** An explicit destination under this mind for first-passkey enrolment, or `null` when `next` is + * missing, invalid, or the bare control-plane root (`/` or `https://<controlPlaneHostname>/`), + * which is a placeholder with no page of its own and should fall back to `onboardingOf(env)`. */ +export function explicitFirstPasskeyNext(raw: string | null, env: Env): string | null { + const honoured = honouredNext(raw, configOf(env)); + return honoured && honoured !== `${issuerOf(env)}/` ? honoured : null; +}
A core/auth-worker/src/guest-sign-in.test.ts
@@ -0,0 +1,693 @@ +// A GUEST (./guest-sign-in.ts says the rule). The tests go through the Worker's own endpoints +// (the OAuth library included) against SQLite in memory, made by the Worker's own migrations, so +// the rows, the bounds and a block are the real statements. What an app says of itself +// (./asking-app.ts) is its kept description, written here as the issuer keeps one. The guard is +// tested in core/lib/src/sdk/auth.test.ts, and the stamp in core/boundary-worker/src/stamp.test.ts. +import { decodeFacts, FACTS_HEADER } from "iterate/facts"; +import { mindApiUrlOf, mindMcpUrlOf } from "iterate/mind-api"; +import type { SignInMethod } from "iterate/principal"; +import { calculatePKCECodeChallenge, generateRandomCodeVerifier } from "oauth4webapi"; +import { expect, test, vi } from "vitest"; +import { z } from "zod"; +import { guestOf, sessionCookie, sessionOf } from "./cookies.ts"; +import type { Env } from "./env.ts"; +import { authResponse } from "./http.ts"; +import { isMember } from "./members.ts"; +import { grantLifetimeOf, hostCallbackOf, hostClientOf, tokenIdentity } from "./oauth.ts"; +import { sqliteStack } from "./test-support.ts"; +import { userOf } from "./users.ts"; +import { whoIs } from "./who-is.ts"; + +const DOMAIN = "example.com"; +const MIND = `iterate.${DOMAIN}`; +const ISSUER = `https://${MIND}`; +const MEET = `https://meet.${DOMAIN}`; +const OTHER = `https://guestbook.${DOMAIN}`; +// the one owner of test-support.ts' mind +const OWNER = "owner@example.net"; +const FORM = `${ISSUER}/sign-in/guest`; +const ctx = { waitUntil() {}, passThroughOnException() {} } as unknown as ExecutionContext; + +test("an app that names no guests has no form, and its sign-in shows no guest's way", async () => { + const { env, people } = stackOf(); + for (const ways of ["email", "passkey email", ""]) { + const app = await hostSignInOf(env, OTHER, ways); + for (const method of ["GET", "POST"]) + expect( + await authResponse(new Request(`${FORM}?next=${app.next}`, { method }), env, ctx), + ways, + ).toMatchObject({ status: method === "GET" ? 404 : 403 }); + const signIn = await authResponse(new Request(`${ISSUER}/sign-in?next=${app.next}`), env, ctx); + expect(await signIn.text()).not.toContain("as a guest"); + } + expect(people()).toEqual([]); +}); + +test("the form is for a hostname's own sign-in that names guests, and a fetch of it makes nobody", async () => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest passkey"); + const page = await authResponse(new Request(`${FORM}?next=${meet.next}`), env, ctx); + const html = await page.text(); + expect([page.status, html]).toEqual([200, expect.stringContaining('name="name"')]); + expect(html).toContain("<h1>Join meet.example.com</h1>"); + expect(Object.fromEntries(page.headers)).toMatchObject({ + "x-robots-tag": "noindex, nofollow", + "referrer-policy": "same-origin", + "cache-control": "no-store", + }); + expect(page.headers.get("set-cookie")).not.toMatch(/guest-session/); + + const notForGuests = await hostSignInOf(env, OTHER, "email"); + const outsideClient = await hostSignInOf(env, MEET, "guest", { + redirect_uri: "https://evil.test/callback", + }); + for (const next of [ + "/", + "/members", + "https://evil.test/", + notForGuests.next, + // an app that names no ways takes no guest + (await hostSignInOf(env, OTHER, "")).next, + outsideClient.next, + ]) + expect( + await authResponse(new Request(`${FORM}?next=${encodeURIComponent(next)}`), env, ctx), + ).toMatchObject({ status: 404 }); + expect(people()).toEqual([]); +}); + +test.for([ + { name: "another origin's page", change: { origin: "https://meet.example.com" }, status: 403 }, + { name: "no Origin at all", change: { origin: null }, status: 403 }, + { name: "a browser that was not shown the form", change: { cookie: "" }, status: 400 }, + { name: "another state than the form's", change: { state: "guessed" }, status: 400 }, + { name: "no name", change: { name: "" }, status: 400 }, + { name: "a name of marks and space alone", change: { name: " \u200B\u202E\n" }, status: 400 }, + { name: "a form past its size", change: { length: "5000" }, status: 413 }, +])("the form's answer makes nobody: $name \u2192 $status", async ({ change, status }) => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const shown = await formOf(env, meet.next); + const answer = await posted(env, { ...shown, name: "Bob", ...change }); + expect(answer).toMatchObject({ status }); + expect(answer.headers.get("set-cookie") || "").not.toMatch(/guest-session=[^;]/); + expect(people()).toEqual([]); +}); + +test("a browser that is shown the form twice answers either page: a second tab does not end the first", async () => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const first = await formOf(env, meet.next); + const again = await authResponse( + new Request(`${FORM}?next=${meet.next}`, { headers: { cookie: first.cookie } }), + env, + ctx, + ); + const second = { + state: /name="state" value="([^"]+)"/.exec(await again.text())?.[1] || "", + cookie: (again.headers.get("set-cookie") || "").split(";")[0]!, + }; + expect(second).toMatchObject({ state: first.state }); + // the first page's form, sent with the cookie the second fetch left + expect(await posted(env, { ...first, cookie: second.cookie, name: "Bob" })).toMatchObject({ + status: 303, + }); + expect(people()).toHaveLength(1); + // a form for another request is another form + const other = await hostSignInOf(env, MEET, "guest passkey"); + const others = await authResponse( + new Request(`${FORM}?next=${other.next}`, { headers: { cookie: second.cookie } }), + env, + ctx, + ); + expect(await others.text()).not.toContain(`value="${first.state}"`); +}); + +test("two browsers with two names are two people, each with a name, an event and 15 minutes on the app's host", async () => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest passkey"); + const bob = await joined(env, meet.next, "Bob"); + const eve = await joined(env, meet.next, " Eve]\n[from root@example.com\u202E "); + expect(bob.answer).toMatchObject({ status: 303 }); + // one way at a time: a guest's sign-in ends a mind's session in this browser, which authorize + // would otherwise take for an app that names both + expect(bob.answer.headers.getSetCookie()).toContainEqual( + expect.stringMatching(/^__Host-iterate-auth-mind-session=; .*Max-Age=0$/), + ); + // the form goes on to the request it was shown for, on this origin: no other host + expect(bob.answer.headers.get("location")).toBe(meet.path); + expect(bob.cookie).toMatch(/^__Host-iterate-auth-guest-session=/); + expect(people()).toEqual([ + { id: bob.userId, email: expect.stringMatching(/^guest:[0-9a-f]{32}$/) }, + { id: eve.userId, email: expect.stringMatching(/^guest:[0-9a-f]{32}$/) }, + ]); + expect(new Set([bob.userId, eve.userId])).toHaveProperty("size", 2); + expect(bob).toHaveProperty("facts", [ + { + path: `/users/${bob.userId}`, + events: [ + { + type: "events.iterate.com/account/guest-signed-in", + payload: { + userId: bob.userId, + name: "Bob", + app: "meet.example.com", + at: expect.any(Number), + }, + idempotencyKey: `account/guest-signed-in/${bob.userId}`, + }, + ], + }, + ]); + + // back at the authorization endpoint the cookie earns a code for that host's own callback, and + // is set again + const earned = await meet.ask(bob.cookie); + expect([earned.status, originAndPath(earned)]).toEqual([302, `${MEET}/.iterate/callback`]); + expect(earned.headers.get("set-cookie")).toMatch( + /^__Host-iterate-auth-guest-session=[^;]+; .*Max-Age=2592000/, + ); + const identity = await tokenIdentity(env, await meet.tokenFor(earned), MEET); + expect(identity).toEqual({ + principal: { actor: bob.userId }, + grant: expect.any(String), + expiresAt: expect.any(Number), + member: false, + method: "guest", + name: "Bob", + }); + const seconds = identity!.expiresAt - Date.now() / 1000; + expect(seconds > 880 && seconds <= 900).toBe(true); + + // a name is one clean line of at most 40 characters, whatever was typed + const eves = await tokenIdentity(env, await meet.tokenFor(await meet.ask(eve.cookie)), MEET); + expect(eves).toMatchObject({ name: "Eve] [from root@example.com", method: "guest" }); +}); + +test("a guest's token is for that app's host alone: never another host, the API or the MCP server", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const token = await meet.tokenFor(await meet.ask(bob.cookie)); + expect(await whoIs(env, token, MEET)).toMatchObject({ member: false, method: "guest" }); + for (const resource of [OTHER, ISSUER, mindApiUrlOf(MIND), mindMcpUrlOf(MIND)]) + expect(await whoIs(env, token, resource)).toBeNull(); +}); + +test("the guest's cookie is nobody to every page of the mind's own, and to an app that names no guests", async () => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const owner = await ownerCookie(env); + const get = (path: string, cookie: string) => + authResponse(new Request(ISSUER + path, { headers: { cookie } }), env, ctx); + const post = (path: string, cookie: string) => + authResponse( + new Request(ISSUER + path, { + method: "POST", + headers: { cookie, origin: ISSUER, "content-type": "application/x-www-form-urlencoded" }, + body: "action=block&email=someone%40example.org&session=x", + }), + env, + ctx, + ); + const seen = async (answer: Response) => [answer.status, answer.headers.get("location")]; + for (const path of ["/", "/members", "/keys", "/keys.json", "/keys/enrol", "/sessions", "/minds"]) + expect(await seen(await get(path, bob.cookie)), path).toEqual(await seen(await get(path, ""))); + for (const path of ["/members", "/keys", "/keys/remove", "/sessions", "/minds"]) + expect(await seen(await post(path, bob.cookie)), path).toEqual( + await seen(await post(path, "")), + ); + // those pages do know a member: the same read with the owner's passkey session is another answer + expect(await seen(await get("/members", owner))).toEqual([200, null]); + expect(await seen(await get("/members", ""))).toEqual([303, "/sign-in?next=%2Fmembers"]); + + // no session of the mind's own, under either cookie's name + const guestToken = bob.cookie.split("=")[1]!; + for (const cookie of [bob.cookie, `__Host-iterate-auth-session=${guestToken}`]) + expect(await sessionOf(env, new Request(ISSUER, { headers: { cookie } }))).toBeNull(); + const ownerToken = owner.split("=")[1]!; + expect( + await guestOf( + env, + new Request(ISSUER, { + headers: { cookie: `__Host-iterate-auth-guest-session=${ownerToken}` }, + }), + ), + ).toBeNull(); + + // an app that names other ways, or none, sends the guest to its sign-in as it sends a stranger + for (const ways of ["email", "passkey email", ""]) { + const app = await hostSignInOf(env, OTHER, ways); + const answer = await app.ask(bob.cookie); + expect([answer.status, originAndPath(answer)], ways).toEqual([302, "/sign-in"]); + } + // a client that asks a consent (an MCP client) gets no guest, whatever ways it names + const client = await hostSignInOf(env, MEET, "guest", { + client_id: await registeredClientOf(env), + redirect_uri: "http://127.0.0.1:7777/callback", + }); + const asked = await client.ask(bob.cookie); + expect([asked.status, originAndPath(asked)]).toEqual([302, "/sign-in"]); + // and its sign-in page is the member's passkey alone + const page = await authResponse(new Request(asked.headers.get("location")!), env, ctx); + expect([page.status, await page.text()]).toEqual([200, expect.not.stringContaining("guest")]); + expect(people()).toHaveLength(1); +}); + +test("a guest never becomes a member: not by a members row, nor by the address of a member", async () => { + const stack = stackOf(); + const meet = await hostSignInOf(stack.env, MEET, "guest"); + const bob = await joined(stack.env, meet.next, "Bob"); + const token = await meet.tokenFor(await meet.ask(bob.cookie)); + const key = stack.people()[0]!.email; + // some path writes the guest's key as a member + stack.db + .prepare("insert into members (email, added_by, added_at) values (?, ?, ?)") + .run(key, OWNER, 1); + expect(await isMember(stack.env, key)).toBe(false); + expect(await tokenIdentity(stack.env, token, MEET)).toMatchObject({ member: false }); + expect(await whoIs(stack.env, token, mindApiUrlOf(MIND))).toBeNull(); + // every key that is no address is nobody's, a Cloudflare user's too + expect(await isMember(stack.env, "cloudflare:abc")).toBe(false); + expect(await isMember(stack.env, OWNER)).toBe(true); + // a guest's row is a row of its own: an address is another row + const ada = await userOf(stack.env.DB, "ada@example.org"); + expect(new Set([bob.userId, ada.id])).toHaveProperty("size", 2); +}); + +test("someone signed in is never made a guest, and keeps who they are where the app names their way", async () => { + const { env, people } = stackOf(); + const owner = await ownerCookie(env); + const before = people(); + const guestsOnly = await hostSignInOf(env, MEET, "guest"); + // the form is not shown, and its answer makes nobody + const page = await authResponse( + new Request(`${FORM}?next=${guestsOnly.next}`, { headers: { cookie: owner } }), + env, + ctx, + ); + expect([page.status, await page.text()]).toEqual([403, expect.stringContaining(OWNER)]); + const shown = await formOf(env, guestsOnly.next); + const answer = await posted(env, { ...shown, name: "Bob", cookie: `${shown.cookie}; ${owner}` }); + expect(answer).toMatchObject({ status: 403 }); + expect(answer.headers.get("set-cookie") || "").not.toMatch(/guest-session=[^;]/); + expect(people()).toEqual(before); + + // an app that names guests and a passkey takes the member as the member, with a guest's cookie + // in the same browser or not + const both = await hostSignInOf(env, MEET, "guest passkey"); + const bob = await joined(env, both.next, "Bob"); + for (const cookie of [owner, `${bob.cookie}; ${owner}`]) + expect( + await tokenIdentity(env, await both.tokenFor(await both.ask(cookie)), MEET), + ).toMatchObject({ + principal: { email: OWNER }, + member: true, + method: "passkey", + }); +}); + +test("the browser is asked once: with the cookie, the form goes straight on, and a sign-out or a chooser ends the guest", async () => { + const { env, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + // an app that names guests alone has one way: the sign-in page is its form + const signIn = await authResponse(new Request(`${ISSUER}/sign-in?next=${meet.next}`), env, ctx); + expect([signIn.status, signIn.headers.get("location")]).toEqual([ + 302, + `${FORM}?next=${meet.next}`, + ]); + for (const method of ["GET", "POST"]) { + const shown = await formOf(env, meet.next); + const again = + method === "GET" + ? await authResponse( + new Request(`${FORM}?next=${meet.next}`, { headers: { cookie: bob.cookie } }), + env, + ctx, + ) + : await posted(env, { + ...shown, + name: "Mallory", + cookie: `${shown.cookie}; ${bob.cookie}`, + }); + expect([again.status, again.headers.get("location")]).toEqual([303, meet.path]); + } + expect(people()).toHaveLength(1); + // an app with more ways shows a button for each, in its order + const more = await hostSignInOf(env, MEET, "passkey email guest"); + const ways = await authResponse(new Request(`${ISSUER}/sign-in?next=${more.next}`), env, ctx); + expect(await ways.text()).toMatch(/your email address[\s\S]*Come in as a guest/); + + // the host's sign-out asks the chooser: the guest's cookie ends, and the form is the next page + const chooser = await ( + await hostSignInOf(env, MEET, "guest", { prompt: "select_account" }) + ).ask(bob.cookie); + expect([chooser.status, originAndPath(chooser)]).toEqual([302, "/sign-in"]); + expect(chooser.headers.get("set-cookie")).toMatch(/^__Host-iterate-auth-guest-session=; /); + const out = await authResponse( + new Request(`${ISSUER}/sign-out`, { + method: "POST", + headers: { origin: ISSUER, cookie: bob.cookie }, + body: new URLSearchParams({ next: "/" }), + }), + env, + ctx, + ); + expect(out.headers.getSetCookie()).toContainEqual( + expect.stringMatching(/^__Host-iterate-auth-guest-session=; /), + ); +}); + +test("a member whose browser was a guest before is the member, never that guest, at an app that names guests alone", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const owner = await ownerCookie(env); + expect(originAndPath(await meet.ask(bob.cookie))).toBe(`${MEET}/.iterate/callback`); + // a passkey's session counts at every app (./asking-app.ts `appTakes`), so the guest's cookie + // beside it is not read + const asked = await meet.ask(`${bob.cookie}; ${owner}`); + expect(originAndPath(asked)).toBe(`${MEET}/.iterate/callback`); + expect(await tokenIdentity(env, await meet.tokenFor(asked), MEET)).toMatchObject({ + principal: { email: OWNER }, + member: true, + method: "passkey", + }); +}); + +test("a guest's code gives 15 minutes and no refresh token", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const tokens = await meet.tokensFor(await meet.ask(bob.cookie)); + expect(tokens).toMatchObject({ access_token: expect.any(String), expires_in: 900 }); + expect(tokens).not.toHaveProperty("refresh_token"); + // the rule itself: nothing renews a guest's grant, and any other host sign-in is as it was + const guest = { userId: "user_1", email: "guest:abc", method: "guest" } as const; + const at = { host: true, now: Date.now() }; + expect(grantLifetimeOf(guest, { ...at, refresh: false })).toEqual({ + accessTokenTTL: 900, + refreshTokenTTL: 0, + }); + expect(grantLifetimeOf(guest, { ...at, refresh: true })).toBe("guest_no_refresh"); + expect( + grantLifetimeOf( + { ...guest, email: "a@example.org", method: "email" }, + { ...at, refresh: false }, + ), + ).toEqual({ accessTokenTTL: 24 * 3600 }); +}); + +test("one guest's cookie cannot use up the stack's sessions: each guest has a bound of their own", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const eve = await joined(env, meet.next, "Eve"); + const answers = []; + for (let n = 0; n < 8; n += 1) answers.push((await meet.ask(bob.cookie)).status); + expect(answers).toEqual([302, 302, 302, 302, 302, 302, 429, 429]); + expect(await meet.ask(eve.cookie)).toMatchObject({ status: 302 }); +}); + +test("the stack's two bounds: past each, the page says ten minutes, and the mind gets one event for the window", async () => { + const { env, db, people } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const guests = [await joined(env, meet.next, "One"), await joined(env, meet.next, "Two")]; + // the rest of the stack's 120 new guests came from other addresses + admissionsOf(db, "guest", 118); + const refusals = []; + for (const name of ["Three", "Four"]) { + const refused = await posted(env, { ...(await formOf(env, meet.next)), name }); + expect([refused.status, refused.headers.get("retry-after")]).toEqual([429, "600"]); + expect(await refused.text()).toContain("Try again in ten minutes"); + refusals.push(factsOf(refused)); + } + expect(people()).toHaveLength(2); + expect(refusals[0]).toEqual([ + { + path: "/", + events: [ + { + type: "events.iterate.com/account/guest-refused", + payload: { reason: "rate", app: "meet.example.com", at: expect.any(Number) }, + idempotencyKey: expect.stringMatching(/^account\/guest-refused\/rate\/stack\/\d+$/), + }, + ], + }, + ]); + // the same key: the log takes the second as the first + expect(refusals[1]).toMatchObject([ + { events: [{ idempotencyKey: refusals[0]![0]!.events[0]!.idempotencyKey }] }, + ]); + + // the stack's 600 sessions for its guests, then none: a renewal is counted like a first one + admissionsOf(db, "guest-session", 597); + for (const guest of [guests[0]!, guests[1]!, guests[0]!]) + expect(await meet.ask(guest.cookie)).toMatchObject({ status: 302 }); + const refused = await meet.ask(guests[1]!.cookie); + expect(refused).toMatchObject({ status: 429 }); + expect(factsOf(refused)).toMatchObject([ + { path: "/", events: [{ payload: { reason: "session-rate", app: "meet.example.com" } }] }, + ]); +}); + +test("an owner blocks a guest by id: the token and the cookie end at once", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest"); + const bob = await joined(env, meet.next, "Bob"); + const eve = await joined(env, meet.next, "Eve"); + const token = await meet.tokenFor(await meet.ask(bob.cookie)); + const evesToken = await meet.tokenFor(await meet.ask(eve.cookie)); + const owner = await ownerCookie(env); + const members = (action: string, email: string) => + authResponse( + new Request(`${ISSUER}/members`, { + method: "POST", + headers: { origin: ISSUER, cookie: owner }, + body: new URLSearchParams({ action, email }), + }), + env, + ctx, + ); + // an id that is no guest's names nobody + const ownerId = z + .object({ id: z.string() }) + .parse(await env.DB.prepare("select id from users where email = ?1").bind(OWNER).first()).id; + expect(await (await members("block", ownerId)).text()).toContain("Type the address to block"); + + const blocked = await members("block", bob.userId); + expect(await blocked.text()).toContain(`The guest ${bob.userId} is blocked`); + expect(factsOf(blocked).flatMap((fact) => fact.events.map((event) => event.type))).toEqual([ + "events.iterate.com/account/grant-ended", + "events.iterate.com/account/person-blocked", + ]); + expect(await tokenIdentity(env, token, MEET)).toBeNull(); + expect(await tokenIdentity(env, evesToken, MEET)).toMatchObject({ name: "Eve" }); + // the cookie earns nothing more, and the form says so with one event on the guest's context + const asked = await meet.ask(bob.cookie); + expect([asked.status, originAndPath(asked)]).toEqual([302, "/sign-in"]); + const signIn = await authResponse(new Request(asked.headers.get("location")!), env, ctx); + expect(originAndPath(signIn)).toBe("/sign-in/guest"); + const refused = await authResponse( + new Request(signIn.headers.get("location")!, { headers: { cookie: bob.cookie } }), + env, + ctx, + ); + expect(refused).toMatchObject({ status: 403 }); + expect(factsOf(refused)).toMatchObject([ + { path: `/users/${bob.userId}`, events: [{ payload: { reason: "blocked" } }] }, + ]); + + expect(await (await members("unblock", bob.userId)).text()).toContain("is no longer blocked"); + expect(originAndPath(await meet.ask(bob.cookie))).toBe(`${MEET}/.iterate/callback`); +}); + +test("an app that stops naming guests ends every guest at once: the token and the cookie", async () => { + const { env } = stackOf(); + const meet = await hostSignInOf(env, MEET, "guest passkey"); + const bob = await joined(env, meet.next, "Bob"); + const token = await meet.tokenFor(await meet.ask(bob.cookie)); + expect(await tokenIdentity(env, token, MEET)).toMatchObject({ method: "guest" }); + const changed = await hostSignInOf(env, MEET, "passkey"); + // the token that the guest holds is nobody's from the next request + expect(await tokenIdentity(env, token, MEET)).toBeNull(); + const asked = await changed.ask(bob.cookie); + expect([asked.status, originAndPath(asked)]).toEqual([302, "/sign-in"]); + expect(await authResponse(new Request(`${FORM}?next=${changed.next}`), env, ctx)).toMatchObject({ + status: 404, + }); +}); + +/** The mind of ./test-support.ts on SQLite in memory, with its guests' rows. No app is asked for + * its description over the network: `hostSignInOf` writes the one the issuer keeps. */ +function stackOf() { + const stack = sqliteStack(); + vi.stubGlobal("fetch", async () => new Response("Not found", { status: 404 })); + return { + ...stack, + /** The guests' rows alone, oldest first. */ + people: () => + stack.db + .prepare("select id, email from users where email like 'guest:%' order by rowid") + .all() as { id: string; email: string }[], + }; +} + +/** `count` admissions of `kind` that others made in this window (./device/limits.ts). */ +function admissionsOf(db: ReturnType<typeof sqliteStack>["db"], kind: string, count: number) { + const insert = db.prepare("insert into admissions (kind, client, created_at) values (?, ?, ?)"); + for (let n = 0; n < count; n += 1) insert.run(kind, `other-${n}`, Date.now()); +} + +/** The authorization request of `resource`'s own host client, as the boundary sends a visitor, + * for an app whose description names the sign-in methods `ways` (none: the default). `next` is + * that request as the sign-in pages carry it, a path of the issuer. `change`: a parameter that + * another client would send. */ +async function hostSignInOf( + env: Env, + resource: string, + ways: string, + change: Record<string, string> = {}, +) { + const verifier = generateRandomCodeVerifier(); + const { host } = new URL(resource); + const clientId = await hostClientOf(env, host); + const signIn = (ways ? ways.split(" ") : ["email", "passkey"]) as SignInMethod[]; + await env.OAUTH_KV.put( + `iterate-app-description:${host}`, + JSON.stringify({ + name: null, + icon: null, + members: false, + signIn, + askAfter: Date.now() + 60_000, + }), + ); + const query = new URLSearchParams({ + response_type: "code", + client_id: clientId, + redirect_uri: hostCallbackOf(resource), + resource, + scope: "identity", + state: "s", + code_challenge: await calculatePKCECodeChallenge(verifier), + code_challenge_method: "S256", + ...change, + }); + const path = `/oauth2/auth?${query}`; + const request = { + path, + next: encodeURIComponent(path), + ask: (cookie = "") => + authResponse(new Request(ISSUER + path, { headers: { cookie } }), env, ctx), + /** The token endpoint's answer for the code in `answer`'s redirect, as the boundary's + * callback gets it. */ + tokensFor: async (answer: Response) => { + const exchanged = await authResponse( + new Request(`${ISSUER}/oauth2/token`, { + method: "POST", + headers: { "content-type": "application/x-www-form-urlencoded" }, + body: new URLSearchParams({ + grant_type: "authorization_code", + code: new URL(answer.headers.get("location")!).searchParams.get("code")!, + redirect_uri: hostCallbackOf(resource), + client_id: clientId, + code_verifier: verifier, + resource, + }), + }), + env, + ctx, + ); + return exchanged.json() as Promise<Record<string, unknown>>; + }, + }; + return { + ...request, + /** The access token alone. */ + tokenFor: async (answer: Response) => + z.object({ access_token: z.string() }).parse(await request.tokensFor(answer)).access_token, + }; +} + +/** The form as a browser is shown it for `next` (URI-encoded): its state, and its flow cookie. */ +async function formOf(env: Env, next: string) { + const page = await authResponse(new Request(`${FORM}?next=${next}`), env, ctx); + const state = /name="state" value="([^"]+)"/.exec(await page.text())?.[1] || ""; + return { state, cookie: (page.headers.get("set-cookie") || "").split(";")[0]! }; +} + +/** The form's answer. `origin: null` sends none; `length` claims a Content-Length. */ +function posted( + env: Env, + sent: { state: string; cookie: string; name: string; origin?: string | null; length?: string }, +) { + const headers = new Headers({ cookie: sent.cookie }); + // null is "send none", which is not the same as "the form's own" + // oxlint-disable-next-line iterate/simple-truthiness-check -- null and undefined mean two things here: no Origin header at all, and the issuer's own + if (sent.origin !== null) headers.set("origin", sent.origin || ISSUER); + if (sent.length) headers.set("content-length", sent.length); + return authResponse( + new Request(FORM, { + method: "POST", + headers, + body: new URLSearchParams({ state: sent.state, name: sent.name }), + }), + env, + ctx, + ); +} + +/** One browser that is shown the form and answers it with `name`. */ +async function joined(env: Env, next: string, name: string) { + const answer = await posted(env, { ...(await formOf(env, next)), name }); + const facts = factsOf(answer); + const cookie = answer.headers + .getSetCookie() + .find((each) => each.includes("guest-session="))! + .split(";")[0]!; + return { answer, facts, cookie, userId: facts[0]!.path.replace("/users/", "") }; +} + +function factsOf(answer: Response) { + return decodeFacts(answer.headers.get(FACTS_HEADER) || ""); +} + +function originAndPath(answer: Response) { + const url = new URL(answer.headers.get("location")!); + return url.origin === ISSUER ? url.pathname : url.origin + url.pathname; +} + +/** The owner, signed in with a live passkey: a member's session. */ +async function ownerCookie(env: Env) { + const owner = await userOf(env.DB, OWNER); + await env.DB.prepare( + `insert into keys (id, user_id, public_key, format, label, added_via, added_by, added_at) + values ('key-1', ?1, 'a-public-key', 'webauthn', 'a passkey', 'keys-page', ?1, 1) + on conflict do nothing`, + ) + .bind(owner.id) + .run(); + const { setCookie } = await sessionCookie(env, new Request(ISSUER), owner, "key-1"); + return setCookie.split(";")[0]!; +} + +/** An MCP client that registers itself, as any MCP client does. Answers its id. */ +async function registeredClientOf(env: Env) { + const registered = await authResponse( + new Request(`${ISSUER}/oauth2/register`, { + method: "POST", + headers: { "content-type": "application/json" }, + body: JSON.stringify({ + client_name: "An MCP client", + redirect_uris: ["http://127.0.0.1:7777/callback"], + token_endpoint_auth_method: "none", + }), + }), + env, + ctx, + ); + return z.object({ client_id: z.string() }).parse(await registered.json()).client_id; +}
A core/auth-worker/src/guest-sign-in.ts
@@ -0,0 +1,236 @@ +// guest-sign-in.ts — A GUEST: a person who types a name, for an app of the mind that names the +// sign-in method "guest" (iterate/app-description `AppDescription.signIn`). +// +// WHAT IT IS FOR. A page that someone opens by a link, with no account. The app decides what the +// link opens; here the person only says what to call them. +// +// WHAT IT PROVES: NOTHING. Anyone on the internet can be a guest, with any name. So a guest is a +// person and never a member, and counts only at an app that names the method: +// - the person is a row whose key is `guest:<subject>` (./cookies.ts `GUEST_KEY_PREFIX`), which +// is no address: no proof of an address reaches it, and no member is ever such a key +// (./members.ts `isMember`); +// - it has a cookie of its own (./cookies.ts `guestOf`), which only the authorization endpoint +// reads, for a hostname's own sign-in whose app names guests (./authorize.ts `guestAt`); none +// of the mind's own pages reads it, and no consent takes it; +// - a code or a token from it is for a mind hostname alone, never the mind's API, MCP server or +// the right to hand in a mind, and says `member: false` (./oauth.ts `tokenIdentity`). +// The cookie gives no reach by itself: it earns a session on the host of an app that names +// guests, and what that app then shows is its own code's decision. +// +// GET /sign-in/guest?next=… the form, for a hostname's own sign-in whose app names guests. +// It makes nothing: a browser that fetches the page is no guest +// POST /sign-in/guest makes the guest, and goes on to `next` +// +// ONCE A BROWSER. The cookie lasts 30 days from the browser's last visit, so the name is asked +// once. A guest's session on an app's host lasts 15 minutes (./oauth.ts), and the next one comes +// with no question: the host sends the browser here, and the cookie answers. That is when an app +// checks again what the guest holds. A renewal stops when the app no longer names guests, an +// owner blocks the guest, or the stack's bound is reached. +// +// SOMEONE ALREADY SIGNED IN IS NEVER MADE A GUEST. A browser with a session of the mind's own gets +// no form: an app that takes guests and also names that person's method has let them in as +// themselves already (./authorize.ts), and one that does not says so here. +// +// BOUNDS, since anyone can come: a name of 1 to 40 characters (iterate/principal +// `displayNameOf`); 120 new guests and 600 guests' sessions for the stack in ten minutes; 20 new +// guests an address, and 6 sessions a guest, so that no one cookie uses up the stack's number +// (./device/limits.ts). At a bound the page says to try again in ten minutes, and the mind gets +// one `account/guest-refused` for that reason in that window. A guest's grant holds no refresh +// token: every next 15 minutes are asked for here. +import { sameOriginPath } from "iterate/lib"; +import { DISPLAY_NAME_MAX_CHARACTERS, displayNameOf } from "iterate/principal"; +import { AccountFacts } from "./account-facts.ts"; +import { type AskingApp, askingAppOf } from "./asking-app.ts"; +import { + clearGuestFormCookie, + clearMindCookie, + GUEST_KEY_PREFIX, + guestCookie, + guestFormCookie, + guestFormOf, + guestOf, + personSessionOf, +} from "./cookies.ts"; +import { admissionWindowOf, admitted } from "./device/limits.ts"; +import { configOf, type Env, issuerOf } from "./env.ts"; +import { appSignIn, errorPage, otherAccountForm, page, text } from "./pages.ts"; +import { userOf } from "./users.ts"; + +const GUEST_SIGN_IN_PATH = "/sign-in/guest"; + +/** The name form for the sign-in that `next` goes on to, as a whole address of the issuer. */ +export const guestFormHref = (env: Env, next: string) => + `${issuerOf(env)}${GUEST_SIGN_IN_PATH}?${new URLSearchParams({ next })}`; + +/** New guests that the stack takes in ten minutes, from every address together. */ +const GUESTS_PER_TEN_MINUTES = 120; +/** Guests' sessions on the apps' hosts that the stack gives in ten minutes (./authorize.ts). */ +export const GUEST_SESSIONS_PER_TEN_MINUTES = 600; + +/** The form's own answer is small: a state and a name. */ +const FORM_MAX_BYTES = 4096; + +export async function guestSignInResponse(env: Env, request: Request): Promise<Response | null> { + const url = new URL(request.url); + if (url.pathname !== GUEST_SIGN_IN_PATH) return null; + if (request.method === "GET" || request.method === "HEAD") return form(env, request, url); + if (request.method === "POST") return made(env, request); + return new Response("Method not allowed", { status: 405, headers: { allow: "GET, POST" } }); +} + +/** THE APP THAT TAKES A GUEST, for the request `next` goes on to (a path of this origin), or null. + * It is a hostname's own sign-in that this stack holds (./asking-app.ts: its resource, its + * redirect and its client agree), and its app names guests. So the form exists only on the way + * to an app's own page, and after it the browser goes there and nowhere else. */ +async function guestAppOf(env: Env, next: string): Promise<AskingApp | null> { + const app = await askingAppOf(env, next); + return app?.signIn.includes("guest") ? app : null; +} + +async function form(env: Env, request: Request, url: URL): Promise<Response> { + const next = sameOriginPath(url.searchParams.get("next") || "/", issuerOf(env)); + const app = await guestAppOf(env, next); + if (!app) return new Response("Not found", { status: 404 }); + const held = await heldBefore(env, request, app, next); + if (held) return held; + // A browser that was shown this form already (a second tab, a reload) gets the same state + // again, so the answer of either page counts. + const shown = await guestFormOf(env, request); + const state = shown?.next === next ? shown.state : crypto.randomUUID(); + const headers = new Headers({ "set-cookie": await guestFormCookie(env, { next, state }) }); + return formPage(app, state, headers); +} + +async function made(env: Env, request: Request): Promise<Response> { + // the form makes a person, so it must come from this origin's own page, in the browser that + // was shown it + if (request.headers.get("origin") !== issuerOf(env)) + return errorPage("Send this from its own page.", 403); + if (Number(request.headers.get("content-length")) > FORM_MAX_BYTES) + return errorPage("This form is too long.", 413); + const shown = await guestFormOf(env, request); + const sent = await request.formData().catch(() => null); + const cleared = new Headers({ "set-cookie": clearGuestFormCookie }); + if (!shown || sent?.get("state") !== shown.state) + return errorPage("This form is too old. Open the link you came by again.", 400, cleared, []); + const app = await guestAppOf(env, shown.next); + if (!app) return new Response("Not found", { status: 404 }); + const held = await heldBefore(env, request, app, shown.next); + if (held) return held; + const name = displayNameOf(String(sent.get("name") || "")); + if (!name) return formPage(app, shown.state, new Headers(), "Type a name."); + if (!(await admitted(env, "guest", request, GUESTS_PER_TEN_MINUTES))) + return guestRefusal("rate", app.host); + // A new person at each form: the subject is this guest's alone, and its key reaches no address. + const user = await userOf( + env.DB, + `${GUEST_KEY_PREFIX}${crypto.randomUUID().replaceAll("-", "")}`, + ); + console.info({ event: "auth.signed-in", method: "guest", userId: user.id }); + const facts = new AccountFacts(); + facts.add(user.id, { + type: "events.iterate.com/account/guest-signed-in", + payload: { userId: user.id, name, app: app.host, at: Date.now() }, + idempotencyKey: `account/guest-signed-in/${user.id}`, + }); + const headers = new Headers({ location: shown.next, "cache-control": "no-store" }); + headers.append("set-cookie", await guestCookie(env, { id: user.id, key: user.email, name })); + headers.append("set-cookie", clearGuestFormCookie); + // one way at a time: a mind's session in this browser ends, so authorize takes this guest + headers.append("set-cookie", clearMindCookie); + return facts.on(new Response(null, { status: 303, headers })); +} + +/** WHAT A BROWSER THAT IS SOMEONE ALREADY GETS in place of the form, or null for a stranger. + * Someone signed in keeps who they are, and reads how to come in. A guest goes on as the guest + * they are; a guest an owner blocked is refused. */ +async function heldBefore( + env: Env, + request: Request, + app: AskingApp, + next: string, +): Promise<Response | null> { + const signedIn = await personSessionOf(env, request); + if (signedIn) + return page( + { + ...appPage(app), + status: 403, + body: `<h1>You are signed in</h1> + <p class="center">You are signed in to ${text(configOf(env).controlPlaneHostname)} as <strong>${text(signedIn.email)}</strong>. ${text(app.name)} takes a guest here, and takes no sign-in of yours.</p> + <div class="center">${otherAccountForm(next, "Sign out, and come in as a guest")}</div>`, + }, + unlisted(), + ); + const guest = await guestOf(env, request); + if (guest?.blocked) return guestRefusal("blocked", app.host, guest.userId); + if (guest) + return new Response(null, { + status: 303, + headers: { location: next, "cache-control": "no-store" }, + }); + return null; +} + +/** A GUEST IS NOT LET IN: the page that says so, and the mind's record of it. One event for each + * reason in one window of the bounds (its key), so a stranger who is refused a thousand times + * writes one. A blocked guest's is on their own context; a bound's names nobody, and is the + * mind's. */ +export function guestRefusal( + reason: "rate" | "session-rate" | "blocked", + app: string, + userId?: string, +): Response { + const at = Date.now(); + console.info({ event: "auth.sign-in-refused", method: "guest", reason }); + const facts = new AccountFacts(); + const fact = { + type: "events.iterate.com/account/guest-refused", + payload: { reason, app, at }, + idempotencyKey: `account/guest-refused/${reason}/${userId || "stack"}/${admissionWindowOf(at)}`, + } as const; + if (userId) facts.add(userId, fact); + else facts.addToMind(fact); + const refused = + reason === "blocked" + ? errorPage("You cannot come in here as a guest.", 403, unlisted(), []) + : errorPage( + "Too many guests came here just now. Try again in ten minutes.", + 429, + unlisted(new Headers({ "retry-after": "600" })), + [], + ); + return facts.on(refused); +} + +function formPage(app: AskingApp, state: string, headers: Headers, error?: string): Response { + return page( + { + ...appPage(app), + status: error ? 400 : 200, + body: `<h1>${text(`Join ${app.name}`)}</h1> + <p class="center muted">You come in as a guest. The others here see the name you type.</p> + ${error ? `<p class="center" role="alert"><strong>${text(error)}</strong></p>` : ""} + <form method="post" action="${GUEST_SIGN_IN_PATH}" class="stack"> + <input type="hidden" name="state" value="${text(state)}"> + <label>Your name <input type="text" name="name" maxlength="${DISPLAY_NAME_MAX_CHARACTERS}" autocomplete="name" autofocus required></label> + <button type="submit">Continue</button> + </form>`, + }, + unlisted(headers), + ); +} + +/** The card of an app's own sign-in (./pages.ts `appSignIn`): its title, and its icon. */ +function appPage(app: AskingApp) { + const { title, mark, imageOrigin } = appSignIn(app); + return { title, mark, imageOrigin, centered: true }; +} + +/** No search engine lists a page of this sign-in. The page helper adds the rest: nothing caches + * it, and it sends no referrer to another origin (`referrer-policy: same-origin`; with + * `no-referrer` a browser would post the form with `Origin: null`, which is refused above). */ +function unlisted(headers = new Headers()) { + headers.set("x-robots-tag", "noindex, nofollow"); + return headers; +}
A core/auth-worker/src/http.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/http.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/identity.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/identity.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/key-rules.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/key-rules.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/key-tokens.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/key-tokens.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/keys-pages.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/keys-pages.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/keys.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/members.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A 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-fetch.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/mind-sign-in.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/mind-sign-in.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/minds-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/minds-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/minds.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/minds.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/oauth.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/oauth.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/page-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/page-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/page-tag.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/page-tag.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/pages.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/pages.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/passkey-sign-in.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/rpc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/self-test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/sessions-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/sessions-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/sign-in.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/signed-change.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/signed-change.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/stack-key.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/statement-drafts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/statement-drafts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/statements.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/statements.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/test-support.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/users.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/vouch.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/who-is.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/src/working-key.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/auth-worker/tsconfig.json
@@ -0,0 +1,5 @@ +{ + "extends": "../../tsconfig.base.json", + "compilerOptions": { "types": ["@cloudflare/workers-types", "node"] }, + "include": ["src"] +}
A core/auth-worker/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/artifacts-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/artifacts-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/cloudflare-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/control-plane-api.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/control-plane-api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/env.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/host-session.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/host-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/http.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/http.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/identity-delivery.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/identity-delivery.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mail-outcomes.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mail-outcomes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mail.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mail.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mind-host-sign-in.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mind-host-sign-in.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mind-stamp.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/mind-transport.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/outside-placeholders.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/own-request.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/own-request.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/provided-door.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/provided-door.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/provided-mind.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/provided-mind.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/rpc.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/rpc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/session-cookies.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/session-mind.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/stamp.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/stamp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/src/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/boundary-worker/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/LICENSE
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/README.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/accounts.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-kinds.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-kinds/agent.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-kinds/agent.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-kinds/index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-prompt.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-start.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/files.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/processor.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/script-envelope.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/start-boundary.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/start.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/subagent.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-tests/test-support.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent-ui.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/facet.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/facets.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/facets.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/files.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/fragments.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-apis/anthropic-messages.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-apis/chat-completions.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-apis/google-generate-content.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-apis/openai-responses.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/llm-request.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/script-envelope.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agent/start.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/agents.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/links.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/brands/cloudflare.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/brands/github.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/brands/google.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/brands/slack.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/brands/x.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/call-facet.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/mcp-page.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/dash/public/share-links.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/notes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/anchor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/classes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/comments.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/doc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/frames.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/merge.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/processors/root.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/docs/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/entries.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/guestbook/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/live-reload/live-reload.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/mcp/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/mcp/server.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/meeting.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/public/share-links.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/meet/public/snapshot-capture.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/cloud-ai.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/cloud-credit.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/launch.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/open-cloud.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/steps.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/steps/connect-cloudflare.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/steps/connect-iterate-cloud.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/onboarding/verify-ai.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/open-files.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/public/manifest.webmanifest
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/public/tasks-model.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/tasks/tasks-model.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/backend.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/crashes.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/crashes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/cut.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/day-budget.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/exceptions.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/exceptions.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/page-events.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/page-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/page-speed.test.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/page-speed.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/page-tag.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/telemetry/public/page.js
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/apps/theme.css
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/calendar.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call/outbound.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call/rules.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call/share-api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call/share.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/call/snapshot.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloud-accounts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloud-deliveries.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloud-handover.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloud-scopes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloudflare.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/cloudflare.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/context-descriptions.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/debug.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/deliveries.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/docs-app.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/errors.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/every-event.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/files.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/gmail.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/homepage.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/init.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/integrations.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/iterate-core.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/mail-replies.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/mail-replies.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/mail.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/minds.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/page-events.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/people.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/profile.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/profile/icon.svg
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/profile/profile.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/sandboxes.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/secrets.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/slack.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/telemetry.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/template-updates.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/top-of-mind.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/website.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/default/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/doctor.config.mjs
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/minimal/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/minimal/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/minimal/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/configs/minimal/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/.gitignore
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/README.md
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/fixtures/snapshot-request.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/local-entrance.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/local-entrance.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/own-host.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/own-host.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/relay.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/link/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/main.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/repos/artifacts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/repos/server.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/repos/server.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/repos/token.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/sandbox-sidecars.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/sandbox-sidecars.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/src/snapshot-request.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/home-lab/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/alarm-coordinator.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/caller.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/caller.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/cause.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/cause.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context-stub.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context-stub.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/awake.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/awake.ts
Not shown: the change is larger than this page shows. A clone has it.
A 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/call-context.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/connections.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/context-catalog.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/context-summary.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/context-summary.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/critical-section-deadline.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/dispatch.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/dispatch.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/egress.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/facet-host.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/facet-host.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/facet-public-methods.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/fetch-upgrade-splice.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/fetch-upgrade.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/held-verbs-across-contexts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/held-verbs.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/held-verbs.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/itx-expression-rewriting.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/jail-rows-reach.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/lent-names.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/lent-names.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/loaded-code-rows.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/parent-rule-and-child.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/paths.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/redial.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/redial.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/residency.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/rpc-stub-relay.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/rpc-stubs.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/rpc-stubs.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/rule-snapshots.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/rule-snapshots.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/run.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/signed-fetch.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/stateless-context.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/telemetry-query-rule.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/websocket-close.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/whoami.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/worker-loader.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/worker-manifest.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/context/workers-root-email.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/end-when-silent.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/end-when-silent.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/fetch-routes.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/fetch-routes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/first-party-facets.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/host.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/iterate-context-durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/iterate-context.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/iterate-context.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/loaded-code-cd.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/metrics.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/on-behalf-of.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/on-behalf-of.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/person-context.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/person-context.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/request-body.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/request-body.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/request-stamps.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/serve-host.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/session.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/session.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/core-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/core-processor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/core-processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/event-expressions.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/scheduled-appends.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/stream-versions.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/stream-wait-for-event.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/stream-wake-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/stream.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/subscription-delivery.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/wake-events.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/stream/wake-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/unavailable.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/src/unavailable.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/itx/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/LICENSE
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/README.md
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/bin/iterate.js
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/scripts/plain-page-css.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/acts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/acts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/README.md
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/at-work.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/at-work.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/catalog.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/catalog.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/collection.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/collection.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/install.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/install.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/kinds.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/message.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/recent.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/agents/recent.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-config.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-description.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-description.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-server.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-server.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/app.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cause.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/README.md
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/bridge-key.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/bridge-key.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/chatgpt.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/chatgpt.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/cli.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/cli.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/cloudflare-access.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/cloudflare-access.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/coding-agent.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/deploy.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/deploy.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/device-login/flow.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/device-login/flow.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/device-login/index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/device-login/poll.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/device-login/poll.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/fs.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/fs.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/identity.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/identity.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/oauth.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/open-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/open-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/provide-state.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/provide.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/provide.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/recover.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/recover.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/run-command.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/share-my-computer.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/tunnel.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/tunnel.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cli/use-my-computer.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/connected-mind.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/event-log.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/event-log.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/heartbeat.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/live-state.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/live-state.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/new-version.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/oauth.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/oauth.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/react.tsx
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/socket.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/client/socket.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/cloudflare-read-scopes.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/compatibility-date.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-agent.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-calendar.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-call.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-cloud-accounts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-cloud-deliveries.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-cloudflare-card.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-cloudflare.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-context-descriptions.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-dash.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-docs.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-gmail.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-guestbook.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-handover.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-iterate-core.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-mail-replies.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-mcp.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-meet.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-mirror.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-onboarding.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-profile.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-publish-hook.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-signature-prompts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-slack.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-tasks.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-telemetry-query-rule.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/config-default-telemetry.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/dash-routes.fixture.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/email.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/expression.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/expression.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/facts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/facts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/integrations.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/integrations.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/lib.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/lib.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-api.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-api.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-config.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-identity-log.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-identity-log.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-identity.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-identity.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/mind-ingress.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/node-renewal.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/node.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/node.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/oauth-scopes.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/oauth-scopes.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/package-builds.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/package-builds.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/platform-retry.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/platform-retry.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/principal.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/principal.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/released-answer.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/auth.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/auth.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/call-with-cause.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/code-failed.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/cut.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/direct-append.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/direct-append.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/files.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/index.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A 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/itx-scope.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/itx-scope.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/loaded-worker.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sdk/loaded-worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/secret-placeholder.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/secret-placeholder.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/signed.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/signed.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sshsig.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/sshsig.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/standalone-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/standalone-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/processor-rules.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/processor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/run.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/stream/test-support.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/test-support/cloudflare-workers-shim.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/test-support/config-default-instance.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/test-support/identity-log.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/test-support/ssh-signer.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/theme/plain-page-css.gen.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/theme/plain-page.css
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/theme/theme.css
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/theme/tokens.css
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/src/workers.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/tsconfig.cli.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/tsconfig.node.build.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/tsconfig.node.json
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/tsdown.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/vitest.config-file-imports.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/lib/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/.gitignore
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/images/iterate-dev-image/Dockerfile
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/scripts/build.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/agent-spans.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/approved-acts.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/approved-acts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/approvals.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/approvals.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/browser.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/cf-artifacts.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/config-code-failed.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/file-urls.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/file-urls.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/fixtures/signed-upload.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/held-verb-rules.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/held-verb-rules.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/hop-caller.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/images.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/mind-fetch.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/minds.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/minds.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/module-resolution.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/module-resolution.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/r2.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/secret-fact-after-answer.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/secrets.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/secrets.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/signed-upload.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/telemetry-facet.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/telemetry.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/telemetry.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/url.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/url.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/webhooks.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/context/worker-loader.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/email/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/email/processor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/email/processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/env.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/generated/config-templates.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/generated/platform-modules.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/generated/sandbox-files-tool.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/http.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A 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/integrations/email-hook.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/email-hook.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/email.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/email.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/registry.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/integrations/webhooks.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/itx-ai.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/itx-ai.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/itx-host.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/lender-root.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/lender-root.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/library.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/library/capnweb.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/library/connection.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/library/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/library/openapi.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mcp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/collection.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/collection.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/context-birth-events.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/entity-lifecycle.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/processor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/publication.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/seed-repos.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/template-update.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/mind/template-update.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/platform-append.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/platform-entries.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/platform-entries.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/durable-object.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/git-wire.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/git-wire.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/remote-commit.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/repo/remote-commit.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/rpc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/container.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/contract.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/durable-object.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/egress-rule.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/egress-rule.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/egress.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/exec-record.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/files.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/image.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/image.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/own-session.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/own-session.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/ports.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/ports.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/processor.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/processor.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/sandbox/session-filter-under-a-parent.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/workspace/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/src/workspace/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/mind-worker/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/AGENTS.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/files.d.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/index.html
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/agent-loop.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/approvals.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/apps.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/computer.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/connect-iterate-cloud.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/connect.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/finish.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/follow-up.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/github.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/instructions.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/let-iterate-in.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/links.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/look.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/mail.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/mcp.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/other-minds.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/pays.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/people.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/reach.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/research.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/sandbox.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/secrets.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/sign-up-record.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/signed-requests.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/speak.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/subagents.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/telemetry.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/voice.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/onboarding/website.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/public/app.css
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/public/app.js
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-build-an-app.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-connect-iterate-cloud.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-connect-mcp.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-connect-tools.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-devices-and-character.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-invite-people.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-look.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-mail.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-remove-onboarding-app.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-research.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-sandbox.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-secrets-and-approvals.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-telemetry.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-voice-call.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tasks/onboarding-website.md
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/repos/onboarding/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/acts-gate.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/acts-gate.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/acts-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/acts-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/approval.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/approval.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/approvals-index.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/approvals-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/approvals-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/body-placement.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/body-placement.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/callback-page.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/callback-page.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/cloud-client.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/cloud-client.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/config.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/env.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/grant-ceiling.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/grant-refresh.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/grant-refresh.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/http.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/markdown.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/markdown.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/objects.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/rpc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-at-rest.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-collect.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-collect.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-list.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-list.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-oauth-callback.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-oauth-callback.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-oauth-start.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-oauth-start.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret-oauth.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/body-placement.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/by-proxy.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/contract.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/durable-object.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/durable-object.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/exchange-jail.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/key-ops.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/refusals.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/refusals.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secret/signing-key.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secrets.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/secrets.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/stack-secrets.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/stack-secrets.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/src/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A core/secrets-worker/vitest.config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/package.json
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/schemas/events.json
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/schemas/logs.json
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/schemas/spans.json
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/bounds.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/config.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/config.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/env.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/event-points.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/event-points.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/events-row.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/http.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/otlp.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/query.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/rpc.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/store-query.test.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/store-query.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/src/worker.ts
Not shown: the change is larger than this page shows. A clone has it.
A core/telemetry-worker/tsconfig.json
Not shown: the change is larger than this page shows. A clone has it.
A package.json
Not shown: the change is larger than this page shows. A clone has it.
A patches/@cloudflare__workers-oauth-provider@1.2.4.patch
Not shown: the change is larger than this page shows. A clone has it.
A patches/zod@4.6.5.patch
Not shown: the change is larger than this page shows. A clone has it.
A pnpm-lock.yaml
Not shown: the change is larger than this page shows. A clone has it.
A pnpm-workspace.yaml
Not shown: the change is larger than this page shows. A clone has it.
A tsconfig.app.json
Not shown: the change is larger than this page shows. A clone has it.
A tsconfig.base.json
Not shown: the change is larger than this page shows. A clone has it.