@fabrika/auth-core 0.6.0 → 0.8.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.6.0",
3
+ "version": "0.8.0",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -11,6 +11,7 @@ import type {
11
11
  OutputShape,
12
12
  RoleArtifact,
13
13
  SchemaShape,
14
+ TableActionArtifact,
14
15
  TablePolicyArtifact,
15
16
  } from './contract'
16
17
 
@@ -21,6 +22,7 @@ import type {
21
22
  */
22
23
  export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifact {
23
24
  return {
25
+ format: artifact.format,
24
26
  app: artifact.app,
25
27
  dimensions: artifact.dimensions,
26
28
  actions: artifact.actions,
@@ -31,6 +33,9 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
31
33
  types: sorted(collection.types),
32
34
  link: typeof collection.link === 'boolean' ? collection.link : sorted(collection.link),
33
35
  })),
36
+ ...(artifact.fileKinds === undefined
37
+ ? {}
38
+ : { fileKinds: mapValues(artifact.fileKinds, (kind) => ({ ...kind, types: sorted(kind.types) })) }),
34
39
  jobs: mapValues(artifact.jobs, (job) => ({ ...job, actions: sorted(job.actions) })),
35
40
  exports: mapValues(artifact.exports, (declaration) => ({ ...declaration, consumers: sorted(declaration.consumers) })),
36
41
  imports: mapValues(artifact.imports, (declaration) => ({
@@ -46,19 +51,37 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
46
51
  ...(artifact.csp.frameSrc === undefined ? {} : { frameSrc: sortedSources(artifact.csp.frameSrc) }),
47
52
  ...(artifact.csp.styleSrc === undefined ? {} : { styleSrc: sortedSources(artifact.csp.styleSrc) }),
48
53
  ...(artifact.csp.fontSrc === undefined ? {} : { fontSrc: sortedSources(artifact.csp.fontSrc) }),
54
+ ...(artifact.csp.workerSrc === undefined ? {} : { workerSrc: sortedSources(artifact.csp.workerSrc) }),
49
55
  },
50
56
  tables: mapValues(artifact.tables, canonicalTable),
51
57
  endpoints: artifact.endpoints.map(canonicalizeEndpoint).sort((a, b) => compare(a.id, b.id)),
52
58
  reservedPrefixes: sorted(artifact.reservedPrefixes),
53
59
  ...(artifact.declared === undefined
54
60
  ? {}
55
- : { declared: mapValues(artifact.declared, (reach) => ({ ...reach, connect: sorted(reach.connect) })) }),
61
+ : {
62
+ declared: mapValues(artifact.declared, (reach) => ({
63
+ ...reach,
64
+ connect: sorted(reach.connect),
65
+ ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
66
+ ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
67
+ ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
68
+ ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
69
+ })),
70
+ }),
56
71
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
57
72
  ...(artifact.locale === undefined ? {} : { locale: artifact.locale }),
58
73
  ...(artifact.displayName === undefined ? {} : { displayName: artifact.displayName }),
59
74
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
60
75
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
61
76
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
77
+ ...(artifact.procedures === undefined
78
+ ? {}
79
+ : {
80
+ procedures: mapValues(artifact.procedures, (rules) => rules.query === undefined ? rules : { ...rules, query: canonicalShape(rules.query) }),
81
+ }),
82
+ ...(artifact.tokens === undefined
83
+ ? {}
84
+ : { tokens: mapValues(artifact.tokens, (purpose) => ({ claims: canonicalShape(purpose.claims), maxDays: purpose.maxDays })) }),
62
85
  }
63
86
  }
64
87
 
