@fabrika/auth-core 0.9.0-dev.5 → 0.9.0-dev.50

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. package/package.json +3 -2
  2. package/src/agent.ts +89 -0
  3. package/src/canonical-path.ts +18 -0
  4. package/src/client-address.ts +74 -0
  5. package/src/contract-canonical.ts +168 -2
  6. package/src/contract-encoding.ts +181 -0
  7. package/src/contract.ts +220 -17
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +70 -0
  11. package/src/framework-variables.ts +14 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +7 -0
  14. package/src/installation-endpoint.ts +3 -2
  15. package/src/locale.ts +13 -1
  16. package/src/managed-environment.ts +11 -0
  17. package/src/membership.ts +12 -4
  18. package/src/oauth.ts +19 -0
  19. package/src/ops.ts +487 -16
  20. package/src/permissions.ts +42 -0
  21. package/src/public-egress.ts +168 -0
  22. package/src/requirement.ts +12 -4
  23. package/src/rpc.ts +137 -9
  24. package/src/scope-values.ts +123 -0
  25. package/src/sha256.ts +52 -14
  26. package/src/token.ts +195 -14
  27. package/src/types.ts +72 -1
  28. package/src/wire.ts +2 -1
  29. package/types/src/agent.d.ts +37 -0
  30. package/types/src/canonical-path.d.ts +6 -0
  31. package/types/src/client-address.d.ts +7 -0
  32. package/types/src/contract-canonical.d.ts +11 -1
  33. package/types/src/contract-encoding.d.ts +18 -0
  34. package/types/src/contract.d.ts +205 -16
  35. package/types/src/egress.d.ts +27 -0
  36. package/types/src/endpoint-digest.d.ts +5 -0
  37. package/types/src/framework-release.d.ts +23 -0
  38. package/types/src/framework-variables.d.ts +6 -1
  39. package/types/src/iam-mail.d.ts +92 -0
  40. package/types/src/index.d.ts +7 -0
  41. package/types/src/installation-endpoint.d.ts +3 -2
  42. package/types/src/locale.d.ts +11 -1
  43. package/types/src/managed-environment.d.ts +1 -1
  44. package/types/src/membership.d.ts +8 -3
  45. package/types/src/oauth.d.ts +11 -0
  46. package/types/src/ops.d.ts +133 -8
  47. package/types/src/permissions.d.ts +12 -0
  48. package/types/src/public-egress.d.ts +31 -0
  49. package/types/src/requirement.d.ts +5 -4
  50. package/types/src/rpc.d.ts +113 -6
  51. package/types/src/scope-values.d.ts +61 -0
  52. package/types/src/sha256.d.ts +10 -0
  53. package/types/src/token.d.ts +70 -8
  54. package/types/src/types.d.ts +48 -1
  55. package/types/src/wire.d.ts +2 -1
package/src/contract.ts CHANGED
@@ -3,6 +3,8 @@
3
3
 
4
4
  import type { Locale } from './locale'
5
5
  import type { MailTemplates } from './mail'
6
+ import type { DeclaredEgress } from './public-egress'
7
+ import type { DimensionValue } from './scope-values'
6
8
  import type { TerminalArtifact } from './terminal'
7
9
 
8
10
  /**
@@ -24,10 +26,15 @@ export interface ContractArtifact extends EndpointTable {
24
26
  /** Action → description. Exact actions only; the artifact holds no wildcard. */
25
27
  readonly actions: Readonly<Record<string, string>>
26
28
  readonly roles: Readonly<Record<string, RoleArtifact>>
29
+ /**
30
+ * The relations a table's rows confer (`relations: { owner: { dimension: 'project' } }`): a role's `via` holds its
31
+ * actions where a row names the caller. Absent unless declared, so the digest stays.
32
+ */
33
+ readonly relations?: Readonly<Record<string, RelationArtifact>>
27
34
  readonly mounts: Readonly<Record<string, MountArtifact>>
28
35
  readonly files: Readonly<Record<string, FileCollectionArtifact>>
29
36
  /**
30
- * The file kinds (`c.files({ types, maxBytes, scan? })`): classes of stored files a table's file column holds. A kind
37
+ * The file kinds (`c.files({ types, maxBytes, scan?, inline? })`): classes of stored files a table's file column holds. A kind
31
38
  * has no owner and no endpoint; the table that holds a file is its authority. Absent unless declared, so the digest stays.
32
39
  */
33
40
  readonly fileKinds?: Readonly<Record<string, FileKindArtifact>>
