@aotter/mantle 0.1.0-alpha.9 → 0.1.2-alpha.2

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 (109) hide show
  1. package/README.md +38 -38
  2. package/dist/cli/generate.d.ts +10 -1
  3. package/dist/cli/generate.d.ts.map +1 -1
  4. package/dist/cli/generate.js +49 -4
  5. package/dist/cli/generate.js.map +1 -1
  6. package/dist/cli/main.js +0 -8
  7. package/dist/cli/main.js.map +1 -1
  8. package/dist/codegen/emitMantleModule.js +8 -0
  9. package/dist/codegen/emitMantleModule.js.map +1 -1
  10. package/docs/adapter-guide.md +23 -26
  11. package/docs/adr/0008-structured-diagnostic-shape.md +7 -2
  12. package/docs/adr/0010-locale-and-translates.md +14 -16
  13. package/docs/adr/0011-adapter-port-spec.md +2 -1
  14. package/docs/adr/0014-auth-better-auth-and-multi-tenant-mcp.md +100 -0
  15. package/docs/adr/0018-core-starters-repository-boundary.md +3 -0
  16. package/docs/adr/0019-sealed-manifest-runtime-pipeline.md +38 -2
  17. package/docs/adr/0020-builtin-handler-contracts-and-matched-upsert.md +199 -0
  18. package/docs/adr/0021-retire-starter-scaffolding.md +30 -0
  19. package/docs/adr/0022-caller-observed-version-occ.md +212 -0
  20. package/docs/adr/0023-port-failure-contract.md +69 -0
  21. package/docs/adr/0024-manifest-native-schema-tables.md +260 -0
  22. package/docs/adr/README.md +19 -3
  23. package/docs/adr/adr-lite-803-request-diagnostics.md +38 -0
  24. package/docs/adr/adr-lite-808-route-readiness.md +47 -0
  25. package/docs/adr/adr-lite-809-bounded-public-content.md +71 -0
  26. package/docs/adr/adr-lite-812-native-parity.md +150 -0
  27. package/docs/adr/adr-lite-823-home-statistics.md +64 -0
  28. package/docs/adr/adr-lite-842-mcp-authoring.md +30 -0
  29. package/docs/adr/adr-lite-861-admin-webmcp.md +42 -0
  30. package/docs/adr/adr-lite-909-admin-ui-kit.md +37 -0
  31. package/docs/api-mcp-authorization.md +3 -664
  32. package/docs/auth-hosting-model.md +4 -4
  33. package/docs/cloudflare-low-level-composition.md +3 -104
  34. package/docs/deferred-lifecycle-queues.md +2 -243
  35. package/docs/design-atoms.md +16 -796
  36. package/docs/direct-authoring.md +5 -0
  37. package/docs/examples/minimal-worker/README.md +37 -0
  38. package/docs/examples/minimal-worker/manifests/site.yaml +25 -0
  39. package/docs/examples/minimal-worker/package.json +26 -0
  40. package/docs/examples/minimal-worker/smoke.mjs +23 -0
  41. package/docs/examples/minimal-worker/src/index.ts +4 -0
  42. package/docs/examples/minimal-worker/tsconfig.json +17 -0
  43. package/docs/examples/minimal-worker/wrangler.jsonc +22 -0
  44. package/docs/handbook/cloudflare/authentication.md +167 -0
  45. package/docs/handbook/cloudflare/bindings.md +236 -0
  46. package/docs/handbook/cloudflare/conventional-worker.md +162 -0
  47. package/docs/handbook/cloudflare/deferred-hooks-queues.md +171 -0
  48. package/docs/handbook/cloudflare/deploy-and-operate.md +105 -0
  49. package/docs/handbook/cloudflare/low-level-composition.md +169 -0
  50. package/docs/handbook/cloudflare/media-r2.md +216 -0
  51. package/docs/handbook/cloudflare/public-web.md +144 -0
  52. package/docs/handbook/concepts/authorization.md +116 -0
  53. package/docs/handbook/concepts/four-atoms.md +173 -0
  54. package/docs/handbook/concepts/lifecycle-and-locales.md +142 -0
  55. package/docs/handbook/concepts/mcp-and-agents.md +109 -0
  56. package/docs/handbook/concepts/procedures-and-triggers.md +221 -0
  57. package/docs/handbook/concepts/runtime-and-adapters.md +177 -0
  58. package/docs/handbook/concepts/views.md +191 -0
  59. package/docs/handbook/examples/commerce-transaction.md +813 -0
  60. package/docs/handbook/examples/guarded-api.md +427 -0
  61. package/docs/handbook/examples/intake-form.md +319 -0
  62. package/docs/handbook/examples/legal-documents.md +218 -0
  63. package/docs/handbook/examples/procurement-approvals.md +240 -0
  64. package/docs/handbook/examples/publication.md +240 -0
  65. package/docs/handbook/examples/reservation.md +220 -0
  66. package/docs/handbook/navigation.json +63 -0
  67. package/docs/handbook/reference/authorization.md +295 -0
  68. package/docs/handbook/reference/diagnostics.md +183 -0
  69. package/docs/handbook/reference/manifest.md +132 -0
  70. package/docs/handbook/reference/procedure.md +263 -0
  71. package/docs/handbook/reference/schema.md +250 -0
  72. package/docs/handbook/reference/site-config.md +233 -0
  73. package/docs/handbook/reference/surface.md +207 -0
  74. package/docs/handbook/reference/trigger.md +193 -0
  75. package/docs/handbook/reference/view.md +256 -0
  76. package/docs/handbook/start/project-and-cli.md +122 -0
  77. package/docs/handbook/start/quickstart-worker.md +193 -0
  78. package/docs/labels.md +3 -1
  79. package/docs/media-uploads.md +3 -184
  80. package/docs/migration-0.1.2.md +60 -3
  81. package/docs/performance-harness.md +127 -10
  82. package/docs/release-process.md +85 -231
  83. package/docs/schema-indexes.md +3 -180
  84. package/docs/sealed-pipeline-ownership.md +6 -5
  85. package/docs/spec-only-host-adoption.md +158 -0
  86. package/docs/transaction-patterns.md +5 -0
  87. package/package.json +21 -25
  88. package/skills/README.md +4 -4
  89. package/skills/develop/SKILL.md +23 -28
  90. package/skills/install/SKILL.md +55 -147
  91. package/skills/provision/SKILL.md +4 -3
  92. package/skills/theme/SKILL.md +6 -6
  93. package/skills/update/SKILL.md +32 -68
  94. package/dist/cli/create.d.ts +0 -2
  95. package/dist/cli/create.d.ts.map +0 -1
  96. package/dist/cli/create.js +0 -243
  97. package/dist/cli/create.js.map +0 -1
  98. package/dist/cli/update.d.ts +0 -2
  99. package/dist/cli/update.d.ts.map +0 -1
  100. package/dist/cli/update.js +0 -413
  101. package/dist/cli/update.js.map +0 -1
  102. package/dist/provision/renderProvisionBundle.d.ts +0 -70
  103. package/dist/provision/renderProvisionBundle.d.ts.map +0 -1
  104. package/dist/provision/renderProvisionBundle.js +0 -367
  105. package/dist/provision/renderProvisionBundle.js.map +0 -1
  106. package/dist/provision.d.ts +0 -2
  107. package/dist/provision.d.ts.map +0 -1
  108. package/dist/provision.js +0 -2
  109. package/dist/provision.js.map +0 -1
