create-ailk 0.40.1 → 0.40.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (59) hide show
  1. package/README.md +26 -4
  2. package/dist/add-module.d.ts +2 -1
  3. package/dist/add-module.js +17 -1
  4. package/dist/cutover.d.ts +7 -3
  5. package/dist/cutover.js +8 -3
  6. package/dist/lib/declared-env.d.ts +5 -1
  7. package/dist/lib/declared-env.js +6 -1
  8. package/dist/lib/env-catalog.d.ts +3 -2
  9. package/dist/lib/env-catalog.js +4 -8
  10. package/dist/module-architecture.js +0 -1
  11. package/dist/programmatic.js +18 -9
  12. package/dist/remove-module.js +1 -1
  13. package/dist/seam-refresh.d.ts +60 -0
  14. package/dist/seam-refresh.js +214 -0
  15. package/dist/spoke-checkout.d.ts +12 -3
  16. package/dist/spoke-checkout.js +14 -5
  17. package/dist/sync-routes.d.ts +10 -1
  18. package/dist/sync-routes.js +61 -6
  19. package/dist/template-record.d.ts +14 -2
  20. package/dist/template-record.js +60 -22
  21. package/dist/topology.js +3 -4
  22. package/dist/update.d.ts +13 -1
  23. package/dist/update.js +100 -8
  24. package/package.json +3 -3
  25. package/templates/.env.example +6 -0
  26. package/templates/.github/workflows/ci.yml +3 -0
  27. package/templates/apps/api/.env.example +12 -0
  28. package/templates/apps/api/CLAUDE.md +10 -7
  29. package/templates/apps/mcp/CLAUDE.md +25 -5
  30. package/templates/apps/web/.env.example +7 -1
  31. package/templates/apps/web/CLAUDE.md +29 -13
  32. package/templates/apps/web/account.config.tsx +3 -2
  33. package/templates/apps/web/app/[locale]/(authed)/account/connect/__tests__/page.test.tsx +1 -1
  34. package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +10 -3
  35. package/templates/apps/web/app/llms.txt/route.ts +13 -3
  36. package/templates/apps/web/app/openapi.json/__tests__/route.test.ts +15 -7
  37. package/templates/apps/web/auth.config.tsx +2 -0
  38. package/templates/apps/web/auth.ts +28 -4
  39. package/templates/apps/web/jest.config.cjs +1 -1
  40. package/templates/apps/web/lib/__tests__/auth-email.test.ts +21 -0
  41. package/templates/apps/web/lib/__tests__/docs-path.test.ts +20 -2
  42. package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +17 -10
  43. package/templates/apps/web/lib/__tests__/relay.test.ts +127 -12
  44. package/templates/apps/web/lib/__tests__/server-api.test.ts +72 -7
  45. package/templates/apps/web/lib/__tests__/services-path.test.ts +22 -1
  46. package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +33 -5
  47. package/templates/apps/web/lib/auth-email.ts +19 -0
  48. package/templates/apps/web/lib/docs-path.ts +1 -1
  49. package/templates/apps/web/lib/hub-site-config.ts +11 -8
  50. package/templates/apps/web/lib/mcp-oauth.ts +123 -17
  51. package/templates/apps/web/lib/relay.ts +48 -9
  52. package/templates/apps/web/lib/server-api.ts +37 -4
  53. package/templates/apps/web/lib/services-path.ts +1 -1
  54. package/templates/apps/web/lib/site-identity.ts +15 -1
  55. package/templates/apps/web/messages/en.json +10 -8
  56. package/templates/apps/web/middleware.ts +4 -2
  57. package/templates/apps/web/src/lib/routes.ts +13 -0
  58. package/templates/tools/declared-env.ts +6 -1
  59. package/versions.json +51 -51
@@ -214,15 +214,23 @@ authorize step. **The purchase link:** after a paid Offerings session the hub
214
214
  mails "Open your account" to `<spoke>/account?claim=<claim>`; that page's GET
215
215
  changes nothing, and its one "Open my account" button POSTs the claim to
216
216
  `/api/hub-session/open`, which spends it at the hub web's
