create-ailk 0.46.5 → 0.47.0
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.
- package/component-catalog.json +90 -7
- package/dist/lib/env-catalog.js +4 -0
- package/package.json +3 -3
- package/templates/apps/api/.env.example +18 -0
- package/templates/apps/api/CLAUDE.md +7 -2
- package/templates/apps/api/src/__tests__/vercel-handler.test.ts +176 -2
- package/templates/apps/api/src/lib/__mocks__/prisma.ts +31 -0
- package/templates/apps/api/src/vercel-handler.ts +32 -2
- package/templates/apps/mcp/.env.example +8 -0
- package/templates/apps/mcp/CLAUDE.md +2 -2
- package/templates/apps/web/CLAUDE.md +31 -3
- package/templates/apps/web/app/[locale]/layout.tsx +98 -37
- package/templates/apps/web/app/llms.txt/__tests__/site-listing.test.ts +13 -3
- package/templates/apps/web/lib/__tests__/grid-read.test.ts +212 -0
- package/templates/apps/web/lib/__tests__/hub-read.test.ts +90 -0
- package/templates/apps/web/lib/__tests__/hub-site-config.test.ts +394 -10
- package/templates/apps/web/lib/__tests__/page-chrome-navigation.test.ts +194 -0
- package/templates/apps/web/lib/__tests__/pricing-page.test.ts +210 -0
- package/templates/apps/web/lib/__tests__/site-identity-feature-list.test.ts +19 -1
- package/templates/apps/web/lib/__tests__/site-navigation.test.ts +288 -0
- package/templates/apps/web/lib/grid-read.ts +115 -0
- package/templates/apps/web/lib/hub-read.ts +35 -0
- package/templates/apps/web/lib/hub-site-config.ts +154 -29
- package/templates/apps/web/lib/in-page-blocks.ts +11 -67
- package/templates/apps/web/lib/in-page-magnet.ts +5 -24
- package/templates/apps/web/lib/page-chrome.ts +70 -3
- package/templates/apps/web/lib/pricing-page.ts +33 -2
- package/templates/apps/web/lib/site-navigation.ts +208 -0
- package/templates/apps/web/next.config.mjs +19 -6
- package/versions.json +51 -51
package/component-catalog.json
CHANGED
|
@@ -11580,8 +11580,95 @@
|
|
|
11580
11580
|
]
|
|
11581
11581
|
}
|
|
11582
11582
|
},
|
|
11583
|
+
"grid": {
|
|
11584
|
+
"oneOf": [
|
|
11585
|
+
{
|
|
11586
|
+
"type": "object",
|
|
11587
|
+
"properties": {
|
|
11588
|
+
"kind": {
|
|
11589
|
+
"type": "string",
|
|
11590
|
+
"const": "capabilities"
|
|
11591
|
+
},
|
|
11592
|
+
"products": {
|
|
11593
|
+
"minItems": 1,
|
|
11594
|
+
"maxItems": 3,
|
|
11595
|
+
"type": "array",
|
|
11596
|
+
"items": {
|
|
11597
|
+
"type": "string",
|
|
11598
|
+
"pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
|
|
11599
|
+
}
|
|
11600
|
+
},
|
|
11601
|
+
"levels": {
|
|
11602
|
+
"minItems": 1,
|
|
11603
|
+
"maxItems": 12,
|
|
11604
|
+
"type": "array",
|
|
11605
|
+
"items": {
|
|
11606
|
+
"type": "string",
|
|
11607
|
+
"pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
|
|
11608
|
+
}
|
|
11609
|
+
},
|
|
11610
|
+
"show": {
|
|
11611
|
+
"type": "string",
|
|
11612
|
+
"enum": [
|
|
11613
|
+
"capabilities",
|
|
11614
|
+
"features"
|
|
11615
|
+
]
|
|
11616
|
+
}
|
|
11617
|
+
},
|
|
11618
|
+
"required": [
|
|
11619
|
+
"kind",
|
|
11620
|
+
"products",
|
|
11621
|
+
"show"
|
|
11622
|
+
],
|
|
11623
|
+
"additionalProperties": false
|
|
11624
|
+
},
|
|
11625
|
+
{
|
|
11626
|
+
"type": "object",
|
|
11627
|
+
"properties": {
|
|
11628
|
+
"kind": {
|
|
11629
|
+
"type": "string",
|
|
11630
|
+
"const": "alternatives"
|
|
11631
|
+
},
|
|
11632
|
+
"category": {
|
|
11633
|
+
"type": "string",
|
|
11634
|
+
"pattern": "^[a-z0-9](?:[a-z0-9-]{0,118}[a-z0-9])?$"
|
|
11635
|
+
},
|
|
11636
|
+
"ours": {
|
|
11637
|
+
"type": "string",
|
|
11638
|
+
"pattern": "^[a-z0-9][a-z0-9-]{0,39}$"
|
|
11639
|
+
},
|
|
11640
|
+
"columns": {
|
|
11641
|
+
"minItems": 1,
|
|
11642
|
+
"maxItems": 12,
|
|
11643
|
+
"type": "array",
|
|
11644
|
+
"items": {
|
|
11645
|
+
"type": "string",
|
|
11646
|
+
"pattern": "^[a-z0-9](?:[a-z0-9-]{0,118}[a-z0-9])?$"
|
|
11647
|
+
}
|
|
11648
|
+
},
|
|
11649
|
+
"show": {
|
|
11650
|
+
"type": "string",
|
|
11651
|
+
"enum": [
|
|
11652
|
+
"capabilities",
|
|
11653
|
+
"features"
|
|
11654
|
+
]
|
|
11655
|
+
},
|
|
11656
|
+
"source": {
|
|
11657
|
+
"type": "boolean",
|
|
11658
|
+
"const": true
|
|
11659
|
+
}
|
|
11660
|
+
},
|
|
11661
|
+
"required": [
|
|
11662
|
+
"kind",
|
|
11663
|
+
"category",
|
|
11664
|
+
"show"
|
|
11665
|
+
],
|
|
11666
|
+
"additionalProperties": false
|
|
11667
|
+
}
|
|
11668
|
+
]
|
|
11669
|
+
},
|
|
11583
11670
|
"columns": {
|
|
11584
|
-
"
|
|
11671
|
+
"default": [],
|
|
11585
11672
|
"type": "array",
|
|
11586
11673
|
"items": {
|
|
11587
11674
|
"type": "object",
|
|
@@ -11606,7 +11693,7 @@
|
|
|
11606
11693
|
}
|
|
11607
11694
|
},
|
|
11608
11695
|
"groups": {
|
|
11609
|
-
"
|
|
11696
|
+
"default": [],
|
|
11610
11697
|
"type": "array",
|
|
11611
11698
|
"items": {
|
|
11612
11699
|
"type": "object",
|
|
@@ -11842,11 +11929,7 @@
|
|
|
11842
11929
|
"ink"
|
|
11843
11930
|
]
|
|
11844
11931
|
}
|
|
11845
|
-
}
|
|
11846
|
-
"required": [
|
|
11847
|
-
"columns",
|
|
11848
|
-
"groups"
|
|
11849
|
-
]
|
|
11932
|
+
}
|
|
11850
11933
|
},
|
|
11851
11934
|
"schemaError": null,
|
|
11852
11935
|
"look": [
|
package/dist/lib/env-catalog.js
CHANGED
|
@@ -7,6 +7,10 @@ export const ENV_CATALOG = {
|
|
|
7
7
|
description: "The hub API origin this site's server calls (forms, flows, listings). Server-only; never NEXT_PUBLIC_.",
|
|
8
8
|
secret: false,
|
|
9
9
|
},
|
|
10
|
+
AILK_PUBLIC_API_URL: {
|
|
11
|
+
description: "The hub API's own public origin. A hub's MCP server resolves stored images onto it; unset leaves stored images out of its reads.",
|
|
12
|
+
secret: false,
|
|
13
|
+
},
|
|
10
14
|
AILK_AUTH_PASSWORD_RESET: {
|
|
11
15
|
description: 'Set to "1" or "true" to offer password reset once the server-side reset flow is wired.',
|
|
12
16
|
secret: false,
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "create-ailk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.47.0",
|
|
4
4
|
"description": "Scaffolder for AI Launch Kit — `pnpm create ailk@latest <dir>` produces a starter repo consuming @working-theory/* from npm (per ADR 0007).",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"main": "./dist/index.js",
|
|
@@ -28,8 +28,8 @@
|
|
|
28
28
|
"tar": "^7.5.21"
|
|
29
29
|
},
|
|
30
30
|
"devDependencies": {
|
|
31
|
-
"@working-theory/schema": "0.
|
|
32
|
-
"@working-theory/templates": "0.
|
|
31
|
+
"@working-theory/schema": "0.81.0",
|
|
32
|
+
"@working-theory/templates": "0.81.0"
|
|
33
33
|
},
|
|
34
34
|
"repository": {
|
|
35
35
|
"type": "git",
|
|
@@ -301,3 +301,21 @@ STRIPE_WEBHOOK_SECRET=whsec_xxx
|
|
|
301
301
|
# unknown_site_key, which is the correct closed default but gives no clue at
|
|
302
302
|
# boot — so set this if the deployment accepts listings.
|
|
303
303
|
# AILK_LISTING_PUBLIC_KEY=
|
|
304
|
+
|
|
305
|
+
# --- Asset file storage (#12428) ---
|
|
306
|
+
# Where the workspace asset store keeps its files. Chosen once per process:
|
|
307
|
+
# - both store tokens set → Vercel Blob, one public and one private store
|
|
308
|
+
# - neither, AILK_ASSET_DIR set (not production) → a local folder
|
|
309
|
+
# - otherwise → the database rows, as before the move
|
|
310
|
+
# One token without the other is a misconfiguration: the hub keeps the
|
|
311
|
+
# database and logs `asset-files.misconfigured` once. The tokens are the
|
|
312
|
+
# read-write tokens Vercel writes when the hub's two stores are connected to the
|
|
313
|
+
# API project's PRODUCTION environment with the prefixes ASSETS_PUBLIC_BLOB and
|
|
314
|
+
# ASSETS_PRIVATE_BLOB (runbook: docs/internal/runbooks/asset-file-move.md). A
|
|
315
|
+
# hub not on Vercel sets the same two names. Never set them on a preview, the
|
|
316
|
+
# Admin or a site.
|
|
317
|
+
# ASSETS_PUBLIC_BLOB_READ_WRITE_TOKEN=
|
|
318
|
+
# ASSETS_PRIVATE_BLOB_READ_WRITE_TOKEN=
|
|
319
|
+
#
|
|
320
|
+
# A development hub keeps files in a folder, so nothing needs a live store.
|
|
321
|
+
# AILK_ASSET_DIR=./.data/assets
|
|
@@ -104,6 +104,7 @@ Routes are versioned under `/v1/*`:
|
|
|
104
104
|
- `/v1/workspaces/:workspaceId/content` (GET, POST), `/v1/workspaces/:workspaceId/content/:type/:slug` (GET, PATCH), `/v1/workspaces/:workspaceId/content/:type/:slug/{publish,unpublish}` (POST) — the tenant-guarded content editor's write surface (#5853, `src/routes/workspaces/content.ts`): list, create, read/save the draft tip (under `X-Draft-Version`; `If-Match` still accepted for one release, #10264), and publish/unpublish, all over `Artifact`/`ArtifactVersion`. `:type` is validated against the page-type registry (`z.enum(SCHEMA_ORG_TYPES)`) rather than accepted as a free string on every addressed operation — an unregistered type is a 400 before any lookup, since it is echoed back and passed to `notifyRevalidate` as the site's cache tag. Role floors from `@working-theory/validation`'s permission table (#7636 D2): publish and unpublish need `content-publish`, and create, read and save need `content-edit` (both owner, admin — an admin builds, a member operates). The list serves `content-edit` the editor's full view and a caller holding only `docs-read` (a member) a published-only projection (D4): draft rows dropped, every row `status: "published"`, `version: null`, `valid: true`, and a `published_with_draft` page's `type`/`tags` read from its PUBLISHED version — applied before every filter, so a member's `?status=draft` or a draft tip's `?tag=` matches nothing. **The GET list is a UNION of page artifacts and DOCUMENT assets** (#6093, D1/D9 — "one store, two views"): every row carries `tags: string[]` (never null, read from the draft tip's stored content for a page, from `Asset.tags` for a file) and a DERIVED `kind: "page" | "post" | "file"` (`BlogPosting` alone maps to `"post"`; an asset row is always `"file"`) — an optional `?tag=<slug>` filters the union AFTER it is built, so a file is returned under either its own tag or a shared one. The asset half of the union (`DOCUMENT_CONTENT_TYPES`, i.e. `application/pdf`) is skipped entirely when `locale`/`type` is supplied or `status` names anything but `"published"`, since a file row can never satisfy those. A foreign `:workspaceId` costs zero artifact **and** zero asset queries. MCP parity: on `/mcp/workspace`, the create's twin is `create_page` (#10956), the draft read and save are `read_report` and `save_draft` (#10336), and the publish is `publish_draft` (#10661); the list and unpublish have none, as `tests/parity/README.md` and the registry record. `POST /v1/workspaces/:workspaceId/documents/save` (#11811) saves a `Document` — agent context or a plugin-owned document — in the common shape, its address in the body as `POST …/assets/save`'s is: `content-edit` is checked before the body (an agent without it `403 agent_refused`, audited), `version: null` creates and a version edits under a compare-and-swap on the tip, a moved tip or a `null` on an existing document is `409 stale` with `currentVersion`, and a wrong field or word — a plugin contract's misfit included — is `422 invalid` with each issue's path; it never publishes. Its twin is `save_document`; the page save (`PUT …/content/:type/:slug`, `save_page`) also takes an editorial page, whose words are `{ body }`, carrying its stored layout forward. While both ways live, `create_page`, `save_draft` and `save_structure` say they are deprecated. `GET /v1/workspaces/:workspaceId/content/:type/:slug/open?locale=&as=` (#11808, #11882) opens a page laid out in sections as the page envelope: `content-edit` is checked before the query or any read, `as` is `record` (the default: its `fields` and its `words`, the stored layout with the body's words applied) or `working-copy` (a `workingCopy`, `{ document, settings }`, in their place) — `form` is its old name, answered until the release after #11882, and the two sent with different values are `422 invalid` at `as` — a type not laid out in sections is `422 invalid` at `address.type` (a `Document` naming `open_document`), a missing page — or one the caller may not read — a blank built in memory and never stored (#11809): `version` and `structureToken` `null`, `state: "draft"`, `report: null`, `fields: {}` and its template's starting sections headed by the slug, in the shape asked for, a page not in the section form, or whose body's words do not apply cleanly to its layout, `409 not_outlined`, and a page whose working copy would lose a value or exceed the working copy's bounds `409 not_representable` with each issue's path; it never writes or audits, and is limited to 60 calls a minute per workspace. Its twin is `open_page`.
|
|
105
105
|
- `/v1/workspaces/:workspaceId/library/pages` (GET, `?type=&status=&limit=&page=`) and `/v1/workspaces/:workspaceId/library/assets` (GET, `?tag=&type=&limit=&page=`) — the library reads, each answering `{ workspace: { id, name }, items, total, page, nextPage }` newest first (`limit` 1–200, default 50; `page` from 1; `libraryPageListQuerySchema` / `libraryAssetListQuerySchema` in `@working-theory/validation`). The page list (`packages-paid/api-content-write/src/routes/workspaces/library-pages.ts`, in the content-write tenant scope) serves every page, drafts included, as `{ id, type, slug, locale, title, status, updatedAt }`; `status` is the Docs list's rule — `disabled` when switched off, else `live` when a version is published (a newer draft included), else `draft` — and the route needs `content-edit` (`allows`, so an agent needs the grant). A disabled page is asked for only on a person's behalf: `tenantDb` keeps every disabled row from an agent. The asset list (`packages-paid/api-workspace/src/routes/assets/manage.ts`, beside the manage list, `assets-read`) serves each file's whole record (#11801), `{ id, key, filename, title, description, version, type, size, dimensions, audience, tags, url, updatedAt }` — `title` and `description` with hidden code points removed (`null` when none is written, never left out), `version` the file's record version (`r<n>`, #11803), `type` the content type, `size` its bytes, `dimensions` a raster image's `{ width, height }` as the Admin's Details panel shows it — read from the head of the file — the few bytes a PNG, GIF or WebP needs, at most 64 KiB for a JPEG or AVIF (`tenantDb.assets.fileHeads`, which never reads a private, Knowledge or disabled file) for the answered page's images alone, a JPEG's Exif and an AVIF's `irot` quarter-turn swapping the two (`routes/assets/dimensions.ts`) — and `null` for an SVG, any other file, or a header that does not say, `audience` who may read it, `url` the public read's path, `updatedAt` when the current file was uploaded — the `createdAt` of the version `currentVersion` names (`tenantDb.assets.currentVersionTimes`), so a replace moves it, a restore takes the restored version's upload time, and a metadata edit does not move it; the list is ordered by it, newest first — narrowed by an exact `tag` and a `type` that is a whole content type (`image/png`) or its top-level part (`image`); a file tagged `private` never lists, `?tag=private` included. MCP parity: `list_workspace_pages` and `list_assets` on `/mcp/workspace`.
|
|
106
106
|
- `/v1/workspaces/:workspaceId/assets/save` (POST, #11803) — save a file's title, description and type: the body is `assetSaveBodySchema` (`{ address: { key }, version: "r<n>" | null, words: { title?, description? }, fields?: { type? } }`, strict at every level; `fields.type` (#11879) is one of the ten asset types and replaces the one the file held, every other tag kept; a type-only save sends `words: {}`), and the answer `{ kind: "asset", address, version, fields: { type }, words, state: "live" }` with the new record version. `assets-write` (`allows`, so an agent may hold it by grant) before the body is read; a wrong body is `422 invalid` with `details.issues` (`{ path, message }`, at most 20); a file the caller may not reach — for an agent also a disabled, private or Knowledge one — the plugin's one `404 not_found`; a save based on another record version, or on `null`, `409 stale` with `details.currentVersion`. One conditional UPDATE (`tenantDb.assets.saveRecord`) writes only `title`, `description`, the type tag and `record_version`, whose `where` carries the version and the reach — and, with a type, the tags it read, so a concurrent tags write reruns it. Every agent call that reaches the body is audited (`assets.save`). An agent's `PATCH …/assets/:assetId` is refused `403 agent_refused`; a person's PATCH of a title or description moves the record version. MCP parity: `save_asset` on `/mcp/workspace`.
|
|
107
|
+
- `/v1/workspaces/:workspaceId/assets/from-url` (POST, #12418; `packages-paid/api-workspace/src/routes/assets/from-url.ts`, registered by `workspaceAssetManageRoutes`, so it shares that plugin's tenant scope and JSON body) — the fetch door: the hub fetches an image from a public `https` address an agent or a person sends and stores it as a NEW public file. The body is `assetFromUrlBodySchema` (`{ url, key, type, title? }`, strict; `url` `https:` with no user name, at most 2,048 characters; `type` one of the ten). Order: `assets-write` (`allows`) before the body; the per-minute limits (`chargeWriteBudget` scope `asset-from-url`, fail closed: 10 per caller keyed as `language.ts` keys its writes, 30 per workspace, `429 rate_limited`; the store unable to count `503 fetch_unavailable`); the body (`422 invalid` with `details.issues`); the key (`tenantDb.assets.keyTaken`, then the Live-page scan — `403 agent_refused` for an agent, `409 key_taken` for a person); the daily cap from the workspace's own rows (`tenantDb.assets.fetchedSince`: 200 files or 500 MB, `429 fetch_quota`); four fetches per process and two per workspace per 10 seconds (`503 fetch_busy`); 400 starts a day (`429 fetch_quota`); then the fetch — every hop's name, every address it resolves to through c-ares (never `dns.lookup`) and the address its socket dials, checked before TLS; at most three redirects; `200`, a raster type proven by its signature, `identity`-encoded, within `assetUploadLimit` and 10 seconds — its metadata stripped to an allowlist without re-encoding and its pixel size bounded; the page scan again; and the write through #12428's seam (`blob`: written with `ttlDays: 1`, recorded with `replace({ createOnly: true, type, title, sourceUrl })`, kept only after the record commits). A refusal answers its own code (`fetch_not_public`, `fetch_bad_redirect`, `fetch_too_many_redirects`, `fetch_type_refused`, `fetch_type_mismatch`, `fetch_image_refused`, `fetch_too_large`, `fetch_unreachable`, `fetch_bad_status`, `fetch_timed_out`) and stores nothing; success is `201` with the open envelope plus `file: { url, contentType, size, version }`. No log line carries the address, its host, the key or the title. `GET …/assets/open` answers `source`, the address the file's first version was fetched from (origin and path only), `null` for an upload. MCP parity: `create_asset_from_url` on `/mcp/workspace`.
|
|
107
108
|
- `/v1/workspaces/:workspaceId/overview` (GET) — the workspace overview (#11806; `packages-paid/api-content-write/src/routes/workspaces/workspace-overview.ts`, in the content-write tenant scope beside the knowledge-base reads), any tenant of the workspace; any query key is 400 `validation_failed` (`Invalid query`, the key never echoed). It answers `{ site: { name, description, defaultLocale }, knowledge: { documents, complete }, language: { term, faq, topic, proof }, magnets: { draft, live }, withheld: [{ part, reason }] }`, each part by the code and under the gate of the read it replaces: the identity and SEO blobs (any tenant), `addressLocale(undefined)`, the knowledge list's own rows for `context: "knowledge"` (`docs-read`, at the list's reading role) with `version` — the draft tip's id — only where `content-edit` holds and the caller's own role reads the doc's audience, the Language count per kind (`docs-read`, at the caller's own role, one `groupBy`, no cap), and the magnet count per state through `magnetListView` (`draft` only for `magnets-manage`; the part needs `multi-tenant` or `signal-collectors`). A part the caller may not read is `null` (or, for `version` and `draft`, absent) and named in `withheld` with reason `grant` or `module` — never a refusal of the read. At most six queries in one `Promise.all`; the answer is re-parsed against `workspaceOverviewSchemaFor` (a version or draft count the caller may not see is a 500, never a leak); `Cache-Control: private, no-store`; an agent read logs one `agent_read` line, and the knowledge or Language part withheld for its grant one `denied_read` line each, naming the `part`, none naming a document. MCP parity: `get_workspace_overview` on `/mcp/workspace`.
|
|
108
109
|
- `/v1/workspaces/:workspaceId/documents/open` (`?type=Document&slug=&locale=&as=`, #11808 #11853 #11882 — `as` is `record` or, at a plugin-owned address only, `working-copy`, else `422 invalid` at the key sent; `form` is its old name, as the page open's), `/v1/workspaces/:workspaceId/language/:kind/:slug/open` (`?locale=`) and `/v1/workspaces/:workspaceId/assets/open` (`?key=`) (all GET; the latter two #11809) — open a document, a Language item or a file's record under the common names, beside `open_page`'s route (#11808): each sits beside the read it parallels and takes that read's gate (`content-edit`, `docs-read`, `assets-read`) before any store read, and answers the thing in the common envelope with the `version` its save takes. Nothing at the address — or a thing the caller's read could not see — answers a blank built in memory and never stored: `version: null`, `state: "draft"` and the kind's starting layout (a contract document's `contract`/`contract_version` and required headings, an item's empty words); a file is never blank (`404 not_found`, under the reach `save_asset` gives an agent, for every caller). No open writes or audits. MCP parity: `open_document`, `open_language_item` and `open_asset` on `/mcp/workspace`.
|
|
109
110
|
- `/v1/workspaces/:workspaceId/page-types` (GET) and `/v1/workspaces/:workspaceId/tag-vocabulary` (GET) — the site-vocabulary reads (#11680; `packages-paid/api-content-write/src/routes/workspaces/site-vocabulary.ts`, in the content-write tenant scope), any tenant of the workspace, no query, no row read. `page-types` answers `{ types: [{ type, route, fixed, template, headings }] }`: every page-type registry entry that is a page, in registry order, with its template's headings as `PAGE_TEMPLATES` states them (`key`, `text`, `required`, `section`, `hint`), filtered per request by the module map `pageTypeModule` in `@working-theory/validation` (the one create-ailk's page-types reference generator reads): `marketing` types always, `scheduling` and `signal-collectors` types when `isModuleEnabled`, and `docs-blog` types when `AILK_ENABLED_MODULES` names `docs-blog` — a site that carries the blog and docs sets that key, since `docs-blog` has no API module. `tag-vocabulary` answers `tagVocabulary()`: `{ classes, topics, status }`, each a list of `{ tag, means, setBy }`. MCP parity: `list_page_types` and `get_tag_vocabulary` on `/mcp/workspace`.
|
|
@@ -111,7 +112,7 @@ Routes are versioned under `/v1/*`:
|
|
|
111
112
|
- `/v1/workspaces/:workspaceId/kinds` (GET) — the kinds read (#11805; the same file and scope), any tenant of the workspace, no query, no row read. It answers `listKinds(request.tenant, isModuleEnabled)` from `@working-theory/metadata`: `{ kinds: [{ kind, address, fields, moreFields, sectionTypes, states, moves }] }`, one entry per kind of `ADMIN_KIND_REGISTRY` (`@working-theory/validation`) — page, document, language_item, magnet, asset — whose address, fields and states are read off that kind's own schemas, and whose `moves` are the catalog rows tagged with the kind, kept only when the row's gate holds for the CLAMPED tenant the guard built (never an agent's stored grants or a token's raw scopes) and one of its modules runs on this hub; a page's `sectionTypes` names `list_section_types` rather than repeating it. Beside `kinds` (#11878) it answers `forms` (`[{ kind, field, values }]` — each kind's form field and its values, read off that field's own schema through `KIND_FORMS`, then an offering's `ailkGroup` and an appointment with no form), `offSiteForms` (`[{ form, formats }]`), `formats` and `origins`, all from `adminKinds()` and the same for every caller and hub. Advice, never an entitlement: no write path may gate on it. MCP parity: `list_kinds` on `/mcp/workspace`.
|
|
112
113
|
- `/v1/workspaces/:workspaceId/assets` (GET, POST), `/v1/workspaces/:workspaceId/assets/:assetId` (PATCH, DELETE), `/v1/assets/:assetId` (GET, public/anonymous) — the workspace asset store (#5854 upload/read; #6093 list/PATCH/DELETE, `src/routes/assets/{index,upload,read,manage}.ts`). Upload accepts an allowlisted union of three named classes (`src/routes/assets/index.ts`): five RASTER images (`image/png`, `image/jpeg`, `image/gif`, `image/webp`, `image/avif`), one VECTOR image (`image/svg+xml`, admitted under the operator's 2026-09-18 `allow-svg-assets` ruling — issue #6093 comment `5731573595` — superseding #5854's original SVG exclusion) and one DOCUMENT type (`application/pdf`), all under the existing 20 MB cap; `?tags=<slug>[,<slug>…]` stores tags on the row. The public read serves a RASTER type `inline` exactly as before; every OTHER admitted type (SVG, PDF) is served `attachment`, with the filename's extension pinned to the stored content type (closing extension spoofing) and a five-directive `Content-Security-Policy` (`default-src 'none'; sandbox; frame-ancestors 'none'; form-action 'none'; base-uri 'none'`) that makes the bytes never a document on this origin — this is what makes admitting SVG safe with NO server-side sanitizer. `GET …/assets` (`assets-read` — every role, a member included) lists a workspace's assets, metadata only, never `bytes`, with an optional `?tag=<slug>` filter; this is what narrows the store's prior "nothing lists assets" premise to its precise form — no ANONYMOUS and no CROSS-TENANT enumeration, both still true. `PATCH …/assets/:assetId` updates `title`/`description`/`tags` (`assets-write`, owner and admin, the upload's permission too; `null` clears a text field to SQL `NULL`, `""` stores empty; the asset's `id` and public URL are untouched). `DELETE …/assets/:assetId` (`assets-write`) removes the row and the bytes at the ORIGIN only — already-cached copies elsewhere are not recallable under the year-long `immutable` promise, and no reference check protects a page that still embeds the URL; absent and foreign ids both take the same 404. Every tenant route here is identity-bound; no MCP twin (#3591 exception). The public read has no MCP twin either — it serves bytes to an `<img>`/download, the same boundary `upload.ts` records for its own sibling. **A client's file is never in the library's public life (#7877 D18):** the default `GET …/assets` listing leaves out every asset tagged `private` — only `?tag=private` lists them (the Admin's Compose) — and the public read answers its uniform 404 for an asset tagged `private`, attached to any member-area message, or (#8171 D3) named by a delivered piece version (one `pieceVersion.count`, since the tag can be removed after delivery), so such a file's bytes are served only by its owner's member reads.
|
|
113
114
|
- `/v1/subscription/me` (GET) — `?include=billing` (#8171 D7), from a cookie session only, adds the optional `planName` and `paymentMethod` (brand, last four, expiry) read from Stripe through `lib/stripe.ts`'s `readCustomerBillingSummary` for the caller's own resolved customer: cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure leaves both keys absent, a value outside the schema's bounds is `null`, and no id is served or logged. A bearer token, another value or none answers exactly as before.
|
|
114
|
-
- `/v1/billing` (GET), `/v1/billing/portal-session` (POST) — org-scoped billing read + Stripe customer-portal session creation. The read stays open to every member (the Admin's plan gate reads it); the portal needs `billing-manage` — the owner alone (`@working-theory/validation`'s permission table (#7636 D2); an admin is refused before any Stripe call). `/v1/billing/usage` (GET) needs `billing-read` (owner, admin). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. **The same gate adds `plugins` (#12009 D2, `routes/billing/plugin-billing.ts`):** the Organization's workspaces (`{ id, name }`, `readOrgWorkspaces`) and one row per plugin in `PLUGIN_IDS` order — `has` (the workspaces `workspaceHasPlugin` answers yes for), `billingReasons` (the union of their reasons, in `PLUGIN_REASONS` order; Billing is the reason's one reader, guarded by `plugin-entitlement-confinement.test.ts`), `bought` (the workspaces on the Organization's active `PluginPurchase` rows, by interval — what their subscriptions bill), `prices` (integer US cents from `services/entitlements.ts`'s `readPluginCatalogue`, the entitlements service's catalogue read on #12001's call, cached 60 s; `null` for growth-ops, an unsold plugin, a placeholder or non-`usd` price, or an unread catalogue — never a fallback) and `forSale` (a shown price, a Stripe customer, the commerce claim `claimed` and a registered grant writer — `services/plugin-purchases.ts`'s `pluginGrantWriter()`, which only the hub's licensing module registers, so a hub without it sells nothing). A failed plugin read leaves the key out and logs `plugins_unavailable`; the rest of the answer stands. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), on the admitted key like the portal (#8463). **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/plugin-checkout` (#12009 D5, `routes/billing/plugin-checkout.ts`)** is the Billing tab's "+ Add" on a plugin row: a subscription Checkout for one plugin at one interval (`year` or `month`), one unit per chosen workspace, on the Organization's own bound customer. Check order: tenant → `billing-manage` (403 before any read) → write budget (scope `plugincheckout`, 10 an hour per Organization and per person) → the commerce claim → a strict `{ plugin, interval, workspaceIds (1–50, distinct), returnUrl }` → plan-checkout's own return-URL rule (`isAcceptableReturnUrl`) → a registered grant writer (`409 purchase_unavailable`) → a bound customer (`409 billing_customer_missing` — no plugin before the plan) → the catalogue (`503 catalogue_unavailable` on an unread one; `409 plugin_not_for_sale` for growth-ops, an unsold plugin or a placeholder price) → the workspaces (each a `wksp_` id of the caller's own Organization, else `400 workspace_refused`; a failed entitlement read for any of them, `503 entitlement_unavailable` — `workspaceHasPluginForSale`, which fails closed where `workspaceHasPlugin` answers no; one it answers yes for, or an active purchase of the plugin names, `409 plugin_already_added`) → the admitted Stripe key → one open Checkout per workspace, from one read of the plugin's `created` and `active` purchases (one confirmed since the step before, `active`, naming a chosen workspace answers `409 plugin_already_added`; an earlier `created` one is expired and ended; a completed one answers `409 purchase_pending`) → `createCheckoutSession` at the catalogue's lookup key with `quantity` equal to the workspace count, no `adjustableQuantity`, `metadata` and `subscriptionMetadata` `{ organizationId, ailk_plugin, ...siteStamp() }`, and a `refusePrice` that refuses any Price whose `unit_amount`, currency or interval is not the catalogue's, or that is not billed per unit, once per interval, with no quantity transform (`500 plugin_price_mismatch`) → a Checkout URL only → the session recorded as a `PluginPurchase` with the Price id `refusePrice` accepted (`state: created`; no accepted Price, or a failed write, expires the session and answers 502) → no rival recorded or confirmed meanwhile for a chosen workspace (else the new session is expired and ended: `409 purchase_pending` for a `created` rival, `409 plugin_already_added` for an `active` one; a recheck that cannot be read does the same and answers 502). **The webhook's plugin path (#12009 D9, `services/plugin-purchases.ts` `fulfilPluginEvent`)** runs once after the site filter and before the `switch`, and only on a hub with billing's grant writer: for a `checkout.session.completed`, `customer.subscription.*`, `invoice.paid` or `invoice.payment_failed` whose object carries the `ailk_plugin` stamp (`PLUGIN_SUBSCRIPTION_METADATA_KEY` — a filter only, never a grant) it traces the event's subscription to a recorded purchase (bound, or by `checkout.sessions.list` and a once-only bind), re-reads the subscription from Stripe, stores `state` and `exp` (the item's `current_period_end` while `active` or `trialing` and still paying for the record — quantity at least the recorded workspaces, the recorded Price and interval, collection not paused — else now; `ended_at` or now, `state: ended`, when `canceled` or `incomplete_expired`; nothing while `incomplete`; now otherwise — no grace), and writes one `add_on` grant per workspace with the latest `exp` among the purchases covering it and that purchase's subscription. It never throws, an untraced subscription grants nothing, and no grant is written without an `exp`. When a read or a grant write fails (Stripe, the database or entitlements down) it answers `"retry"`: the webhook un-marks the event (`unmarkSeen`) and answers `503`, before any arm of the `switch` runs, so Stripe redelivers it and the idempotent path re-derives every grant.
|
|
115
|
+
- `/v1/billing` (GET), `/v1/billing/portal-session` (POST) — org-scoped billing read + Stripe customer-portal session creation. The read stays open to every member (the Admin's plan gate reads it); the portal needs `billing-manage` — the owner alone (`@working-theory/validation`'s permission table (#7636 D2); an admin is refused before any Stripe call). `/v1/billing/usage` (GET) needs `billing-read` (owner, admin). **The read's `commerce` field (#8907 D14)** is the deployment's commerce claim, `claimed | unclaimed | undetermined` (`resolveCommerceClaim()`; a rejected read is `undetermined` and the answer stays `200`) — what the Admin's Billing card reads (#8908 D10). **`?include=billing` (#9067 D1)** — exactly that string, never an array — adds `details` only for a caller holding `billing-manage` (the owner; an agent never qualifies): `licenseExpiresAt` (`checkLicense().expiresAt`, `null` on a failed read) always, and for an Organization with a Stripe customer `renewsAt` (the current subscription's first item's `current_period_end`, only while it will renew), `sites` (its quantity) and `paymentMethod` (brand, last four, expiry), read through `lib/stripe.ts`'s `readCustomerBillingSummary` by `services/entitlements.ts`'s `readOrgBillingSummary` — cached per customer for 60 s (a failure too), one read in flight per customer, bounded at 3 s; a failure answers `details: { licenseExpiresAt }` and still `200`, a value outside `orgBillingDetailsSchema`'s bounds is `null`, no id is served or logged, and the reply carries `Cache-Control: private, no-store`. **The same gate adds `plugins` (#12009 D2, `routes/billing/plugin-billing.ts`):** the Organization's workspaces (`{ id, name }`, `readOrgWorkspaces`) and one row per plugin in `PLUGIN_IDS` order — `has` (the workspaces `workspaceHasPlugin` answers yes for), `billingReasons` (the union of their reasons, in `PLUGIN_REASONS` order; Billing is the reason's one reader, guarded by `plugin-entitlement-confinement.test.ts`), `bought` (the workspaces on the Organization's active `PluginPurchase` rows, by interval — what their subscriptions bill), `prices` (integer US cents from `services/entitlements.ts`'s `readPluginCatalogue`, the entitlements service's catalogue read on #12001's call, cached 60 s; `null` for growth-ops, an unsold plugin, a placeholder or non-`usd` price, or an unread catalogue — never a fallback) and `forSale` (a shown price, a Stripe customer, the commerce claim `claimed` and a registered grant writer — `services/plugin-purchases.ts`'s `pluginGrantWriter()`, which only the hub's licensing module registers, so a hub without it sells nothing). A failed plugin read leaves the key out and logs `plugins_unavailable`; the rest of the answer stands. Every other request is answered exactly as before, with no Stripe or licence read. **`POST /v1/billing/plan-checkout` (#9067 D3, `routes/billing/plan-checkout.ts`)** is the Billing tab's Purchase plan: a subscription Checkout for the caller's own Organization's plan (`planPurchaseLookupKey` — `ailk-pro_monthly` / `ailk-pro-plus_monthly`, `PLAN_PURCHASE_LOOKUP_KEYS` built by the Offerings lookup-key grammar, #9338 DD1), on the admitted key like the portal (#8463). **It sells only an Offerings plan (#9338 DD4):** `createCheckoutSession` gets a `refuseProduct` that refuses every Product whose `metadata.ailk_group` is not exactly `plan` (`isOfferingsPlanProduct`, `services/offerings/catalog.ts`), checked on the same expanded Price it sells; a refused or unexpanded Product answers `500 plan_price_missing`. Check order: tenant → `billing-manage` (403 before any lookup) → write budget (`chargeWriteBudget` scope `plancheckout`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{ returnUrl }` (`bodyLimit` 4 KiB, `400 validation_failed`) → the return URL (canonical, no userinfo, query, fragment or `//` path, `https:` or a local `http:`, on `config.TRUSTED_ORIGINS`; `400 return_url_refused`, `500 config-error` when none is trusted) → no customer yet (`409 billing_customer_exists`) and a purchasable tier (`409 plan_not_purchasable`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` → one payable session (an open earlier one is expired first, a completed one is `409 purchase_pending`) → `createCheckoutSession` with `mode: "subscription"`, 1–50 sites, `metadata` and `subscriptionMetadata` `{ organizationId, ...siteStamp() }` and `PLATFORM_TERMS_OF_SERVICE`, never a `buyer` → a Checkout URL only → the session id recorded on `Organization.planCheckoutSessionId` by compare-and-set (a lost race or a failed write expires the new session). It answers `{ url }` with `Cache-Control: private, no-store`; no body or log line carries the return URL, an id or a Stripe message. **A body with `change` (#12336 D6)** — `{ period, level, writers, builders }`, names only (`planChangeRequestSchema`), `null` for "None" — changes the bound customer's plan instead: after steps 1–6 and the key, a bound customer (`409 billing_customer_missing`) → a fresh read of the change (`readPlanChangeBasis`, never the cache; `409 plan_change_unavailable` when Plan overview would offer none — a plan Stripe paused when its trial ended with no card included, #12337) → each name a choice of its row at that period, re-priced on the server (`400 choice_refused`) → an order that differs from what is held (`409 plan_unchanged`) → one change at a time on `Organization.planChangeSessionId` (`settlePlanChange`: an open recorded session is expired, a paid one nothing finished is finished, a pending one is `409 purchase_pending`) → one subscription Checkout on the bound customer for the whole order at one period (`createPlanChangeCheckoutSession`: `billing_mode` flexible, no discount or trial, metadata `ailk_plan_change: "1"` and `ailk_replaces`) → a Checkout URL only → the session recorded by compare-and-set → `forgetPlanOverview`. Nothing changes until the customer pays on Stripe. **The webhook's Organization arm binds only that recorded session (#9067 D13):** a `checkout.session.completed` with `metadata.organizationId` links `session.customer` through one guarded `updateMany` on `{ id, planCheckoutSessionId: session.id, billingCustomerId: null }` (clearing the session); anything else — an unrecorded session, a bound customer, every `customer.created` — writes nothing and logs `org_bind_unproven`. No MCP twin for the purchase — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/trial-card` (#12337 D6, `routes/billing/trial-card.ts`)** is Plan overview's "Add card" coming back: on the caller's own Organization's plan, read fresh on the deployment's key (`finishPlanTrialCard`), it moves a running no-card trial's end 14 days later once (`extended`), or — only with a live return token — starts a paused plan with a charge that day (`started`); else `unchanged`. Check order: tenant (401) → `billing-manage` (403 before any lookup or budget) → write budget (scope `plantrial`, 10 an hour per Organization and per person, `429` with `Retry-After`) → the commerce claim (`409 purchase_unavailable`, `503 license_undetermined`) → a strict `{}` or `{ token }` (`400 validation_failed`; no id, date or price is taken from the body) → the Organization's billing customer (`404 no-billing-customer`) → its payer, `readOrgPayer`, must be `own` (`409 not-own-plan` for an agency's client, bound or not, or a failed classification) → a customer a User shares (`409 billing-customer-shared`) → `STRIPE_SECRET_KEY` and `assertAdmittedStripeKey` (500) → the token spent by `consumeReservation` (one delete of the live `plan-trial-card` reservation of the caller's own Workspace and Organization whose `ref` is the token's SHA-256; only a deleted row allows a start), then the one write (`500 config-error`, `502 trial-unavailable`) → `{ outcome }` with `Cache-Control: private, no-store`. From the token step on the customer's cached Plan overview is forgotten on every answer, and an `extended` or `started` answer records one audit row. The token is minted by the portal session's Plan overview path (`returnUrl` `/workspaces/<id>/settings/org-plan`, the payment-method screen only), which holds its hash for an hour; every portal-session path also refuses any payer but `own` with `409 not-own-plan` after its key checks and before a token or any call on the deployment's key. No MCP twin — owner-only, recorded in `tests/parity/README.md`. **`POST /v1/billing/plugin-checkout` (#12009 D5, `routes/billing/plugin-checkout.ts`)** is the Billing tab's "+ Add" on a plugin row: a subscription Checkout for one plugin at one interval (`year` or `month`), one unit per chosen workspace, on the Organization's own bound customer. Check order: tenant → `billing-manage` (403 before any read) → write budget (scope `plugincheckout`, 10 an hour per Organization and per person) → the commerce claim → a strict `{ plugin, interval, workspaceIds (1–50, distinct), returnUrl }` → plan-checkout's own return-URL rule (`isAcceptableReturnUrl`) → a registered grant writer (`409 purchase_unavailable`) → a bound customer (`409 billing_customer_missing` — no plugin before the plan) → the catalogue (`503 catalogue_unavailable` on an unread one; `409 plugin_not_for_sale` for growth-ops, an unsold plugin or a placeholder price) → the workspaces (each a `wksp_` id of the caller's own Organization, else `400 workspace_refused`; a failed entitlement read for any of them, `503 entitlement_unavailable` — `workspaceHasPluginForSale`, which fails closed where `workspaceHasPlugin` answers no; one it answers yes for, or an active purchase of the plugin names, `409 plugin_already_added`) → the admitted Stripe key → one open Checkout per workspace, from one read of the plugin's `created` and `active` purchases (one confirmed since the step before, `active`, naming a chosen workspace answers `409 plugin_already_added`; an earlier `created` one is expired and ended; a completed one answers `409 purchase_pending`) → `createCheckoutSession` at the catalogue's lookup key with `quantity` equal to the workspace count, no `adjustableQuantity`, `metadata` and `subscriptionMetadata` `{ organizationId, ailk_plugin, ...siteStamp() }`, and a `refusePrice` that refuses any Price whose `unit_amount`, currency or interval is not the catalogue's, or that is not billed per unit, once per interval, with no quantity transform (`500 plugin_price_mismatch`) → a Checkout URL only → the session recorded as a `PluginPurchase` with the Price id `refusePrice` accepted (`state: created`; no accepted Price, or a failed write, expires the session and answers 502) → no rival recorded or confirmed meanwhile for a chosen workspace (else the new session is expired and ended: `409 purchase_pending` for a `created` rival, `409 plugin_already_added` for an `active` one; a recheck that cannot be read does the same and answers 502). **The webhook's plugin path (#12009 D9, `services/plugin-purchases.ts` `fulfilPluginEvent`)** runs once after the site filter and before the `switch`, and only on a hub with billing's grant writer: for a `checkout.session.completed`, `customer.subscription.*`, `invoice.paid` or `invoice.payment_failed` whose object carries the `ailk_plugin` stamp (`PLUGIN_SUBSCRIPTION_METADATA_KEY` — a filter only, never a grant) it traces the event's subscription to a recorded purchase (bound, or by `checkout.sessions.list` and a once-only bind), re-reads the subscription from Stripe, stores `state` and `exp` (the item's `current_period_end` while `active` or `trialing` and still paying for the record — quantity at least the recorded workspaces, the recorded Price and interval, collection not paused — else now; `ended_at` or now, `state: ended`, when `canceled` or `incomplete_expired`; nothing while `incomplete`; now otherwise — no grace), and writes one `add_on` grant per workspace with the latest `exp` among the purchases covering it and that purchase's subscription. It never throws, an untraced subscription grants nothing, and no grant is written without an `exp`. When a read or a grant write fails (Stripe, the database or entitlements down) it answers `"retry"`: the webhook un-marks the event (`unmarkSeen`) and answers `503`, before any arm of the `switch` runs, so Stripe redelivers it and the idempotent path re-derives every grant. **The webhook's plan-change path (#12336 D8, `services/offerings/plan-change.ts` `fulfilPlanChangeEvent`)** runs right after it, the same way: for a `checkout.session.*` stamped `ailk_plan_change: "1"` by this site, whose Organization recorded that session for that customer, a completed or async-succeeded session whose new subscription is live and its first invoice paid (`isLivePaidSubscription`, never `payment_status` alone) reaches `finishPlanChange` — the one function that stamps (`ailk_plan_change: "replaced"`) and cancels each replaced subscription, prorated only for paid, unpaused time, keeping one that now holds an item the order never showed — and an expired or failed one only clears the column; `"retry"` un-marks the event and answers `503`. The owner's Plan overview read and the next change press reach the same function for a change whose event never arrived.
|
|
115
116
|
- `/v1/billing/stripe-connection` (GET, PUT, DELETE), `/v1/billing/stripe-connection/live` (POST), `/v1/billing/stripe-connection/webhook-secret` (PUT), `/v1/billing/stripe-connection/webhook-reset` (POST) — the Organization's own Stripe connection (#8907, `src/routes/billing/stripe-connection.ts`; spec `docs/specs/8907-the-organization-stripe-connection-custody-spec.md`; contract `docs/specs/8879-the-offerings-security-contract-key-spec.md`). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. **Data access and the cipher** are `src/services/offerings/connection.ts`, the only file that touches the StripeConnection model (exactly ten delegate calls, `architecture.yaml` `paths_scoped`): the key and the webhook secret are AES-256-GCM ciphertext under `STRIPE_CONNECTION_KEY`, bound to the Organization, the column and (for the secret) the mode; decryption also tries `STRIPE_CONNECTION_KEY_PREVIOUS`. The GET needs `billing-read` and answers `null` or exactly `{ mode, last4, webhookPath, webhookSecretSet, connectedAt, liveAt, updatedAt }` (a corrupt row `500 connection_unreadable`); with no stored row it answers `{ source: "environment", mode }` to the Organization that owns `STRIPE_SECRET_KEY` and `null` to every other (#9285 — without the `multi-tenant` module selected the single Organization owns it; with it selected in `AILK_ENABLED_MODULES`, whether or not the licence claims it (#9968), only the one `STRIPE_ENV_ORGANIZATION_ID` names, so unset is nobody: a deployment that selects `multi-tenant` must set `STRIPE_ENV_ORGANIZATION_ID` for any Organization to own the environment key, a downgraded one whose licence no longer claims the module included), and that Organization's Offerings reads and shown set go through the same key (`services/offerings/connection.ts`'s `getOfferingsConnectionState` and the `stripeClientForOrganization` fallback), but its checkout stays on the env path — `resolveOfferingsCheckoutPath` returns the Offerings path only for a stored connection, because a session stamped `ailk_offering` on the environment key is acked `offerings_path` by the legacy webhook and never recorded (#9296; the bridge until a stored connection exists, #8936); every write needs `billing-manage` (the owner alone), checked before the body is read, and answers `{ mode, webhookSecretSet, liveAt, updatedAt }` — never `last4` or the path. PUT `{ key }` admits a restricted test key only (`400 stripe_key_refused` with a `reason` from the class table: `key_unrestricted`, `key_publishable`, `live_key_needs_go_live`, `key_unrecognized`); a replace keeps the webhook token and returns the connection to test mode, clearing a live secret. POST `…/live` `{ key, webhookSecret, confirm: "go-live" }` admits a restricted live key only when a cookie session (`403 session_required`), the commerce claim (`409 commerce_required`, `503 license_undetermined`), a production build (`409 live_mode_unavailable` — `lib/stripe.ts`'s `isProductionBuild`), the confirmation (`400 confirmation_required`) and a `whsec_` secret (`400 webhook_secret_invalid`) all hold. Connect and go-live run three read probes — `products.list`, `prices.list`, `checkout.sessions.list`, together, 10 s — through `lib/stripe.ts`'s `stripeClientForConnection` (the per-key factory's one caller, confined in `architecture.yaml`) before anything is stored: `400 stripe_key_refused` `key_not_usable` or `502 stripe_unavailable`, nothing written. The secret PUT binds it to the row's mode; the reset mints a new token and clears the secret; DELETE removes the row, so the token's lookup (`findStripeConnectionByWebhookToken`, #8861's receiver) answers `not-found` at once; it is a compare-and-swap on the row it read, so it answers `{ revoked: false }` when that read found none, and `409 connection_changed` when the row keeps changing between the read and the delete. On a build that is not production, every write to a live row is `409 live_mode_unavailable` and nothing decrypts one. With `STRIPE_CONNECTION_KEY` unset, connect, go-live and the secret answer `503 credential_key_not_configured`; the GET, reset and DELETE need no key and no claim. **The write budget (K10):** every write but DELETE that passes the permission is counted, refused keys included — 10 an hour per Organization, 20 per person (`middleware/rate-limit.ts`'s `chargeWriteBudget`, always its own database store) — `429 rate_limited` with `Retry-After`. Every success writes one `billing.stripe_connection.<connect|replace|go_live|webhook_secret|webhook_reset|remove>` audit row whose summary is `{ mode, last4 }` and emails every owner, the actor included (`@working-theory/email`'s `sendStripeConnectionChangedEmail`); neither can change the answer. Every response is `Cache-Control: private, no-store`; no response, log line, audit row or email carries the key, the secret, the token or a ciphertext. The rekey bin is `stripe-connections:rekey` (`node dist/bin/stripe-connections-rekey.js`), run with the production environment; anywhere else it answers `not_production` and touches nothing. No MCP twin — owner-only key custody that no agent can hold, recorded in `tests/parity/README.md`.
|
|
116
117
|
- `/v1/billing/stripe-products` (GET, PUT) — the may-sell product list and the org-enabled write (#8922, `src/routes/billing/stripe-products.ts`; spec `docs/specs/8922-the-may-sell-product-list-spec.md`; contract A12, G3, G4, T6). Registered from `routes/billing/index.ts`, so the same multi-tenant tenant scope and module gate; the target is always `request.tenant.organizationId`. Check order: tenant → permission (GET `billing-read`, owner and admin; PUT `billing-manage`, the owner alone — checked before the body, so an admin, a member and an agent key get `403` whatever they send) → the commerce claim (`409 commerce_required`, `503 license_undetermined` with `Retry-After: 300`) → the body → the connection → the catalog read. The GET answers `{ ok: true, data: { connected, products } }`: every active Product `normalizeCatalog` keeps, offerings first in its order then the held ones, each exactly `{ productId, name, description, enabled, heldReason }` — `heldReason` an `OFFERINGS_HELD_REASONS` value or `null`, a held entry always `enabled: false` with `description: null`, and no price, lookup key, image or URL. No connection is `connected: false, products: []`; a corrupt one is `409 connection_unreadable` on both routes, never the empty list. The PUT takes a strict `{ productIds }` (`bodyLimit` 32 KiB; `400 validation_failed` for a malformed body, a duplicate or a malformed id) and replaces the whole set: more than 100 ids, an id in neither list, and a held id are `400 offerings_enabled_refused` with `reason` `too_many_products`, `product_not_in_catalog` or `product_held` (the lookup-key gate — `needs_lookup_key` covers a missing `{plan}_{period}` key and a period that disagrees with the Price, `plan_conflict` a plan two Products share), nothing written; no connection is `409 stripe_not_connected`. It answers the GET body for the new set, parsed before the write. The set's one writer is `services/offerings/store.ts`'s `writeEnabledProductIds` (an `upsert`, `architecture.yaml` `paths_scoped`), through `services/offerings/index.ts`'s `listOrgProducts` and `setOrgEnabledProducts`; both share the per-Organization catalog read (one a minute per process, T7), so `getOrgEnabledProducts` afterwards reads the row with no Stripe call. The catalog comes from `services/offerings/source.ts`'s `stripeCatalogSourceFor` — the Organization's own client (`stripeClientForOrganization`), paged at most 10 product and 30 price calls, 20 s for the whole read, confined in `architecture.yaml`; a disconnected or unusable connection rejects rather than reading as empty, and any source failure is `502 offerings_source_unavailable` with a fixed message. Every successful write records one `offerings.enabled.set` audit row naming the actor, whose summary is `{ enabled, added, removed }` counts only; a failed audit write is one `error` line and the answer stays `200`. Every response is `Cache-Control: private, no-store`, every error message is fixed, and no log line carries a product or price id, a name or the body. The wire names are #8923's, the Admin card that reads it. No MCP twin — owner and admin settings that no agent can hold, recorded in `tests/parity/README.md`.
|
|
117
118
|
- `/v1/workspaces/:workspaceId/offerings` (GET, PUT) — the Library → Offerings tab's read and the workspace's selection write (#8926, `src/routes/workspaces/offerings.ts`; spec `docs/specs/8926-the-workspace-offerings-route-get-spec.md`; contract A12, T6, T7; the wire shape is #8928 D10's, made per Stripe Price by #9070, spec `docs/specs/9070-the-workspace-offerings-page-becomes-spec.md`). Registered in the multi-tenant tenant scope beside the billing routes; every read and write keys on `request.tenant`, never the path or the body. The GET is open to every member, an agent key included: with the `commerce` claim `unclaimed` it answers `{ status: "unavailable", reason: "no_commerce" }`, with no StripeConnection `reason: "no_connection"` (both `200`, no catalog read); `undetermined` is `503 license_undetermined` with `Retry-After: 300`, and an unreadable connection is `502 offerings_source_unavailable`, never unconnected or an empty list. Available, it answers `{ status: "available", products, shown, recommended: { plan, addon } }`: `products` are `getOrgEnabledProducts`' offerings (enabled and sellable, the normalizer's order, plans before add-ons, each `recommended: false`, never a held product), `shown` one `{ productId, periods }` per Product with an effective shown Price, in products order with each Product's periods in its Price order, and each Recommended only while it is such a Product of its group, read from the selection row (`readWorkspaceSelection`), never the snapshot; a read never rewrites the row. **The shown set is per Stripe Price (#9070):** the row stores `shown_price_ids` beside `shown_product_ids` (the Products with at least one of them), and `services/offerings/index.ts`'s `shownPriceIdsFor` is the one rule every reader applies — the stored Price ids the catalog still carries, or, for a row saved before #9070 (none stored), every Price of each shown Product; a Price the seller replaced in Stripe is off until switched on. The PUT needs `workspace-settings` (owner, admin; never agent-grantable) checked by role before the body, then the claim (`409 offerings_unavailable`, `503 license_undetermined`), then a write budget charged before the body — 30 saves an hour per person, then 60 per Organization only while the person is within theirs (`chargeWriteBudget`, scope `offeringsshown`; `429 rate_limited` with `Retry-After`) — then a strict `{ productId, period, shown }` — ONE Price's switch, named by its Product and period, never a price id (`bodyLimit` 32 KiB, `400 validation_failed`, so no body can name a Recommended or a whole set) — the connection (`409 offerings_unavailable` for none, `502` for unreadable) and the catalog read (`502 offerings_source_unavailable`). A Product that is not enabled and sellable is `400 offerings_shown_refused` `reason: "product_not_enabled"`, a period it has no Price for `reason: "price_not_offered"`, nothing written; it never writes the Organization's enabled set. The save adds or removes that Price from the previous row's effective set (a legacy row expanded once, here), and keeps each stored Recommended while its Product keeps a shown Price, clearing it otherwise — it never sets one (a Recommended is written only by code or a recommender). A save goes through `services/offerings/store.ts`'s `updateWorkspaceSelection`, which reads the stored selection and `upsert`s the next one in one transaction under the advisory lock `ailk:workspace-offerings:<workspaceId>` (#9970 D7), creating the row on a first save and never naming the snapshot (`architecture.yaml` `paths_scoped`), records one `offerings.shown.set` audit row whose summary is `{ shown, added, removed, recommended }` counts only — `shown`, `added` and `removed` count Prices against the previous effective set since #9070 (a failed audit is one `error` line and the answer stays `200`), and awaits `refreshWorkspaceSnapshot` with `force` — logged once as `snapshot_refreshed` or `snapshot_pending`; a failed refresh never fails the save — then answers `{ shown, recommended }`. Every response is `Cache-Control: private, no-store`, every error message is fixed, and no log line carries a product or price id, a name or the body. MCP parity: the GET's twin is `get_workspace_offerings` on `/mcp/workspace` (#10949); the PUT has no tool — it needs `workspace-settings`, which is never agent-grantable — recorded in `tests/parity/README.md`.
|
|
@@ -247,7 +248,11 @@ sweep's own DB constraint (never a caller-side lock).
|
|
|
247
248
|
- Don't bundle `apps/api` (esbuild, rollup, webpack). Slice specifiers cannot survive it — see `## Deploy path`.
|
|
248
249
|
- Don't construct Fastify with `logger: true` or any `logger:` option. Pass `loggerInstance` built from `createLogger` in `@working-theory/observability` (see `packages/api/src/server.ts`). Fastify's own pino carries none of the redaction.
|
|
249
250
|
|
|
250
|
-
Last updated: 2026-11-
|
|
251
|
+
Last updated: 2026-11-25 — #12337: `POST /v1/billing/trial-card` and its check order beside plan-checkout, the portal session's payer check and Plan overview return token, and a paused plan offering no change — verified against `packages-paid/api-multi-tenant/src/routes/billing/{trial-card,portal}.ts`, `packages/api/src/lib/write-reservations.ts` and `packages/api/src/services/offerings/{plan-change,member-billing}.ts`.
|
|
252
|
+
|
|
253
|
+
Prior: 2026-11-25 — #12336: the plan-checkout sentence names the `change` branch and its check order, and the webhook gains the plan-change path after the plugin path — verified against `packages-paid/api-multi-tenant/src/routes/billing/plan-checkout.ts`, `packages/api/src/services/offerings/{plan-change,member-billing}.ts` and `packages/api/src/routes/webhooks/stripe.ts`.
|
|
254
|
+
|
|
255
|
+
Prior: 2026-11-20 — #12009 U2: plugin-checkout's workspace check fails closed (`503 entitlement_unavailable`); the `/v1/billing` bullet names `bought` from the purchase record and the registered grant writer behind `forSale`, `POST /v1/billing/plugin-checkout` with its check order, and the webhook's plugin path — verified against `packages-paid/api-multi-tenant/src/routes/billing/{read,plugin-billing,plugin-checkout}.ts`, `packages/api/src/services/plugin-purchases.ts` and `packages/api/src/routes/webhooks/stripe.ts`.
|
|
251
256
|
|
|
252
257
|
Prior: 2026-11-20 — #12009: the `/v1/billing` bullet names the owner's `plugins` rows under `?include=billing`, their fields and the catalogue read behind `prices` — verified against `packages-paid/api-multi-tenant/src/routes/billing/{read,plugin-billing}.ts` and `packages/api/src/services/entitlements.ts`.
|
|
253
258
|
|
|
@@ -35,7 +35,7 @@
|
|
|
35
35
|
*/
|
|
36
36
|
|
|
37
37
|
import { createHmac } from 'node:crypto';
|
|
38
|
-
import { PassThrough } from 'node:stream';
|
|
38
|
+
import { PassThrough, Readable } from 'node:stream';
|
|
39
39
|
|
|
40
40
|
import type { VercelRequest, VercelResponse } from '@vercel/node';
|
|
41
41
|
import Fastify from 'fastify';
|
|
@@ -245,7 +245,7 @@ jest.mock('@working-theory/license', () => ({
|
|
|
245
245
|
jest.mock('@working-theory/analytics/server', () => ({
|
|
246
246
|
track: jest.fn().mockResolvedValue(undefined),
|
|
247
247
|
}));
|
|
248
|
-
|
|
248
|
+
|
|
249
249
|
jest.mock('@working-theory/api/lib/prisma.js');
|
|
250
250
|
|
|
251
251
|
/** Stripe's v1 scheme: `t=<ts>,v1=<hex HMAC-SHA256(secret, "<ts>.<payload>")>`. */
|
|
@@ -671,3 +671,177 @@ describe('vercel-handler — the request log carries no query string (#5970)', (
|
|
|
671
671
|
expect(inject.mock.calls[0][0]).toMatchObject({ url: '/v1/webhooks/stripe/whk_SECRETTOKEN123' });
|
|
672
672
|
});
|
|
673
673
|
});
|
|
674
|
+
|
|
675
|
+
// ── #12428 D4: a deliverable leaves the handler as a stream ─────────────────
|
|
676
|
+
//
|
|
677
|
+
// Vercel refuses a whole response over 4.5 MB; a streamed one is exempt. A
|
|
678
|
+
// `GET`/`HEAD` under `/v1/deliverables/` is injected with `payloadAsStream`
|
|
679
|
+
// and piped into `res`; every other request keeps the whole-payload `send`.
|
|
680
|
+
|
|
681
|
+
/** A writable `res` that records what is piped into it. */
|
|
682
|
+
function makeStreamRes() {
|
|
683
|
+
const res = Object.assign(new PassThrough(), {
|
|
684
|
+
headersSent: false,
|
|
685
|
+
_status: undefined as number | undefined,
|
|
686
|
+
_headers: {} as Record<string, string>,
|
|
687
|
+
_sent: undefined as unknown,
|
|
688
|
+
chunks: [] as Buffer[],
|
|
689
|
+
ended: false,
|
|
690
|
+
status(code: number) {
|
|
691
|
+
this._status = code;
|
|
692
|
+
return this;
|
|
693
|
+
},
|
|
694
|
+
setHeader(key: string, value: string) {
|
|
695
|
+
this._headers[key] = value;
|
|
696
|
+
return this;
|
|
697
|
+
},
|
|
698
|
+
getHeader(key: string) {
|
|
699
|
+
return this._headers[key];
|
|
700
|
+
},
|
|
701
|
+
send(body: unknown) {
|
|
702
|
+
this._sent = body;
|
|
703
|
+
return this;
|
|
704
|
+
},
|
|
705
|
+
json(body: unknown) {
|
|
706
|
+
this._sent = body;
|
|
707
|
+
return this;
|
|
708
|
+
},
|
|
709
|
+
});
|
|
710
|
+
res.on('data', (chunk: Buffer) => res.chunks.push(chunk));
|
|
711
|
+
res.on('finish', () => {
|
|
712
|
+
res.ended = true;
|
|
713
|
+
});
|
|
714
|
+
return res;
|
|
715
|
+
}
|
|
716
|
+
|
|
717
|
+
function asStreamResponse(stub: ReturnType<typeof makeStreamRes>): VercelResponse {
|
|
718
|
+
// @ts-expect-error: a PassThrough carrying the MockRes surface satisfies the
|
|
719
|
+
// subset of VercelResponse the handler calls (status/setHeader/getHeader/
|
|
720
|
+
// send/json, plus the Writable `pipe` writes to).
|
|
721
|
+
return stub;
|
|
722
|
+
}
|
|
723
|
+
|
|
724
|
+
describe('vercel-handler — a deliverable answer leaves as a stream (#12428 D4)', () => {
|
|
725
|
+
const FILE = Buffer.from([0x25, 0x50, 0x44, 0x46, 0x2d, 0x80, 0xff, 0xfe, 0x00, 0x01]);
|
|
726
|
+
let app: ReturnType<typeof Fastify>;
|
|
727
|
+
|
|
728
|
+
beforeEach(async () => {
|
|
729
|
+
jest.resetModules();
|
|
730
|
+
app = Fastify();
|
|
731
|
+
app.get('/v1/deliverables/:grantId', async (_request, reply) => {
|
|
732
|
+
reply
|
|
733
|
+
.header('content-type', 'application/pdf')
|
|
734
|
+
.header('content-disposition', 'attachment; filename="report.pdf"')
|
|
735
|
+
.header('cache-control', 'private, no-store');
|
|
736
|
+
return reply.send(Readable.from([FILE.subarray(0, 4), FILE.subarray(4)]));
|
|
737
|
+
});
|
|
738
|
+
// `/late` fails after the first chunk has gone out; `/early` fails before
|
|
739
|
+
// the handler has read the stream at all.
|
|
740
|
+
app.get('/v1/deliverables/broken/:when', async (request, reply) => {
|
|
741
|
+
const { when } = request.params as { when: string };
|
|
742
|
+
const failure = new Error('store said https://x.private.blob.vercel-storage.com/a');
|
|
743
|
+
let reads = 0;
|
|
744
|
+
const failing = new Readable({
|
|
745
|
+
read() {
|
|
746
|
+
if (when === 'early') {
|
|
747
|
+
this.push(FILE.subarray(0, 4));
|
|
748
|
+
this.destroy(failure);
|
|
749
|
+
} else if (reads++ === 0) {
|
|
750
|
+
this.push(FILE.subarray(0, 4));
|
|
751
|
+
} else {
|
|
752
|
+
setImmediate(() => this.destroy(failure));
|
|
753
|
+
}
|
|
754
|
+
},
|
|
755
|
+
});
|
|
756
|
+
reply.header('content-type', 'application/pdf');
|
|
757
|
+
return reply.send(failing);
|
|
758
|
+
});
|
|
759
|
+
app.get('/v1/other', async () => ({ ok: true }));
|
|
760
|
+
await app.ready();
|
|
761
|
+
});
|
|
762
|
+
|
|
763
|
+
afterEach(async () => {
|
|
764
|
+
await app.close();
|
|
765
|
+
});
|
|
766
|
+
|
|
767
|
+
it('pipes a GET under /v1/deliverables/ with payloadAsStream and no Location', async () => {
|
|
768
|
+
const inject = jest.spyOn(app, 'inject');
|
|
769
|
+
jest.doMock('../server', () => ({ build: jest.fn().mockResolvedValue(app) }));
|
|
770
|
+
const handler = loadHandler();
|
|
771
|
+
const res = makeStreamRes();
|
|
772
|
+
const send = jest.spyOn(res, 'send');
|
|
773
|
+
|
|
774
|
+
await handler(
|
|
775
|
+
asRequest({ method: 'GET', url: '/v1/deliverables/grant_1', headers: {}, body: undefined, query: {} }),
|
|
776
|
+
asStreamResponse(res),
|
|
777
|
+
);
|
|
778
|
+
|
|
779
|
+
expect(inject.mock.calls[0][0]).toMatchObject({ payloadAsStream: true });
|
|
780
|
+
expect(send).not.toHaveBeenCalled();
|
|
781
|
+
expect(res._status).toBe(200);
|
|
782
|
+
expect(res._headers['content-type']).toBe('application/pdf');
|
|
783
|
+
expect(res._headers['content-disposition']).toBe('attachment; filename="report.pdf"');
|
|
784
|
+
expect(Object.keys(res._headers).map((k) => k.toLowerCase())).not.toContain('location');
|
|
785
|
+
expect(res.ended).toBe(true);
|
|
786
|
+
expect(Buffer.compare(Buffer.concat(res.chunks), FILE)).toBe(0);
|
|
787
|
+
});
|
|
788
|
+
|
|
789
|
+
it('streams a HEAD under /v1/deliverables/ too', async () => {
|
|
790
|
+
const inject = jest.spyOn(app, 'inject');
|
|
791
|
+
jest.doMock('../server', () => ({ build: jest.fn().mockResolvedValue(app) }));
|
|
792
|
+
const handler = loadHandler();
|
|
793
|
+
const res = makeStreamRes();
|
|
794
|
+
|
|
795
|
+
await handler(
|
|
796
|
+
asRequest({ method: 'HEAD', url: '/v1/deliverables/grant_1', headers: {}, body: undefined, query: {} }),
|
|
797
|
+
asStreamResponse(res),
|
|
798
|
+
);
|
|
799
|
+
|
|
800
|
+
expect(inject.mock.calls[0][0]).toMatchObject({ payloadAsStream: true });
|
|
801
|
+
expect(res._status).toBe(200);
|
|
802
|
+
expect(res.ended).toBe(true);
|
|
803
|
+
});
|
|
804
|
+
|
|
805
|
+
it.each(['late', 'early'])('ends the response when the stream fails (%s) and logs the error name only', async (when) => {
|
|
806
|
+
jest.doMock('../server', () => ({ build: jest.fn().mockResolvedValue(app) }));
|
|
807
|
+
const handler = loadHandler();
|
|
808
|
+
const res = makeStreamRes();
|
|
809
|
+
|
|
810
|
+
await handler(
|
|
811
|
+
asRequest({ method: 'GET', url: `/v1/deliverables/broken/${when}`, headers: {}, body: undefined, query: {} }),
|
|
812
|
+
asStreamResponse(res),
|
|
813
|
+
);
|
|
814
|
+
|
|
815
|
+
const { logger } = require('@working-theory/observability') as {
|
|
816
|
+
logger: { error: jest.Mock };
|
|
817
|
+
};
|
|
818
|
+
const failure = logger.error.mock.calls.find(
|
|
819
|
+
([, msg]) => msg === '[Vercel Handler] Streamed response failed',
|
|
820
|
+
);
|
|
821
|
+
expect(failure?.[0]).toEqual({ err: 'Error' });
|
|
822
|
+
expect(JSON.stringify(logger.error.mock.calls)).not.toContain('blob.vercel-storage.com');
|
|
823
|
+
// `pipeline` destroys the response on a failure: the download aborts.
|
|
824
|
+
expect(res.ended || res.destroyed).toBe(true);
|
|
825
|
+
});
|
|
826
|
+
|
|
827
|
+
it.each([
|
|
828
|
+
['GET', '/v1/other'],
|
|
829
|
+
['POST', '/v1/deliverables/grant_1'],
|
|
830
|
+
])('keeps the whole payload for %s %s', async (method, url) => {
|
|
831
|
+
const rawPayload = Buffer.from('{"ok":true}');
|
|
832
|
+
const inject = jest.fn().mockResolvedValue({
|
|
833
|
+
statusCode: 200,
|
|
834
|
+
headers: { 'content-type': 'application/json' },
|
|
835
|
+
body: rawPayload.toString(),
|
|
836
|
+
rawPayload,
|
|
837
|
+
});
|
|
838
|
+
jest.doMock('../server', () => ({ build: jest.fn().mockResolvedValue({ inject }) }));
|
|
839
|
+
const handler = loadHandler();
|
|
840
|
+
const res = makeRes();
|
|
841
|
+
|
|
842
|
+
await handler(asRequest({ method, url, headers: {}, body: undefined, query: {} }), asResponse(res));
|
|
843
|
+
|
|
844
|
+
expect(inject.mock.calls[0][0]).not.toHaveProperty('payloadAsStream');
|
|
845
|
+
expect(res._sent).toBe(rawPayload);
|
|
846
|
+
});
|
|
847
|
+
});
|
|
@@ -138,6 +138,21 @@ export const prisma = {
|
|
|
138
138
|
update: jest.fn(),
|
|
139
139
|
updateMany: jest.fn(),
|
|
140
140
|
},
|
|
141
|
+
// #12343 D1, D2 — the hub's agency mark and each client's customer in the
|
|
142
|
+
// agency's connection, written and read only by services/entitlements.ts.
|
|
143
|
+
// Bare `jest.fn()`s: an unprogrammed `findUnique` answers `undefined`, which
|
|
144
|
+
// that file reads as no agency, so a suite that never marks one is FR6.
|
|
145
|
+
hubAgency: {
|
|
146
|
+
findUnique: jest.fn(),
|
|
147
|
+
create: jest.fn(),
|
|
148
|
+
updateMany: jest.fn(),
|
|
149
|
+
deleteMany: jest.fn(),
|
|
150
|
+
},
|
|
151
|
+
agencyClientCustomer: {
|
|
152
|
+
findMany: jest.fn(),
|
|
153
|
+
create: jest.fn(),
|
|
154
|
+
updateMany: jest.fn(),
|
|
155
|
+
},
|
|
141
156
|
workspace: {
|
|
142
157
|
// #6335 — NO default implementation, deliberately. Until this issue the
|
|
143
158
|
// delegate carried a PERMISSIVE one (#6203): it resolved ANY requested
|
|
@@ -198,6 +213,22 @@ export const prisma = {
|
|
|
198
213
|
upsert: jest.fn(),
|
|
199
214
|
deleteMany: jest.fn(),
|
|
200
215
|
},
|
|
216
|
+
// #12400 D2 — the site navigation and its versions: the accessor's guarded
|
|
217
|
+
// save, list and read, and the workspace-delete helper's `deleteMany`.
|
|
218
|
+
workspaceSiteNavigation: {
|
|
219
|
+
findUnique: jest.fn(),
|
|
220
|
+
findMany: jest.fn(),
|
|
221
|
+
createManyAndReturn: jest.fn(),
|
|
222
|
+
updateManyAndReturn: jest.fn(),
|
|
223
|
+
deleteMany: jest.fn(),
|
|
224
|
+
},
|
|
225
|
+
workspaceSiteNavigationVersion: {
|
|
226
|
+
findUnique: jest.fn(),
|
|
227
|
+
findFirst: jest.fn(),
|
|
228
|
+
findMany: jest.fn(),
|
|
229
|
+
create: jest.fn(),
|
|
230
|
+
deleteMany: jest.fn(),
|
|
231
|
+
},
|
|
201
232
|
// `findUnique` — the public meetings read (`lib/public-meetings-config.ts`),
|
|
202
233
|
// which a spoke's meeting-types read and booking gate reach (#7532 D3/D4).
|
|
203
234
|
workspaceMeetings: {
|
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
* This file wraps the Fastify server for Vercel's serverless functions
|
|
4
4
|
*/
|
|
5
5
|
|
|
6
|
+
import { pipeline } from "node:stream";
|
|
7
|
+
|
|
6
8
|
import type { VercelRequest, VercelResponse } from "@vercel/node";
|
|
7
9
|
import { redactLogPath } from "@working-theory/api";
|
|
8
10
|
import { logger } from "@working-theory/observability";
|
|
@@ -240,7 +242,18 @@ export default async function handler(
|
|
|
240
242
|
query: req.query as Record<string, string>,
|
|
241
243
|
};
|
|
242
244
|
|
|
243
|
-
|
|
245
|
+
// A deliverable's file leaves as a STREAM (#12428 D4): Vercel refuses a
|
|
246
|
+
// whole response over 4.5 MB, and a streamed one is exempt. Every other
|
|
247
|
+
// request keeps the whole-payload path below, byte for byte.
|
|
248
|
+
const streamed =
|
|
249
|
+
(method === "GET" || method === "HEAD") &&
|
|
250
|
+
pathname.startsWith("/v1/deliverables/");
|
|
251
|
+
|
|
252
|
+
const response = await server.inject(
|
|
253
|
+
(streamed
|
|
254
|
+
? { ...fastifyRequest, payloadAsStream: true }
|
|
255
|
+
: fastifyRequest) as InjectOptions,
|
|
256
|
+
);
|
|
244
257
|
|
|
245
258
|
logger.info(
|
|
246
259
|
{ status: response.statusCode },
|
|
@@ -264,7 +277,24 @@ export default async function handler(
|
|
|
264
277
|
res.setHeader("Content-Type", "application/json");
|
|
265
278
|
}
|
|
266
279
|
|
|
267
|
-
if (!res.headersSent) {
|
|
280
|
+
if (streamed && !res.headersSent) {
|
|
281
|
+
// A stream that fails mid-file ends the response — `pipeline` destroys
|
|
282
|
+
// it, so the client sees an aborted download, never a short file as if
|
|
283
|
+
// whole — and the log names the error alone, never its message (which
|
|
284
|
+
// could carry a store address). It also destroys the file stream when
|
|
285
|
+
// the client goes away, so an aborted download holds no store read open.
|
|
286
|
+
await new Promise<void>((resolve) => {
|
|
287
|
+
pipeline(response.stream(), res, (error) => {
|
|
288
|
+
if (error) {
|
|
289
|
+
logger.error(
|
|
290
|
+
{ err: error.name },
|
|
291
|
+
"[Vercel Handler] Streamed response failed",
|
|
292
|
+
);
|
|
293
|
+
}
|
|
294
|
+
resolve();
|
|
295
|
+
});
|
|
296
|
+
});
|
|
297
|
+
} else if (!res.headersSent) {
|
|
268
298
|
// Forward the raw bytes light-my-request kept alongside `.body` — the
|
|
269
299
|
// decoded-as-UTF-8-string form corrupts any non-UTF-8 response (a
|
|
270
300
|
// generated PDF, any binary payload) by replacing every invalid byte
|
|
@@ -105,6 +105,14 @@ MCP_ABUSE_BLOCKED_USER_AGENTS=
|
|
|
105
105
|
# Required ONLY on a hub's CONTENT_ADAPTER=database — never on a spoke.
|
|
106
106
|
# DATABASE_URL=
|
|
107
107
|
|
|
108
|
+
# A hub's CONTENT_ADAPTER=database only (#12420): the hub API's public URL —
|
|
109
|
+
# the SAME value the hub's apps/api holds. A page's stored images (asset:<key>)
|
|
110
|
+
# resolve onto its origin, so read_content, list_pages and search_content
|
|
111
|
+
# answer the address the API's routes do. Unset or not http(s), stored images
|
|
112
|
+
# are left out of every read and the server writes one stderr line saying so.
|
|
113
|
+
# A spoke reads its hub's API, which resolves them: leave it unset there.
|
|
114
|
+
# AILK_PUBLIC_API_URL=
|
|
115
|
+
|
|
108
116
|
# ── STEALTH ──────────────────────────────────────────────────────────────────
|
|
109
117
|
|
|
110
118
|
# Optional. Set to "true" on this server's own hosting project to keep its
|