@fabrika/auth-core 0.5.5 → 0.7.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.5.5",
3
+ "version": "0.7.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) => ({
@@ -52,13 +57,30 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
52
57
  reservedPrefixes: sorted(artifact.reservedPrefixes),
53
58
  ...(artifact.declared === undefined
54
59
  ? {}
55
- : { declared: mapValues(artifact.declared, (reach) => ({ ...reach, connect: sorted(reach.connect) })) }),
60
+ : {
61
+ declared: mapValues(artifact.declared, (reach) => ({
62
+ ...reach,
63
+ connect: sorted(reach.connect),
64
+ ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
65
+ ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
66
+ ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
67
+ ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
68
+ })),
69
+ }),
56
70
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
57
71
  ...(artifact.locale === undefined ? {} : { locale: artifact.locale }),
58
72
  ...(artifact.displayName === undefined ? {} : { displayName: artifact.displayName }),
59
73
  ...(artifact.mail === undefined ? {} : { mail: artifact.mail }),
60
74
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
61
75
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
76
+ ...(artifact.procedures === undefined
77
+ ? {}
78
+ : {
79
+ procedures: mapValues(artifact.procedures, (rules) => rules.query === undefined ? rules : { ...rules, query: canonicalShape(rules.query) }),
80
+ }),
81
+ ...(artifact.tokens === undefined
82
+ ? {}
83
+ : { tokens: mapValues(artifact.tokens, (purpose) => ({ claims: canonicalShape(purpose.claims), maxDays: purpose.maxDays })) }),
62
84
  }
63
85
  }
64
86
 
