@fabrika/auth-core 0.9.0-dev.4 → 0.9.0-dev.41

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/canonical-path.ts +18 -0
  3. package/src/client-address.ts +74 -0
  4. package/src/contract-canonical.ts +168 -2
  5. package/src/contract-encoding.ts +181 -0
  6. package/src/contract.ts +212 -12
  7. package/src/dev-environment.ts +6 -0
  8. package/src/egress.ts +97 -0
  9. package/src/endpoint-digest.ts +22 -2
  10. package/src/framework-release.ts +72 -0
  11. package/src/framework-variables.ts +23 -0
  12. package/src/iam-mail.ts +354 -0
  13. package/src/index.ts +10 -0
  14. package/src/locale.ts +13 -1
  15. package/src/managed-environment.ts +147 -0
  16. package/src/membership.ts +12 -4
  17. package/src/oauth.ts +11 -0
  18. package/src/ops.ts +1933 -0
  19. package/src/permissions.ts +42 -0
  20. package/src/public-egress.ts +168 -0
  21. package/src/requirement.ts +5 -2
  22. package/src/rpc.ts +8 -8
  23. package/src/scope-values.ts +123 -0
  24. package/src/sha256.ts +52 -14
  25. package/src/terminal.ts +105 -0
  26. package/src/token.ts +170 -19
  27. package/src/types.ts +68 -2
  28. package/src/wire.ts +7 -0
  29. package/types/src/canonical-path.d.ts +6 -0
  30. package/types/src/client-address.d.ts +7 -0
  31. package/types/src/contract-canonical.d.ts +11 -1
  32. package/types/src/contract-encoding.d.ts +18 -0
  33. package/types/src/contract.d.ts +197 -11
  34. package/types/src/dev-environment.d.ts +5 -0
  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 +25 -0
  38. package/types/src/framework-variables.d.ts +12 -1
  39. package/types/src/iam-mail.d.ts +92 -0
  40. package/types/src/index.d.ts +10 -0
  41. package/types/src/locale.d.ts +11 -1
  42. package/types/src/managed-environment.d.ts +32 -0
  43. package/types/src/membership.d.ts +8 -3
  44. package/types/src/oauth.d.ts +7 -0
  45. package/types/src/ops.d.ts +657 -0
  46. package/types/src/permissions.d.ts +12 -0
  47. package/types/src/public-egress.d.ts +31 -0
  48. package/types/src/requirement.d.ts +2 -2
  49. package/types/src/rpc.d.ts +5 -5
  50. package/types/src/scope-values.d.ts +61 -0
  51. package/types/src/sha256.d.ts +10 -0
  52. package/types/src/terminal.d.ts +72 -0
  53. package/types/src/token.d.ts +69 -12
  54. package/types/src/types.d.ts +47 -2
  55. package/types/src/wire.d.ts +6 -0
package/src/contract.ts CHANGED
@@ -3,6 +3,9 @@
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'
8
+ import type { TerminalArtifact } from './terminal'
6
9
 
7
10
  /**
8
11
  * The artifact format this release writes. A release that changes the artifact raises it, and Control upcasts every
@@ -23,10 +26,15 @@ export interface ContractArtifact extends EndpointTable {
23
26
  /** Action → description. Exact actions only; the artifact holds no wildcard. */
24
27
  readonly actions: Readonly<Record<string, string>>
25
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>>
26
34
  readonly mounts: Readonly<Record<string, MountArtifact>>
27
35
  readonly files: Readonly<Record<string, FileCollectionArtifact>>
28
36
  /**
29
- * 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
30
38
  * has no owner and no endpoint; the table that holds a file is its authority. Absent unless declared, so the digest stays.
31
39
  */
32
40
  readonly fileKinds?: Readonly<Record<string, FileKindArtifact>>