@@ -67,6 +74,11 @@ export interface ContractArtifact extends EndpointTable {
67
74
  * terminal's browser there, and only an application that declares it may assert a person. Absent unless declared.
68
75
  */
69
76
  readonly terminal?: TerminalArtifact
77
+ /**
78
+ * The application notifies people through Web Push (ADR-0088), so the table holds the framework's push rows under
79
+ * `/__fabrika/push`. Absent unless declared, so the digest stays.
80
+ */
81
+ readonly notifications?: true
70
82
  /**
71
83
  * What each procedure of the staged kit admits and how long it runs, by endpoint id, with every default applied: the
72
84
  * rules the application applies itself, beside the row the proxy applies. Absent for a contract with no such
@@ -131,8 +143,11 @@ export interface EndpointTable {
131
143
  readonly reservedPrefixes: readonly string[]
132
144
  }
133
145
 
134
- /** Who may call a credentialed endpoint. There is no public caller: anonymous traffic is a fixed endpoint kind. */
135
- export type Caller = 'human' | 'machine' | 'link' | `app:${string}`
146
+ /**
147
+ * Who may call a credentialed endpoint. There is no public caller: anonymous traffic is a fixed endpoint kind. `agent` is a
148
+ * person's agent holding a device grant for the environment (ADR-0090).
149
+ */
150
+ export type Caller = 'human' | 'machine' | 'agent' | 'link' | `app:${string}`
136
151
 
137
152
  /** `app:<id>`: the connector of the consuming application `<id>`. */
138
153
  export const APP_CALLER_PREFIX = 'app:'
@@ -141,7 +156,7 @@ export const APP_CALLER_PREFIX = 'app:'
141
156
  export const CONNECT_PREFIX = '/__fabrika/connect'
142
157
 
143
158
  /** An RPC mount's callers: a link holder reaches only its own link mount, and an `app:<id>` only an export. */
144
- export type RpcCaller = 'human' | 'machine'
159
+ export type RpcCaller = 'human' | 'machine' | 'agent'
145
160
 
146
161
  export type EndpointMethod = 'GET' | 'POST'
147
162
 
@@ -160,10 +175,11 @@ export type EndpointKind = CredentialedEndpointKind | AnonymousEndpointKind
160
175
 
161
176
  /**
162
177
  * The contract entry that declared an endpoint. A `challenge` row is the framework's own: the endpoint that issues the
163
- * ALTCHA challenge of the public procedure `name`.
178
+ * ALTCHA challenge of the public procedure `name`. A `push` row is the framework's own too: one of the rows a contract
179
+ * that declares `notifications` gets under `/__fabrika/push` (ADR-0088), named by its part (`worker`).
164
180
  */
165
181
  export interface EndpointSource {
166
- readonly kind: 'mount' | 'export' | 'files' | 'challenge'
182
+ readonly kind: 'mount' | 'export' | 'files' | 'challenge' | 'push'
167
183
  readonly name: string
168
184
  }
169
185
 
@@ -189,7 +205,8 @@ interface EndpointRowBase {
189
205
  readonly crossOrigin?: CrossOriginForm
190
206
  /**
191
207
  * `file`: the procedure answers a stored file (an output `file('<kind>')`), so the proxy and the application give every
192
- * answer of it, a denial included, ADR-0022's file treatment. Absent otherwise, so every other row keeps its digest.
208
+ * answer of it, a denial included, ADR-0022's file treatment. `inline-file`: the same, for a kind declared `inline:
209
+ * true`, whose XML documents are shown too. Absent otherwise, so every other row keeps its digest.
193
210
  */
194
211
  readonly response?: EndpointResponse
195
212
  /**
@@ -209,8 +226,8 @@ interface EndpointRowBase {
209
226
  /** What the proxy does with an anonymous request's `Authorization` on a row that names it: forward it to the application. */
210
227
  export type EndpointAuthorization = 'forward'
211
228
 
212
- /** The answer profile of a row that answers a stored file. */
213
- export type EndpointResponse = 'file'
229
+ /** The answer profile of a row that answers a stored file: `inline-file` also shows the XML documents a machine reads. */
230
+ export type EndpointResponse = 'file' | 'inline-file'
214
231
 
215
232
  /** A cacheable row's lifetime: `maxAgeSeconds`, or `immutable`, a year, for an input that names an immutable value. */
216
233
  export type EndpointCache = { readonly maxAgeSeconds: number } | 'immutable'
@@ -223,7 +240,7 @@ export const FILE_RESPONSE_KINDS: readonly EndpointKind[] = ['query', 'mutation'
223
240
 
224
241
  /** Whether every answer of a row gets the file treatment: a collection's download, or a procedure that answers a file. */
225
242
  export function answersFile(row: { readonly kind: string; readonly response?: EndpointResponse }): boolean {
226
- return row.kind === 'download' || row.response === 'file'
243
+ return row.kind === 'download' || row.response !== undefined
227
244
  }
228
245
 
229
246
  /** How an endpoint admits another origin: from the environment's list, or (a form or a public procedure) from any origin. */
@@ -257,7 +274,7 @@ export interface BodyAdmission {
257
274
  * `action` is that action in some scope, global included, and only globally under the `app` form. The access form is
258
275
  * what the framework then resolves.
259
276
  */
260
- export type EndpointRequirement = MemberRequirement | ActionRequirement | CapabilitiesRequirement
277
+ export type EndpointRequirement = MemberRequirement | ActionRequirement | AnyOfRequirement | CapabilitiesRequirement
261
278
 
262
279
  export interface MemberRequirement {
263
280
  readonly kind: 'member'
@@ -269,6 +286,24 @@ export interface ActionRequirement {
269
286
  readonly access: AccessForm
270
287
  }
271
288
 
289
+ /**
290
+ * Any one of several actions (`access: { anyOf, app: true }`), each held as a global grant, the `app` form's rule: two to
291
+ * `MAX_ANY_OF` distinct actions, sorted, so the order in the source does not change the digest.
292
+ */
293
+ export interface AnyOfRequirement {
294
+ readonly kind: 'anyOf'
295
+ readonly actions: readonly [string, string, ...string[]]
296
+ readonly access: { readonly form: 'app' }
297
+ }
298
+
299
+ /** The most actions an `anyOf` requirement lists. */
300
+ export const MAX_ANY_OF = 16
301
+
302
+ /** Whether `actions` is an `anyOf` list as a row carries it: two to `MAX_ANY_OF` actions, strictly ascending. */
303
+ export function isAnyOfList(actions: readonly string[]): boolean {
304
+ return actions.length >= 2 && actions.length <= MAX_ANY_OF && actions.every((action, index) => index === 0 || (actions[index - 1] ?? '') < action)
305
+ }
306
+
272
307
  /**
273
308
  * Several capabilities (`access: { capabilities }`), by the name the handler reads each under (`ctx.capabilities.<name>`):
274
309
  * the token must carry every action, and the access form of each narrows it as it narrows a single one. At least two.
@@ -343,6 +378,29 @@ export function isFileShape(shape: OutputShape): shape is FileShape {
343
378
  return shape.type === 'file'
344
379
  }
345
380
 
381
+ /** The kinds of the files a schema holds, anywhere in it, each once per place it appears. */
382
+ export function fileKindsIn(shape: SchemaShape): readonly string[] {
383
+ switch (shape.type) {
384
+ case 'file':
385
+ return [shape.kind]
386
+ case 'array':
387
+ return fileKindsIn(shape.items)
388
+ case 'tuple':
389
+ return [...shape.items.flatMap(fileKindsIn), ...(shape.rest === null ? [] : fileKindsIn(shape.rest))]
390
+ case 'record':
391
+ return fileKindsIn(shape.value)
392
+ case 'object':
393
+ return Object.values(shape.fields).flatMap(fileKindsIn)
394
+ case 'optional':
395
+ case 'nullable':
396
+ return fileKindsIn(shape.inner)
397
+ case 'union':
398
+ return shape.options.flatMap(fileKindsIn)
399
+ default:
400
+ return []
401
+ }
402
+ }
403
+
346
404
  /**
347
405
  * What a procedure answers: a JSON value of a schema, a file of rows (`attachment()` of `@fabrika/app/contract`), or a
348
406
  * redirect (`redirect()`).
@@ -449,6 +507,13 @@ export interface DimensionArtifact {
449
507
  readonly members: { readonly manage: string; readonly list: string } | null
450
508
  /** `labels`: the member directory shows labels to `members.list` holders. Absent unless declared, so digests stay. */
451
509
  readonly directory?: 'labels'
510
+ /** The values the console offers for a grant in this dimension (ADR-0085). Absent unless declared, so digests stay. */
511
+ readonly values?: readonly DimensionValue[]
512
+ /**
513
+ * The id of the query procedure IAM asks, as the administrator, for this dimension's values (ADR-0085 §4). Absent
514
+ * unless declared, so digests stay.
515
+ */
516
+ readonly valuesFrom?: string
452
517
  }
453
518
 
454
519
  export interface RoleArtifact {
@@ -460,6 +525,16 @@ export interface RoleArtifact {
460
525
  readonly member: { readonly scope: string; readonly assignableBy: readonly string[] } | null
461
526
  /** An external principal may hold this membership role (ADR-0051). Absent unless declared, so digests stay. */
462
527
  readonly external?: true
528
+ /**
529
+ * Relation → actions the holder of a global grant of this role holds at each node a relation row names them at.
530
+ * Absent unless declared, so digests stay.
531
+ */
532
+ readonly via?: Readonly<Record<string, readonly string[]>>
533
+ }
534
+
535
+ /** A relation of the vocabulary: the dimension whose nodes its rows name. */
536
+ export interface RelationArtifact {
537
+ readonly dimension: string
463
538
  }
464
539
 
465
540
  // ── Mounts and companions ───────────────────────────────────────────────────────────────────────
@@ -674,6 +749,11 @@ export interface FileKindArtifact {
674
749
  readonly maxBytes: number
675
750
  /** Present when every file of the kind waits `quarantined` for a clean malware verdict before it is served. */
676
751
  readonly scan?: true
752
+ /**
753
+ * Present when its files are shown rather than downloaded: every type is an inert image or an XML document a machine
754
+ * reads, and a row answering it is `response: 'inline-file'`. Absent otherwise, so every other kind keeps its digest.
755
+ */
756
+ readonly inline?: true
677
757
  }
678
758
 
679
759
  export interface JobArtifact {
@@ -754,10 +834,12 @@ export interface DeclaredReach {
754
834
  */
755
835
  readonly signs?: readonly string[]
756
836
  /**
757
- * The HTTPS origins this site's code calls (`fetch`), sorted: a credentialed procedure, a webhook or a job. Absent
758
- * unless declared, so the digest stays.
837
+ * The HTTPS origins this site's code calls (`fetch`), sorted, each an exact origin or a one-label pattern
838
+ * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Or `'public'` (a cron job only): every public
839
+ * host over HTTPS or HTTP, never the installation or a private network (ADR-0075). Absent unless declared, so the
840
+ * digest stays.
759
841
  */
760
- readonly egress?: readonly string[]
842
+ readonly egress?: DeclaredEgress
761
843
  /**
762
844
  * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
763
845
  * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
@@ -802,6 +884,12 @@ export interface CspSource {
802
884
  */
803
885
  export type TableActionArtifact = string | readonly string[]
804
886
 
887
+ /**
888
+ * An application table's `actions.read` that every `app` endpoint, job and webhook reads with, whatever its action; never
889
+ * a public procedure, a scoped site, a link or an export. No vocabulary may declare an action of this name.
890
+ */
891
+ export const READ_ANY = 'any'
892
+
805
893
  export interface TablePolicyArtifact {
806
894
  readonly scope: TableScope
807
895
  /** An inbox's read action is `read`; it has no write action, because only its form appends. */
@@ -832,12 +920,127 @@ export interface TablePolicyArtifact {
832
920
  * actions are the file's authority. Absent unless declared, so the digest stays.
833
921
  */
834
922
  readonly files?: Readonly<Record<string, string>>
923
+ /**
924
+ * A view (ADR-0072): read like its scope's tables, written by nothing, its containment stated by its SQL alone.
925
+ * Absent for a table, so the digest stays.
926
+ */
927
+ readonly view?: true
928
+ /** Relation → how a row of this table confers it. Absent unless declared, so the digest stays. */
929
+ readonly confers?: Readonly<Record<string, ConfersArtifact>>
930
+ /** Action → the condition a row must meet for it, narrowing what any grant of it reaches. Absent unless declared. */
931
+ readonly when?: Readonly<Record<string, ConditionArtifact>>
932
+ /**
933
+ * Relation → action → the condition a row the relation reaches must meet for it; it narrows that relation's reach only.
934
+ * Absent unless declared, so the digest stays. A reader that ignores it reaches more: Control refuses to publish it to
935
+ * an application pinned below the release that enforces it.
936
+ */
937
+ readonly relationWhen?: Readonly<Record<string, Readonly<Record<string, ConditionArtifact>>>>
938
+ /**
939
+ * Relation of the table's own dimension → the ancestor its rows reveal. Absent unless declared, so the digest stays.
940
+ * A reader that ignores it reaches less, never more.
941
+ */
942
+ readonly reveals?: Readonly<Record<string, RevealsArtifact>>
943
+ /**
944
+ * Dimension outside the chain → the column a `Within`'s read reaches a row through. Absent unless declared, so the
945
+ * digest stays. A reader that ignores it reaches less, never more.
946
+ */
947
+ readonly readThrough?: Readonly<Record<string, string>>
948
+ /**
949
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
950
+ * path's column must hold each at the node it names. Absent unless declared, so the digest stays. A reader that
951
+ * ignores it reaches less, never more.
952
+ */
953
+ readonly writeThrough?: Readonly<Record<string, readonly string[]>>
954
+ /**
955
+ * The table's own dimension → the ancestor its rows reveal to a grant at their node, for a `Within`'s reads. Absent
956
+ * unless declared, so the digest stays. A reader that ignores it reaches less, never more.
957
+ */
958
+ readonly memberReveals?: Readonly<Record<string, MemberRevealsArtifact>>
959
+ /**
960
+ * Relation → the access view that lists the rows it reaches (ADR-0076). Absent unless declared, so the digest stays.
961
+ * A reader that ignores it reaches less, never more.
962
+ */
963
+ readonly access?: Readonly<Record<string, AccessArtifact>>
964
+ }
965
+
966
+ /** An access view: its `row` column names the table's key; `principal` is compared to the caller, `member` to its nodes. */
967
+ export interface AccessArtifact {
968
+ readonly view: string
969
+ readonly row: string
970
+ readonly principal: string | null
971
+ readonly member: string | null
972
+ }
973
+
974
+ /**
975
+ * A row reveals its node in `to` for `actions` to a grant of them at the row's own node, or at the node its path to the
976
+ * key's dimension names, while `when` admits the row.
977
+ */
978
+ export interface MemberRevealsArtifact {
979
+ readonly to: string
980
+ readonly actions: readonly string[]
981
+ readonly when?: ConditionArtifact
982
+ /**
983
+ * Through a path, on a table with an insert: the writer picks the node, and `self` lets it pick one where it holds a
984
+ * grant the reveal counts. Absent otherwise; only a reader that refuses a path's key reads it.
985
+ */
986
+ readonly assign?: { readonly self: boolean }
987
+ }
988
+
989
+ /** A row the relation reaches reveals its node in `to` for `actions`, while `when` admits the row. */
990
+ export interface RevealsArtifact {
991
+ readonly to: string
992
+ readonly actions: readonly string[]
993
+ readonly when?: ConditionArtifact
994
+ /** On a reveal matched through `readThrough`: an insert delegates, and `self` lets it name a node its writer holds. */
995
+ readonly assign?: { readonly self: boolean }
996
+ }
997
+
998
+ /** A row names `principal` at the node in `node`, until `expires`, while `when` admits it; `assign` bounds its writer. */
999
+ export interface ConfersArtifact {
1000
+ /** The column that holds the principal, or `<column>.<principal column>` through one foreign key of the table. */
1001
+ readonly principal: string
1002
+ readonly node: string
1003
+ readonly expires: string | null
1004
+ readonly when?: ConditionArtifact
1005
+ readonly assign: { readonly maxDays: number | null; readonly self: boolean } | null
1006
+ }
1007
+
1008
+ /**
1009
+ * A structured row condition: connectives, `{ '<column or fk_column.column>': test }` with every test holding, or
1010
+ * `some` / `none` of the rows of one table whose foreign key names the row, also at the end of a path
1011
+ * (`{ '<fk_column>': { some: … } }`). Each form is absent from a condition that does not use it, so its digest stays.
1012
+ */
1013
+ export type ConditionArtifact =
1014
+ | { readonly allOf: readonly ConditionArtifact[] }
1015
+ | { readonly anyOf: readonly ConditionArtifact[] }
1016
+ | { readonly not: ConditionArtifact }
1017
+ | RowsTestArtifact
1018
+ | { readonly [path: string]: ColumnTestArtifact | RowsTestArtifact }
1019
+
1020
+ /** `some` or `none` of the rows of one table whose foreign key names the row. */
1021
+ export type RowsTestArtifact =
1022
+ | { readonly some: Readonly<Record<string, ConditionArtifact>> }
1023
+ | { readonly none: Readonly<Record<string, ConditionArtifact>> }
1024
+
1025
+ export type ConditionLiteralArtifact = string | number | boolean
1026
+
1027
+ /** One operator of a column test; `{ now: true }` compares a timestamp with the statement's clock. */
1028
+ export interface ColumnTestArtifact {
1029
+ readonly eq?: ConditionLiteralArtifact
1030
+ readonly notEq?: ConditionLiteralArtifact
1031
+ readonly in?: readonly ConditionLiteralArtifact[]
1032
+ readonly notIn?: readonly ConditionLiteralArtifact[]
1033
+ readonly isNull?: boolean
1034
+ readonly lt?: ConditionLiteralArtifact | { readonly now: true }
1035
+ readonly lte?: ConditionLiteralArtifact | { readonly now: true }
1036
+ readonly gt?: ConditionLiteralArtifact | { readonly now: true }
1037
+ readonly gte?: ConditionLiteralArtifact | { readonly now: true }
835
1038
  }
836
1039
 
837
- /** A column's own read action, its own write action, or both; an absent one is left out. */
1040
+ /** A column's own read actions, its own write actions (each one as its text, several as a list), or both; an absent one is left out. */
838
1041
  export interface ColumnPolicyArtifact {
839
- readonly read?: string
840
- readonly write?: string
1042
+ readonly read?: TableActionArtifact
1043
+ readonly write?: TableActionArtifact
841
1044
  }
842
1045
 
843
1046
  export type TableScope =
package/src/egress.ts ADDED
@@ -0,0 +1,97 @@
1
+ // What a site's `egress` entry is, and which request URL it admits: the one rule the contract build, the artifact parser,
2
+ // the runtime guard on `fetch`, the checker and the approval diff share (ADR-0012 §15). An entry is an exact `https`
3
+ // origin or a pattern `https://*.<domain>[:port]` whose `*` stands for exactly one DNS label.
4
+
5
+ /** One parsed `egress` entry. `port` is `''` for the default port, as `URL.port` spells it. */
6
+ export type EgressEntry =
7
+ | { readonly kind: 'origin'; readonly origin: string; readonly host: string; readonly port: string }
8
+ | { readonly kind: 'pattern'; readonly pattern: string; readonly domain: string; readonly port: string }
9
+
10
+ export type EgressEntryParse = { readonly ok: true; readonly entry: EgressEntry } | { readonly ok: false; readonly problem: string }
11
+
12
+ /** What every pattern starts with: the scheme and the one wildcard label. */
13
+ const EGRESS_WILDCARD_PREFIX = 'https://*.'
14
+
15
+ const HOSTNAME = /^(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)*[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/
16
+ const NUMERIC_LABEL = /^[0-9]+$/
17
+
18
+ /**
19
+ * `value` as an `egress` entry, or why it is none. Each entry is written canonically (lower case, punycode, no default
20
+ * port, no trailing dot, no path), so an artifact names one entry one way; a problem names the canonical spelling when
21
+ * there is one.
22
+ */
23
+ export function parseEgressEntry(value: string): EgressEntryParse {
24
+ return value.startsWith(EGRESS_WILDCARD_PREFIX) ? parsePattern(value) : parseOrigin(value)
25
+ }
26
+
27
+ function parseOrigin(value: string): EgressEntryParse {
28
+ const url = urlOf(value)
29
+ if (url === null || url.protocol !== 'https:') return refused('is not an https origin')
30
+ if (url.hostname.endsWith('.')) return refused(canonicalProblem(url, `https://${url.host.replace(/\.(?=:|$)/, '')}`))
31
+ if (!HOSTNAME.test(url.hostname)) {
32
+ return refused(url.hostname.includes('*') ? 'puts a wildcard elsewhere than one leading label' : 'is not an https origin with a literal host')
33
+ }
34
+ if (url.origin !== value) return refused(canonicalProblem(url, url.origin))
35
+ return { ok: true, entry: { kind: 'origin', origin: value, host: url.hostname, port: url.port } }
36
+ }
37
+
38
+ function parsePattern(value: string): EgressEntryParse {
39
+ const rest = value.slice(EGRESS_WILDCARD_PREFIX.length)
40
+ const url = urlOf(`https://${rest}`)
41
+ if (url === null) return refused('is not an https origin pattern')
42
+ if (url.hostname.includes('*')) return refused('has more than one wildcard label (allowed: one leading *.)')
43
+ if (url.hostname.endsWith('.')) return refused(canonicalProblem(url, `${EGRESS_WILDCARD_PREFIX}${url.host.replace(/\.(?=:|$)/, '')}`))
44
+ if (!HOSTNAME.test(url.hostname)) return refused('is not an https origin pattern with a literal domain')
45
+ const labels = url.hostname.split('.')
46
+ if (NUMERIC_LABEL.test(labels.at(-1) ?? '')) return refused('puts its wildcard on an IP address (allowed: a domain name)')
47
+ if (isPublicSuffix(labels)) {
48
+ return refused(`puts its wildcard on the public suffix '${url.hostname}' (allowed: a domain of your own, as in 'https://*.example.com')`)
49
+ }
50
+ if (url.origin !== `https://${rest}`) return refused(canonicalProblem(url, `${EGRESS_WILDCARD_PREFIX}${url.host}`))
51
+ return { ok: true, entry: { kind: 'pattern', pattern: value, domain: url.hostname, port: url.port } }
52
+ }
53
+
54
+ /**
55
+ * Whether `labels` name a public suffix by this rule, which stands in for the public suffix list (the platform ships no
56
+ * copy of it): one label (`com`), or two labels under a two-letter country code whose first has at
57
+ * most three characters (`co.uk`, `com.au`, `ne.jp`). A suffix this rule cannot tell, such as a longer second-level
58
+ * label or a shared hosting domain, is the approver's to judge: the diff shows every pattern as a wider grant.
59
+ */
60
+ function isPublicSuffix(labels: readonly string[]): boolean {
61
+ if (labels.length < 2) return true
62
+ const top = labels.at(-1) ?? ''
63
+ const second = labels.at(-2) ?? ''
64
+ return labels.length === 2 && /^[a-z]{2}$/.test(top) && second.length <= 3
65
+ }
66
+
67
+ /** Whether `url` is a request an entry of `entries` admits: its host and port, a trailing dot of the host aside. */
68
+ export function egressAdmits(entries: readonly EgressEntry[], url: URL): boolean {
69
+ if (url.protocol !== 'https:') return false
70
+ const host = url.hostname.endsWith('.') ? url.hostname.slice(0, -1) : url.hostname
71
+ return entries.some((entry) => entry.port === url.port && (entry.kind === 'origin' ? entry.host === host : isOneLabelUnder(host, entry.domain)))
72
+ }
73
+
74
+ /** `host` is exactly one non-empty label followed by `.<domain>`, so `evil-example.com` is not under `example.com`. */
75
+ function isOneLabelUnder(host: string, domain: string): boolean {
76
+ const suffix = `.${domain}`
77
+ if (!host.endsWith(suffix)) return false
78
+ const label = host.slice(0, -suffix.length)
79
+ return label.length > 0 && !label.includes('.')
80
+ }
81
+
82
+ function canonicalProblem(url: URL, canonical: string): string {
83
+ const bare = url.pathname === '/' && url.search === '' && url.hash === '' && url.username === '' && url.password === ''
84
+ return bare ? `is not written canonically (write it as '${canonical}')` : 'carries a path, query or credentials (allowed: an origin only)'
85
+ }
86
+
87
+ function refused(problem: string): EgressEntryParse {
88
+ return { ok: false, problem }
89
+ }
90
+
91
+ function urlOf(value: string): URL | null {
92
+ try {
93
+ return new URL(value)
94
+ } catch {
95
+ return null
96
+ }
97
+ }
@@ -2,9 +2,9 @@
2
2
  // with every allowed request, and one for the whole contract, checked once at startup.
3
3
 
4
4
  import type { ContractArtifact, EndpointRow, ExportDescription } from './contract'
5
- import { canonicalAdmission, canonicalArtifactJson, canonicalJson, canonicalShape } from './contract-canonical'
5
+ import { canonicalAdmission, canonicalArtifactJson, canonicalJson, canonicalShape, writeCanonicalJson } from './contract-canonical'
6
6
  import type { InstallationEndpointRow, InstallationEndpointTable } from './installation-endpoint'
7
- import { sha256Hex } from './sha256'
7
+ import { Sha256, sha256Hex } from './sha256'
8
8
 
9
9
  /** The variable that carries the digest of the contract a deploy was approved with; the application compares its own. */
10
10
  export const FABRIKA_CONTRACT_DIGEST = 'FABRIKA_CONTRACT_DIGEST'
@@ -109,6 +109,26 @@ export function contractDigest(artifact: ContractArtifact): string {
109
109
  return digestOf(canonicalArtifactJson(artifact))
110
110
  }
111
111
 
112
+ /**
113
+ * `contractDigest` of an artifact that already is canonical (`canonicalizeArtifact`'s, as a decoded artifact is),
114
+ * hashed as it is serialized: neither a canonical copy nor its text is built. A shared shape is hashed at each place.
115
+ */
116
+ export function canonicalArtifactDigest(canonical: ContractArtifact): string {
117
+ const hash = new Sha256()
118
+ let pending = ''
119
+ writeCanonicalJson(canonical, (piece) => {
120
+ pending += piece
121
+ if (pending.length >= HASH_CHUNK) {
122
+ hash.update(pending)
123
+ pending = ''
124
+ }
125
+ })
126
+ return `sha256:${hash.update(pending).hex()}`
127
+ }
128
+
129
+ /** Pieces are hashed in chunks of about this many code units: one encode per piece would dominate the digest. */
130
+ const HASH_CHUNK = 16_384
131
+
112
132
  /**
113
133
  * The digest of an installation service's table: each row's id and `requirementDigest`, and the reserved prefixes. A
114
134
  * composition writes it beside the service from the table its proxy publishes, so the service refuses to start under
@@ -1,2 +1,72 @@
1
1
  /** A framework release as npm publishes it; the only form one may take before it reaches a generated build command. */
2
2
  export const FRAMEWORK_RELEASE_PATTERN = /^\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?$/
3
+
4
+ /**
5
+ * Whether framework release `release` is at least `since`. A prerelease counts as its `major.minor`; a release that
6
+ * does not start with `<major>.<minor>.` is never at least anything (ADR-0062).
7
+ */
8
+ export const releaseAtLeast = (release: string, since: { readonly major: number; readonly minor: number }): boolean => {
9
+ const match = /^(\d+)\.(\d+)\./.exec(release)
10
+ if (match === null) return false
11
+ const major = Number(match[1])
12
+ return major > since.major || (major === since.major && Number(match[2]) >= since.minor)
13
+ }
14
+
15
+ /** A release as semver orders it: the numeric core, then the prerelease identifiers (none sorts above any). */
16
+ interface ReleaseVersion {
17
+ readonly core: readonly number[]
18
+ readonly prerelease: readonly string[]
19
+ }
20
+
21
+ const parseReleaseVersion = (release: string): ReleaseVersion | null => {
22
+ const match = /^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z.-]+)?$/.exec(release)
23
+ if (match === null) return null
24
+ return { core: [Number(match[1]), Number(match[2]), Number(match[3])], prerelease: match[4] === undefined ? [] : match[4].split('.') }
25
+ }
26
+
27
+ /** Semver's order of two prerelease identifiers: numerically when both are numeric, a numeric one first, else by ASCII. */
28
+ const compareIdentifiers = (a: string, b: string): number => {
29
+ const numericA = /^\d+$/.test(a)
30
+ const numericB = /^\d+$/.test(b)
31
+ if (numericA && numericB) return Number(a) - Number(b)
32
+ if (numericA !== numericB) return numericA ? -1 : 1
33
+ return a < b ? -1 : a > b ? 1 : 0
34
+ }
35
+
36
+ const compareReleases = (a: ReleaseVersion, b: ReleaseVersion): number => {
37
+ for (const [index, part] of a.core.entries()) {
38
+ const other = b.core[index] ?? 0
39
+ if (part !== other) return part - other
40
+ }
41
+ if (a.prerelease.length === 0 || b.prerelease.length === 0) return b.prerelease.length - a.prerelease.length
42
+ for (const [index, identifier] of a.prerelease.entries()) {
43
+ const other = b.prerelease[index]
44
+ if (other === undefined) return 1
45
+ const order = compareIdentifiers(identifier, other)
46
+ if (order !== 0) return order
47
+ }
48
+ return a.prerelease.length - b.prerelease.length
49
+ }
50
+
51
+ /**
52
+ * Whether framework release `release` is at or above the exact version `since` in semver's precedence, prerelease
53
+ * included; a release that is not a semver version never is (ADR-0062).
54
+ */
55
+ export const releaseFrom = (release: string, since: string): boolean => {
56
+ const floor = parseReleaseVersion(since)
57
+ if (floor === null) throw new Error(`releaseFrom: \`${since}\` is not a semver version`)
58
+ const version = parseReleaseVersion(release)
59
+ return version !== null && compareReleases(version, floor) >= 0
60
+ }
61
+
62
+ /**
63
+ * The release a gate reads for an approved access: the application's pin, never the reader's `checker`, which is this
64
+ * platform's patch of the pin's minor and so passes a `releaseFrom` gate a prerelease pin does not. An access approved before Control recorded the pin is read as the oldest release of its
65
+ * reader's minor (`<major>.<minor>.0-0`): every `releaseAtLeast` gate answers as for that minor, and every `releaseFrom`
66
+ * gate of a prerelease or a patch fails closed, as for an older application, until a deploy reads its pin.
67
+ */
68
+ export const applicationRelease = (access: { readonly checker: string; readonly framework?: string }): string => {
69
+ if (access.framework !== undefined) return access.framework
70
+ const minor = /^(\d+)\.(\d+)\./.exec(access.checker)
71
+ return minor === null ? access.checker : `${minor[1]}.${minor[2]}.0-0`
72
+ }
@@ -18,6 +18,11 @@ export const FABRIKA_TOKEN_KEYS = 'FABRIKA_TOKEN_KEYS'
18
18
  export const FABRIKA_APP_ORIGIN = 'FABRIKA_APP_ORIGIN'
19
19
  /** The digests of the environment's ops keys, which the object checks Control's key against (`parseOpsKeyDigests`, ADR-0069). */
20
20
  export const FABRIKA_OPS_KEY_DIGESTS = 'FABRIKA_OPS_KEY_DIGESTS'
21
+ /**
22
+ * The installation's own hosts, which a cron job's public egress refuses (ADR-0075): Control's, IAM's, Operations' and
23
+ * every application environment's domain, normalized and joined by `,`. Written only for a contract with such a job.
24
+ */
25
+ export const FABRIKA_EGRESS_REFUSED_HOSTS = 'FABRIKA_EGRESS_REFUSED_HOSTS'
21
26
  /** The name of the object that serves an environment's ordinary traffic on Cloudflare; `application` without it. */
22
27
  export const FABRIKA_APPLICATION_OBJECT = 'FABRIKA_APPLICATION_OBJECT'
23
28
  /** The object names an ops request may target, all in the environment's own namespace (`parseApplicationObjects`). */
@@ -45,7 +50,15 @@ export const FRAMEWORK_VARIABLE_NAMES = [
45
50
  'FABRIKA_APP_STORAGE_BUCKET',
46
51
  'FABRIKA_APP_STORAGE_ACCESS_KEY_ID',
47
52
  'FABRIKA_APP_STORAGE_SECRET_ACCESS_KEY',
53
+ 'FABRIKA_APP_STORAGE_REGION',
54
+ // `path` or `virtual`, and `static` or `container`: how a container cloud's storage is addressed and signed for.
55
+ 'FABRIKA_APP_STORAGE_ADDRESSING',
56
+ 'FABRIKA_APP_STORAGE_CREDENTIALS',
48
57
  'FABRIKA_STORAGE_PROVENANCE',
58
+ // Who schedules the jobs, and the deploy that keeps the schedule (ADR-0080). Not `FABRIKA_JOB_*`: that family is the
59
+ // jobs' keys, and a deploy removes a member of it that Control no longer hands it.
60
+ 'FABRIKA_JOBS_SCHEDULE',
61
+ 'FABRIKA_JOBS_SCHEDULE_GENERATION',
49
62
  FABRIKA_PROXY_SECRET,
50
63
  'FABRIKA_IAM_RPC_URL',
51
64
  'FABRIKA_IAM_RPC_KEY',
@@ -54,6 +67,7 @@ export const FRAMEWORK_VARIABLE_NAMES = [
54
67
  FABRIKA_TOKEN_KEYS,
55
68
  FABRIKA_APP_ORIGIN,
56
69
  FABRIKA_OPS_KEY_DIGESTS,
70
+ FABRIKA_EGRESS_REFUSED_HOSTS,
57
71
  FABRIKA_APPLICATION_OBJECT,
58
72
  FABRIKA_APPLICATION_OBJECTS,
59
73
  ] as const