@@ -83,7 +105,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
83
105
  function canonicalMount(mount: MountArtifact): MountArtifact {
84
106
  switch (mount.kind) {
85
107
  case 'rpc':
86
- return { ...mount, callers: sortedTuple(mount.callers) }
108
+ return { ...mount, callers: sorted(mount.callers) }
87
109
  case 'link':
88
110
  return { ...mount, grants: sorted(mount.grants) }
89
111
  case 'webhook':
@@ -95,12 +117,32 @@ function canonicalMount(mount: MountArtifact): MountArtifact {
95
117
  }
96
118
  }
97
119
 
120
+ /** Each action of one table operation, `[]` for none: how a reader of the artifact reads `actions.read` and the others. */
121
+ export function tableActions(actions: TableActionArtifact | null): readonly string[] {
122
+ if (actions === null) {
123
+ return []
124
+ }
125
+ return typeof actions === 'string' ? [actions] : actions
126
+ }
127
+
128
+ /** A list of actions sorted; one action as it is. */
129
+ function canonicalActions(actions: TableActionArtifact): TableActionArtifact {
130
+ return typeof actions === 'string' ? actions : sorted(actions)
131
+ }
132
+
133
+ function canonicalOptionalActions(actions: TableActionArtifact | null): TableActionArtifact | null {
134
+ return actions === null ? null : canonicalActions(actions)
135
+ }
136
+
98
137
  function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
99
138
  const { appRead, appCount } = table.actions
100
139
  return {
101
140
  ...table,
102
141
  actions: {
103
- ...table.actions,
142
+ read: canonicalActions(table.actions.read),
143
+ insert: canonicalOptionalActions(table.actions.insert),
144
+ update: canonicalOptionalActions(table.actions.update),
145
+ delete: canonicalOptionalActions(table.actions.delete),
104
146
  ...(appRead === undefined ? {} : { appRead: sorted(appRead) }),
105
147
  ...(appCount === undefined ? {} : { appCount: sorted(appCount) }),
106
148
  },
@@ -129,6 +171,9 @@ export function canonicalAdmission(admission: BodyAdmission): BodyAdmission {
129
171
 
130
172
  /** An output shape: an attachment keeps its column order, which is the file's; each column's shape is canonical. */
131
173
  export function canonicalOutput(shape: OutputShape): OutputShape {
174
+ if (shape.type === 'redirect') {
175
+ return { type: 'redirect', origins: sorted(shape.origins) }
176
+ }
132
177
  if (shape.type !== 'attachment') {
133
178
  return canonicalShape(shape)
134
179
  }
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,9 +144,11 @@ 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
 
@@ -110,18 +174,55 @@ interface EndpointRowBase {
110
174
  readonly output: OutputShape | null
111
175
  /**
112
176
  * 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.
177
+ * the origins its environment lists, `any` (a form or a public procedure only) from every origin. Absent unless
178
+ * declared, so every other row keeps its digest. Only an RPC procedure, a public procedure and a form may carry it.
115
179
  */
116
180
  readonly crossOrigin?: CrossOriginForm
181
+ /**
182
+ * `file`: the procedure answers a stored file (an output `file('<kind>')`), so the proxy and the application give every
183
+ * answer of it, a denial included, ADR-0022's file treatment. Absent otherwise, so every other row keeps its digest.
184
+ */
185
+ readonly response?: EndpointResponse
186
+ /**
187
+ * How long a browser or a CDN may reuse a successful answer: a public `GET` query only (`http.cache`). Absent for
188
+ * every other row, which answers `no-store`, so every row without it keeps its digest.
189
+ */
190
+ readonly cache?: EndpointCache
191
+ /**
192
+ * `forward`: the proxy passes the request's own `Authorization` to the application, never reading it as a platform
193
+ * credential: a webhook row whose verifier (`basic`, `bearer`) compares it with the binding's secret. A value that
194
+ * carries a `px_` key is still removed, and every other anonymous row loses the header (ADR-0022 rule 3). Absent
195
+ * otherwise, so every other row keeps its digest.
196
+ */
197
+ readonly authorization?: EndpointAuthorization
117
198
  }
118
199
 
119
- /** How an endpoint admits another origin: from the environment's list, or (a form only) from any origin. */
200
+ /** What the proxy does with an anonymous request's `Authorization` on a row that names it: forward it to the application. */
201
+ export type EndpointAuthorization = 'forward'
202
+
203
+ /** The answer profile of a row that answers a stored file. */
204
+ export type EndpointResponse = 'file'
205
+
206
+ /** A cacheable row's lifetime: `maxAgeSeconds`, or `immutable`, a year, for an input that names an immutable value. */
207
+ export type EndpointCache = { readonly maxAgeSeconds: number } | 'immutable'
208
+
209
+ /** The longest `maxAgeSeconds`: one year, the lifetime the proxy gives `immutable` too. */
210
+ export const MAX_CACHE_AGE_SECONDS = 31_536_000
211
+
212
+ /** The endpoint kinds whose row may answer a stored file: a procedure's. */
213
+ export const FILE_RESPONSE_KINDS: readonly EndpointKind[] = ['query', 'mutation', 'public']
214
+
215
+ /** Whether every answer of a row gets the file treatment: a collection's download, or a procedure that answers a file. */
216
+ export function answersFile(row: { readonly kind: string; readonly response?: EndpointResponse }): boolean {
217
+ return row.kind === 'download' || row.response === 'file'
218
+ }
219
+
220
+ /** How an endpoint admits another origin: from the environment's list, or (a form or a public procedure) from any origin. */
120
221
  export type CrossOriginForm = 'environment' | 'any'
121
222
 
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']
223
+ /** The endpoint kinds that may declare `crossOrigin`, and those of them that may admit any origin. */
224
+ export const CROSS_ORIGIN_KINDS: readonly EndpointKind[] = ['query', 'mutation', 'form', 'public']
225
+ export const ANY_ORIGIN_KINDS: readonly EndpointKind[] = ['form', 'public']
125
226
 
126
227
  export interface CredentialedEndpoint extends EndpointRowBase {
127
228
  readonly kind: CredentialedEndpointKind
@@ -147,7 +248,7 @@ export interface BodyAdmission {
147
248
  * `action` is that action in some scope, global included, and only globally under the `app` form. The access form is
148
249
  * what the framework then resolves.
149
250
  */
150
- export type EndpointRequirement = MemberRequirement | ActionRequirement
251
+ export type EndpointRequirement = MemberRequirement | ActionRequirement | CapabilitiesRequirement
151
252
 
152
253
  export interface MemberRequirement {
153
254
  readonly kind: 'member'
@@ -159,6 +260,26 @@ export interface ActionRequirement {
159
260
  readonly access: AccessForm
160
261
  }
161
262
 
263
+ /**
264
+ * Several capabilities (`access: { capabilities }`), by the name the handler reads each under (`ctx.capabilities.<name>`):
265
+ * the token must carry every action, and the access form of each narrows it as it narrows a single one. At least two.
266
+ */
267
+ export interface CapabilitiesRequirement {
268
+ readonly kind: 'capabilities'
269
+ readonly capabilities: Readonly<Record<string, CapabilityRequirement>>
270
+ }
271
+
272
+ /** One capability of several: an action in a dimension, its value read from an input field or listed `over` it. */
273
+ export interface CapabilityRequirement {
274
+ readonly action: string
275
+ readonly access: CapabilityAccessForm
276
+ }
277
+
278
+ export type CapabilityAccessForm =
279
+ | { readonly form: 'over'; readonly dimension: string }
280
+ | { readonly form: 'in'; readonly dimension: string; readonly from: string }
281
+ | { readonly form: 'on'; readonly dimension: string; readonly from: string }
282
+
162
283
  /** `from` names an input field or a path parameter of the endpoint. */
163
284
  export type AccessForm =
164
285
  | { readonly form: 'over'; readonly dimension: string }
@@ -187,9 +308,56 @@ export type SchemaShape =
187
308
  | { readonly type: 'optional'; readonly inner: SchemaShape }
188
309
  | { readonly type: 'nullable'; readonly inner: SchemaShape }
189
310
  | { readonly type: 'union'; readonly options: readonly SchemaShape[] }
311
+ | TokenShape
312
+ | FileShape
190
313
 
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
314
+ /**
315
+ * A signed token of a declared purpose (`signedToken('<purpose>')`): on the wire a string, verified by the application's
316
+ * framework as it parses the input (an HMAC over the purpose and the claims, and the expiry), and handed to the handler
317
+ * as the purpose's typed claims. Only a top-level field of a procedure's input or its `http.query`.
318
+ */
319
+ export interface TokenShape {
320
+ readonly type: 'token'
321
+ readonly purpose: string
322
+ }
323
+
324
+ /**
325
+ * A stored file of a declared kind (`file('<kind>')`). In an input it is a top-level field, optional, or a bounded
326
+ * array of them: a multipart part of its own beside the JSON input. As an output it is the file the procedure answers.
327
+ */
328
+ export interface FileShape {
329
+ readonly type: 'file'
330
+ readonly kind: string
331
+ }
332
+
333
+ export function isFileShape(shape: OutputShape): shape is FileShape {
334
+ return shape.type === 'file'
335
+ }
336
+
337
+ /**
338
+ * What a procedure answers: a JSON value of a schema, a file of rows (`attachment()` of `@fabrika/app/contract`), or a
339
+ * redirect (`redirect()`).
340
+ */
341
+ export type OutputShape = SchemaShape | AttachmentShape | RedirectShape
342
+
343
+ /**
344
+ * A procedure whose handler returns `{ to }` and whose answer is a redirect there: 303 after a POST, 302 after a GET.
345
+ * A target is a path of the application's own origin or a URL of one of `origins`; anything else fails the invocation.
346
+ */
347
+ export interface RedirectShape {
348
+ readonly type: 'redirect'
349
+ /** Exact `https://` origins a target may name, besides the application's own. */
350
+ readonly origins: readonly string[]
351
+ }
352
+
353
+ export function isRedirectShape(shape: OutputShape): shape is RedirectShape {
354
+ return shape.type === 'redirect'
355
+ }
356
+
357
+ /** An output answered as JSON of a schema: neither a file nor a redirect. */
358
+ export function isSchemaOutput(shape: OutputShape): shape is SchemaShape {
359
+ return shape.type !== 'attachment' && shape.type !== 'redirect' && shape.type !== 'file'
360
+ }
193
361
 
194
362
  /**
195
363
  * A procedure whose handler returns rows and whose answer is a file the framework encodes from them. The columns are
@@ -298,9 +466,18 @@ export type MountArtifact =
298
466
  export interface RpcMountArtifact {
299
467
  readonly kind: 'rpc'
300
468
  readonly prefix: string
301
- readonly callers: readonly [RpcCaller, ...RpcCaller[]]
469
+ /** The callers of its credentialed procedures; none when every procedure it mounts is public. */
470
+ readonly callers: readonly RpcCaller[]
471
+ /**
472
+ * `backward`: Control refuses a publication that breaks a caller of a procedure it mounts (`incompatibleMountChanges`).
473
+ * Absent for the default, `unchecked`, so every other mount keeps its digest.
474
+ */
475
+ readonly compatibility?: MountCompatibility
302
476
  }
303
477
 
478
+ /** The promise a mount makes its callers; only `backward` is recorded. */
479
+ export type MountCompatibility = 'backward'
480
+
304
481
  export interface LinkMountArtifact {
305
482
  readonly kind: 'link'
306
483
  readonly prefix: string
@@ -354,6 +531,9 @@ export interface FormMountArtifact {
354
531
  */
355
532
  export const FORM_MULTIPART_TYPE = 'multipart/form-data'
356
533
 
534
+ /** The media type of a public procedure that declares `http: { body: 'urlencoded' }`: flat scalar fields, as a native form posts them. */
535
+ export const FORM_URLENCODED_TYPE = 'application/x-www-form-urlencoded'
536
+
357
537
  /** One file field of a form: the collection the file lands in, and whether a submission must carry it. */
358
538
  export interface FormFileArtifact {
359
539
  readonly collection: string
@@ -378,12 +558,57 @@ export interface FormChallenge {
378
558
  readonly siteKey?: string
379
559
  }
380
560
 
561
+ /** A public procedure's challenge: a form's, and the widget `action` the verification expects back. */
562
+ export interface ProcedureChallenge extends FormChallenge {
563
+ /** The declared `action`, or the endpoint id with `_` for `.`. */
564
+ readonly action: string
565
+ }
566
+
381
567
  export interface WebhookMountArtifact {
382
568
  readonly kind: 'webhook'
383
569
  readonly path: string
384
- readonly scheme: 'github-sha256'
570
+ readonly scheme: WebhookScheme
385
571
  readonly boundTo: ScopeBinding
386
572
  readonly actions: readonly string[]
573
+ /** How long a delivery's handler may run after the last body byte, in ms; its body limit is its row's `admission`. */
574
+ readonly timeoutMs: number
575
+ }
576
+
577
+ /**
578
+ * The providers whose signature the framework checks by name; every one signs the raw body with the binding's secret,
579
+ * and Twilio the public URL with it. Slack and Twilio post forms as well as JSON.
580
+ */
581
+ export const WEBHOOK_PRESETS = ['github-sha256', 'slack', 'standard-webhooks', 'stripe', 'twilio'] as const
582
+
583
+ export type WebhookPreset = (typeof WEBHOOK_PRESETS)[number]
584
+
585
+ /**
586
+ * How a delivery proves it holds its binding's secret: a preset, an HMAC the framework computes in a declared shape,
587
+ * or the secret itself as a Basic password or a bearer token. A verifier is framework code, never the application's.
588
+ * `basic` and `bearer` read `Authorization`, which the proxy passes only to a row that declares `authorization:
589
+ * 'forward'` (ADR-0022 rule 3).
590
+ */
591
+ export type WebhookScheme =
592
+ | WebhookPreset
593
+ | { readonly hmac: HmacScheme }
594
+ | { readonly basic: true }
595
+ | { readonly bearer: true }
596
+
597
+ export type HmacAlgorithm = 'sha1' | 'sha256' | 'sha512'
598
+
599
+ /**
600
+ * An HMAC of the binding's secret over the signed content, read from `header` as `prefix` and the encoded digest.
601
+ * `'timestamp.body'` signs `<timestamp>.<body>` with the `timestamp` header's Unix seconds, which must be within five
602
+ * minutes of now; `id` names a header whose value the signed content starts with, as `<id>.`.
603
+ */
604
+ export interface HmacScheme {
605
+ readonly header: string
606
+ readonly algorithm: HmacAlgorithm
607
+ readonly encoding: 'hex' | 'base64'
608
+ readonly prefix?: string
609
+ readonly timestamp?: string
610
+ readonly signed: 'body' | 'timestamp.body'
611
+ readonly id?: string
387
612
  }
388
613
 
389
614
  /** Where a workload's authority applies: the whole application, or one value of a dimension per binding. */
@@ -410,11 +635,20 @@ export interface FileCollectionArtifact {
410
635
  readonly scan?: true
411
636
  }
412
637
 
638
+ /** One file kind: the media types its files may be, the largest file, and whether each waits for a clean scan. */
639
+ export interface FileKindArtifact {
640
+ readonly types: readonly string[]
641
+ readonly maxBytes: number
642
+ /** Present when every file of the kind waits `quarantined` for a clean malware verdict before it is served. */
643
+ readonly scan?: true
644
+ }
645
+
413
646
  export interface JobArtifact {
414
647
  readonly schedule: string
415
648
  readonly actions: readonly string[]
416
649
  readonly scope: ScopeBinding
417
- readonly timeout: string | null
650
+ /** How long one attempt may run, in ms, every default applied. */
651
+ readonly timeoutMs: number
418
652
  readonly retries: number
419
653
  }
420
654
 
@@ -467,10 +701,35 @@ export interface DeclaredReach {
467
701
  readonly unscoped: Readonly<Record<string, 'read' | 'write'>>
468
702
  readonly connect: readonly string[]
469
703
  readonly issues: string | null
470
- /** The cron job this mutation kicks after its commit; absent unless declared, so the digest stays. */
704
+ /** The cron job this mutation kicks after its commit (an older release's form); absent unless declared, so the digest stays. */
471
705
  readonly then?: string
706
+ /**
707
+ * The cron jobs this site may kick (`ctx.kick`), sorted: a mutation, a webhook or a job. Absent unless declared, so
708
+ * the digest stays. A contract's kick edges between jobs are acyclic.
709
+ */
710
+ readonly kicks?: readonly string[]
472
711
  /** The mail transport this job reaches: the installation's or its own; absent unless declared. */
473
712
  readonly mailer?: JobMailer
713
+ /**
714
+ * The webhook whose bindings this mutation creates and removes (`ctx.webhooks('<name>')`), seeing each new binding's
715
+ * secret once. Absent unless declared, so the digest stays.
716
+ */
717
+ readonly binds?: string
718
+ /**
719
+ * The token purposes this site signs (`ctx.tokens.sign('<purpose>', …)`), sorted. Absent unless declared, so the digest
720
+ * stays.
721
+ */
722
+ readonly signs?: readonly string[]
723
+ /**
724
+ * The HTTPS origins this site's code calls (`fetch`), sorted: a credentialed procedure, a webhook or a job. Absent
725
+ * unless declared, so the digest stays.
726
+ */
727
+ readonly egress?: readonly string[]
728
+ /**
729
+ * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
730
+ * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
731
+ */
732
+ readonly actions?: readonly string[]
474
733
  }
475
734
 
476
735
  /** The mail transports a job may declare: the installation's default, or the application's own. */
@@ -499,14 +758,20 @@ export interface CspSource {
499
758
 
500
759
  // ── Table policies ──────────────────────────────────────────────────────────────────────────────
501
760
 
761
+ /**
762
+ * The actions of one table operation, any one of which allows it: one action as its text, several as a list of at least
763
+ * two. A single action stays text, so the artifact of a policy that names one keeps its shape and digest.
764
+ */
765
+ export type TableActionArtifact = string | readonly string[]
766
+
502
767
  export interface TablePolicyArtifact {
503
768
  readonly scope: TableScope
504
769
  /** An inbox's read action is `read`; it has no write action, because only its form appends. */
505
770
  readonly actions: {
506
- readonly read: string
507
- readonly insert: string | null
508
- readonly update: string | null
509
- readonly delete: string | null
771
+ readonly read: TableActionArtifact
772
+ readonly insert: TableActionArtifact | null
773
+ readonly update: TableActionArtifact | null
774
+ readonly delete: TableActionArtifact | null
510
775
  /**
511
776
  * A dimension or child table's actions besides `read` with which an `app` endpoint reads every row, read-only;
512
777
  * present only when the policy names one.
@@ -524,6 +789,11 @@ export interface TablePolicyArtifact {
524
789
  * is updated by that action only, never by the table's update action.
525
790
  */
526
791
  readonly columns: Readonly<Record<string, ColumnPolicyArtifact>>
792
+ /**
793
+ * Column → the file kind it holds: a foreign key to `fabrika_files`, written only with a file reference. The table's
794
+ * actions are the file's authority. Absent unless declared, so the digest stays.
795
+ */
796
+ readonly files?: Readonly<Record<string, string>>
527
797
  }
528
798
 
529
799
  /** 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
+ }