217
- `POST /api/auth/hub/purchase` and 303s to the hub's verify URL (`409` →
218
- `?error=exists`, anything else → `?error=claim`). `/account/billing` lists the
217
+ `POST /api/auth/hub/purchase`. That route runs the magic-link verify
218
+ in-process (the account and its `sign_up` grant are created as for a
219
+ browser verify), uses the session only to mint this spoke's PKCE-bound code,
220
+ deletes the session and answers `{ code }`, so the spoke's server never holds
221
+ a hub session (#11109); the spoke 303s to its own callback with it (`409
222
+ account_exists` or `consent_required` → `?error=exists`, anything else →
223
+ `?error=claim`). `/account/billing` lists the
219
224
  member's purchases (`member.purchases`, the verified-email join) on such a
220
225
  spoke only. **One Tap** (off by default): `AILK_HUB_ONE_TAP=on` on the spoke
221
226
  and `AILK_GOOGLE_ONE_TAP_CLIENT_ID` on the hub API render the `OneTap`
222
227
  island, which takes a nonce from `/api/hub-session/one-tap/nonce` (a 300 s
223
228
  sealed cookie) and posts Google's credential to `/api/hub-session/one-tap`;
224
229
  the hub verifies it and the route seals the session (`sessionCookieFor`) before
225
- the page moves. `middleware.ts` adds Google's One Tap origins
230
+ the page moves. Because that token reaches the spoke's server, the hub's own
231
+ Better Auth Google provider (here and in the Admin) sets
232
+ `disableIdTokenSignIn: true`: `POST /api/auth/sign-in/social` never accepts a
233
+ raw ID token, whatever its audience (#11109). `middleware.ts` adds Google's One Tap origins
226
234
  (`ONE_TAP_CSP`) to every page's CSP only while that setting is on. Every new
227
235
  spoke route is same-origin only, and every body is `.strict()`: a password is
228
236
  never accepted. `claim` is in both telemetry scrub lists.
@@ -257,11 +265,12 @@ spoke removal seed, so no spoke carries the hub route.
257
265
  **The site is the OAuth 2.1 authorization server an MCP client signs in through (#10357).** `auth.ts`'s block between `// mcp-oauth:begin` and `// mcp-oauth:end` installs better-auth's `mcp` plugin (dynamic client registration, S256 PKCE, one-hour access tokens, seven-day refresh tokens) and AILK's `lib/mcp-oauth.ts` beside it, only when `BETTER_AUTH_URL` pins the issuer. The plugin is configured, never patched: every AILK behaviour is a hook or an endpoint in that file.
258
266
 
259
267
  - **Tokens are opaque, validated by lookup** (decision (a)): no JWKS and no `jwt` plugin. `GET /api/auth/mcp/token-info` is the self-check: the bound workspace, the member-clamped `actingRole` and the grants the person's live role still holds — never a token.
260
- - **Every authorization asks** (decision (b)): a before-hook forces `prompt=consent`, so the plugin always redirects to `/consent` (an `(auth)` page, `AUTH_SEGMENTS`). The page reads only `consent_code` and asks `GET /mcp/consent-details`; Allow posts `POST /mcp/consent`, which binds one `ailk:workspace:<id>` and only role-held `ailk:*` scopes. `/mcp/token` refuses any code that did not pass it or whose approving session has ended, any `code` not shaped like one (so no AILK verification row can be named and consumed), and any non-string body field. The plugin's own `/oauth2/consent`, `/mcp/get-session` and discovery copy are `disabledPaths`; the site serves `/.well-known/oauth-authorization-server` at its root.
261
- - **Rotation and revocation**: a refresh deletes the used pair and leaves a tombstone, so a replayed refresh token ends the person's line for that client. `POST /mcp/revoke` (RFC 7009) and the person's own `POST /mcp/revoke-client` delete tokens.
262
- - **A password reset or change deletes every MCP token** of the person: `onPasswordReset`'s guarded blocks, which end the person's sessions first (so none can mint a token in between) and then their tokens (`reason: "session_revocation_failed"` / `"mcp_token_revocation_failed"` on failure, never a rejection) and an after-hook on `/change-password`.
268
+ - **Every authorization asks** (decision (b)): a before-hook forces `prompt=consent`, so the plugin always redirects to `/consent` (an `(auth)` page, `AUTH_SEGMENTS`) — the plugin never reads the `oauthConsent` row, so a client an admin revoked asks the person again (#10459 D2). The page reads only `consent_code` and asks `GET /mcp/consent-details`; Allow posts `POST /mcp/consent`, which binds one `ailk:workspace:<id>` and only role-held `ailk:*` scopes. `/mcp/token` refuses any code that did not pass it or whose approving session has ended, any `code` not shaped like one (so no AILK verification row can be named and consumed), and any non-string body field. The plugin's own `/oauth2/consent`, `/mcp/get-session` and discovery copy are `disabledPaths`; the site serves `/.well-known/oauth-authorization-server` at its root.
269
+ - **Rotation and revocation**: a refresh deletes the used pair and leaves a tombstone, so a replayed refresh token ends the person's line for that client. A refresh whose used row is already gone when AILK's after-hook reads it — deleted by a revoke, a password change or a second refresh of the same token after the plugin read it — answers `invalid_grant` and its new pair is deleted (#10459 D1). `POST /mcp/revoke` (RFC 7009) and the person's own `POST /mcp/revoke-client` delete tokens.
270
+ - **A password reset or change deletes every MCP token** of the person: `onPasswordReset`'s guarded blocks, which end the person's sessions first (so none can mint a token in between) and then their tokens (`reason: "session_revocation_failed"` / `"mcp_token_revocation_failed"` on failure, never a rejection) and on `/change-password` a before-hook that forces `revokeOtherSessions: true` (the caller gets a new session, every other device is signed out, #10459 D5) and an after-hook that then deletes the tokens.
263
271
  - **One issuer per token (#10912)**: the plugin takes an optional `issuerTag` and `signInLocation`; this site passes neither, so its tokens carry no `ailk:issuer:` entry and its code exchange, refresh and token-info refuse any token or code that carries one. On a hub the Admin runs a byte-identical copy (`packages-paid/admin/lib/mcp-oauth.ts`, a parity test holds it equal) with `issuerTag: "admin"`, so an edit here is an edit there.
264
- - Two plugin facts AILK works around: `/mcp/register` answers a raw `Response`, so no after-hook runs on it (the sweep runs before), and the plugin's `/mcp/token` treats any `oauthApplication.type` but `public` as confidential, so `POST /mcp/consent` re-derives it from the stored secret (`public` for a client with no secret, the column defaulting to `web`).
272
+ - **Registration** is limited to 10 per hour with or without `AILK_AUTH_TRUSTED_PROXIES` — without it a site-wide bucket, the one rule outside the trusted-proxy guard (#10459 D3).
273
+ - Two plugin facts AILK works around: `/mcp/register` answers a raw `Response`, so no after-hook runs on it (the cleanup sweep runs after an accepted `POST /mcp/consent`, in the background, never on the anonymous register — #10459 D4), and the plugin's `/mcp/token` treats any `oauthApplication.type` but `public` as confidential, so `POST /mcp/consent` re-derives it from the stored secret (`public` for a client with no secret, the column defaulting to `web`).
265
274
 
266
275
  ## Contact page
267
276
 
@@ -305,7 +314,8 @@ declares any, else the built-in form, which is the seeded config itself. Any
305
314
  failed read (absent, draft, a Free build with no flow route, a throw) is the
306
315
  fallback, never an error. A magnet-driven post carries a hidden
307
316
  `source: "flow:contact"`, so it is an Inbox submission of the Contact form
308
- with every answer shown; a fallback post is `contact-form` (#8747). The terms statement
317
+ with every answer shown — and, with its Person, a thread in Messages
318
+ (#10943); a fallback post is `contact-form` (#8747). The terms statement
309
319
  links Terms, Privacy Policy and Working Agreement from a page-built
310
320
  `policies` map, and `captureLeadAction` refuses a post without
311
321
  `consent=true` whatever its source (#8730 D2 — the hidden `source` picks the
@@ -709,10 +719,10 @@ What a site that carries `commerce` gets (#8748, #11253); a site without
709
719
 
710
720
  A visitor's browser never calls the hub. Lead capture, newsletter signup, callback, scheduling and the commerce invoice call post to this site's own `/v1/...` address, and `app/v1/[...path]/route.ts` hands each request to `lib/relay.ts` (`handleRelay`), which forwards it server-side through `@working-theory/api-client`'s `relayToApi` with the site's own `AILK_SPOKE_KEY` when it has one (#7644). The browser never holds the key, so a hub can refuse unknown callers (#7633) without taking a site's forms down.
711
721
 
712
- - **Only the list.** `RELAY_ROUTES` is the fixed set of (method, path) pairs: `POST /v1/leads/{submit,subscribe,callback}`, `GET /v1/schedule/availability`, `POST /v1/schedule/book`, `POST /v1/commerce/invoices`. Anything else is a 404 with no hub call. Adding a route is a reviewed change to that list, its test and `.env.example`.
722
+ - **Only the list.** `RELAY_ROUTES` is the fixed set of (method, path) pairs: `POST /v1/leads/{submit,subscribe,callback}`, `GET /v1/schedule/availability`, `POST /v1/schedule/book`, and on a hub only `POST /v1/commerce/invoices` (a spoke answers it 404 with no hub call, #8066). Anything else is a 404 with no hub call. Adding a route is a reviewed change to that list, its test and `.env.example`.
713
723
  - **No cross-site POST.** A `Sec-Fetch-Site` other than `same-origin`, or an `Origin` not on this site's own host, is refused 403 before the hub is called.
714
- - **Headers are an allow-list.** The visitor's `x-forwarded-for` (else `x-real-ip`) and `user-agent` pass through so per-visitor rate limits still count each visitor; no `authorization`, client-sent `x-ailk-*` or `host` is forwarded, and a `cookie` goes only on `POST /v1/commerce/invoices`, the one session route.
715
- - **The relay has its own per-visitor budget (#7707).** Each visitor gets 8 calls per 10 minutes across the five visitor routes, and the session route (`POST /v1/commerce/invoices`) gets its own, wider budget of 30 per 10 minutes; the call that exceeds either gets `429 rate_limited` before any hub call. The budget is held in this instance's own process (no shared store, no env variable) and holds only where the site's edge overwrites `x-forwarded-for` and `x-real-ip` — Vercel does; a bare self-hosted Next server does not.
724
+ - **Headers are an allow-list.** The visitor's `x-forwarded-for` (else `x-real-ip`) and `user-agent` pass through so per-visitor rate limits still count each visitor; no `authorization`, client-sent `x-ailk-*` or `host` is forwarded, and a `cookie` goes only on `POST /v1/commerce/invoices`, the one session route — and there only one of the two Better Auth session cookies the hub reads (`__Secure-better-auth.session_token` first, else `better-auth.session_token`), never a spoke's sealed `__Host-ailk-hub-session` or any other cookie (#8066).
725
+ - **The relay has its own per-visitor budget (#7707).** Each visitor gets 8 calls per 10 minutes across the five visitor routes, and the session route (`POST /v1/commerce/invoices`, a hub only) gets its own, wider budget of 30 per 10 minutes; the call that exceeds either gets `429 rate_limited` before any hub call. The budget is held in this instance's own process (no shared store, no env variable) and holds only where the site's edge overwrites `x-forwarded-for` and `x-real-ip` — Vercel does; a bare self-hosted Next server does not.
716
726
  - **A bot check on the public writes (#9889, #9255).** On Vercel, `lib/bot-check.ts`'s `runBotCheck` asks Vercel BotID for a verdict before the hub is called — in the relay for `POST /v1/leads/{submit,subscribe,callback}` and `POST /v1/schedule/book` (`BOT_CHECKED_ROUTES`: `403 bot_detected`, or `503 bot_check_unavailable` when the check throws, answers no boolean or takes over 5 seconds), and in the contact, careers, newsletter, flow-step, flow-checkout, saved-recommendation and `/dev/purchase` Server Actions immediately before their hub call, which answer their own existing failure variant. The locale layout's `BotIdClient` protects every same-origin POST (`BOT_CLIENT_PROTECT`, `/*`), because a Server Action posts to the page it was submitted from; `next.config.mjs` wraps `withBotId` and `middleware.ts` keeps BotID's proxy prefix out of its matcher. It is on by default and inert off Vercel: `AILK_BOT_CHECK=off` turns every check off, `AILK_BOOKING_BOT_CHECK=off` the booking's alone, and MCP tools never pass through a site, so they are never challenged. A refusal logs `[<source>] bot refused` with BotID's `classificationReason`, `bypassed` and `isVerifiedBot`, the request's `host` and `forwardedHost`, and `proxied` (a `cf-ray` header) — no other header value, no form field (#10715). `AILK_BOT_CHECK=observe` runs the check and logs the same facts plus `isBot` as `observed`, but passes every write — for diagnosis only. **A BotID-protected site must be reached directly — Cloudflare DNS-only, no reverse proxy in front of Vercel (#10715).** Behind a proxy the write reaches Vercel from the proxy's egress rather than the browser that solved the challenge, so BotID refuses every real visitor; the first proxied request per process logs `[<source>] reverse proxy detected` (outcome `proxied`) naming that fix.
717
727
  - `/v1` is exempt from next-intl's locale rewrite in `middleware.ts`, as `/api` is.
718
728
 
@@ -757,7 +767,7 @@ A list page whose frontmatter sets `navOnly: true` (valid on a registry list typ
757
767
 
758
768
  ## A hub-connected site's identity
759
769
 
760
- **A site connected to its hub reads its name, description, legal name, contact, sameAs and indexing switch from the hub (#11456).** Hub-connected means `CONTENT_ADAPTER=database` (the switch `resolveBlogSource` uses) and a spoke key on the wire (`sendsSpokeKey()`); `lib/hub-site-config.ts`'s `readHubSite()` then reads `GET /v1/content/site-config` through `siteConfig.get()` — the key's own workspace's identity and seo rows, 401 to any other caller — cached by `unstable_cache` under `siteConfigTag()` for at most 300 s. Any other site makes no call and renders from `_site.mdx` exactly as before.
770
+ **A site connected to its hub reads its name, description, legal name, contact, sameAs and indexing switch from the hub (#11456).** Hub-connected means a spoke key on the wire (`sendsSpokeKey()`), whatever the content adapter — a site serving file content with a key reads the hub too (#11515); `lib/hub-site-config.ts`'s `readHubSite()` then reads `GET /v1/content/site-config` through `siteConfig.get()` — the key's own workspace's identity and seo rows, 401 to any other caller — cached by `unstable_cache` under `siteConfigTag()` for at most 300 s. A site with no spoke key makes no call and renders from `_site.mdx` exactly as before.
761
771
 
762
772
  - **Who reads it.** `resolveSiteBrand()` (`lib/site-brand.tsx`) gives the locale layout's title, description, og/twitter copy, Nav/Footer `siteName` and copyright holder, and both llms.txt headings; `lib/site-identity.ts` registers a JSON-LD reader (`setSiteIdentityReader`) whose registration keeps the file's `baseUrl`, so no hub value moves an `@id`; the contact email and the closing footer's contact lines read the value the last read resolved (`heldHubSite()`), because their seam is synchronous. `SITE_NAME`'s other readers (og image, icons, auth, mcp.json, ai-plugin.json) keep the file value.
763
773
  - **A hub row is the whole identity.** A field the operator cleared is absent, never refilled from the file; only a missing row, an unreadable one or a failed read falls back to `_site.mdx`. The file's top-level `contactEmail` stays the contact email's fallback. Hub values are collapsed to one line.
@@ -780,7 +790,13 @@ A list page whose frontmatter sets `navOnly: true` (valid on a registry list typ
780
790
  - Don't reach into `apps/api` or `apps/mcp` from `apps/web`. They're peer apps — talk via HTTP/MCP.
781
791
  - Don't commit images to `screenshots/` — only the `.gitkeep` is tracked.
782
792
 
783
- Last updated: 2026-11-11 — § A hub-connected site's identity: the hub read, the brand, JSON-LD reader and contact readers that take it, the `site-config` revalidate event, and `<meta robots>`'s second writer (#11456) — verified against `lib/{hub-site-config.ts,site-brand.tsx,site-identity.ts,site-contact-email.ts,site-contact-lines.ts}`, `app/[locale]/layout.tsx`, `app/llms.txt/route.ts` and `app/api/revalidate/route.ts`.
793
+ Last updated: 2026-11-12 — § The `(auth)` route group: the purchase spend answers this spoke's code, never the hub's verify URL, and the hub's Google provider refuses a raw ID token (#11109) — verified against `packages/auth/src/api/{auth/hub/purchase,hub-session/open}/route.ts` and `auth.ts`.
794
+
795
+ Prior: 2026-11-12 — § The MCP authorization server: a refresh racing a revoke is refused, the forced prompt is what makes a revoked client ask again, `/change-password` signs other devices out, the register limit applies without a trusted proxy, and the sweep runs after an accepted consent (#10459) — verified against `lib/mcp-oauth.ts` and `auth.ts`.
796
+
797
+ Prior: 2026-11-12 — § A hub-connected site's identity: hub-connected is a spoke key on the wire, whatever the content adapter (#11515) — verified against `lib/hub-site-config.ts`.
798
+
799
+ Prior: 2026-11-11 — § A hub-connected site's identity: the hub read, the brand, JSON-LD reader and contact readers that take it, the `site-config` revalidate event, and `<meta robots>`'s second writer (#11456) — verified against `lib/{hub-site-config.ts,site-brand.tsx,site-identity.ts,site-contact-email.ts,site-contact-lines.ts}`, `app/[locale]/layout.tsx`, `app/llms.txt/route.ts` and `app/api/revalidate/route.ts`.
784
800
 
785
801
  Prior: 2026-11-11 — § Where the base pages live: the 63 base pages, their actions, loaders and libs ship in `@working-theory/site-pages`, this app holds their generated route files and `site-pages.config.tsx`, and the ten namespaces ship in the package (#11259) — verified against `packages/site-pages/{routes.json,src/site.ts,src/index.ts}`, `site-pages.config.tsx` and `i18n/request.ts`.
786
802
 
@@ -36,7 +36,7 @@ import { consentVisitorHeader, readConsentVisitor } from "./lib/consent-visitor"
36
36
  import { formatMinorUnits, offeringsCheckoutHref } from "./lib/offerings-pricing";
37
37
  import { readShownOfferings } from "./lib/pricing-page";
38
38
  import { forwardedCookieInit } from "./lib/server-api";
39
- import { SITE_NAME } from "./lib/site-brand";
39
+ import { resolveSiteBrand } from "./lib/site-brand";
40
40
  import { siteBillingSections } from "./lib/site-contributions";
41
41
  import { siteLogo } from "./lib/site-logo";
42
42
  import {
@@ -77,7 +77,8 @@ export const site = {
77
77
  get signOutEndpoint() {
78
78
  return SIGN_OUT_ENDPOINT;
79
79
  },
80
- siteName: SITE_NAME,
80
+ // The hub identity's name when it holds one, else the file's (#11644).
81
+ siteName: async () => (await resolveSiteBrand()).siteName,
81
82
  siteLogo,
82
83
  readSession,
83
84
  readOwnAccounts,
@@ -40,7 +40,7 @@ jest.mock("next-intl/server", () => {
40
40
  jest.mock("next/headers", () => ({
41
41
  __esModule: true,
42
42
  headers: jest.fn().mockResolvedValue(new Headers()),
43
- cookies: jest.fn().mockResolvedValue({ toString: () => "session=abc" }),
43
+ cookies: jest.fn().mockResolvedValue({ toString: () => "better-auth.session_token=abc" }),
44
44
  }));
45
45
 
46
46
  const mockSecret = "k".repeat(43);
@@ -149,8 +149,10 @@ describe("the llms.txt heading — a hub-connected site's name (#11456 D4, AC-2)
149
149
  body: { identity: { kind: "Organization", name, url: "https://elsewhere.example" }, seo: null },
150
150
  });
151
151
 
152
+ // #11515 — hub-connected is a spoke key on the wire alone, so these cases
153
+ // run a file-content site (CONTENT_ADAPTER unset).
152
154
  beforeEach(() => {
153
- process.env.CONTENT_ADAPTER = "database";
155
+ delete process.env.CONTENT_ADAPTER;
154
156
  process.env.NEXT_PUBLIC_BASE_URL = BASE;
155
157
  process.env.AILK_API_URL = "https://hub.example";
156
158
  mockSiteConfigGet.mockReset();
@@ -162,10 +164,11 @@ describe("the llms.txt heading — a hub-connected site's name (#11456 D4, AC-2)
162
164
  delete process.env.AILK_SPOKE_KEY;
163
165
  });
164
166
 
165
- it("carries the hub name on a hub-connected site", async () => {
167
+ it("carries the hub name on a hub-connected site with no CONTENT_ADAPTER", async () => {
166
168
  process.env.AILK_SPOKE_KEY = KEY;
167
169
  mockSiteConfigGet.mockResolvedValue(identity("Hub Co"));
168
170
  expect((await llms("../route", PUBLIC_ROWS)).split("\n")[0]).toBe("# Hub Co — content index");
171
+ expect(mockSiteConfigGet).toHaveBeenCalled();
169
172
  });
170
173
 
171
174
  it("a hub name holding a newline heads llms.txt on one line", async () => {
@@ -176,7 +179,11 @@ describe("the llms.txt heading — a hub-connected site's name (#11456 D4, AC-2)
176
179
  expect(text.split("\n")[1]).toBe("");
177
180
  });
178
181
 
179
- it("carries SITE_NAME on a site that is not hub-connected, and never calls the hub", async () => {
182
+ it.each([
183
+ ["CONTENT_ADAPTER unset", () => undefined],
184
+ ["CONTENT_ADAPTER=database", () => (process.env.CONTENT_ADAPTER = "database")],
185
+ ])("carries SITE_NAME with no AILK_SPOKE_KEY (%s), and never calls the hub", async (_label, arrange) => {
186
+ arrange();
180
187
  mockSiteConfigGet.mockResolvedValue(identity("Hub Co"));
181
188
  const { SITE_NAME } = jest.requireActual<typeof import("../../../lib/site-brand")>("../../../lib/site-brand");
182
189
  expect((await llms("../route", PUBLIC_ROWS)).split("\n")[0]).toBe(`# ${SITE_NAME} — content index`);
@@ -28,6 +28,10 @@
28
28
  *
29
29
  * Blog (#10644 D1): under the database adapter the adapter's `BlogList` /
30
30
  * `BlogPosting` rows are the blog, and `getBlogPages` is not called.
31
+ *
32
+ * Agent contact (#11423): on a site that serves `/contact` (`MARKETING_PAGES`),
33
+ * the body ends with `agentContactLines` — the operator's decision of
34
+ * 2026-11-11 on #11423.
31
35
  */
32
36
 
33
37
  import { siteDiscoverable } from "@working-theory/api-client";
@@ -48,10 +52,10 @@ import {
48
52
  listDocsPages,
49
53
  type DocsIndexPage,
50
54
  } from "../../lib/docs-index";
51
- import { PUBLIC_PAGES } from "../../lib/modules.generated";
55
+ import { MARKETING_PAGES, PUBLIC_PAGES } from "../../lib/modules.generated";
52
56
  import { resolveSiteBrand } from "../../lib/site-brand";
53
57
  import { SITE_LISTING } from "../../lib/site-listing";
54
- import { pagePathFor, resolveBaseUrl } from "../../src/lib/routes";
58
+ import { agentContactLines, pagePathFor, resolveBaseUrl } from "../../src/lib/routes";
55
59
 
56
60
  // #10510 D4 — read per request: the owner's discovery switch is a runtime
57
61
  // setting a prerendered file could never follow.
@@ -77,6 +81,8 @@ export interface LlmsHandlerDeps {
77
81
  discoverable?: () => Promise<boolean>;
78
82
  /** The site's own listing (#10940 D3). Defaults to `SITE_LISTING`. */
79
83
  getSiteListing?: () => SiteListing;
84
+ /** Whether this site serves /contact (#11423). Defaults to `MARKETING_PAGES`. */
85
+ hasContactPage?: () => boolean;
80
86
  }
81
87
 
82
88
  /**
@@ -89,6 +95,7 @@ export function createLlmsHandler(deps: LlmsHandlerDeps = {}) {
89
95
  const resolveDocsPages = deps.getDocsPages ?? listDocsPages;
90
96
  const isDiscoverable = deps.discoverable ?? siteDiscoverable;
91
97
  const resolveSiteListing = deps.getSiteListing ?? (() => SITE_LISTING);
98
+ const resolveHasContactPage = deps.hasContactPage ?? (() => MARKETING_PAGES);
92
99
 
93
100
  return async function llmsGET(): Promise<Response> {
94
101
  // #10040 decision 7 — no public page, no content index: 404 before the adapter.
@@ -97,8 +104,9 @@ export function createLlmsHandler(deps: LlmsHandlerDeps = {}) {
97
104
  if (!(await isDiscoverable())) return new Response(null, { status: 404, headers: { "cache-control": "no-store" } });
98
105
  const adapter = resolveAdapter();
99
106
  const baseUrl = resolveBaseUrl();
107
+ const { siteName } = await resolveSiteBrand();
100
108
  const lines: string[] = [
101
- `# ${(await resolveSiteBrand()).siteName} — content index`,
109
+ `# ${siteName} — content index`,
102
110
  "",
103
111
  ];
104
112
 
@@ -162,6 +170,8 @@ export function createLlmsHandler(deps: LlmsHandlerDeps = {}) {
162
170
  }
163
171
  }
164
172
 
173
+ if (resolveHasContactPage()) lines.push(...agentContactLines(baseUrl, siteName));
174
+
165
175
  return new Response(lines.join("\n"), {
166
176
  status: 200,
167
177
  headers: {
@@ -40,14 +40,22 @@ const { TOPOLOGY: SEAM_TOPOLOGY } = jest.requireActual<
40
40
  // The generated topology seam (#7426 D5), mocked so each case picks its
41
41
  // topology: the hub cases below run against `"hub"`, exactly as before; the
42
42
  // spoke cases (D12) flip it. Mocked rather than imported because the hub
43
- // render imports `../auth`, which this route never touches.
44
- const mockTopology: { value: "hub" | "spoke" } = { value: "hub" };
43
+ // render imports `../auth`, which this route never touches. The factory owns
44
+ // the state because `lib/relay` reads `TOPOLOGY` while it loads (#8066 D2),
45
+ // before a module-scope `const` here would be initialised.
45
46
  // eslint-disable-next-line no-restricted-syntax -- #507: the topology is a generated constant (#7426 D5), not a runtime input; the seam IS the boundary between a hub and a spoke build, and there is no env or HTTP surface that selects it.
46
- jest.mock("../../../lib/topology.generated", () => ({
47
- get TOPOLOGY() {
48
- return mockTopology.value;
49
- },
50
- }));
47
+ jest.mock("../../../lib/topology.generated", () => {
48
+ const state: { value: "hub" | "spoke" } = { value: "hub" };
49
+ return {
50
+ __state: state,
51
+ get TOPOLOGY() {
52
+ return state.value;
53
+ },
54
+ };
55
+ });
56
+ const mockTopology = jest.requireMock<{
57
+ __state: { value: "hub" | "spoke" };
58
+ }>("../../../lib/topology.generated").__state;
51
59
 
52
60
  const SPEC = {
53
61
  openapi: "3.1.0",
@@ -26,6 +26,7 @@ import {
26
26
  confirmSignUpEmail,
27
27
  makeSendAccountOpen,
28
28
  purchaseCapture,
29
+ senderWorkspace,
29
30
  } from "./lib/auth-email";
30
31
  import {
31
32
  getActiveProviderIds,
@@ -102,6 +103,7 @@ export const site = {
102
103
  buildAuthEmailRequest: (payload, secret) =>
103
104
  buildAuthEmailRequest(payload, secret),
104
105
  purchaseCapture,
106
+ senderWorkspace,
105
107
  },
106
108
  },
107
109
  } satisfies AuthSite;
@@ -207,8 +207,9 @@ export const MCP_DISABLED_PATHS = [
207
207
  ];
208
208
 
209
209
  /**
210
- * Rate rules for the anonymous MCP endpoints — applied only beside the other
211
- * custom rules, where the client IP resolves (see the rate-limit block).
210
+ * Rate rules for the anonymous MCP endpoints — applied beside the other
211
+ * custom rules where the client IP resolves; `/mcp/register` alone applies
212
+ * without one too (#10459 D3, see the rate-limit block).
212
213
  */
213
214
  export const MCP_RATE_RULES = {
214
215
  "/mcp/register": { window: 3600, max: 10 },
@@ -364,7 +365,11 @@ interface VerificationStore {
364
365
  }
365
366
 
366
367
  type SocialProviders = {
367
- google?: { clientId: string; clientSecret: string };
368
+ google?: {
369
+ clientId: string;
370
+ clientSecret: string;
371
+ disableIdTokenSignIn?: boolean;
372
+ };
368
373
  github?: { clientId: string; clientSecret: string };
369
374
  };
370
375
 
@@ -376,6 +381,10 @@ function buildSocialProviders(): SocialProviders {
376
381
  providers.google = {
377
382
  clientId: process.env.GOOGLE_CLIENT_ID!,
378
383
  clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
384
+ // #11109: refuse `POST /sign-in/social` with a raw `idToken`. A One Tap
385
+ // token a spoke's server received may carry this same audience, and
386
+ // must never buy a hub session here; sign-in uses the redirect flow.
387
+ disableIdTokenSignIn: true,
379
388
  };
380
389
  }
381
390
 
@@ -971,7 +980,22 @@ export function createAuth(deps: CreateAuthDeps = {}) {
971
980
  ...(baseURL ? MCP_RATE_RULES : {}),
972
981
  },
973
982
  }
974
- : {}),
983
+ : baseURL
984
+ ? {
985
+ // #10459 D3: registration keeps its 10 per hour without a
986
+ // resolvable IP too, and nothing else leaves the guard. Under
987
+ // the shared `no-trusted-ip` bucket this is a site-wide 10
988
+ // registrations an hour, so a caller can hold NEW-client
989
+ // registration closed — accepted, because that is all it
990
+ // denies (every connected client keeps refreshing, revoking
991
+ // and checking under the library defaults), and the
992
+ // alternative is unbounded anonymous row creation. With a
993
+ // single-hop header the key is the caller's claimed address,
994
+ // which a scripted caller rotates. AILK_AUTH_TRUSTED_PROXIES is
995
+ // what makes the limit per visitor.
996
+ customRules: { "/mcp/register": MCP_RATE_RULES["/mcp/register"] },
997
+ }
998
+ : {}),
975
999
  },
976
1000
  // Ids are minted by the DATABASE (ADR-0031): generateId: false makes the
977
1001
  // Prisma adapter omit `id` on insert so the dbgenerated prefixed-UUIDv7
@@ -159,7 +159,7 @@ module.exports = {
159
159
  // from their own install, a second physical copy of each (the #5025
160
160
  // class above), so a test's `jest.mock()` of either would miss them.
161
161
  // Collapse every copy onto the one this app resolves.
162
- "^next/headers$": require.resolve("next/headers"),
162
+ "^next/headers(\\.js)?$": require.resolve("next/headers"),
163
163
  "^better-auth/react$": require.resolve("better-auth/react"),
164
164
  // The dependency-free tenancy-constants subpath (database/tenancy.ts).
165
165
  // Mapped to source like every sibling above; `database/dist` is not
@@ -33,6 +33,7 @@ import {
33
33
  makeSendVerificationEmail,
34
34
  makeSendPasswordChangedNotice,
35
35
  purchaseCapture,
36
+ senderWorkspace,
36
37
  } from "../auth-email";
37
38
 
38
39
  const ORIGINAL_ENV = process.env;
@@ -420,6 +421,26 @@ describe("sendMagicLink — existing users only, deferred (#7435 § D3, AC-2)",
420
421
  expect(serialized).not.toContain("magic-link/verify");
421
422
  });
422
423
 
424
+ it("inside senderWorkspace.run, the payload names the workspace the link is sent for (workspace-email-sender-name)", async () => {
425
+ const send = jest.fn().mockResolvedValue({ ok: true });
426
+ const { log } = makeLog();
427
+ const { ctx, background } = makeCtx({ id: "user_1", email: "person@example.com" });
428
+ const { sendMagicLink } = makeMagicLinkOptions({ send, log });
429
+
430
+ await senderWorkspace.run("wksp_1", () =>
431
+ sendMagicLink({ email: "person@example.com", url: LINK, token: "MLTOKEN" }, ctx),
432
+ );
433
+ await Promise.all(background);
434
+
435
+ expect(JSON.parse(send.mock.calls[0]![0] as string)).toEqual({
436
+ kind: "magic-link",
437
+ userId: "user_1",
438
+ to: "person@example.com",
439
+ url: LINK,
440
+ workspaceId: "wksp_1",
441
+ });
442
+ });
443
+
423
444
  it("never throws, and sends nothing, when the user lookup fails", async () => {
424
445
  const send = jest.fn();
425
446
  const { lines, log } = makeLog();
@@ -125,10 +125,10 @@ describe("docs-path — docsPath /working-theory/docs (AC-2a, AC-2b)", () => {
125
125
  expect(mapped[0]!.flyout!.groups![0]!.items[0]!.path).toBe(
126
126
  "/working-theory/docs",
127
127
  );
128
- expect(mapped[0]!.flyout!.actions[0]!.path).toBe(
128
+ expect(mapped[0]!.flyout!.actions![0]!.path).toBe(
129
129
  "/working-theory/docs/start",
130
130
  );
131
- expect(mapped[0]!.flyout!.actions[0]!.icon).toBe(Icon);
131
+ expect(mapped[0]!.flyout!.actions![0]!.icon).toBe(Icon);
132
132
  expect(mapped[0]!.flyout!.features[0]!.icon).toBe(Icon);
133
133
  expect(mapped[0]!.flyout!.width).toBe("panel");
134
134
  expect(mapped[1]).toEqual({
@@ -144,6 +144,24 @@ describe("docs-path — docsPath /working-theory/docs (AC-2a, AC-2b)", () => {
144
144
  expect(items[1]!.path).toBe("/docs");
145
145
  });
146
146
 
147
+ it("maps a flyout with no actions and adds none (#10047)", () => {
148
+ const items: NavItem[] = [
149
+ {
150
+ labelKey: "resources",
151
+ flyout: {
152
+ features: [{ labelKey: "docs", path: "/docs" }],
153
+ groups: [
154
+ { headingKey: "h", items: [{ labelKey: "docs", path: "/docs" }] },
155
+ ],
156
+ },
157
+ },
158
+ ];
159
+ const flyout = m.withPublicDocsPaths(items)[0]!.flyout!;
160
+ expect(flyout.features[0]!.path).toBe("/working-theory/docs");
161
+ expect(flyout.groups![0]!.items[0]!.path).toBe("/working-theory/docs");
162
+ expect(flyout).not.toHaveProperty("actions");
163
+ });
164
+
147
165
  it("maps footer column items", () => {
148
166
  const cols = [
149
167
  {
@@ -75,7 +75,6 @@ const savedEnv = new Map(ENV_KEYS.map((k) => [k, process.env[k]]));
75
75
  let root: string;
76
76
 
77
77
  function hubConnect(): void {
78
- process.env.CONTENT_ADAPTER = "database";
79
78
  process.env.AILK_SPOKE_KEY = KEY;
80
79
  process.env.AILK_API_URL = "https://hub.example";
81
80
  }
@@ -105,31 +104,39 @@ afterEach(() => {
105
104
  }
106
105
  });
107
106
 
108
- describe("hubConnected (#11456 D3)", () => {
109
- it("is true only with CONTENT_ADAPTER=database and a spoke key on the wire", () => {
107
+ describe("hubConnected (#11456 D3, #11515)", () => {
108
+ it("is true with a spoke key on the wire, whatever the content adapter", () => {
110
109
  expect(hubConnected()).toBe(false);
111
110
  hubConnect();
111
+ expect(process.env.CONTENT_ADAPTER).toBeUndefined();
112
+ expect(hubConnected()).toBe(true);
113
+ process.env.CONTENT_ADAPTER = "database";
112
114
  expect(hubConnected()).toBe(true);
113
115
  delete process.env.AILK_SPOKE_KEY;
114
116
  expect(hubConnected()).toBe(false);
115
- hubConnect();
116
- delete process.env.CONTENT_ADAPTER;
117
- expect(hubConnected()).toBe(false);
118
117
  });
119
118
  });
120
119
 
121
120
  describe("readHubSite (#11456 D3, AC-3)", () => {
122
121
  it.each([
123
- ["no AILK_SPOKE_KEY", () => delete process.env.AILK_SPOKE_KEY],
124
- ["CONTENT_ADAPTER unset", () => delete process.env.CONTENT_ADAPTER],
125
- ])("with %s answers undefined and never calls the hub", async (_label, unset) => {
122
+ ["CONTENT_ADAPTER unset", () => undefined],
123
+ ["CONTENT_ADAPTER=database", () => (process.env.CONTENT_ADAPTER = "database")],
124
+ ])("with no AILK_SPOKE_KEY and %s answers undefined and never calls the hub", async (_label, arrange) => {
126
125
  hubConnect();
127
- unset();
126
+ delete process.env.AILK_SPOKE_KEY;
127
+ arrange();
128
128
  await expect(readHubSite()).resolves.toBeUndefined();
129
129
  expect(mockGet).not.toHaveBeenCalled();
130
130
  expect(mockUnstableCache).not.toHaveBeenCalled();
131
131
  });
132
132
 
133
+ it("with a spoke key and CONTENT_ADAPTER unset reads the hub (#11515)", async () => {
134
+ hubConnect();
135
+ mockGet.mockResolvedValue(ok({ identity: HUB_IDENTITY, seo: HUB_SEO }));
136
+ await expect(readHubSite()).resolves.toEqual({ identity: HUB_IDENTITY, seo: HUB_SEO });
137
+ expect(mockGet).toHaveBeenCalledTimes(1);
138
+ });
139
+
133
140
  it("wraps the read with tags [siteConfigTag()] and revalidate 300, keyed by a digest of the key, never the key", async () => {
134
141
  hubConnect();
135
142
  mockGet.mockResolvedValue(ok({ identity: HUB_IDENTITY, seo: HUB_SEO }));