@@ -61,6 +69,11 @@ export interface ContractArtifact extends EndpointTable {
61
69
  readonly members?: { readonly manage: string; readonly list: string }
62
70
  /** `labels`: the application's directory shows labels to `members.list` holders. Absent unless declared, so digests stay. */
63
71
  readonly directory?: 'labels'
72
+ /**
73
+ * The page on the application's own origin that identifies a person at an enrolled terminal (ADR-0067): IAM sends a
74
+ * terminal's browser there, and only an application that declares it may assert a person. Absent unless declared.
75
+ */
76
+ readonly terminal?: TerminalArtifact
64
77
  /**
65
78
  * What each procedure of the staged kit admits and how long it runs, by endpoint id, with every default applied: the
66
79
  * rules the application applies itself, beside the row the proxy applies. Absent for a contract with no such
@@ -183,7 +196,8 @@ interface EndpointRowBase {
183
196
  readonly crossOrigin?: CrossOriginForm
184
197
  /**
185
198
  * `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.
199
+ * answer of it, a denial included, ADR-0022's file treatment. `inline-file`: the same, for a kind declared `inline:
200
+ * true`, whose XML documents are shown too. Absent otherwise, so every other row keeps its digest.
187
201
  */
188
202
  readonly response?: EndpointResponse
189
203
  /**
@@ -203,8 +217,8 @@ interface EndpointRowBase {
203
217
  /** What the proxy does with an anonymous request's `Authorization` on a row that names it: forward it to the application. */
204
218
  export type EndpointAuthorization = 'forward'
205
219
 
206
- /** The answer profile of a row that answers a stored file. */
207
- export type EndpointResponse = 'file'
220
+ /** The answer profile of a row that answers a stored file: `inline-file` also shows the XML documents a machine reads. */
221
+ export type EndpointResponse = 'file' | 'inline-file'
208
222
 
209
223
  /** A cacheable row's lifetime: `maxAgeSeconds`, or `immutable`, a year, for an input that names an immutable value. */
210
224
  export type EndpointCache = { readonly maxAgeSeconds: number } | 'immutable'
@@ -217,7 +231,7 @@ export const FILE_RESPONSE_KINDS: readonly EndpointKind[] = ['query', 'mutation'
217
231
 
218
232
  /** Whether every answer of a row gets the file treatment: a collection's download, or a procedure that answers a file. */
219
233
  export function answersFile(row: { readonly kind: string; readonly response?: EndpointResponse }): boolean {
220
- return row.kind === 'download' || row.response === 'file'
234
+ return row.kind === 'download' || row.response !== undefined
221
235
  }
222
236
 
223
237
  /** How an endpoint admits another origin: from the environment's list, or (a form or a public procedure) from any origin. */
@@ -251,7 +265,7 @@ export interface BodyAdmission {
251
265
  * `action` is that action in some scope, global included, and only globally under the `app` form. The access form is
252
266
  * what the framework then resolves.
253
267
  */
254
- export type EndpointRequirement = MemberRequirement | ActionRequirement | CapabilitiesRequirement
268
+ export type EndpointRequirement = MemberRequirement | ActionRequirement | AnyOfRequirement | CapabilitiesRequirement
255
269
 
256
270
  export interface MemberRequirement {
257
271
  readonly kind: 'member'
@@ -263,6 +277,24 @@ export interface ActionRequirement {
263
277
  readonly access: AccessForm
264
278
  }
265
279
 
280
+ /**
281
+ * Any one of several actions (`access: { anyOf, app: true }`), each held as a global grant, the `app` form's rule: two to
282
+ * `MAX_ANY_OF` distinct actions, sorted, so the order in the source does not change the digest.
283
+ */
284
+ export interface AnyOfRequirement {
285
+ readonly kind: 'anyOf'
286
+ readonly actions: readonly [string, string, ...string[]]
287
+ readonly access: { readonly form: 'app' }
288
+ }
289
+
290
+ /** The most actions an `anyOf` requirement lists. */
291
+ export const MAX_ANY_OF = 16
292
+
293
+ /** Whether `actions` is an `anyOf` list as a row carries it: two to `MAX_ANY_OF` actions, strictly ascending. */
294
+ export function isAnyOfList(actions: readonly string[]): boolean {
295
+ return actions.length >= 2 && actions.length <= MAX_ANY_OF && actions.every((action, index) => index === 0 || (actions[index - 1] ?? '') < action)
296
+ }
297
+
266
298
  /**
267
299
  * Several capabilities (`access: { capabilities }`), by the name the handler reads each under (`ctx.capabilities.<name>`):
268
300
  * the token must carry every action, and the access form of each narrows it as it narrows a single one. At least two.
@@ -337,6 +369,29 @@ export function isFileShape(shape: OutputShape): shape is FileShape {
337
369
  return shape.type === 'file'
338
370
  }
339
371
 
372
+ /** The kinds of the files a schema holds, anywhere in it, each once per place it appears. */
373
+ export function fileKindsIn(shape: SchemaShape): readonly string[] {
374
+ switch (shape.type) {
375
+ case 'file':
376
+ return [shape.kind]
377
+ case 'array':
378
+ return fileKindsIn(shape.items)
379
+ case 'tuple':
380
+ return [...shape.items.flatMap(fileKindsIn), ...(shape.rest === null ? [] : fileKindsIn(shape.rest))]
381
+ case 'record':
382
+ return fileKindsIn(shape.value)
383
+ case 'object':
384
+ return Object.values(shape.fields).flatMap(fileKindsIn)
385
+ case 'optional':
386
+ case 'nullable':
387
+ return fileKindsIn(shape.inner)
388
+ case 'union':
389
+ return shape.options.flatMap(fileKindsIn)
390
+ default:
391
+ return []
392
+ }
393
+ }
394
+
340
395
  /**
341
396
  * What a procedure answers: a JSON value of a schema, a file of rows (`attachment()` of `@fabrika/app/contract`), or a
342
397
  * redirect (`redirect()`).
@@ -443,6 +498,13 @@ export interface DimensionArtifact {
443
498
  readonly members: { readonly manage: string; readonly list: string } | null
444
499
  /** `labels`: the member directory shows labels to `members.list` holders. Absent unless declared, so digests stay. */
445
500
  readonly directory?: 'labels'
501
+ /** The values the console offers for a grant in this dimension (ADR-0085). Absent unless declared, so digests stay. */
502
+ readonly values?: readonly DimensionValue[]
503
+ /**
504
+ * The id of the query procedure IAM asks, as the administrator, for this dimension's values (ADR-0085 §4). Absent
505
+ * unless declared, so digests stay.
506
+ */
507
+ readonly valuesFrom?: string
446
508
  }
447
509
 
448
510
  export interface RoleArtifact {
@@ -454,6 +516,16 @@ export interface RoleArtifact {
454
516
  readonly member: { readonly scope: string; readonly assignableBy: readonly string[] } | null
455
517
  /** An external principal may hold this membership role (ADR-0051). Absent unless declared, so digests stay. */
456
518
  readonly external?: true
519
+ /**
520
+ * Relation → actions the holder of a global grant of this role holds at each node a relation row names them at.
521
+ * Absent unless declared, so digests stay.
522
+ */
523
+ readonly via?: Readonly<Record<string, readonly string[]>>
524
+ }
525
+
526
+ /** A relation of the vocabulary: the dimension whose nodes its rows name. */
527
+ export interface RelationArtifact {
528
+ readonly dimension: string
457
529
  }
458
530
 
459
531
  // ── Mounts and companions ───────────────────────────────────────────────────────────────────────
@@ -668,6 +740,11 @@ export interface FileKindArtifact {
668
740
  readonly maxBytes: number
669
741
  /** Present when every file of the kind waits `quarantined` for a clean malware verdict before it is served. */
670
742
  readonly scan?: true
743
+ /**
744
+ * Present when its files are shown rather than downloaded: every type is an inert image or an XML document a machine
745
+ * reads, and a row answering it is `response: 'inline-file'`. Absent otherwise, so every other kind keeps its digest.
746
+ */
747
+ readonly inline?: true
671
748
  }
672
749
 
673
750
  export interface JobArtifact {
@@ -748,10 +825,12 @@ export interface DeclaredReach {
748
825
  */
749
826
  readonly signs?: readonly string[]
750
827
  /**
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.
828
+ * The HTTPS origins this site's code calls (`fetch`), sorted, each an exact origin or a one-label pattern
829
+ * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Or `'public'` (a cron job only): every public
830
+ * host over HTTPS or HTTP, never the installation or a private network (ADR-0075). Absent unless declared, so the
831
+ * digest stays.
753
832
  */
754
- readonly egress?: readonly string[]
833
+ readonly egress?: DeclaredEgress
755
834
  /**
756
835
  * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
757
836
  * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
@@ -796,6 +875,12 @@ export interface CspSource {
796
875
  */
797
876
  export type TableActionArtifact = string | readonly string[]
798
877
 
878
+ /**
879
+ * An application table's `actions.read` that every `app` endpoint, job and webhook reads with, whatever its action; never
880
+ * a public procedure, a scoped site, a link or an export. No vocabulary may declare an action of this name.
881
+ */
882
+ export const READ_ANY = 'any'
883
+
799
884
  export interface TablePolicyArtifact {
800
885
  readonly scope: TableScope
801
886
  /** An inbox's read action is `read`; it has no write action, because only its form appends. */
@@ -826,12 +911,127 @@ export interface TablePolicyArtifact {
826
911
  * actions are the file's authority. Absent unless declared, so the digest stays.
827
912
  */
828
913
  readonly files?: Readonly<Record<string, string>>
914
+ /**
915
+ * A view (ADR-0072): read like its scope's tables, written by nothing, its containment stated by its SQL alone.
916
+ * Absent for a table, so the digest stays.
917
+ */
918
+ readonly view?: true
919
+ /** Relation → how a row of this table confers it. Absent unless declared, so the digest stays. */
920
+ readonly confers?: Readonly<Record<string, ConfersArtifact>>
921
+ /** Action → the condition a row must meet for it, narrowing what any grant of it reaches. Absent unless declared. */
922
+ readonly when?: Readonly<Record<string, ConditionArtifact>>
923
+ /**
924
+ * Relation → action → the condition a row the relation reaches must meet for it; it narrows that relation's reach only.
925
+ * Absent unless declared, so the digest stays. A reader that ignores it reaches more: Control refuses to publish it to
926
+ * an application pinned below the release that enforces it.
927
+ */
928
+ readonly relationWhen?: Readonly<Record<string, Readonly<Record<string, ConditionArtifact>>>>
929
+ /**
930
+ * Relation of the table's own dimension → the ancestor its rows reveal. Absent unless declared, so the digest stays.
931
+ * A reader that ignores it reaches less, never more.
932
+ */
933
+ readonly reveals?: Readonly<Record<string, RevealsArtifact>>
934
+ /**
935
+ * Dimension outside the chain → the column a `Within`'s read reaches a row through. Absent unless declared, so the
936
+ * digest stays. A reader that ignores it reaches less, never more.
937
+ */
938
+ readonly readThrough?: Readonly<Record<string, string>>
939
+ /**
940
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
941
+ * path's column must hold each at the node it names. Absent unless declared, so the digest stays. A reader that
942
+ * ignores it reaches less, never more.
943
+ */
944
+ readonly writeThrough?: Readonly<Record<string, readonly string[]>>
945
+ /**
946
+ * The table's own dimension → the ancestor its rows reveal to a grant at their node, for a `Within`'s reads. Absent
947
+ * unless declared, so the digest stays. A reader that ignores it reaches less, never more.
948
+ */
949
+ readonly memberReveals?: Readonly<Record<string, MemberRevealsArtifact>>
950
+ /**
951
+ * Relation → the access view that lists the rows it reaches (ADR-0076). Absent unless declared, so the digest stays.
952
+ * A reader that ignores it reaches less, never more.
953
+ */
954
+ readonly access?: Readonly<Record<string, AccessArtifact>>
955
+ }
956
+
957
+ /** An access view: its `row` column names the table's key; `principal` is compared to the caller, `member` to its nodes. */
958
+ export interface AccessArtifact {
959
+ readonly view: string
960
+ readonly row: string
961
+ readonly principal: string | null
962
+ readonly member: string | null
963
+ }
964
+
965
+ /**
966
+ * 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
967
+ * key's dimension names, while `when` admits the row.
968
+ */
969
+ export interface MemberRevealsArtifact {
970
+ readonly to: string
971
+ readonly actions: readonly string[]
972
+ readonly when?: ConditionArtifact
973
+ /**
974
+ * Through a path, on a table with an insert: the writer picks the node, and `self` lets it pick one where it holds a
975
+ * grant the reveal counts. Absent otherwise; only a reader that refuses a path's key reads it.
976
+ */
977
+ readonly assign?: { readonly self: boolean }
978
+ }
979
+
980
+ /** A row the relation reaches reveals its node in `to` for `actions`, while `when` admits the row. */
981
+ export interface RevealsArtifact {
982
+ readonly to: string
983
+ readonly actions: readonly string[]
984
+ readonly when?: ConditionArtifact
985
+ /** On a reveal matched through `readThrough`: an insert delegates, and `self` lets it name a node its writer holds. */
986
+ readonly assign?: { readonly self: boolean }
987
+ }
988
+
989
+ /** A row names `principal` at the node in `node`, until `expires`, while `when` admits it; `assign` bounds its writer. */
990
+ export interface ConfersArtifact {
991
+ /** The column that holds the principal, or `<column>.<principal column>` through one foreign key of the table. */
992
+ readonly principal: string
993
+ readonly node: string
994
+ readonly expires: string | null
995
+ readonly when?: ConditionArtifact
996
+ readonly assign: { readonly maxDays: number | null; readonly self: boolean } | null
997
+ }
998
+
999
+ /**
1000
+ * A structured row condition: connectives, `{ '<column or fk_column.column>': test }` with every test holding, or
1001
+ * `some` / `none` of the rows of one table whose foreign key names the row, also at the end of a path
1002
+ * (`{ '<fk_column>': { some: … } }`). Each form is absent from a condition that does not use it, so its digest stays.
1003
+ */
1004
+ export type ConditionArtifact =
1005
+ | { readonly allOf: readonly ConditionArtifact[] }
1006
+ | { readonly anyOf: readonly ConditionArtifact[] }
1007
+ | { readonly not: ConditionArtifact }
1008
+ | RowsTestArtifact
1009
+ | { readonly [path: string]: ColumnTestArtifact | RowsTestArtifact }
1010
+
1011
+ /** `some` or `none` of the rows of one table whose foreign key names the row. */
1012
+ export type RowsTestArtifact =
1013
+ | { readonly some: Readonly<Record<string, ConditionArtifact>> }
1014
+ | { readonly none: Readonly<Record<string, ConditionArtifact>> }
1015
+
1016
+ export type ConditionLiteralArtifact = string | number | boolean
1017
+
1018
+ /** One operator of a column test; `{ now: true }` compares a timestamp with the statement's clock. */
1019
+ export interface ColumnTestArtifact {
1020
+ readonly eq?: ConditionLiteralArtifact
1021
+ readonly notEq?: ConditionLiteralArtifact
1022
+ readonly in?: readonly ConditionLiteralArtifact[]
1023
+ readonly notIn?: readonly ConditionLiteralArtifact[]
1024
+ readonly isNull?: boolean
1025
+ readonly lt?: ConditionLiteralArtifact | { readonly now: true }
1026
+ readonly lte?: ConditionLiteralArtifact | { readonly now: true }
1027
+ readonly gt?: ConditionLiteralArtifact | { readonly now: true }
1028
+ readonly gte?: ConditionLiteralArtifact | { readonly now: true }
829
1029
  }
830
1030
 
831
- /** A column's own read action, its own write action, or both; an absent one is left out. */
1031
+ /** 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. */
832
1032
  export interface ColumnPolicyArtifact {
833
- readonly read?: string
834
- readonly write?: string
1033
+ readonly read?: TableActionArtifact
1034
+ readonly write?: TableActionArtifact
835
1035
  }
836
1036
 
837
1037
  export type TableScope =
@@ -13,6 +13,12 @@ export const DEV_LAUNCHER_MODULE = '@fabrika/app/dev'
13
13
  /** Where the launcher records what it holds, so a restart of the same container resumes it. A new container has none. */
14
14
  export const DEV_LAUNCHER_STATE_FILE = 'fabrika/dev-state.json'
15
15
 
16
+ /**
17
+ * The launcher writes it once its boot reconcile reported, served or failed. A dev container's readiness check passes on
18
+ * it too, so a boot that failed still activates, and `reset_dev` can reach the launcher that reports the failure.
19
+ */
20
+ export const DEV_LAUNCHER_BOOTED_FILE = 'fabrika/dev-booted'
21
+
16
22
  /** One command of the build's check chain, run by the shell in the application root. */
17
23
  export interface DevLauncherCheck {
18
24
  readonly name: string
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
@@ -0,0 +1,72 @@
1
+ /** A framework release as npm publishes it; the only form one may take before it reaches a generated build command. */
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
+ }
@@ -16,6 +16,17 @@ export const FABRIKA_SOURCE_MAP_UPLOAD_KEY = 'FABRIKA_SOURCE_MAP_UPLOAD_KEY'
16
16
  export const FABRIKA_TOKEN_KEYS = 'FABRIKA_TOKEN_KEYS'
17
17
  /** The environment's canonical origin (`https://crm.example`), which `ctx.url` builds absolute links on. */
18
18
  export const FABRIKA_APP_ORIGIN = 'FABRIKA_APP_ORIGIN'
19
+ /** The digests of the environment's ops keys, which the object checks Control's key against (`parseOpsKeyDigests`, ADR-0069). */
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'
26
+ /** The name of the object that serves an environment's ordinary traffic on Cloudflare; `application` without it. */
27
+ export const FABRIKA_APPLICATION_OBJECT = 'FABRIKA_APPLICATION_OBJECT'
28
+ /** The object names an ops request may target, all in the environment's own namespace (`parseApplicationObjects`). */
29
+ export const FABRIKA_APPLICATION_OBJECTS = 'FABRIKA_APPLICATION_OBJECTS'
19
30
 
20
31
  /**
21
32
  * The environment names only the platform writes into an application
@@ -39,7 +50,15 @@ export const FRAMEWORK_VARIABLE_NAMES = [
39
50
  'FABRIKA_APP_STORAGE_BUCKET',
40
51
  'FABRIKA_APP_STORAGE_ACCESS_KEY_ID',
41
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',
42
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',
43
62
  FABRIKA_PROXY_SECRET,
44
63
  'FABRIKA_IAM_RPC_URL',
45
64
  'FABRIKA_IAM_RPC_KEY',
@@ -47,6 +66,10 @@ export const FRAMEWORK_VARIABLE_NAMES = [
47
66
  FABRIKA_SOURCE_MAP_UPLOAD_KEY,
48
67
  FABRIKA_TOKEN_KEYS,
49
68
  FABRIKA_APP_ORIGIN,
69
+ FABRIKA_OPS_KEY_DIGESTS,
70
+ FABRIKA_EGRESS_REFUSED_HOSTS,
71
+ FABRIKA_APPLICATION_OBJECT,
72
+ FABRIKA_APPLICATION_OBJECTS,
50
73
  ] as const
51
74
 
52
75
  export type FrameworkVariableName = (typeof FRAMEWORK_VARIABLE_NAMES)[number]