@@ -83,7 +106,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
83
106
  function canonicalMount(mount: MountArtifact): MountArtifact {
84
107
  switch (mount.kind) {
85
108
  case 'rpc':
86
- return { ...mount, callers: sortedTuple(mount.callers) }
109
+ return { ...mount, callers: sorted(mount.callers) }
87
110
  case 'link':
88
111
  return { ...mount, grants: sorted(mount.grants) }
89
112
  case 'webhook':
@@ -95,12 +118,32 @@ function canonicalMount(mount: MountArtifact): MountArtifact {
95
118
  }
96
119
  }
97
120
 
121
+ /** Each action of one table operation, `[]` for none: how a reader of the artifact reads `actions.read` and the others. */
122
+ export function tableActions(actions: TableActionArtifact | null): readonly string[] {
123
+ if (actions === null) {
124
+ return []
125
+ }
126
+ return typeof actions === 'string' ? [actions] : actions
127
+ }
128
+
129
+ /** A list of actions sorted; one action as it is. */
130
+ function canonicalActions(actions: TableActionArtifact): TableActionArtifact {
131
+ return typeof actions === 'string' ? actions : sorted(actions)
132
+ }
133
+
134
+ function canonicalOptionalActions(actions: TableActionArtifact | null): TableActionArtifact | null {
135
+ return actions === null ? null : canonicalActions(actions)
136
+ }
137
+
98
138
  function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
99
139
  const { appRead, appCount } = table.actions
100
140
  return {
101
141
  ...table,
102
142
  actions: {
103
- ...table.actions,
143
+ read: canonicalActions(table.actions.read),
144
+ insert: canonicalOptionalActions(table.actions.insert),
145
+ update: canonicalOptionalActions(table.actions.update),
146
+ delete: canonicalOptionalActions(table.actions.delete),
104
147
  ...(appRead === undefined ? {} : { appRead: sorted(appRead) }),
105
148
  ...(appCount === undefined ? {} : { appCount: sorted(appCount) }),
106
149
  },
@@ -129,6 +172,9 @@ export function canonicalAdmission(admission: BodyAdmission): BodyAdmission {
129
172
 
130
173
  /** An output shape: an attachment keeps its column order, which is the file's; each column's shape is canonical. */
131
174
  export function canonicalOutput(shape: OutputShape): OutputShape {
175
+ if (shape.type === 'redirect') {
176
+ return { type: 'redirect', origins: sorted(shape.origins) }
177
+ }
132
178
  if (shape.type !== 'attachment') {
133
179
  return canonicalShape(shape)
134
180
  }
package/src/contract.ts CHANGED
@@ -4,6 +4,12 @@
4
4
  import type { Locale } from './locale'
5
5
  import type { MailTemplates } from './mail'
6
6
 
7
+ /**
8
+ * The artifact format this release writes. A release that changes the artifact raises it, and Control upcasts every
9
+ * older format of its window to this one (ADR-0062). The 0.4, 0.5 and 0.6 artifacts carry no `format`.
10
+ */
11
+ export const CONTRACT_FORMAT = 2
12
+
7
13
  /**
8
14
  * An application's whole access surface as plain JSON. `compileContract` produces it from the evaluated contract and
9
15
  * the static reader from source; both must produce the same value for the same contract. Every optional authored
@@ -11,6 +17,7 @@ import type { MailTemplates } from './mail'
11
17
  * carry no meaning.
12
18
  */
13
19
  export interface ContractArtifact extends EndpointTable {
20
+ readonly format: typeof CONTRACT_FORMAT
14
21
  readonly app: string
15
22
  readonly dimensions: Readonly<Record<string, DimensionArtifact>>
16
23
  /** Action → description. Exact actions only; the artifact holds no wildcard. */
@@ -18,6 +25,11 @@ export interface ContractArtifact extends EndpointTable {
18
25
  readonly roles: Readonly<Record<string, RoleArtifact>>
19
26
  readonly mounts: Readonly<Record<string, MountArtifact>>
20
27
  readonly files: Readonly<Record<string, FileCollectionArtifact>>
28
+ /**
29
+ * The file kinds (`c.files({ types, maxBytes, scan? })`): classes of stored files a table's file column holds. A kind
30
+ * has no owner and no endpoint; the table that holds a file is its authority. Absent unless declared, so the digest stays.
31
+ */
32
+ readonly fileKinds?: Readonly<Record<string, FileKindArtifact>>
21
33
  readonly jobs: Readonly<Record<string, JobArtifact>>
22
34
  readonly exports: Readonly<Record<string, ExportArtifact>>
23
35
  readonly imports: Readonly<Record<string, ImportArtifact>>
@@ -49,6 +61,56 @@ export interface ContractArtifact extends EndpointTable {
49
61
  readonly members?: { readonly manage: string; readonly list: string }
50
62
  /** `labels`: the application's directory shows labels to `members.list` holders. Absent unless declared, so digests stay. */
51
63
  readonly directory?: 'labels'
64
+ /**
65
+ * What each procedure of the staged kit admits and how long it runs, by endpoint id, with every default applied: the
66
+ * rules the application applies itself, beside the row the proxy applies. Absent for a contract with no such
67
+ * procedure (a `defineContract` one, an older release's), so its digest stays.
68
+ */
69
+ readonly procedures?: Readonly<Record<string, ProcedureArtifact>>
70
+ /**
71
+ * The purposes of the signed tokens the application issues (`token(Claims, { maxDays })` of `defineApp`'s options): each
72
+ * purpose's claims and the longest lifetime a token of it may have. Control keeps a retired signing key verifying until
73
+ * the last token it signed may expire. Absent unless declared, so the digest stays.
74
+ */
75
+ readonly tokens?: Readonly<Record<string, TokenPurposeArtifact>>
76
+ }
77
+
78
+ /** One token purpose: the claims a token of it carries, and the most days a site may sign one for. */
79
+ export interface TokenPurposeArtifact {
80
+ readonly claims: SchemaShape
81
+ readonly maxDays: number
82
+ }
83
+
84
+ /**
85
+ * One procedure's own admission and time limit, effective values only. The body limit and codec are the row's
86
+ * `admission`, the origin rule its `crossOrigin`.
87
+ */
88
+ export interface ProcedureArtifact {
89
+ readonly rate: AdmissionRate
90
+ /** The challenge the framework verifies before the handler; a public procedure only. */
91
+ readonly challenge: ProcedureChallenge | null
92
+ /** How long the handler may run after the last body byte, in ms. */
93
+ readonly timeoutMs: number
94
+ /** A POST's flat schema of the URL's parameters, the handler's `query`; absent without one, so digests stay. */
95
+ readonly query?: SchemaShape
96
+ /**
97
+ * A public mutation served on `GET` (its input holds a signed token): a link scanner that follows the URL changes
98
+ * state. Absent otherwise, so digests stay.
99
+ */
100
+ readonly changesStateOnGet?: true
101
+ }
102
+
103
+ /**
104
+ * A procedure's buckets, per minute and shared by every instance; `null` is no bucket. `perClient` counts by the client
105
+ * address (public only), `perCaller` by the principal or link key (credentialed and link only), `perEndpoint` every
106
+ * call. Every bucket is charged before the body is read and stays charged whatever the handler does.
107
+ */
108
+ export interface AdmissionRate {
109
+ readonly perClient: number | null
110
+ readonly perCaller: number | null
111
+ readonly perEndpoint: number | null
112
+ /** The bytes the procedure's file fields may write per hour, all calls together. */
113
+ readonly bytesPerHour: number | null
52
114
  }
53
115
 
54
116
  // ── The endpoint table ──────────────────────────────────────────────────────────────────────────
@@ -82,15 +144,20 @@ export type CredentialedEndpointKind = 'query' | 'mutation' | 'spa' | 'upload' |
82
144
 
83
145
  /**
84
146
  * Fixed anonymous kinds: no caller, no requirement, no token. `link-spa` is the shell of a link mount's SPA;
85
- * `public-spa` is an SPA anyone opens (`access: { public: true }`).
147
+ * `public-spa` is an SPA anyone opens (`access: { public: true }`); `public` is a procedure anyone calls, whose handler
148
+ * runs as the endpoint's own workload. A proxy that does not know `public` refuses the manifest that holds one, so no
149
+ * proxy serves a public procedure without its admission rules.
86
150
  */
87
- export type AnonymousEndpointKind = 'health' | 'form' | 'webhook' | 'link-spa' | 'public-spa'
151
+ export type AnonymousEndpointKind = 'health' | 'form' | 'webhook' | 'link-spa' | 'public-spa' | 'public'
88
152
 
89
153
  export type EndpointKind = CredentialedEndpointKind | AnonymousEndpointKind
90
154
 
91
- /** The contract entry that declared an endpoint. */
155
+ /**
156
+ * The contract entry that declared an endpoint. A `challenge` row is the framework's own: the endpoint that issues the
157
+ * ALTCHA challenge of the public procedure `name`.
158
+ */
92
159
  export interface EndpointSource {
93
- readonly kind: 'mount' | 'export' | 'files'
160
+ readonly kind: 'mount' | 'export' | 'files' | 'challenge'
94
161
  readonly name: string
95
162
  }
96
163
 
@@ -110,18 +177,55 @@ interface EndpointRowBase {
110
177
  readonly output: OutputShape | null
111
178
  /**
112
179
  * Whether a page on another origin may call the endpoint (ADR-0022 "Cross-origin endpoints"): `environment` from
113
- * the origins its environment lists, `any` (a form only) from every origin. Absent unless declared, so every other
114
- * row keeps its digest. Only an RPC procedure and a form may carry it.
180
+ * the origins its environment lists, `any` (a form or a public procedure only) from every origin. Absent unless
181
+ * declared, so every other row keeps its digest. Only an RPC procedure, a public procedure and a form may carry it.
115
182
  */
116
183
  readonly crossOrigin?: CrossOriginForm
184
+ /**
185
+ * `file`: the procedure answers a stored file (an output `file('<kind>')`), so the proxy and the application give every
186
+ * answer of it, a denial included, ADR-0022's file treatment. Absent otherwise, so every other row keeps its digest.
187
+ */
188
+ readonly response?: EndpointResponse
189
+ /**
190
+ * How long a browser or a CDN may reuse a successful answer: a public `GET` query only (`http.cache`). Absent for
191
+ * every other row, which answers `no-store`, so every row without it keeps its digest.
192
+ */
193
+ readonly cache?: EndpointCache
194
+ /**
195
+ * `forward`: the proxy passes the request's own `Authorization` to the application, never reading it as a platform
196
+ * credential: a webhook row whose verifier (`basic`, `bearer`) compares it with the binding's secret. A value that
197
+ * carries a `px_` key is still removed, and every other anonymous row loses the header (ADR-0022 rule 3). Absent
198
+ * otherwise, so every other row keeps its digest.
199
+ */
200
+ readonly authorization?: EndpointAuthorization
117
201
  }
118
202
 
119
- /** How an endpoint admits another origin: from the environment's list, or (a form only) from any origin. */
203
+ /** What the proxy does with an anonymous request's `Authorization` on a row that names it: forward it to the application. */
204
+ export type EndpointAuthorization = 'forward'
205
+
206
+ /** The answer profile of a row that answers a stored file. */
207
+ export type EndpointResponse = 'file'
208
+
209
+ /** A cacheable row's lifetime: `maxAgeSeconds`, or `immutable`, a year, for an input that names an immutable value. */
210
+ export type EndpointCache = { readonly maxAgeSeconds: number } | 'immutable'
211
+
212
+ /** The longest `maxAgeSeconds`: one year, the lifetime the proxy gives `immutable` too. */
213
+ export const MAX_CACHE_AGE_SECONDS = 31_536_000
214
+
215
+ /** The endpoint kinds whose row may answer a stored file: a procedure's. */
216
+ export const FILE_RESPONSE_KINDS: readonly EndpointKind[] = ['query', 'mutation', 'public']
217
+
218
+ /** Whether every answer of a row gets the file treatment: a collection's download, or a procedure that answers a file. */
219
+ export function answersFile(row: { readonly kind: string; readonly response?: EndpointResponse }): boolean {
220
+ return row.kind === 'download' || row.response === 'file'
221
+ }
222
+
223
+ /** How an endpoint admits another origin: from the environment's list, or (a form or a public procedure) from any origin. */
120
224
  export type CrossOriginForm = 'environment' | 'any'
121
225
 
122
- /** The endpoint kinds that may declare `crossOrigin`, and the one of them that may admit any origin. */
123
- export const CROSS_ORIGIN_KINDS: readonly EndpointKind[] = ['query', 'mutation', 'form']
124
- export const ANY_ORIGIN_KINDS: readonly EndpointKind[] = ['form']
226
+ /** The endpoint kinds that may declare `crossOrigin`, and those of them that may admit any origin. */
227
+ export const CROSS_ORIGIN_KINDS: readonly EndpointKind[] = ['query', 'mutation', 'form', 'public']
228
+ export const ANY_ORIGIN_KINDS: readonly EndpointKind[] = ['form', 'public']
125
229
 
126
230
  export interface CredentialedEndpoint extends EndpointRowBase {
127
231
  readonly kind: CredentialedEndpointKind
@@ -147,7 +251,7 @@ export interface BodyAdmission {
147
251
  * `action` is that action in some scope, global included, and only globally under the `app` form. The access form is
148
252
  * what the framework then resolves.
149
253
  */
150
- export type EndpointRequirement = MemberRequirement | ActionRequirement
254
+ export type EndpointRequirement = MemberRequirement | ActionRequirement | CapabilitiesRequirement
151
255
 
152
256
  export interface MemberRequirement {
153
257
  readonly kind: 'member'
@@ -159,6 +263,26 @@ export interface ActionRequirement {
159
263
  readonly access: AccessForm
160
264
  }
161
265
 
266
+ /**
267
+ * Several capabilities (`access: { capabilities }`), by the name the handler reads each under (`ctx.capabilities.<name>`):
268
+ * the token must carry every action, and the access form of each narrows it as it narrows a single one. At least two.
269
+ */
270
+ export interface CapabilitiesRequirement {
271
+ readonly kind: 'capabilities'
272
+ readonly capabilities: Readonly<Record<string, CapabilityRequirement>>
273
+ }
274
+
275
+ /** One capability of several: an action in a dimension, its value read from an input field or listed `over` it. */
276
+ export interface CapabilityRequirement {
277
+ readonly action: string
278
+ readonly access: CapabilityAccessForm
279
+ }
280
+
281
+ export type CapabilityAccessForm =
282
+ | { readonly form: 'over'; readonly dimension: string }
283
+ | { readonly form: 'in'; readonly dimension: string; readonly from: string }
284
+ | { readonly form: 'on'; readonly dimension: string; readonly from: string }
285
+
162
286
  /** `from` names an input field or a path parameter of the endpoint. */
163
287
  export type AccessForm =
164
288
  | { readonly form: 'over'; readonly dimension: string }
@@ -187,9 +311,56 @@ export type SchemaShape =
187
311
  | { readonly type: 'optional'; readonly inner: SchemaShape }
188
312
  | { readonly type: 'nullable'; readonly inner: SchemaShape }
189
313
  | { readonly type: 'union'; readonly options: readonly SchemaShape[] }
314
+ | TokenShape
315
+ | FileShape
316
+
317
+ /**
318
+ * A signed token of a declared purpose (`signedToken('<purpose>')`): on the wire a string, verified by the application's
319
+ * framework as it parses the input (an HMAC over the purpose and the claims, and the expiry), and handed to the handler
320
+ * as the purpose's typed claims. Only a top-level field of a procedure's input or its `http.query`.
321
+ */
322
+ export interface TokenShape {
323
+ readonly type: 'token'
324
+ readonly purpose: string
325
+ }
326
+
327
+ /**
328
+ * A stored file of a declared kind (`file('<kind>')`). In an input it is a top-level field, optional, or a bounded
329
+ * array of them: a multipart part of its own beside the JSON input. As an output it is the file the procedure answers.
330
+ */
331
+ export interface FileShape {
332
+ readonly type: 'file'
333
+ readonly kind: string
334
+ }
335
+
336
+ export function isFileShape(shape: OutputShape): shape is FileShape {
337
+ return shape.type === 'file'
338
+ }
339
+
340
+ /**
341
+ * What a procedure answers: a JSON value of a schema, a file of rows (`attachment()` of `@fabrika/app/contract`), or a
342
+ * redirect (`redirect()`).
343
+ */
344
+ export type OutputShape = SchemaShape | AttachmentShape | RedirectShape
345
+
346
+ /**
347
+ * A procedure whose handler returns `{ to }` and whose answer is a redirect there: 303 after a POST, 302 after a GET.
348
+ * A target is a path of the application's own origin or a URL of one of `origins`; anything else fails the invocation.
349
+ */
350
+ export interface RedirectShape {
351
+ readonly type: 'redirect'
352
+ /** Exact `https://` origins a target may name, besides the application's own. */
353
+ readonly origins: readonly string[]
354
+ }
190
355
 
191
- /** What a procedure answers: a JSON value of a schema, or a file of rows (`attachment()` of `@fabrika/app/contract`). */
192
- export type OutputShape = SchemaShape | AttachmentShape
356
+ export function isRedirectShape(shape: OutputShape): shape is RedirectShape {
357
+ return shape.type === 'redirect'
358
+ }
359
+
360
+ /** An output answered as JSON of a schema: neither a file nor a redirect. */
361
+ export function isSchemaOutput(shape: OutputShape): shape is SchemaShape {
362
+ return shape.type !== 'attachment' && shape.type !== 'redirect' && shape.type !== 'file'
363
+ }
193
364
 
194
365
  /**
195
366
  * A procedure whose handler returns rows and whose answer is a file the framework encodes from them. The columns are
@@ -298,9 +469,18 @@ export type MountArtifact =
298
469
  export interface RpcMountArtifact {
299
470
  readonly kind: 'rpc'
300
471
  readonly prefix: string
301
- readonly callers: readonly [RpcCaller, ...RpcCaller[]]
472
+ /** The callers of its credentialed procedures; none when every procedure it mounts is public. */
473
+ readonly callers: readonly RpcCaller[]
474
+ /**
475
+ * `backward`: Control refuses a publication that breaks a caller of a procedure it mounts (`incompatibleMountChanges`).
476
+ * Absent for the default, `unchecked`, so every other mount keeps its digest.
477
+ */
478
+ readonly compatibility?: MountCompatibility
302
479
  }
303
480
 
481
+ /** The promise a mount makes its callers; only `backward` is recorded. */
482
+ export type MountCompatibility = 'backward'
483
+
304
484
  export interface LinkMountArtifact {
305
485
  readonly kind: 'link'
306
486
  readonly prefix: string
@@ -354,6 +534,9 @@ export interface FormMountArtifact {
354
534
  */
355
535
  export const FORM_MULTIPART_TYPE = 'multipart/form-data'
356
536
 
537
+ /** The media type of a public procedure that declares `http: { body: 'urlencoded' }`: flat scalar fields, as a native form posts them. */
538
+ export const FORM_URLENCODED_TYPE = 'application/x-www-form-urlencoded'
539
+
357
540
  /** One file field of a form: the collection the file lands in, and whether a submission must carry it. */
358
541
  export interface FormFileArtifact {
359
542
  readonly collection: string
@@ -367,23 +550,92 @@ export interface FormRate {
367
550
  readonly bytesPerHour?: number
368
551
  }
369
552
 
370
- /** The closed list of challenge providers; each one's verification endpoint and browser origins are fixed. */
371
- export type ChallengeProvider = 'turnstile'
553
+ /**
554
+ * The closed list of challenge providers. Turnstile is verified at Cloudflare's endpoint and loads its widget from
555
+ * Cloudflare; ALTCHA is issued and verified by the application itself, and its widget is bundled with the page.
556
+ */
557
+ export type ChallengeProvider = 'turnstile' | 'altcha'
372
558
 
559
+ /** A 0.4/0.5 form's challenge: Turnstile, the only provider those releases verified. */
373
560
  export interface FormChallenge {
374
- readonly provider: ChallengeProvider
561
+ readonly provider: 'turnstile'
375
562
  /** The application variable holding the provider's secret: a name, never the value. */
376
563
  readonly secret: string
377
564
  /** The application variable holding the widget's public site key, which every SPA mount's browser config serves. */
378
565
  readonly siteKey?: string
379
566
  }
380
567
 
568
+ /** A public procedure's challenge, by provider. */
569
+ export type ProcedureChallenge = TurnstileChallenge | AltchaChallenge
570
+
571
+ /** Turnstile: a form's challenge, and the widget `action` the verification expects back. */
572
+ export interface TurnstileChallenge extends FormChallenge {
573
+ /** The declared `action`, or the endpoint id with `_` for `.`. */
574
+ readonly action: string
575
+ }
576
+
577
+ /**
578
+ * ALTCHA: a proof of work the application issues at its endpoint `GET /__fabrika/challenge/<action>` and verifies itself,
579
+ * signed with the HMAC key the application variable `secret` holds. A challenge carries the action and the host it was
580
+ * issued for, and passes for those only, before it expires.
581
+ */
582
+ export interface AltchaChallenge {
583
+ readonly provider: 'altcha'
584
+ /** The application variable holding the HMAC key: a name, never the value. */
585
+ readonly secret: string
586
+ /** The declared `action`, or the endpoint id with `_` for `.`. */
587
+ readonly action: string
588
+ /** The PBKDF2 iterations of one attempt; a visitor's browser makes several thousand attempts. */
589
+ readonly cost: number
590
+ /** How long an issued challenge may be solved and submitted, in ms; a passed one is recorded as long. */
591
+ readonly maxAgeMs: number
592
+ }
593
+
381
594
  export interface WebhookMountArtifact {
382
595
  readonly kind: 'webhook'
383
596
  readonly path: string
384
- readonly scheme: 'github-sha256'
597
+ readonly scheme: WebhookScheme
385
598
  readonly boundTo: ScopeBinding
386
599
  readonly actions: readonly string[]
600
+ /** How long a delivery's handler may run after the last body byte, in ms; its body limit is its row's `admission`. */
601
+ readonly timeoutMs: number
602
+ }
603
+
604
+ /**
605
+ * The providers whose signature the framework checks by name; every one signs the raw body with the binding's secret,
606
+ * and Twilio the public URL with it. Slack and Twilio post forms as well as JSON.
607
+ */
608
+ export const WEBHOOK_PRESETS = ['github-sha256', 'slack', 'standard-webhooks', 'stripe', 'twilio'] as const
609
+
610
+ export type WebhookPreset = (typeof WEBHOOK_PRESETS)[number]
611
+
612
+ /**
613
+ * How a delivery proves it holds its binding's secret: a preset, an HMAC the framework computes in a declared shape,
614
+ * or the secret itself as a Basic password or a bearer token. A verifier is framework code, never the application's.
615
+ * `basic` and `bearer` read `Authorization`, which the proxy passes only to a row that declares `authorization:
616
+ * 'forward'` (ADR-0022 rule 3).
617
+ */
618
+ export type WebhookScheme =
619
+ | WebhookPreset
620
+ | { readonly hmac: HmacScheme }
621
+ | { readonly basic: true }
622
+ | { readonly bearer: true }
623
+
624
+ export type HmacAlgorithm = 'sha1' | 'sha256' | 'sha512'
625
+
626
+ /**
627
+ * An HMAC of the binding's secret over the signed content, read from `header` as `prefix` and the encoded digest.
628
+ * `'timestamp.body'` signs `<timestamp>.<body>` with the `timestamp` header's Unix seconds, which must be within five
629
+ * minutes of now; `id` names a header whose value the signed content starts with, as `<id>.`.
630
+ */
631
+ export interface HmacScheme {
632
+ readonly header: string
633
+ readonly algorithm: HmacAlgorithm
634
+ readonly encoding: 'hex' | 'base64'
635
+ readonly prefix?: string
636
+ readonly timestamp?: string
637
+ readonly signed: 'body' | 'timestamp.body'
638
+ readonly id?: string
387
639
  }
388
640
 
389
641
  /** Where a workload's authority applies: the whole application, or one value of a dimension per binding. */
@@ -410,11 +662,20 @@ export interface FileCollectionArtifact {
410
662
  readonly scan?: true
411
663
  }
412
664
 
665
+ /** One file kind: the media types its files may be, the largest file, and whether each waits for a clean scan. */
666
+ export interface FileKindArtifact {
667
+ readonly types: readonly string[]
668
+ readonly maxBytes: number
669
+ /** Present when every file of the kind waits `quarantined` for a clean malware verdict before it is served. */
670
+ readonly scan?: true
671
+ }
672
+
413
673
  export interface JobArtifact {
414
674
  readonly schedule: string
415
675
  readonly actions: readonly string[]
416
676
  readonly scope: ScopeBinding
417
- readonly timeout: string | null
677
+ /** How long one attempt may run, in ms, every default applied. */
678
+ readonly timeoutMs: number
418
679
  readonly retries: number
419
680
  }
420
681
 
@@ -467,10 +728,35 @@ export interface DeclaredReach {
467
728
  readonly unscoped: Readonly<Record<string, 'read' | 'write'>>
468
729
  readonly connect: readonly string[]
469
730
  readonly issues: string | null
470
- /** The cron job this mutation kicks after its commit; absent unless declared, so the digest stays. */
731
+ /** The cron job this mutation kicks after its commit (an older release's form); absent unless declared, so the digest stays. */
471
732
  readonly then?: string
733
+ /**
734
+ * The cron jobs this site may kick (`ctx.kick`), sorted: a mutation, a webhook or a job. Absent unless declared, so
735
+ * the digest stays. A contract's kick edges between jobs are acyclic.
736
+ */
737
+ readonly kicks?: readonly string[]
472
738
  /** The mail transport this job reaches: the installation's or its own; absent unless declared. */
473
739
  readonly mailer?: JobMailer
740
+ /**
741
+ * The webhook whose bindings this mutation creates and removes (`ctx.webhooks('<name>')`), seeing each new binding's
742
+ * secret once. Absent unless declared, so the digest stays.
743
+ */
744
+ readonly binds?: string
745
+ /**
746
+ * The token purposes this site signs (`ctx.tokens.sign('<purpose>', …)`), sorted. Absent unless declared, so the digest
747
+ * stays.
748
+ */
749
+ readonly signs?: readonly string[]
750
+ /**
751
+ * The HTTPS origins this site's code calls (`fetch`), sorted: a credentialed procedure, a webhook or a job. Absent
752
+ * unless declared, so the digest stays.
753
+ */
754
+ readonly egress?: readonly string[]
755
+ /**
756
+ * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
757
+ * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
758
+ */
759
+ readonly actions?: readonly string[]
474
760
  }
475
761
 
476
762
  /** The mail transports a job may declare: the installation's default, or the application's own. */
@@ -490,6 +776,11 @@ export interface CspExtensions {
490
776
  readonly styleSrc?: readonly CspSource[]
491
777
  /** Present only when the contract names a font origin. */
492
778
  readonly fontSrc?: readonly CspSource[]
779
+ /**
780
+ * Present only when a challenge provider's widget starts its Web Workers from `blob:` URLs (ALTCHA): its one source is
781
+ * `blob:` (`WORKER_BLOB_SOURCE` of `@fabrika/proxy-core/headers`), never an origin, and the contract cannot declare it.
782
+ */
783
+ readonly workerSrc?: readonly CspSource[]
493
784
  }
494
785
 
495
786
  export interface CspSource {
@@ -499,14 +790,20 @@ export interface CspSource {
499
790
 
500
791
  // ── Table policies ──────────────────────────────────────────────────────────────────────────────
501
792
 
793
+ /**
794
+ * The actions of one table operation, any one of which allows it: one action as its text, several as a list of at least
795
+ * two. A single action stays text, so the artifact of a policy that names one keeps its shape and digest.
796
+ */
797
+ export type TableActionArtifact = string | readonly string[]
798
+
502
799
  export interface TablePolicyArtifact {
503
800
  readonly scope: TableScope
504
801
  /** An inbox's read action is `read`; it has no write action, because only its form appends. */
505
802
  readonly actions: {
506
- readonly read: string
507
- readonly insert: string | null
508
- readonly update: string | null
509
- readonly delete: string | null
803
+ readonly read: TableActionArtifact
804
+ readonly insert: TableActionArtifact | null
805
+ readonly update: TableActionArtifact | null
806
+ readonly delete: TableActionArtifact | null
510
807
  /**
511
808
  * A dimension or child table's actions besides `read` with which an `app` endpoint reads every row, read-only;
512
809
  * present only when the policy names one.
@@ -524,6 +821,11 @@ export interface TablePolicyArtifact {
524
821
  * is updated by that action only, never by the table's update action.
525
822
  */
526
823
  readonly columns: Readonly<Record<string, ColumnPolicyArtifact>>
824
+ /**
825
+ * Column → the file kind it holds: a foreign key to `fabrika_files`, written only with a file reference. The table's
826
+ * actions are the file's authority. Absent unless declared, so the digest stays.
827
+ */
828
+ readonly files?: Readonly<Record<string, string>>
527
829
  }
528
830
 
529
831
  /** A column's own read action, its own write action, or both; an absent one is left out. */
@@ -27,9 +27,12 @@ export type EndpointDelegation = 'members' | 'creates'
27
27
  * installation row adds its OAuth scopes; an application row has no `oauth` field.
28
28
  */
29
29
  export type EndpointRules =
30
- | (Pick<EndpointRow, 'kind' | 'method' | 'path' | 'callers' | 'requirement' | 'admission' | 'crossOrigin'> & {
31
- readonly delegation: EndpointDelegation | null
32
- })
30
+ | (
31
+ & Pick<EndpointRow, 'kind' | 'method' | 'path' | 'callers' | 'requirement' | 'admission' | 'crossOrigin' | 'response' | 'cache' | 'authorization'>
32
+ & {
33
+ readonly delegation: EndpointDelegation | null
34
+ }
35
+ )
33
36
  | (Pick<InstallationEndpointRow, 'kind' | 'method' | 'path' | 'callers' | 'requirement' | 'admission' | 'oauth'> & {
34
37
  readonly delegation: null
35
38
  })
@@ -64,7 +67,8 @@ export function endpointDigest(artifact: Pick<ContractArtifact, 'dimensions'>, r
64
67
 
65
68
  /**
66
69
  * The digest of what the proxy applies to an endpoint: its kind, method, path, callers, requirement, admission and
67
- * delegation, an installation row's OAuth scopes, and an application row's cross-origin form.
70
+ * delegation, an installation row's OAuth scopes, and an application row's cross-origin form, file-response profile, cache
71
+ * and `Authorization` forwarding.
68
72
  * Caller, content-type and scope order carry no meaning, so they do not change it; input and output schemas are not
69
73
  * part of it, because the proxy does not apply them.
70
74
  */
@@ -79,13 +83,20 @@ export function requirementDigest(rules: EndpointRules): string {
79
83
  admission: rules.admission === null ? null : canonicalAdmission(rules.admission),
80
84
  delegation: rules.delegation,
81
85
  }
82
- // Only a row that admits `oauth` or another origin adds the key, so every other row keeps its digest byte for byte.
86
+ // Only a row that admits `oauth` or another origin, answers a file, caches or forwards `Authorization` adds the key, so
87
+ // every other row keeps its digest byte for byte.
83
88
  const oauth = 'oauth' in rules ? rules.oauth : null
84
89
  const crossOrigin = 'crossOrigin' in rules ? rules.crossOrigin : undefined
90
+ const response = 'response' in rules ? rules.response : undefined
91
+ const cache = 'cache' in rules ? rules.cache : undefined
92
+ const authorization = 'authorization' in rules ? rules.authorization : undefined
85
93
  return digestOf(canonicalJson({
86
94
  ...applied,
87
95
  ...(oauth === null ? {} : { oauth: { scopes: sortedCodeUnits(oauth.scopes) } }),
88
96
  ...(crossOrigin === undefined ? {} : { crossOrigin }),
97
+ ...(response === undefined ? {} : { response }),
98
+ ...(cache === undefined ? {} : { cache }),
99
+ ...(authorization === undefined ? {} : { authorization }),
89
100
  }))
90
101
  }
91
102
 
@@ -1,12 +1,21 @@
1
1
  import { FABRIKA_IAM_APP_ID } from './app-environment'
2
2
  import { FABRIKA_CONTRACT_DIGEST } from './endpoint-digest'
3
3
  import { FABRIKA_IAM_ISSUER } from './environment'
4
+ import { sha256Hex } from './sha256'
5
+ import type { WorkloadKind } from './types'
4
6
  import { FABRIKA_PROXY_SECRET } from './wire'
5
7
 
6
8
  /** Where a platform build uploads its source maps: the destination without its bearer, and the asset roots (JSON). */
7
9
  export const FABRIKA_SOURCE_MAP_UPLOAD = 'FABRIKA_SOURCE_MAP_UPLOAD'
8
10
  /** The run-scoped bearer of that upload. */
9
11
  export const FABRIKA_SOURCE_MAP_UPLOAD_KEY = 'FABRIKA_SOURCE_MAP_UPLOAD_KEY'
12
+ /**
13
+ * The keys an application environment signs and verifies its signed tokens with: `<kid>:<secret>` entries joined by `,`,
14
+ * the signing key first, then each retired key still verifying. Written only for a contract that declares token purposes.
15
+ */
16
+ export const FABRIKA_TOKEN_KEYS = 'FABRIKA_TOKEN_KEYS'
17
+ /** The environment's canonical origin (`https://crm.example`), which `ctx.url` builds absolute links on. */
18
+ export const FABRIKA_APP_ORIGIN = 'FABRIKA_APP_ORIGIN'
10
19
 
11
20
  /**
12
21
  * The environment names only the platform writes into an application
@@ -36,16 +45,27 @@ export const FRAMEWORK_VARIABLE_NAMES = [
36
45
  'FABRIKA_IAM_RPC_KEY',
37
46
  FABRIKA_SOURCE_MAP_UPLOAD,
38
47
  FABRIKA_SOURCE_MAP_UPLOAD_KEY,
48
+ FABRIKA_TOKEN_KEYS,
49
+ FABRIKA_APP_ORIGIN,
39
50
  ] as const
40
51
 
41
52
  export type FrameworkVariableName = (typeof FRAMEWORK_VARIABLE_NAMES)[number]
42
53
 
43
54
  /**
44
- * The name families only the platform writes: one variable per job or webhook, named after it (`workloadKeyVariable`),
45
- * a connector import's address, key and Worker binding (`connectVariables`), and the installation's mail transport
46
- * (`isEmailTransportVariable`). Every name under one is framework-only.
55
+ * The name families only the platform writes: one variable per job, webhook or public procedure, named after it
56
+ * (`workloadKeyVariable`), a connector import's address, key and Worker binding (`connectVariables`), the
57
+ * installation's mail transport (`isEmailTransportVariable`), and a platform receiver's address and key
58
+ * (`platformTransportVariables`). Every name under one is framework-only. A public procedure's family is
59
+ * `FABRIKA_PROCEDURE_`, because `FABRIKA_PUBLIC_*` names an application's public build values.
47
60
  */
48
- export const FRAMEWORK_VARIABLE_PREFIXES = ['FABRIKA_JOB_', 'FABRIKA_WEBHOOK_', 'FABRIKA_CONNECT_', 'FABRIKA_EMAIL_'] as const
61
+ export const FRAMEWORK_VARIABLE_PREFIXES = [
62
+ 'FABRIKA_JOB_',
63
+ 'FABRIKA_WEBHOOK_',
64
+ 'FABRIKA_PROCEDURE_',
65
+ 'FABRIKA_CONNECT_',
66
+ 'FABRIKA_EMAIL_',
67
+ 'FABRIKA_PLATFORM_',
68
+ ] as const
49
69
 
50
70
  const FRAMEWORK_VARIABLES: ReadonlySet<string> = new Set(FRAMEWORK_VARIABLE_NAMES)
51
71
 
@@ -59,15 +79,25 @@ export function variableSegment(name: string): string {
59
79
  return name.replace(/([a-z0-9])([A-Z])/g, '$1_$2').toUpperCase()
60
80
  }
61
81
 
62
- const WORKLOAD_KEY_VARIABLE = /^FABRIKA_(?:JOB|WEBHOOK)_[A-Z0-9][A-Z0-9_]*_KEY$/
82
+ const WORKLOAD_KEY_VARIABLE = /^FABRIKA_(?:JOB|WEBHOOK|PROCEDURE)_[A-Z0-9][A-Z0-9_]*_KEY$/
63
83
 
64
- /** Whether `name` is the variable of a job's or a webhook's credential, as `workloadKeyVariable` names one. */
84
+ /** Whether `name` is the variable of a job's, a webhook's or a public procedure's credential, as `workloadKeyVariable` names one. */
65
85
  export function isWorkloadKeyVariable(name: string): boolean {
66
86
  return WORKLOAD_KEY_VARIABLE.test(name)
67
87
  }
68
88
 
69
- /** The variable a job's or a webhook's credential travels under: `FABRIKA_JOB_NIGHTLY_DIGEST_KEY`. */
70
- export function workloadKeyVariable(kind: 'job' | 'webhook', name: string): string {
89
+ /** The workload kinds an application holds its own key of; an `app` key is a connector's (`connectVariables`). */
90
+ export type OwnWorkloadKind = Exclude<WorkloadKind, 'app'>
91
+
92
+ /**
93
+ * The variable a workload's credential travels under: `FABRIKA_JOB_NIGHTLY_DIGEST_KEY`. A public procedure's endpoint id
94
+ * has dots and may differ from another only by case or `_`, so its readable segment carries the first 8 hex digits of
95
+ * the id's SHA-256 as well: `api.stats.cta` → `FABRIKA_PROCEDURE_API_STATS_CTA_<8 hex>_KEY`.
96
+ */
97
+ export function workloadKeyVariable(kind: OwnWorkloadKind, name: string): string {
98
+ if (kind === 'public') {
99
+ return `FABRIKA_PROCEDURE_${variableSegment(name.replaceAll('.', '_'))}_${sha256Hex(name).slice(0, 8).toUpperCase()}_KEY`
100
+ }
71
101
  return `FABRIKA_${kind.toUpperCase()}_${variableSegment(name)}_KEY`
72
102
  }
73
103
 
@@ -128,3 +158,29 @@ export function frameworkVariableReference(text: string): string | null {
128
158
  }
129
159
  return null
130
160
  }
161
+
162
+ /** The platform's receivers an application reaches over the platform transport. */
163
+ export const PLATFORM_RECEIVERS = ['mail'] as const
164
+
165
+ export type PlatformReceiver = (typeof PLATFORM_RECEIVERS)[number]
166
+
167
+ /** The variables that carry one platform receiver: its base URL, which is public, and the application's key, which is secret. */
168
+ export interface PlatformTransportVariables {
169
+ readonly url: string
170
+ readonly key: string
171
+ }
172
+
173
+ /** `mail` → `FABRIKA_PLATFORM_MAIL_URL` and `FABRIKA_PLATFORM_MAIL_KEY`. */
174
+ export function platformTransportVariables(receiver: PlatformReceiver): PlatformTransportVariables {
175
+ const prefix = `FABRIKA_PLATFORM_${variableSegment(receiver)}`
176
+ return { url: `${prefix}_URL`, key: `${prefix}_KEY` }
177
+ }
178
+
179
+ const PLATFORM_TRANSPORT_VARIABLES: ReadonlySet<string> = new Set(
180
+ PLATFORM_RECEIVERS.flatMap((receiver) => Object.values(platformTransportVariables(receiver))),
181
+ )
182
+
183
+ /** Whether `name` carries a platform receiver's URL or key, as `platformTransportVariables` names them. */
184
+ export function isPlatformTransportVariable(name: string): boolean {
185
+ return PLATFORM_TRANSPORT_VARIABLES.has(name)
186
+ }
package/src/index.ts CHANGED
@@ -21,3 +21,4 @@ export { sha256Hex } from './sha256'
21
21
  export * from './token'
22
22
  export * from './types'
23
23
  export * from './wire'
24
+ export * from './workloads'
@@ -1,4 +1,4 @@
1
- import { APP_CALLER_PREFIX, CONNECT_PREFIX, type EndpointRequirement } from './contract'
1
+ import { type ActionRequirement, APP_CALLER_PREFIX, type CapabilityRequirement, CONNECT_PREFIX, type EndpointRequirement } from './contract'
2
2
  import { type AuthenticatedRequirement, OAUTH_CALLER, type TokenCaller } from './installation-endpoint'
3
3
  import { permits } from './permissions'
4
4
  import type { AccessTokenClaims } from './token'
@@ -8,8 +8,8 @@ import type { PermissionEntry } from './types'
8
8
  * Whether a token's permissions meet an endpoint's requirement. This is authorization, not a gate: it reads only the
9
9
  * token. `member` is any permission of this application; an action is that action in some scope, global included.
10
10
  * The access form narrows it to one scope afterwards, against the application's own data. The `app` form is the
11
- * action held as a global grant, so an entry scoped to any value does not meet it. `authenticated`, which only an
12
- * installation row carries, needs no permission.
11
+ * action held as a global grant, so an entry scoped to any value does not meet it. Several capabilities need every
12
+ * one of their actions. `authenticated`, which only an installation row carries, needs no permission.
13
13
  */
14
14
  export function satisfies(requirement: EndpointRequirement | AuthenticatedRequirement, perms: readonly PermissionEntry[]): boolean {
15
15
  if (requirement.kind === 'authenticated') {
@@ -18,6 +18,13 @@ export function satisfies(requirement: EndpointRequirement | AuthenticatedRequir
18
18
  if (requirement.kind === 'member') {
19
19
  return perms.length > 0
20
20
  }
21
+ if (requirement.kind === 'capabilities') {
22
+ return Object.values(requirement.capabilities).every((capability) => holdsAction(capability, perms))
23
+ }
24
+ return holdsAction(requirement, perms)
25
+ }
26
+
27
+ function holdsAction(requirement: ActionRequirement | CapabilityRequirement, perms: readonly PermissionEntry[]): boolean {
21
28
  if (requirement.access.form === 'app') {
22
29
  return perms.some((entry) => permits([entry], requirement.action))
23
30
  }
@@ -27,8 +34,8 @@ export function satisfies(requirement: EndpointRequirement | AuthenticatedRequir
27
34
  /**
28
35
  * The caller kind a verified token presents: a `user` principal is `human`, a `service` principal is `machine`, a
29
36
  * connector key of application `<id>` is `app:<id>`, and a token bound to no principal is a share link. An OAuth
30
- * resource token is `oauth`, which only an installation row admits. A job or webhook token is no caller: `null` is
31
- * refused by every endpoint.
37
+ * resource token is `oauth`, which only an installation row admits. A job, webhook or public procedure token is no
38
+ * caller: `null` is refused by every endpoint.
32
39
  */
33
40
  export function callerOf(claims: AccessTokenClaims): TokenCaller | null {
34
41
  if (claims.oauth !== undefined) {
@@ -43,6 +50,7 @@ export function callerOf(claims: AccessTokenClaims): TokenCaller | null {
43
50
  return claims.workload === undefined ? null : `app:${claims.workload}`
44
51
  case 'job':
45
52
  case 'webhook':
53
+ case 'public':
46
54
  return null
47
55
  case undefined:
48
56
  return 'link'
package/src/token.ts CHANGED
@@ -26,7 +26,8 @@ import { numberField, prop, stringField } from './json'
26
26
  import { isNormalizedMailbox } from './membership'
27
27
  import { isCimdClientId, isOAuthResourceUri, parseOAuthScopes } from './oauth'
28
28
  import type { ResolvedPrincipal } from './rpc'
29
- import { isWorkloadKind, type PermissionEntry, type PermissionSource, type Scope, type TokenPrincipalType } from './types'
29
+ import { isWorkloadKind, type PermissionEntry, type PermissionSource, type Scope, type TokenPrincipalType, type WorkloadKind } from './types'
30
+ import { isOwnWorkloadName } from './workloads'
30
31
 
31
32
  // ── Names & knobs on the wire (both sides agree) ───────────────────────────────
32
33
 
@@ -99,8 +100,8 @@ export interface AccessTokenClaims {
99
100
  /** Present only when the token is bound to a principal (`sub` is that principal). */
100
101
  ptype?: TokenPrincipalType
101
102
  /**
102
- * Present exactly when `ptype` is a workload kind: the job's or the webhook's name, or for `app` the id of the
103
- * consuming application, which the proxy admits as the caller `app:<id>`.
103
+ * Present exactly when `ptype` is a workload kind: the job's or the webhook's name, a public procedure's endpoint id,
104
+ * or for `app` the id of the consuming application, which the proxy admits as the caller `app:<id>`.
104
105
  */
105
106
  workload?: string
106
107
  /** Audit actor label — the principal's label, or the credential label, or null (anonymous). */
@@ -266,7 +267,8 @@ export function buildAccessClaims(params: AccessTokenParams): AccessTokenClaims
266
267
  if (params.type !== undefined) {
267
268
  claims.ptype = params.type
268
269
  }
269
- if (isWorkloadKind(params.type) !== (params.workload !== undefined) || (params.workload !== undefined && !isWorkloadName(params.workload))) {
270
+ const kind = isWorkloadKind(params.type) ? params.type : null
271
+ if (kind === null ? params.workload !== undefined : params.workload === undefined || !isWorkloadName(kind, params.workload)) {
270
272
  throw new Error('A workload token names its workload, and only a workload token does')
271
273
  }
272
274
  if (params.workload !== undefined) {
@@ -356,8 +358,9 @@ export function parseAccessClaims(payload: unknown): AccessTokenClaims | null {
356
358
  /** A job, webhook or mount name, or an application id. */
357
359
  const WORKLOAD_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/
358
360
 
359
- function isWorkloadName(value: string): boolean {
360
- return WORKLOAD_NAME.test(value)
361
+ /** A public procedure is named by its endpoint id; every other workload by a name or an application id. */
362
+ function isWorkloadName(kind: WorkloadKind, value: string): boolean {
363
+ return kind === 'public' ? isOwnWorkloadName('public', value) : WORKLOAD_NAME.test(value)
361
364
  }
362
365
 
363
366
  /** A workload kind requires its name and every other kind refuses one: the name → the name, none → null, else undefined. */
@@ -365,7 +368,7 @@ function parseWorkload(value: unknown, ptype: TokenPrincipalType | null): string
365
368
  if (!isWorkloadKind(ptype)) {
366
369
  return value === undefined ? null : undefined
367
370
  }
368
- return typeof value === 'string' && isWorkloadName(value) ? value : undefined
371
+ return typeof value === 'string' && isWorkloadName(ptype, value) ? value : undefined
369
372
  }
370
373
 
371
374
  /** Absent → null; a normalized mailbox on a user token → it; anything else → undefined. */
package/src/types.ts CHANGED
@@ -10,19 +10,19 @@ export type PrincipalType = 'user' | 'service'
10
10
  export type PrincipalAffiliation = 'internal' | 'external'
11
11
 
12
12
  /**
13
- * The principal kind of a workload credential (ADR-0022 "Principal kinds"): a contract job, a webhook, or the connector
14
- * of a consuming application. IAM stores a workload principal as a `service` row and mints its key with this kind, so
15
- * a workload key is never a `machine` caller.
13
+ * The principal kind of a workload credential (ADR-0022 "Principal kinds"): a contract job, a webhook, a public
14
+ * procedure (named by its endpoint id), or the connector of a consuming application. IAM stores a workload principal as
15
+ * a `service` row and mints its key with this kind, so a workload key is never a `machine` caller.
16
16
  */
17
- export type WorkloadKind = 'job' | 'webhook' | 'app'
17
+ export type WorkloadKind = 'job' | 'webhook' | 'public' | 'app'
18
18
 
19
- export const WORKLOAD_KINDS: readonly WorkloadKind[] = ['job', 'webhook', 'app']
19
+ export const WORKLOAD_KINDS = ['job', 'webhook', 'public', 'app'] as const satisfies readonly WorkloadKind[]
20
20
 
21
21
  /** The principal kind a token carries in `ptype`: a stored principal type, or a workload kind. */
22
22
  export type TokenPrincipalType = PrincipalType | WorkloadKind
23
23
 
24
24
  export function isWorkloadKind(value: unknown): value is WorkloadKind {
25
- return value === 'job' || value === 'webhook' || value === 'app'
25
+ return value === 'job' || value === 'webhook' || value === 'public' || value === 'app'
26
26
  }
27
27
 
28
28
  /**
@@ -180,8 +180,8 @@ export interface AppSchema {
180
180
  }
181
181
 
182
182
  /**
183
- * A job or a webhook of a contract application, or a consuming application of its exports (`app`, named by that
184
- * application's id): the actions its credential carries.
183
+ * A job, a webhook or a public procedure (`public`, named by its endpoint id) of a contract application, or a consuming
184
+ * application of its exports (`app`, named by that application's id): the actions its credential carries.
185
185
  */
186
186
  export interface AppWorkloadDef {
187
187
  kind: WorkloadKind
@@ -0,0 +1,47 @@
1
+ // The workloads of a contract (ADR-0022 "Principal kinds"): each job, each webhook and each public procedure holds a key
2
+ // of its own, which Control issues from the approved artifact and IAM resolves to the actions the workload declares.
3
+ // IAM's schema, Control's keys and the application's boot all enumerate them here, so they cannot disagree.
4
+
5
+ import type { ContractArtifact } from './contract'
6
+ import type { OwnWorkloadKind } from './framework-variables'
7
+
8
+ /** A job or webhook name of a contract. */
9
+ export const WORKLOAD_NAME = /^[A-Za-z][A-Za-z0-9_]{0,63}$/
10
+
11
+ /**
12
+ * A public procedure's workload name: its full endpoint id, `<mount>.<group>.<procedure>`, so one group mounted twice
13
+ * holds two workloads and never merges their authority.
14
+ */
15
+ export const PUBLIC_WORKLOAD_NAME = /^[A-Za-z][A-Za-z0-9_]*(?:\.[A-Za-z][A-Za-z0-9_]*)+$/
16
+
17
+ /** IAM stores the name in the principal's external id, and the token carries it. */
18
+ export const MAX_PUBLIC_WORKLOAD_NAME_LENGTH = 128
19
+
20
+ /** Whether `name` names a workload of an application's own `kind`. */
21
+ export function isOwnWorkloadName(kind: OwnWorkloadKind, name: string): boolean {
22
+ return kind === 'public' ? name.length <= MAX_PUBLIC_WORKLOAD_NAME_LENGTH && PUBLIC_WORKLOAD_NAME.test(name) : WORKLOAD_NAME.test(name)
23
+ }
24
+
25
+ /** One workload the contract declares: what IAM stores, what its key is named after and what its token carries. */
26
+ export interface ContractWorkload {
27
+ readonly kind: OwnWorkloadKind
28
+ readonly name: string
29
+ /** The workload's declared actions, sorted. */
30
+ readonly actions: readonly string[]
31
+ }
32
+
33
+ /**
34
+ * Every workload of `artifact`: its jobs, its webhooks, and each endpoint whose declared reach names `actions` — a public
35
+ * procedure, which runs as its own workload.
36
+ */
37
+ export function contractWorkloads(artifact: Pick<ContractArtifact, 'jobs' | 'mounts' | 'declared'>): readonly ContractWorkload[] {
38
+ const sorted = (actions: readonly string[]): readonly string[] => [...actions].sort()
39
+ const jobs = Object.entries(artifact.jobs).map(([name, job]): ContractWorkload => ({ kind: 'job', name, actions: sorted(job.actions) }))
40
+ const webhooks = Object.entries(artifact.mounts).flatMap(([name, mount]): ContractWorkload[] =>
41
+ mount.kind === 'webhook' ? [{ kind: 'webhook', name, actions: sorted(mount.actions) }] : []
42
+ )
43
+ const procedures = Object.entries(artifact.declared ?? {}).flatMap(([endpoint, reach]): ContractWorkload[] =>
44
+ reach.actions === undefined ? [] : [{ kind: 'public', name: endpoint, actions: sorted(reach.actions) }]
45
+ )
46
+ return [...jobs, ...webhooks, ...procedures]
47
+ }