@aotter/mantle 0.1.2-alpha.6 → 0.1.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.
- package/README.md +15 -10
- package/dist/cli/generate.d.ts +9 -0
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/cli/generate.js +40 -1
- package/dist/cli/generate.js.map +1 -1
- package/dist/cli/main.d.ts +1 -1
- package/dist/cli/main.d.ts.map +1 -1
- package/dist/cli/main.js +37 -9
- package/dist/cli/main.js.map +1 -1
- package/docs/adapter-guide.md +6 -1
- package/docs/adr/adr-lite-845-frontend-client.md +38 -0
- package/docs/agent-prompts.md +91 -0
- package/docs/api-mcp-authorization.md +1 -1
- package/docs/auth-hosting-model.md +1 -1
- package/docs/examples/README.md +22 -0
- package/docs/examples/builtin-commerce.md +269 -0
- package/docs/examples/builtin-intake.md +143 -0
- package/docs/examples/builtin-legal-documents.md +189 -0
- package/docs/examples/builtin-procurement.md +241 -0
- package/docs/examples/builtin-publication.md +241 -0
- package/docs/examples/builtin-reservation.md +149 -0
- package/docs/examples/cf-primitives-commerce-inventory.md +809 -0
- package/docs/examples/cf-primitives-guarded-api.md +429 -0
- package/docs/examples/cf-primitives-intake-hooks.md +319 -0
- package/docs/examples/host-chatgpt-sites/.openai/hosting.json +1 -0
- package/docs/examples/host-chatgpt-sites/README.md +53 -0
- package/docs/examples/host-chatgpt-sites/drizzle/0000_sites_users.sql +8 -0
- package/docs/examples/host-chatgpt-sites/drizzle/0001_mantle.sql +294 -0
- package/docs/examples/host-chatgpt-sites/drizzle/0002_article_cover.sql +5 -0
- package/docs/examples/host-chatgpt-sites/drizzle/meta/_journal.json +1 -0
- package/docs/examples/host-chatgpt-sites/manifests/site.yaml +27 -0
- package/docs/examples/host-chatgpt-sites/package.json +1 -0
- package/docs/examples/host-chatgpt-sites/public/site.css +1 -0
- package/docs/examples/host-chatgpt-sites/scripts/build.mjs +12 -0
- package/docs/examples/host-chatgpt-sites/scripts/check.mjs +99 -0
- package/docs/examples/host-chatgpt-sites/scripts/migration.mjs +9 -0
- package/docs/examples/host-chatgpt-sites/src/chatgpt-auth.ts +63 -0
- package/docs/examples/host-chatgpt-sites/src/index.ts +46 -0
- package/docs/examples/host-chatgpt-sites/src/mcp.ts +49 -0
- package/docs/examples/host-chatgpt-sites/src/media.ts +109 -0
- package/docs/examples/host-chatgpt-sites/src/r2-lab.ts +38 -0
- package/docs/examples/host-chatgpt-sites/src/storage-fingerprint.json +1 -0
- package/docs/examples/host-chatgpt-sites/src/web.ts +35 -0
- package/docs/examples/host-chatgpt-sites/tsconfig.json +1 -0
- package/docs/examples/host-chatgpt-sites/wrangler.jsonc +10 -0
- package/docs/examples/host-local-admin-otp/.dev.vars.example +3 -0
- package/docs/examples/host-local-admin-otp/README.md +70 -0
- package/docs/examples/host-local-admin-otp/ensure-dev-vars.mjs +5 -0
- package/docs/examples/host-local-admin-otp/package.json +29 -0
- package/docs/examples/host-local-admin-otp/public/.gitkeep +1 -0
- package/docs/examples/host-local-admin-otp/smoke.mjs +141 -0
- package/docs/examples/host-local-admin-otp/src/index.ts +54 -0
- package/docs/examples/host-local-admin-otp/wrangler.jsonc +23 -0
- package/docs/examples/{minimal-worker → host-minimal-worker}/README.md +9 -5
- package/docs/examples/host-minimal-worker/manifests/site.yaml +25 -0
- package/docs/examples/{minimal-worker → host-minimal-worker}/package.json +3 -3
- package/docs/examples/host-minimal-worker/tsconfig.json +17 -0
- package/docs/handbook/cloudflare/authentication.md +17 -2
- package/docs/handbook/cloudflare/bindings.md +9 -7
- package/docs/handbook/cloudflare/chatgpt-sites.md +29 -0
- package/docs/handbook/cloudflare/conventional-worker.md +3 -3
- package/docs/handbook/cloudflare/deferred-hooks-queues.md +0 -1
- package/docs/handbook/cloudflare/deploy-and-operate.md +14 -20
- package/docs/handbook/cloudflare/media-r2.md +2 -2
- package/docs/handbook/cloudflare/public-web.md +1 -1
- package/docs/handbook/cloudflare/site-chrome.md +75 -0
- package/docs/handbook/concepts/authorization.md +2 -2
- package/docs/handbook/concepts/four-atoms.md +2 -2
- package/docs/handbook/concepts/lifecycle-and-locales.md +1 -1
- package/docs/handbook/concepts/mcp-and-agents.md +1 -1
- package/docs/handbook/concepts/procedures-and-triggers.md +1 -1
- package/docs/handbook/concepts/runtime-and-adapters.md +2 -2
- package/docs/handbook/concepts/views.md +2 -2
- package/docs/handbook/examples/commerce-transaction.md +4 -806
- package/docs/handbook/examples/commerce.md +11 -0
- package/docs/handbook/examples/guarded-api.md +3 -420
- package/docs/handbook/examples/hub.md +10 -0
- package/docs/handbook/examples/intake-form.md +6 -313
- package/docs/handbook/examples/intake-hooks.md +11 -0
- package/docs/handbook/examples/legal-documents.md +3 -211
- package/docs/handbook/examples/procurement-approvals.md +3 -233
- package/docs/handbook/examples/publication.md +3 -233
- package/docs/handbook/examples/reservation.md +3 -213
- package/docs/handbook/navigation.json +17 -2
- package/docs/handbook/reference/authorization.md +1 -1
- package/docs/handbook/reference/procedure.md +2 -2
- package/docs/handbook/reference/schema.md +3 -3
- package/docs/handbook/reference/site-config.md +5 -16
- package/docs/handbook/reference/surface.md +3 -7
- package/docs/handbook/sites/equipment-checkout.md +231 -0
- package/docs/handbook/sites/host-reference.md +113 -0
- package/docs/handbook/sites/index.md +111 -0
- package/docs/handbook/start/project-and-cli.md +22 -14
- package/docs/handbook/start/quickstart-admin.md +239 -0
- package/docs/handbook/start/quickstart-worker.md +22 -23
- package/docs/migration-0.1.2.md +26 -0
- package/docs/release-process.md +92 -7
- package/docs/sealed-pipeline-ownership.md +2 -2
- package/docs/spec-only-host-adoption.md +3 -4
- package/docs/transaction-patterns.md +2 -2
- package/package.json +15 -15
- package/skills/README.md +18 -2
- package/skills/develop/SKILL.md +32 -23
- package/skills/install/SKILL.md +50 -11
- package/skills/provision/SKILL.md +21 -5
- /package/docs/examples/{minimal-worker → host-local-admin-otp}/manifests/site.yaml +0 -0
- /package/docs/examples/{minimal-worker → host-local-admin-otp}/tsconfig.json +0 -0
- /package/docs/examples/{minimal-worker → host-minimal-worker}/smoke.mjs +0 -0
- /package/docs/examples/{minimal-worker → host-minimal-worker}/src/index.ts +0 -0
- /package/docs/examples/{minimal-worker → host-minimal-worker}/wrangler.jsonc +0 -0
|
@@ -0,0 +1,429 @@
|
|
|
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
|
+
**Handler class:** cf-primitives · **Builder:** no · [Examples hub](./README.md).
|
|
7
|
+
|
|
8
|
+
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.
|
|
9
|
+
|
|
10
|
+
## Problem
|
|
11
|
+
|
|
12
|
+
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.
|
|
13
|
+
|
|
14
|
+
## Manifest
|
|
15
|
+
|
|
16
|
+
```yaml
|
|
17
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
18
|
+
kind: Schema
|
|
19
|
+
metadata:
|
|
20
|
+
name: catalog-items
|
|
21
|
+
spec:
|
|
22
|
+
title: Catalog items
|
|
23
|
+
lifecycle: publishing
|
|
24
|
+
uniqueIndexes:
|
|
25
|
+
- [slug]
|
|
26
|
+
schema:
|
|
27
|
+
type: object
|
|
28
|
+
additionalProperties: false
|
|
29
|
+
required: [slug, title, priceMinor]
|
|
30
|
+
properties:
|
|
31
|
+
slug: { type: string, pattern: "^[a-z0-9-]+$" }
|
|
32
|
+
title: { type: string, minLength: 1, maxLength: 160 }
|
|
33
|
+
priceMinor: { type: integer, minimum: 0, x-mcp-hint: money-minor }
|
|
34
|
+
---
|
|
35
|
+
# 1. Anonymous public read
|
|
36
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
37
|
+
kind: View
|
|
38
|
+
metadata:
|
|
39
|
+
name: public-catalog
|
|
40
|
+
spec:
|
|
41
|
+
surface: public
|
|
42
|
+
from: catalog-items
|
|
43
|
+
fields: [id, slug, title, priceMinor, updatedAt]
|
|
44
|
+
filter:
|
|
45
|
+
eq: { field: status, value: published }
|
|
46
|
+
orderBy:
|
|
47
|
+
- { field: title, direction: asc }
|
|
48
|
+
limit: 100
|
|
49
|
+
---
|
|
50
|
+
# 2. Verified credential with a scope
|
|
51
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
52
|
+
kind: Procedure
|
|
53
|
+
metadata:
|
|
54
|
+
name: read-catalog
|
|
55
|
+
spec:
|
|
56
|
+
requires:
|
|
57
|
+
auth:
|
|
58
|
+
all:
|
|
59
|
+
- ctx.auth
|
|
60
|
+
- { "ctx.auth.scope": "catalog:read" }
|
|
61
|
+
input: { type: object }
|
|
62
|
+
output: { type: object }
|
|
63
|
+
handler: { kind: ref, ref: readCatalog }
|
|
64
|
+
---
|
|
65
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
66
|
+
kind: Trigger
|
|
67
|
+
metadata:
|
|
68
|
+
name: read-catalog-http
|
|
69
|
+
spec:
|
|
70
|
+
source: { kind: http, method: POST, path: /api/catalog/read }
|
|
71
|
+
target: { procedure: read-catalog }
|
|
72
|
+
---
|
|
73
|
+
# 3. Scope plus a live entitlement guard
|
|
74
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
75
|
+
kind: Procedure
|
|
76
|
+
metadata:
|
|
77
|
+
name: require-active-api-access
|
|
78
|
+
spec:
|
|
79
|
+
input: { type: object }
|
|
80
|
+
output: { type: object }
|
|
81
|
+
handler: { kind: ref, ref: requireActiveApiAccess }
|
|
82
|
+
---
|
|
83
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
84
|
+
kind: Procedure
|
|
85
|
+
metadata:
|
|
86
|
+
name: download-export
|
|
87
|
+
spec:
|
|
88
|
+
requires:
|
|
89
|
+
auth:
|
|
90
|
+
all:
|
|
91
|
+
- ctx.auth
|
|
92
|
+
- { "ctx.auth.scope": "exports:read" }
|
|
93
|
+
guard: { procedure: require-active-api-access }
|
|
94
|
+
input:
|
|
95
|
+
type: object
|
|
96
|
+
required: [reportId]
|
|
97
|
+
properties:
|
|
98
|
+
reportId: { type: string }
|
|
99
|
+
output: { type: object }
|
|
100
|
+
handler: { kind: ref, ref: downloadExport }
|
|
101
|
+
---
|
|
102
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
103
|
+
kind: Trigger
|
|
104
|
+
metadata:
|
|
105
|
+
name: download-export-http
|
|
106
|
+
spec:
|
|
107
|
+
source: { kind: http, method: POST, path: /api/exports/download }
|
|
108
|
+
target: { procedure: download-export }
|
|
109
|
+
---
|
|
110
|
+
# 4. Personal token with a user subject, shared by REST and MCP
|
|
111
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
112
|
+
kind: Procedure
|
|
113
|
+
metadata:
|
|
114
|
+
name: require-active-membership
|
|
115
|
+
spec:
|
|
116
|
+
input: { type: object }
|
|
117
|
+
output: { type: object }
|
|
118
|
+
handler: { kind: ref, ref: requireActiveMembership }
|
|
119
|
+
---
|
|
120
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
121
|
+
kind: Procedure
|
|
122
|
+
metadata:
|
|
123
|
+
name: read-account
|
|
124
|
+
spec:
|
|
125
|
+
requires:
|
|
126
|
+
auth:
|
|
127
|
+
all:
|
|
128
|
+
- ctx.user
|
|
129
|
+
- ctx.auth
|
|
130
|
+
- { "ctx.auth.scope": "accounts:read" }
|
|
131
|
+
guard: { procedure: require-active-membership }
|
|
132
|
+
input:
|
|
133
|
+
type: object
|
|
134
|
+
required: [accountId]
|
|
135
|
+
properties:
|
|
136
|
+
accountId: { type: string }
|
|
137
|
+
output:
|
|
138
|
+
type: object
|
|
139
|
+
required: [accountId]
|
|
140
|
+
properties:
|
|
141
|
+
accountId: { type: string }
|
|
142
|
+
handler: { kind: ref, ref: readAccount }
|
|
143
|
+
---
|
|
144
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
145
|
+
kind: Trigger
|
|
146
|
+
metadata:
|
|
147
|
+
name: read-account-http
|
|
148
|
+
spec:
|
|
149
|
+
source: { kind: http, method: POST, path: /api/accounts/read }
|
|
150
|
+
target: { procedure: read-account }
|
|
151
|
+
---
|
|
152
|
+
apiVersion: cms.mantle.aotter.net/v1
|
|
153
|
+
kind: Trigger
|
|
154
|
+
metadata:
|
|
155
|
+
name: read-account-mcp
|
|
156
|
+
spec:
|
|
157
|
+
source: { kind: mcp, surface: public }
|
|
158
|
+
target: { procedure: read-account }
|
|
159
|
+
```
|
|
160
|
+
|
|
161
|
+
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](../handbook/concepts/authorization.md) and the [authorization reference](../handbook/reference/authorization.md).
|
|
162
|
+
|
|
163
|
+
## Worker and handlers
|
|
164
|
+
|
|
165
|
+
### Credential resolver
|
|
166
|
+
|
|
167
|
+
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 does not create or own it.
|
|
168
|
+
|
|
169
|
+
```ts
|
|
170
|
+
// src/auth/credentialResolver.ts
|
|
171
|
+
import type { ConsumerCredentialResolver } from "@aotter/mantle/cloudflare";
|
|
172
|
+
|
|
173
|
+
type CredentialRow = {
|
|
174
|
+
id: string;
|
|
175
|
+
kind: "api-key" | "personal-token";
|
|
176
|
+
user_id: string | null;
|
|
177
|
+
scopes_json: string;
|
|
178
|
+
revoked_at: string | null;
|
|
179
|
+
};
|
|
180
|
+
|
|
181
|
+
export function siteCredentialResolver(db: D1Database): ConsumerCredentialResolver {
|
|
182
|
+
return async (request) => {
|
|
183
|
+
const apiKey = request.headers.get("x-api-key");
|
|
184
|
+
const authorization = request.headers.get("authorization");
|
|
185
|
+
|
|
186
|
+
let kind: CredentialRow["kind"];
|
|
187
|
+
let raw: string;
|
|
188
|
+
if (apiKey !== null) {
|
|
189
|
+
kind = "api-key";
|
|
190
|
+
raw = apiKey;
|
|
191
|
+
} else if (authorization?.startsWith("Bearer site_pat_")) {
|
|
192
|
+
kind = "personal-token";
|
|
193
|
+
raw = authorization.slice("Bearer ".length);
|
|
194
|
+
} else {
|
|
195
|
+
return { kind: "not-handled" }; // let OAuth bearer or the cookie session try next
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
const digest = await sha256(raw);
|
|
199
|
+
const row = await db
|
|
200
|
+
.prepare("SELECT id, kind, user_id, scopes_json, revoked_at FROM site_credentials WHERE token_sha256 = ? AND kind = ? LIMIT 1")
|
|
201
|
+
.bind(digest, kind)
|
|
202
|
+
.first<CredentialRow>();
|
|
203
|
+
if (!row || row.revoked_at !== null) return { kind: "invalid" };
|
|
204
|
+
|
|
205
|
+
const scopes = parseScopes(row.scopes_json);
|
|
206
|
+
if (!scopes) return { kind: "invalid" };
|
|
207
|
+
return {
|
|
208
|
+
kind: "verified",
|
|
209
|
+
credential: {
|
|
210
|
+
credential: row.kind,
|
|
211
|
+
credentialId: row.id, // opaque row id, never the raw key
|
|
212
|
+
userId: row.user_id,
|
|
213
|
+
scopes,
|
|
214
|
+
},
|
|
215
|
+
};
|
|
216
|
+
};
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
async function sha256(value: string): Promise<string> {
|
|
220
|
+
const bytes = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(value));
|
|
221
|
+
return [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function parseScopes(json: string): string[] | null {
|
|
225
|
+
try {
|
|
226
|
+
const value: unknown = JSON.parse(json);
|
|
227
|
+
return Array.isArray(value) && value.every((s) => typeof s === "string") ? value : null;
|
|
228
|
+
} catch {
|
|
229
|
+
return null;
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
```
|
|
233
|
+
|
|
234
|
+
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.
|
|
235
|
+
|
|
236
|
+
### Guards and targets
|
|
237
|
+
|
|
238
|
+
```ts
|
|
239
|
+
// src/handlers.ts
|
|
240
|
+
import { DiagnosticError, runtimeDiagnostic } from "@aotter/mantle/spec";
|
|
241
|
+
import type { HandlerContext } from "@aotter/mantle/runtime";
|
|
242
|
+
import type { Env } from "./index.js";
|
|
243
|
+
|
|
244
|
+
export const handlers = {
|
|
245
|
+
readCatalog: async (_input: unknown, ctx: HandlerContext<Env>) => ({
|
|
246
|
+
credentialId: ctx.auth!.credentialId,
|
|
247
|
+
items: [],
|
|
248
|
+
}),
|
|
249
|
+
|
|
250
|
+
requireActiveApiAccess: async (_input: unknown, ctx: HandlerContext<Env>) => {
|
|
251
|
+
const credentialId = ctx.auth?.credentialId;
|
|
252
|
+
const paid = credentialId
|
|
253
|
+
? await ctx.env.DB.prepare("SELECT 1 FROM site_api_entitlements WHERE credential_id = ? AND state = 'paid' LIMIT 1")
|
|
254
|
+
.bind(credentialId)
|
|
255
|
+
.first()
|
|
256
|
+
: null;
|
|
257
|
+
if (!paid) {
|
|
258
|
+
throw new DiagnosticError(
|
|
259
|
+
runtimeDiagnostic({
|
|
260
|
+
code: "ENTITLEMENT_REQUIRED",
|
|
261
|
+
severity: "error",
|
|
262
|
+
path: "site:api-entitlement",
|
|
263
|
+
message: "Active paid API access is required.",
|
|
264
|
+
}),
|
|
265
|
+
);
|
|
266
|
+
}
|
|
267
|
+
return {};
|
|
268
|
+
},
|
|
269
|
+
|
|
270
|
+
downloadExport: async ({ reportId }: { reportId: string }) => ({ reportId }),
|
|
271
|
+
|
|
272
|
+
requireActiveMembership: async (_input: unknown, ctx: HandlerContext<Env>) => {
|
|
273
|
+
const active = await ctx.env.DB.prepare("SELECT 1 FROM site_memberships WHERE user_id = ? AND state = 'active' LIMIT 1")
|
|
274
|
+
.bind(ctx.user!.id)
|
|
275
|
+
.first();
|
|
276
|
+
if (!active) {
|
|
277
|
+
throw new DiagnosticError(
|
|
278
|
+
runtimeDiagnostic({
|
|
279
|
+
code: "ENTITLEMENT_REQUIRED",
|
|
280
|
+
severity: "error",
|
|
281
|
+
path: `site:membership/${ctx.user!.id}`,
|
|
282
|
+
message: "Active membership is required.",
|
|
283
|
+
}),
|
|
284
|
+
);
|
|
285
|
+
}
|
|
286
|
+
return {};
|
|
287
|
+
},
|
|
288
|
+
|
|
289
|
+
readAccount: async ({ accountId }: { accountId: string }) => ({ accountId }),
|
|
290
|
+
};
|
|
291
|
+
```
|
|
292
|
+
|
|
293
|
+
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.
|
|
294
|
+
|
|
295
|
+
### Wiring
|
|
296
|
+
|
|
297
|
+
```ts
|
|
298
|
+
// src/index.ts
|
|
299
|
+
import { createMantleWorker, type MantleCloudflareEnv } from "@aotter/mantle/cloudflare";
|
|
300
|
+
import { plan } from "../.mantle/generated/mantle.js";
|
|
301
|
+
import { siteCredentialResolver } from "./auth/credentialResolver.js";
|
|
302
|
+
import { handlers } from "./handlers.js";
|
|
303
|
+
|
|
304
|
+
export interface Env extends MantleCloudflareEnv {
|
|
305
|
+
readonly DB: D1Database;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
export default createMantleWorker<Env>({
|
|
309
|
+
plan,
|
|
310
|
+
handlers,
|
|
311
|
+
extend: ({ env }) => ({
|
|
312
|
+
credentialResolver: siteCredentialResolver(env.DB),
|
|
313
|
+
jwtBearer: {
|
|
314
|
+
audience: "https://api.example.com",
|
|
315
|
+
scopes: ["api"], // optional server-wide floor; manifest scopes still run per target
|
|
316
|
+
},
|
|
317
|
+
}),
|
|
318
|
+
});
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
`jwtBearer` is optional; it enables JWT bearer verification for manifest REST routes against the site's own Auth issuer. See [The conventional Worker](../handbook/cloudflare/conventional-worker.md).
|
|
322
|
+
|
|
323
|
+
## Try it
|
|
324
|
+
|
|
325
|
+
Rung 1, anonymous:
|
|
326
|
+
|
|
327
|
+
```sh
|
|
328
|
+
curl -sS http://localhost:8787/api/views/public-catalog
|
|
329
|
+
# 200 {"ok":true,"data":{"rows":[...],"page":1,"show":100,"hasMore":false}}
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Rung 2, API key with scope:
|
|
333
|
+
|
|
334
|
+
```sh
|
|
335
|
+
curl -i -X POST http://localhost:8787/api/catalog/read \
|
|
336
|
+
-H 'content-type: application/json' -H "x-api-key: $SITE_API_KEY" -d '{}'
|
|
337
|
+
```
|
|
338
|
+
|
|
339
|
+
Rung 3, API key plus paid state:
|
|
340
|
+
|
|
341
|
+
```sh
|
|
342
|
+
curl -i -X POST http://localhost:8787/api/exports/download \
|
|
343
|
+
-H 'content-type: application/json' -H "x-api-key: $SITE_API_KEY" -d '{"reportId":"report-1"}'
|
|
344
|
+
```
|
|
345
|
+
|
|
346
|
+
Rung 4, personal token over REST:
|
|
347
|
+
|
|
348
|
+
```sh
|
|
349
|
+
curl -i -X POST http://localhost:8787/api/accounts/read \
|
|
350
|
+
-H 'content-type: application/json' -H "authorization: Bearer $SITE_PERSONAL_TOKEN" -d '{"accountId":"acct-1"}'
|
|
351
|
+
```
|
|
352
|
+
|
|
353
|
+
REST outcomes for a protected target:
|
|
354
|
+
|
|
355
|
+
| Caller state | HTTP | `diagnostic.code` |
|
|
356
|
+
|---|---|---|
|
|
357
|
+
| valid credential, required scope, entitled | 200 | — (`{ ok: true, data }`) |
|
|
358
|
+
| missing credential, or recognized but invalid or revoked | 401 | `UNAUTHENTICATED` |
|
|
359
|
+
| verified credential missing a required scope (or `ctx.user` for rung 4) | 403 | `AUTH_DENIED` |
|
|
360
|
+
| verified and scoped, but the guard finds no paid or active row | 402 | `ENTITLEMENT_REQUIRED` |
|
|
361
|
+
|
|
362
|
+
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:
|
|
363
|
+
|
|
364
|
+
```sh
|
|
365
|
+
curl -sS -X POST http://localhost:8787/mcp \
|
|
366
|
+
-H 'content-type: application/json' -H "authorization: Bearer $MCP_OAUTH_ACCESS_TOKEN" \
|
|
367
|
+
-d '{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{"name":"read_account","arguments":{"accountId":"acct-1"}}}'
|
|
368
|
+
```
|
|
369
|
+
|
|
370
|
+
| State | REST | MCP |
|
|
371
|
+
|---|---|---|
|
|
372
|
+
| valid user credential, `accounts:read`, active membership | `200` | JSON-RPC `result` |
|
|
373
|
+
| missing or invalid credential | `401` | OAuth layer rejects the request |
|
|
374
|
+
| verified caller missing `ctx.user` or `accounts:read` | `403` | JSON-RPC error, `error.data.code = "AUTH_DENIED"` |
|
|
375
|
+
| membership revoked while the credential stays valid | `402` | JSON-RPC error, `error.data.code = "ENTITLEMENT_REQUIRED"` |
|
|
376
|
+
| MCP bearer lacking the resource-level `mcp` scope | n/a | HTTP `403` plus `WWW-Authenticate: ... insufficient_scope` |
|
|
377
|
+
|
|
378
|
+
`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.
|
|
379
|
+
|
|
380
|
+
`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`.
|
|
381
|
+
|
|
382
|
+
## What this deliberately leaves out
|
|
383
|
+
|
|
384
|
+
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:
|
|
385
|
+
|
|
386
|
+
- **Key issuance UI.** Generating, hashing, showing once, rotating and revoking keys is application code writing to `site_credentials`.
|
|
387
|
+
- **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.
|
|
388
|
+
- **CORS policy and business response fields.**
|
|
389
|
+
|
|
390
|
+
Related: [Procurement approvals](./builtin-procurement.md) shows session-based `ctx.user` and `ctx.staff` predicates; [Commerce](./cf-primitives-commerce-inventory.md) shows a payment callback that is verified by the application rather than by a guard.
|
|
391
|
+
|
|
392
|
+
## Runnable contract check
|
|
393
|
+
|
|
394
|
+
The integration fixture uses mutable, consumer-owned credential and
|
|
395
|
+
entitlement fakes. It proves this sequence for one Procedure over REST and MCP:
|
|
396
|
+
|
|
397
|
+
```text
|
|
398
|
+
grant -> REST succeeds -> MCP succeeds
|
|
399
|
+
revoke entitlement while credential remains valid
|
|
400
|
+
-> next REST call is 402 -> next MCP call is ENTITLEMENT_REQUIRED
|
|
401
|
+
```
|
|
402
|
+
|
|
403
|
+
Run the guide/contract and normalization checks from the Mantle repository:
|
|
404
|
+
|
|
405
|
+
```bash
|
|
406
|
+
pnpm --filter @aotter/mantle-cloudflare exec vitest run \
|
|
407
|
+
test/authorization-integration.test.ts \
|
|
408
|
+
test/resolve-caller.test.ts \
|
|
409
|
+
test/mount-http-trigger-auth.test.ts
|
|
410
|
+
```
|
|
411
|
+
|
|
412
|
+
`authorization-integration.test.ts` also asserts that the handbook still
|
|
413
|
+
contains all four scenarios and the exact public API names used by the fixture.
|
|
414
|
+
The package typecheck catches changes to those APIs; the integration test
|
|
415
|
+
catches changes to REST/MCP enforcement and mutable guard behavior.
|
|
416
|
+
|
|
417
|
+
The canonical MCP grant check joins the JWT's exact consent and original
|
|
418
|
+
session in one indexed D1 statement. Both identities, their user/client
|
|
419
|
+
bindings, session expiration, resource and the complete token scope set must
|
|
420
|
+
still match. The adapter then reads the user's role on every protected request;
|
|
421
|
+
no grant or role result is cached. With warm JWKS, this is one grant binding
|
|
422
|
+
call plus one role binding call, excluding DPoP replay, catalog and tool work.
|
|
423
|
+
|
|
424
|
+
## Source
|
|
425
|
+
|
|
426
|
+
- [`packages/adapters/cloudflare/src/mount/resolveCaller.ts`](../../packages/adapters/cloudflare/src/mount/resolveCaller.ts) — `ConsumerCredentialResolution` shape and precedence
|
|
427
|
+
- [`packages/adapters/cloudflare/src/worker/createMantleWorker.ts`](../../packages/adapters/cloudflare/src/worker/createMantleWorker.ts) — `extend` returning `credentialResolver` and `jwtBearer`
|
|
428
|
+
- [`packages/mantle-runtime/src/domain/model/HandlerContext.ts`](../../packages/mantle-runtime/src/domain/model/HandlerContext.ts) — `ctx.auth`
|
|
429
|
+
- [`packages/mantle-runtime/src/usecase/procedure/InvokeProcedureUseCase.ts`](../../packages/mantle-runtime/src/usecase/procedure/InvokeProcedureUseCase.ts) — guard order
|