@@ -0,0 +1,427 @@
1
+ ---
2
+ description: Protect Views and Procedures with site-issued API keys, opaque scopes and a live entitlement guard, over REST and MCP.
3
+ ---
4
+ # Guarded API access: API keys, scopes and entitlement
5
+
6
+ This example climbs a ladder of four access levels: anonymous, verified credential with a scope, credential plus a live paid-state guard, and a personal token that identifies a user. Read it if other systems or agents call your site with keys instead of browser sessions.
7
+
8
+ ## Problem
9
+
10
+ A site sells API access. Anyone may read the public catalog. Customers get API keys the site issues and stores itself; each key carries site-defined scopes such as `catalog:read` or `exports:read`. Some operations also require that the customer's subscription is currently paid, a fact that changes independently of the key. Individual users may create personal tokens that act as them, and the same operation must be callable over REST and through the public MCP surface with identical authorization. Mantle verifies, normalizes and enforces; the site owns keys, scopes and billing.
11
+
12
+ ## Manifest
13
+
14
+ ```yaml
15
+ apiVersion: cms.mantle.aotter.net/v1
16
+ kind: Schema
17
+ metadata:
18
+ name: catalog-items
19
+ spec:
20
+ title: Catalog items
21
+ lifecycle: publishing
22
+ uniqueIndexes:
23
+ - [slug]
24
+ schema:
25
+ type: object
26
+ additionalProperties: false
27
+ required: [slug, title, priceMinor]
28
+ properties:
29
+ slug: { type: string, pattern: "^[a-z0-9-]+$" }
30
+ title: { type: string, minLength: 1, maxLength: 160 }
31
+ priceMinor: { type: integer, minimum: 0, x-mcp-hint: money-minor }
32
+ ---
33
+ # 1. Anonymous public read
34
+ apiVersion: cms.mantle.aotter.net/v1
35
+ kind: View
36
+ metadata:
37
+ name: public-catalog
38
+ spec:
39
+ surface: public
40
+ from: catalog-items
41
+ fields: [id, slug, title, priceMinor, updatedAt]
42
+ filter:
43
+ eq: { field: status, value: published }
44
+ orderBy:
45
+ - { field: title, direction: asc }
46
+ limit: 100
47
+ ---
48
+ # 2. Verified credential with a scope
49
+ apiVersion: cms.mantle.aotter.net/v1
50
+ kind: Procedure
51
+ metadata:
52
+ name: read-catalog
53
+ spec:
54
+ requires:
55
+ auth:
56
+ all:
57
+ - ctx.auth
58
+ - { "ctx.auth.scope": "catalog:read" }
59
+ input: { type: object }
60
+ output: { type: object }
61
+ handler: { kind: ref, ref: readCatalog }
62
+ ---
63
+ apiVersion: cms.mantle.aotter.net/v1
64
+ kind: Trigger
65
+ metadata:
66
+ name: read-catalog-http
67
+ spec:
68
+ source: { kind: http, method: POST, path: /api/catalog/read }
69
+ target: { procedure: read-catalog }
70
+ ---
71
+ # 3. Scope plus a live entitlement guard
72
+ apiVersion: cms.mantle.aotter.net/v1
73
+ kind: Procedure
74
+ metadata:
75
+ name: require-active-api-access
76
+ spec:
77
+ input: { type: object }
78
+ output: { type: object }
79
+ handler: { kind: ref, ref: requireActiveApiAccess }
80
+ ---
81
+ apiVersion: cms.mantle.aotter.net/v1
82
+ kind: Procedure
83
+ metadata:
84
+ name: download-export
85
+ spec:
86
+ requires:
87
+ auth:
88
+ all:
89
+ - ctx.auth
90
+ - { "ctx.auth.scope": "exports:read" }
91
+ guard: { procedure: require-active-api-access }
92
+ input:
93
+ type: object
94
+ required: [reportId]
95
+ properties:
96
+ reportId: { type: string }
97
+ output: { type: object }
98
+ handler: { kind: ref, ref: downloadExport }
99
+ ---
100
+ apiVersion: cms.mantle.aotter.net/v1
101
+ kind: Trigger
102
+ metadata:
103
+ name: download-export-http
104
+ spec:
105
+ source: { kind: http, method: POST, path: /api/exports/download }
106
+ target: { procedure: download-export }
107
+ ---
108
+ # 4. Personal token with a user subject, shared by REST and MCP
109
+ apiVersion: cms.mantle.aotter.net/v1
110
+ kind: Procedure
111
+ metadata:
112
+ name: require-active-membership
113
+ spec:
114
+ input: { type: object }
115
+ output: { type: object }
116
+ handler: { kind: ref, ref: requireActiveMembership }
117
+ ---
118
+ apiVersion: cms.mantle.aotter.net/v1
119
+ kind: Procedure
120
+ metadata:
121
+ name: read-account
122
+ spec:
123
+ requires:
124
+ auth:
125
+ all:
126
+ - ctx.user
127
+ - ctx.auth
128
+ - { "ctx.auth.scope": "accounts:read" }
129
+ guard: { procedure: require-active-membership }
130
+ input:
131
+ type: object
132
+ required: [accountId]
133
+ properties:
134
+ accountId: { type: string }
135
+ output:
136
+ type: object
137
+ required: [accountId]
138
+ properties:
139
+ accountId: { type: string }
140
+ handler: { kind: ref, ref: readAccount }
141
+ ---
142
+ apiVersion: cms.mantle.aotter.net/v1
143
+ kind: Trigger
144
+ metadata:
145
+ name: read-account-http
146
+ spec:
147
+ source: { kind: http, method: POST, path: /api/accounts/read }
148
+ target: { procedure: read-account }
149
+ ---
150
+ apiVersion: cms.mantle.aotter.net/v1
151
+ kind: Trigger
152
+ metadata:
153
+ name: read-account-mcp
154
+ spec:
155
+ source: { kind: mcp, surface: public }
156
+ target: { procedure: read-account }
157
+ ```
158
+
159
+ The predicate vocabulary is closed. `ctx.auth` means any adapter-verified credential (session, OAuth, API key or personal token); there is no credential-kind predicate. `ctx.user` requires a user subject, which a service API key may lack. Each `ctx.auth.scope` entry requires one opaque, site-defined scope; repeat it for several. `guard.procedure` names one ordinary, unguarded `ref` Procedure. The runtime order is fixed: verify credential → static predicates → validate input → guard → target. See [Authorization](../concepts/authorization.md) and the [authorization reference](../reference/authorization.md).
160
+
161
+ ## Worker and handlers
162
+
163
+ ### Credential resolver
164
+
165
+ The Cloudflare adapter exposes one seam, `ConsumerCredentialResolver`. It answers `not-handled` when the request carries none of the site's credential formats, `invalid` when it carries a recognized but bad or revoked one, and `verified` after checking the site's own record. The table below is application-owned; Mantle has no migration for it.
166
+
167
+ ```ts
168
+ // src/auth/credentialResolver.ts
169
+ import type { ConsumerCredentialResolver } from "@aotter/mantle/cloudflare";
170
+
171
+ type CredentialRow = {
172
+ id: string;
173
+ kind: "api-key" | "personal-token";
174
+ user_id: string | null;
175
+ scopes_json: string;
176
+ revoked_at: string | null;
177
+ };
178
+
179
+ export function siteCredentialResolver(db: D1Database): ConsumerCredentialResolver {
180
+ return async (request) => {
181
+ const apiKey = request.headers.get("x-api-key");
182
+ const authorization = request.headers.get("authorization");
183
+
184
+ let kind: CredentialRow["kind"];
185
+ let raw: string;
186
+ if (apiKey !== null) {
187
+ kind = "api-key";
188
+ raw = apiKey;
189
+ } else if (authorization?.startsWith("Bearer site_pat_")) {
190
+ kind = "personal-token";
191
+ raw = authorization.slice("Bearer ".length);
192
+ } else {
193
+ return { kind: "not-handled" }; // let OAuth bearer or the cookie session try next
194
+ }
195
+
196
+ const digest = await sha256(raw);
197
+ const row = await db
198
+ .prepare("SELECT id, kind, user_id, scopes_json, revoked_at FROM site_credentials WHERE token_sha256 = ? AND kind = ? LIMIT 1")
199
+ .bind(digest, kind)
200
+ .first<CredentialRow>();
201
+ if (!row || row.revoked_at !== null) return { kind: "invalid" };
202
+
203
+ const scopes = parseScopes(row.scopes_json);
204
+ if (!scopes) return { kind: "invalid" };
205
+ return {
206
+ kind: "verified",
207
+ credential: {
208
+ credential: row.kind,
209
+ credentialId: row.id, // opaque row id, never the raw key
210
+ userId: row.user_id,
211
+ scopes,
212
+ },
213
+ };
214
+ };
215
+ }
216
+
217
+ async function sha256(value: string): Promise<string> {
218
+ const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
219
+ return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
220
+ }
221
+
222
+ function parseScopes(json: string): string[] | null {
223
+ try {
224
+ const value: unknown = JSON.parse(json);
225
+ return Array.isArray(value) && value.every((s) => typeof s === "string") ? value : null;
226
+ } catch {
227
+ return null;
228
+ }
229
+ }
230
+ ```
231
+
232
+ Resolution precedence is site resolver, then configured OAuth bearer, then cookie session. A recognized-but-invalid credential never falls back to a valid cookie. Handlers see only normalized metadata on `ctx.auth`: `{ credential, credentialId, clientId, scopes }`. Raw keys never enter the runtime.
233
+
234
+ ### Guards and targets
235
+
236
+ ```ts
237
+ // src/handlers.ts
238
+ import { DiagnosticError, runtimeDiagnostic } from "@aotter/mantle/spec";
239
+ import type { HandlerContext } from "@aotter/mantle/runtime";
240
+ import type { Env } from "./index.js";
241
+
242
+ export const handlers = {
243
+ readCatalog: async (_input: unknown, ctx: HandlerContext<Env>) => ({
244
+ credentialId: ctx.auth!.credentialId,
245
+ items: [],
246
+ }),
247
+
248
+ requireActiveApiAccess: async (_input: unknown, ctx: HandlerContext<Env>) => {
249
+ const credentialId = ctx.auth?.credentialId;
250
+ const paid = credentialId
251
+ ? await ctx.env.DB.prepare("SELECT 1 FROM site_api_entitlements WHERE credential_id = ? AND state = 'paid' LIMIT 1")
252
+ .bind(credentialId)
253
+ .first()
254
+ : null;
255
+ if (!paid) {
256
+ throw new DiagnosticError(
257
+ runtimeDiagnostic({
258
+ code: "ENTITLEMENT_REQUIRED",
259
+ severity: "error",
260
+ path: "site:api-entitlement",
261
+ message: "Active paid API access is required.",
262
+ }),
263
+ );
264
+ }
265
+ return {};
266
+ },
267
+
268
+ downloadExport: async ({ reportId }: { reportId: string }) => ({ reportId }),
269
+
270
+ requireActiveMembership: async (_input: unknown, ctx: HandlerContext<Env>) => {
271
+ const active = await ctx.env.DB.prepare("SELECT 1 FROM site_memberships WHERE user_id = ? AND state = 'active' LIMIT 1")
272
+ .bind(ctx.user!.id)
273
+ .first();
274
+ if (!active) {
275
+ throw new DiagnosticError(
276
+ runtimeDiagnostic({
277
+ code: "ENTITLEMENT_REQUIRED",
278
+ severity: "error",
279
+ path: `site:membership/${ctx.user!.id}`,
280
+ message: "Active membership is required.",
281
+ }),
282
+ );
283
+ }
284
+ return {};
285
+ },
286
+
287
+ readAccount: async ({ accountId }: { accountId: string }) => ({ accountId }),
288
+ };
289
+ ```
290
+
291
+ A guard receives the already validated target input and the same `HandlerContext`, runs on every call, and is never cached. Any diagnostic, throw, missing handler or invalid output fails closed; on failure the target is not invoked.
292
+
293
+ ### Wiring
294
+
295
+ ```ts
296
+ // src/index.ts
297
+ import { createMantleWorker, type MantleCloudflareEnv } from "@aotter/mantle/cloudflare";
298
+ import { plan } from "../.mantle/generated/mantle.js";
299
+ import { siteCredentialResolver } from "./auth/credentialResolver.js";
300
+ import { handlers } from "./handlers.js";
301
+
302
+ export interface Env extends MantleCloudflareEnv {
303
+ readonly DB: D1Database;
304
+ }
305
+
306
+ export default createMantleWorker<Env>({
307
+ plan,
308
+ handlers,
309
+ extend: ({ env }) => ({
310
+ credentialResolver: siteCredentialResolver(env.DB),
311
+ jwtBearer: {
312
+ audience: "https://api.example.com",
313
+ scopes: ["api"], // optional server-wide floor; manifest scopes still run per target
314
+ },
315
+ }),
316
+ });
317
+ ```
318
+
319
+ `jwtBearer` is optional; it enables JWT bearer verification for manifest REST routes against the site's own Auth issuer. See [The conventional Worker](../cloudflare/conventional-worker.md).
320
+
321
+ ## Try it
322
+
323
+ Rung 1, anonymous:
324
+
325
+ ```sh
326
+ curl -sS http://localhost:8787/api/views/public-catalog
327
+ # 200 {"ok":true,"data":{"rows":[...],"page":1,"show":100,"hasMore":false}}
328
+ ```
329
+
330
+ Rung 2, API key with scope:
331
+
332
+ ```sh
333
+ curl -i -X POST http://localhost:8787/api/catalog/read \
334
+ -H 'content-type: application/json' -H "x-api-key: $SITE_API_KEY" -d '{}'
335
+ ```
336
+
337
+ Rung 3, API key plus paid state:
338
+
339
+ ```sh
340
+ curl -i -X POST http://localhost:8787/api/exports/download \
341
+ -H 'content-type: application/json' -H "x-api-key: $SITE_API_KEY" -d '{"reportId":"report-1"}'
342
+ ```
343
+
344
+ Rung 4, personal token over REST:
345
+
346
+ ```sh
347
+ curl -i -X POST http://localhost:8787/api/accounts/read \
348
+ -H 'content-type: application/json' -H "authorization: Bearer $SITE_PERSONAL_TOKEN" -d '{"accountId":"acct-1"}'
349
+ ```
350
+
351
+ REST outcomes for a protected target:
352
+
353
+ | Caller state | HTTP | `diagnostic.code` |
354
+ |---|---|---|
355
+ | valid credential, required scope, entitled | 200 | — (`{ ok: true, data }`) |
356
+ | missing credential, or recognized but invalid or revoked | 401 | `UNAUTHENTICATED` |
357
+ | verified credential missing a required scope (or `ctx.user` for rung 4) | 403 | `AUTH_DENIED` |
358
+ | verified and scoped, but the guard finds no paid or active row | 402 | `ENTITLEMENT_REQUIRED` |
359
+
360
+ Standard remote MCP uses the MCP server's OAuth bearer, not the raw personal token. After OAuth normalization the call reaches the same target and guard:
361
+
362
+ ```sh
363
+ curl -sS -X POST http://localhost:8787/mcp \
364
+ -H 'content-type: application/json' -H "authorization: Bearer $MCP_OAUTH_ACCESS_TOKEN" \
365
+ -d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_account","arguments":{"accountId":"acct-1"}}}'
366
+ ```
367
+
368
+ | State | REST | MCP |
369
+ |---|---|---|
370
+ | valid user credential, `accounts:read`, active membership | `200` | JSON-RPC `result` |
371
+ | missing or invalid credential | `401` | OAuth layer rejects the request |
372
+ | verified caller missing `ctx.user` or `accounts:read` | `403` | JSON-RPC error, `error.data.code = "AUTH_DENIED"` |
373
+ | membership revoked while the credential stays valid | `402` | JSON-RPC error, `error.data.code = "ENTITLEMENT_REQUIRED"` |
374
+ | MCP bearer lacking the resource-level `mcp` scope | n/a | HTTP `403` plus `WWW-Authenticate: ... insufficient_scope` |
375
+
376
+ `tools/list` on `/mcp` includes `read_account` because its MCP Trigger selects the public surface, and `query_view_public_catalog` because the View is public. Discovery is not enforcement: every `tools/call` re-evaluates the predicates and the guard. `read_catalog` and `download_export` have no MCP Trigger and are not tools.
377
+
378
+ `mantle emit-openapi` reflects all of this: anonymous operations carry no `security`, protected ones list the configured schemes, repeated `ctx.auth.scope` predicates become OAuth scopes plus `x-mantle-required-scopes`, and guarded targets advertise `402` under `x-mantle-guard-procedure`.
379
+
380
+ ## What this deliberately leaves out
381
+
382
+ Mantle does not issue or store API keys or personal tokens, does not define a scope catalog, and does not read payment-provider state. Accordingly this page omits:
383
+
384
+ - **Key issuance UI.** Generating, hashing, showing once, rotating and revoking keys is application code writing to `site_credentials`.
385
+ - **Billing.** Whatever fills `site_api_entitlements` and `site_memberships` (webhooks, a Stripe sync, a manual Admin action) is outside the guard. The guard only reads the current row.
386
+ - **CORS policy and business response fields.**
387
+
388
+ Related: [Procurement approvals](./procurement-approvals.md) shows session-based `ctx.user` and `ctx.staff` predicates; [Commerce](./commerce-transaction.md) shows a payment callback that is verified by the application rather than by a guard.
389
+
390
+ ## Runnable contract check
391
+
392
+ The integration fixture uses mutable, consumer-owned credential and
393
+ entitlement fakes. It proves this sequence for one Procedure over REST and MCP:
394
+
395
+ ```text
396
+ grant -> REST succeeds -> MCP succeeds
397
+ revoke entitlement while credential remains valid
398
+ -> next REST call is 402 -> next MCP call is ENTITLEMENT_REQUIRED
399
+ ```
400
+
401
+ Run the guide/contract and normalization checks from the Mantle repository:
402
+
403
+ ```bash
404
+ pnpm --filter @aotter/mantle-cloudflare exec vitest run \
405
+ test/authorization-integration.test.ts \
406
+ test/resolve-caller.test.ts \
407
+ test/mount-http-trigger-auth.test.ts
408
+ ```
409
+
410
+ `authorization-integration.test.ts` also asserts that the handbook still
411
+ contains all four scenarios and the exact public API names used by the fixture.
412
+ The package typecheck catches changes to those APIs; the integration test
413
+ catches changes to REST/MCP enforcement and mutable guard behavior.
414
+
415
+ The canonical MCP grant check joins the JWT's exact consent and original
416
+ session in one indexed D1 statement. Both identities, their user/client
417
+ bindings, session expiration, resource and the complete token scope set must
418
+ still match. The adapter then reads the user's role on every protected request;
419
+ no grant or role result is cached. With warm JWKS, this is one grant binding
420
+ call plus one role binding call, excluding DPoP replay, catalog and tool work.
421
+
422
+ ## Source
423
+
424
+ - [`packages/adapters/cloudflare/src/mount/resolveCaller.ts`](../../../packages/adapters/cloudflare/src/mount/resolveCaller.ts) — `ConsumerCredentialResolution` shape and precedence
425
+ - [`packages/adapters/cloudflare/src/worker/createMantleWorker.ts`](../../../packages/adapters/cloudflare/src/worker/createMantleWorker.ts) — `extend` returning `credentialResolver` and `jwtBearer`
426
+ - [`packages/mantle-runtime/src/domain/model/HandlerContext.ts`](../../../packages/mantle-runtime/src/domain/model/HandlerContext.ts) — `ctx.auth`
427
+ - [`packages/mantle-runtime/src/usecase/procedure/InvokeProcedureUseCase.ts`](../../../packages/mantle-runtime/src/usecase/procedure/InvokeProcedureUseCase.ts) — guard order