@fabrika/auth-core 0.9.0-dev.13 → 0.9.0-dev.15

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.9.0-dev.13",
3
+ "version": "0.9.0-dev.15",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -73,7 +73,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
73
73
  ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
74
74
  ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
75
75
  ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
76
- ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
76
+ ...(reach.egress === undefined ? {} : { egress: typeof reach.egress === 'string' ? reach.egress : sorted(reach.egress) }),
77
77
  })),
78
78
  }),
79
79
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
@@ -161,6 +161,9 @@ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
161
161
  insert: sorted(table.insert),
162
162
  update: sorted(table.update),
163
163
  ...(table.when === undefined ? {} : { when: mapValues(table.when, canonicalCondition) }),
164
+ ...(table.relationWhen === undefined
165
+ ? {}
166
+ : { relationWhen: mapValues(table.relationWhen, (conditions) => mapValues(conditions, canonicalCondition)) }),
164
167
  ...(table.confers === undefined ? {} : { confers: mapValues(table.confers, canonicalConfers) }),
165
168
  ...(table.reveals === undefined ? {} : { reveals: mapValues(table.reveals, canonicalReveals) }),
166
169
  ...(table.memberReveals === undefined ? {} : { memberReveals: mapValues(table.memberReveals, canonicalMemberReveals) }),
@@ -343,3 +346,41 @@ function sortKeys(_key: string, value: unknown): unknown {
343
346
  }
344
347
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
345
348
  }
349
+
350
+ /**
351
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
352
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
353
+ */
354
+ export function writeCanonicalJson(value: unknown, write: (piece: string) => void): void {
355
+ if (Array.isArray(value)) {
356
+ write('[')
357
+ for (const [index, item] of value.entries()) {
358
+ if (index > 0) write(',')
359
+ if (isOmitted(item)) write('null')
360
+ else writeCanonicalJson(item, write)
361
+ }
362
+ write(']')
363
+ return
364
+ }
365
+ if (typeof value === 'object' && value !== null) {
366
+ write('{')
367
+ let first = true
368
+ const rebuilt = Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
369
+ for (const [key, item] of Object.entries(rebuilt)) {
370
+ if (isOmitted(item)) continue
371
+ if (!first) write(',')
372
+ first = false
373
+ write(JSON.stringify(key))
374
+ write(':')
375
+ writeCanonicalJson(item, write)
376
+ }
377
+ write('}')
378
+ return
379
+ }
380
+ write(JSON.stringify(value) ?? 'null')
381
+ }
382
+
383
+ /** What `JSON.stringify` leaves out of an object and writes as `null` in an array. */
384
+ function isOmitted(value: unknown): boolean {
385
+ return value === undefined || typeof value === 'function' || typeof value === 'symbol'
386
+ }
@@ -0,0 +1,181 @@
1
+ // The shared encoding of a contract artifact: how a build bundles it and how Control stores a large one. Each composite
2
+ // schema shape that occurs more than once is written once, in `shapes`, and referenced by its index; a shape's null
3
+ // constraints are left out. Decoding (`@fabrika/app/contract`) restores the canonical artifact exactly, so its digest
4
+ // is the one `contractDigest` takes: the encoding is a storage form, never what a digest is taken over.
5
+
6
+ import type { ContractArtifact, OutputShape, SchemaShape } from './contract'
7
+ import { canonicalizeArtifact, canonicalJson } from './contract-canonical'
8
+
9
+ /** The `encoding` of an encoded artifact; a plain artifact has no such key. */
10
+ export const SHARED_SHAPES_ENCODING = 'shared-shapes'
11
+
12
+ /** In place of a shape: `shapes[index]` of the encoded artifact, which is always written before it is referenced. */
13
+ export interface SharedShapeReference {
14
+ readonly type: 'shared'
15
+ readonly index: number
16
+ }
17
+
18
+ /** An artifact in the shared encoding, as JSON. */
19
+ export interface EncodedArtifact {
20
+ readonly encoding: typeof SHARED_SHAPES_ENCODING
21
+ readonly shapes: readonly object[]
22
+ readonly artifact: object
23
+ }
24
+
25
+ /** The canonical artifact in the shared encoding. */
26
+ export function encodeArtifact(artifact: ContractArtifact): EncodedArtifact {
27
+ const canonical = canonicalizeArtifact(artifact)
28
+ const interner = new ShapeInterner()
29
+ mapShapes(canonical, (shape) => {
30
+ interner.node(shape).uses++
31
+ return null
32
+ })
33
+ for (const node of interner.nodes) {
34
+ for (const child of node.children) child.uses++
35
+ }
36
+ const writer = new SharedWriter(interner)
37
+ const encoded = mapShapes(canonical, (shape) => writer.write(shape))
38
+ return { encoding: SHARED_SHAPES_ENCODING, shapes: writer.shapes, artifact: encoded }
39
+ }
40
+
41
+ /** The encoded artifact as text, keys sorted: what a build bundles. */
42
+ export function encodedArtifactJson(artifact: ContractArtifact): string {
43
+ return canonicalJson(encodeArtifact(artifact))
44
+ }
45
+
46
+ /** One distinct shape: equal shapes, wherever they occur, are one node. */
47
+ interface ShapeNode {
48
+ readonly id: number
49
+ readonly shape: SchemaShape
50
+ readonly children: readonly ShapeNode[]
51
+ uses: number
52
+ }
53
+
54
+ class ShapeInterner {
55
+ readonly nodes: ShapeNode[] = []
56
+ readonly #byForm = new Map<string, ShapeNode>()
57
+ readonly #byObject = new WeakMap<SchemaShape, ShapeNode>()
58
+
59
+ node(shape: SchemaShape): ShapeNode {
60
+ const known = this.#byObject.get(shape)
61
+ if (known !== undefined) return known
62
+ const children: ShapeNode[] = []
63
+ // A node's identity is its own fields and its children's identities, so equal subtrees are found bottom up.
64
+ const form = canonicalJson(compactShape(shape, (child) => {
65
+ const node = this.node(child)
66
+ children.push(node)
67
+ return node.id
68
+ }))
69
+ let node = this.#byForm.get(form)
70
+ if (node === undefined) {
71
+ node = { id: this.nodes.length, shape, children, uses: 0 }
72
+ this.nodes.push(node)
73
+ this.#byForm.set(form, node)
74
+ }
75
+ this.#byObject.set(shape, node)
76
+ return node
77
+ }
78
+ }
79
+
80
+ class SharedWriter {
81
+ readonly shapes: object[] = []
82
+ readonly #indexes = new Map<ShapeNode, number>()
83
+ readonly #interner: ShapeInterner
84
+
85
+ constructor(interner: ShapeInterner) {
86
+ this.#interner = interner
87
+ }
88
+
89
+ write(shape: SchemaShape): object {
90
+ const node = this.#interner.node(shape)
91
+ if (node.children.length === 0 || node.uses < 2) {
92
+ return compactShape(shape, (child) => this.write(child))
93
+ }
94
+ let index = this.#indexes.get(node)
95
+ if (index === undefined) {
96
+ // Children first, so every reference points to a shape written before it.
97
+ const written = compactShape(shape, (child) => this.write(child))
98
+ index = this.shapes.length
99
+ this.shapes.push(written)
100
+ this.#indexes.set(node, index)
101
+ }
102
+ const reference: SharedShapeReference = { type: 'shared', index }
103
+ return reference
104
+ }
105
+ }
106
+
107
+ /** The shape without its null constraints, each child replaced by `child`'s answer; an object's fields in key order. */
108
+ function compactShape(shape: SchemaShape, child: (shape: SchemaShape) => unknown): object {
109
+ switch (shape.type) {
110
+ case 'string':
111
+ return {
112
+ type: 'string',
113
+ ...present('format', shape.format),
114
+ ...present('minLength', shape.minLength),
115
+ ...present('maxLength', shape.maxLength),
116
+ ...present('pattern', shape.pattern),
117
+ ...present('startsWith', shape.startsWith),
118
+ ...present('endsWith', shape.endsWith),
119
+ ...present('includes', shape.includes),
120
+ }
121
+ case 'number':
122
+ return {
123
+ type: 'number',
124
+ int: shape.int,
125
+ ...present('min', shape.min),
126
+ exclusiveMin: shape.exclusiveMin,
127
+ ...present('max', shape.max),
128
+ exclusiveMax: shape.exclusiveMax,
129
+ ...present('multipleOf', shape.multipleOf),
130
+ }
131
+ case 'array':
132
+ return { type: 'array', items: child(shape.items), ...present('minItems', shape.minItems), ...present('maxItems', shape.maxItems) }
133
+ case 'tuple':
134
+ return { type: 'tuple', items: shape.items.map(child), ...(shape.rest === null ? {} : { rest: child(shape.rest) }) }
135
+ case 'record':
136
+ return { type: 'record', key: child(shape.key), value: child(shape.value) }
137
+ case 'object':
138
+ return { type: 'object', fields: Object.fromEntries(sortedEntries(shape.fields).map(([name, field]) => [name, child(field)])) }
139
+ case 'optional':
140
+ case 'nullable':
141
+ return { type: shape.type, inner: child(shape.inner) }
142
+ case 'union':
143
+ return { type: 'union', options: shape.options.map(child) }
144
+ default:
145
+ return shape
146
+ }
147
+ }
148
+
149
+ function present(key: string, value: string | number | null): object {
150
+ return value === null ? {} : { [key]: value }
151
+ }
152
+
153
+ /** The artifact with each schema shape replaced by `map`'s answer; records are visited in key order. */
154
+ function mapShapes(artifact: ContractArtifact, map: (shape: SchemaShape) => unknown): object {
155
+ const output = (shape: OutputShape): unknown => {
156
+ if (shape.type === 'redirect') return shape
157
+ if (shape.type === 'attachment') return { ...shape, columns: shape.columns.map((column) => ({ name: column.name, shape: map(column.shape) })) }
158
+ return map(shape)
159
+ }
160
+ const endpoints = artifact.endpoints.map((row) => ({
161
+ ...row,
162
+ input: row.input === null ? null : map(row.input),
163
+ output: row.output === null ? null : output(row.output),
164
+ }))
165
+ const procedures = artifact.procedures === undefined ? undefined : Object.fromEntries(
166
+ sortedEntries(artifact.procedures).map(([id, rules]) => [id, rules.query === undefined ? rules : { ...rules, query: map(rules.query) }]),
167
+ )
168
+ const tokens = artifact.tokens === undefined ? undefined : Object.fromEntries(
169
+ sortedEntries(artifact.tokens).map(([purpose, token]) => [purpose, { ...token, claims: map(token.claims) }]),
170
+ )
171
+ return {
172
+ ...artifact,
173
+ endpoints,
174
+ ...(procedures === undefined ? {} : { procedures }),
175
+ ...(tokens === undefined ? {} : { tokens }),
176
+ }
177
+ }
178
+
179
+ function sortedEntries<T>(record: Readonly<Record<string, T>>): [string, T][] {
180
+ return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
181
+ }
package/src/contract.ts CHANGED
@@ -3,6 +3,7 @@
3
3
 
4
4
  import type { Locale } from './locale'
5
5
  import type { MailTemplates } from './mail'
6
+ import type { DeclaredEgress } from './public-egress'
6
7
  import type { TerminalArtifact } from './terminal'
7
8
 
8
9
  /**
@@ -799,9 +800,11 @@ export interface DeclaredReach {
799
800
  readonly signs?: readonly string[]
800
801
  /**
801
802
  * The HTTPS origins this site's code calls (`fetch`), sorted, each an exact origin or a one-label pattern
802
- * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Absent unless declared, so the digest stays.
803
+ * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Or `'public'` (a cron job only): every public
804
+ * host over HTTPS or HTTP, never the installation or a private network (ADR-0075). Absent unless declared, so the
805
+ * digest stays.
803
806
  */
804
- readonly egress?: readonly string[]
807
+ readonly egress?: DeclaredEgress
805
808
  /**
806
809
  * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
807
810
  * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
@@ -885,6 +888,12 @@ export interface TablePolicyArtifact {
885
888
  readonly confers?: Readonly<Record<string, ConfersArtifact>>
886
889
  /** Action → the condition a row must meet for it, narrowing what any grant of it reaches. Absent unless declared. */
887
890
  readonly when?: Readonly<Record<string, ConditionArtifact>>
891
+ /**
892
+ * Relation → action → the condition a row the relation reaches must meet for it; it narrows that relation's reach only.
893
+ * Absent unless declared, so the digest stays. A reader that ignores it reaches more: Control refuses to publish it to
894
+ * an application pinned below the release that enforces it.
895
+ */
896
+ readonly relationWhen?: Readonly<Record<string, Readonly<Record<string, ConditionArtifact>>>>
888
897
  /**
889
898
  * Relation of the table's own dimension → the ancestor its rows reveal. Absent unless declared, so the digest stays.
890
899
  * A reader that ignores it reaches less, never more.
@@ -895,18 +904,45 @@ export interface TablePolicyArtifact {
895
904
  * digest stays. A reader that ignores it reaches less, never more.
896
905
  */
897
906
  readonly readThrough?: Readonly<Record<string, string>>
907
+ /**
908
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
909
+ * path's column must hold each at the node it names. Absent unless declared, so the digest stays. A reader that
910
+ * ignores it reaches less, never more.
911
+ */
912
+ readonly writeThrough?: Readonly<Record<string, readonly string[]>>
898
913
  /**
899
914
  * The table's own dimension → the ancestor its rows reveal to a grant at their node, for a `Within`'s reads. Absent
900
915
  * unless declared, so the digest stays. A reader that ignores it reaches less, never more.
901
916
  */
902
917
  readonly memberReveals?: Readonly<Record<string, MemberRevealsArtifact>>
918
+ /**
919
+ * Relation → the access view that lists the rows it reaches (ADR-0076). Absent unless declared, so the digest stays.
920
+ * A reader that ignores it reaches less, never more.
921
+ */
922
+ readonly access?: Readonly<Record<string, AccessArtifact>>
903
923
  }
904
924
 
905
- /** A row reveals its node in `to` for `actions` to a grant of them at the row's own node, while `when` admits the row. */
925
+ /** An access view: its `row` column names the table's key; `principal` is compared to the caller, `member` to its nodes. */
926
+ export interface AccessArtifact {
927
+ readonly view: string
928
+ readonly row: string
929
+ readonly principal: string | null
930
+ readonly member: string | null
931
+ }
932
+
933
+ /**
934
+ * 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
935
+ * key's dimension names, while `when` admits the row.
936
+ */
906
937
  export interface MemberRevealsArtifact {
907
938
  readonly to: string
908
939
  readonly actions: readonly string[]
909
940
  readonly when?: ConditionArtifact
941
+ /**
942
+ * Through a path, on a table with an insert: the writer picks the node, and `self` lets it pick one where it holds a
943
+ * grant the reveal counts. Absent otherwise; only a reader that refuses a path's key reads it.
944
+ */
945
+ readonly assign?: { readonly self: boolean }
910
946
  }
911
947
 
912
948
  /** A row the relation reaches reveals its node in `to` for `actions`, while `when` admits the row. */
@@ -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
@@ -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`). */
@@ -54,6 +59,7 @@ export const FRAMEWORK_VARIABLE_NAMES = [
54
59
  FABRIKA_TOKEN_KEYS,
55
60
  FABRIKA_APP_ORIGIN,
56
61
  FABRIKA_OPS_KEY_DIGESTS,
62
+ FABRIKA_EGRESS_REFUSED_HOSTS,
57
63
  FABRIKA_APPLICATION_OBJECT,
58
64
  FABRIKA_APPLICATION_OBJECTS,
59
65
  ] as const
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ export * from './canonical-path'
4
4
  export * from './client-address'
5
5
  export * from './contract'
6
6
  export * from './contract-canonical'
7
+ export * from './contract-encoding'
7
8
  export * from './dev-environment'
8
9
  export * from './device'
9
10
  export * from './egress'
@@ -21,6 +22,7 @@ export * from './membership'
21
22
  export * from './oauth'
22
23
  export * from './ops'
23
24
  export * from './permissions'
25
+ export * from './public-egress'
24
26
  export * from './requirement'
25
27
  export * from './rpc'
26
28
  export { sha256Hex } from './sha256'
@@ -3,6 +3,7 @@ import { FABRIKA_CONTRACT_DIGEST } from './endpoint-digest'
3
3
  import { FABRIKA_IAM_ISSUER } from './environment'
4
4
  import {
5
5
  FABRIKA_APP_ORIGIN,
6
+ FABRIKA_EGRESS_REFUSED_HOSTS,
6
7
  FABRIKA_OPS_KEY_DIGESTS,
7
8
  FABRIKA_TOKEN_KEYS,
8
9
  FRAMEWORK_VARIABLE_PREFIXES,
@@ -35,6 +36,7 @@ export const MANAGED_VARIABLE_NAMES = [
35
36
  FABRIKA_APP_ORIGIN,
36
37
  FABRIKA_TOKEN_KEYS,
37
38
  FABRIKA_OPS_KEY_DIGESTS,
39
+ FABRIKA_EGRESS_REFUSED_HOSTS,
38
40
  ] as const satisfies readonly FrameworkVariableName[]
39
41
 
40
42
  export type ManagedVariableName = (typeof MANAGED_VARIABLE_NAMES)[number]
@@ -53,6 +55,8 @@ const PUBLIC_VARIABLES: ReadonlySet<string> = new Set<FrameworkVariableName>([
53
55
  FABRIKA_APP_ORIGIN,
54
56
  // SHA-256 of 256-bit random keys: a digest neither is a key nor lets anyone forge one.
55
57
  FABRIKA_OPS_KEY_DIGESTS,
58
+ // Host names anyone can look up in DNS.
59
+ FABRIKA_EGRESS_REFUSED_HOSTS,
56
60
  ])
57
61
 
58
62
  const PLATFORM_URL_VARIABLES: ReadonlySet<string> = new Set(PLATFORM_RECEIVERS.map((receiver) => platformTransportVariables(receiver).url))
@@ -0,0 +1,168 @@
1
+ // `egress: 'public'`: a cron job that calls the websites its operators name (a crawler, an auditor, a link checker)
2
+ // reaches any public host over HTTPS or HTTP, and never the installation or a private network (ADR-0075). These are the
3
+ // rules a URL alone decides, which the runtime guard and the checker share. The guard adds the installation's own hosts
4
+ // and, where the runtime exposes name resolution, the addresses a name resolves to.
5
+
6
+ /** The declared form of public egress: every public host, over HTTPS or HTTP, on its default port. */
7
+ export const PUBLIC_EGRESS = 'public'
8
+
9
+ export type PublicEgress = typeof PUBLIC_EGRESS
10
+
11
+ /** What a site declares in `egress`: its exact HTTPS origins, sorted, or every public host (a cron job only). */
12
+ export type DeclaredEgress = readonly string[] | PublicEgress
13
+
14
+ /**
15
+ * The name suffixes public egress refuses, each with every name under it: local and special-use names (RFC 6761,
16
+ * RFC 6762, RFC 8375, RFC 9476), the names private networks conventionally use (`.internal` holds Google's metadata
17
+ * host and Control's own `operations.internal`), and the platform subdomains an installation is served on beside its
18
+ * own domains: Cloudflare's `workers.dev`, where its Workers have their default routes, and Zerops' `zerops.app`, where
19
+ * its proxies, Control and IAM have their subdomains (a namespace proxy's `proxy-…-8080.<region>.zerops.app`), with the
20
+ * `zerops` suffix of a Zerops project's private network. Control knows no list of those subdomains, so every one is
21
+ * refused, another installation's too.
22
+ */
23
+ export const PUBLIC_EGRESS_REFUSED_SUFFIXES = [
24
+ 'localhost',
25
+ 'local',
26
+ 'internal',
27
+ 'intranet',
28
+ 'lan',
29
+ 'home',
30
+ 'corp',
31
+ 'private',
32
+ 'arpa',
33
+ 'test',
34
+ 'invalid',
35
+ 'example',
36
+ 'onion',
37
+ 'alt',
38
+ 'zerops',
39
+ 'zerops.app',
40
+ 'workers.dev',
41
+ ] as const
42
+
43
+ /** A host name without its trailing dots, lowercased: the form every comparison here uses. */
44
+ export function normalizedHost(hostname: string): string {
45
+ return hostname.toLowerCase().replace(/\.+$/, '')
46
+ }
47
+
48
+ const IPV4 = /^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/
49
+
50
+ /**
51
+ * Why public egress refuses `url`, or `null` when the URL alone admits it: a scheme other than `https:` and `http:`, a
52
+ * port other than the scheme's default, credentials in the URL, an IP literal, a name of one label, a name under a
53
+ * refused suffix, or one of `refusedHosts` (normalized names). A host it admits may still resolve to a private address,
54
+ * which only a runtime that resolves names refuses.
55
+ */
56
+ export function publicEgressRefusal(url: URL, refusedHosts: ReadonlySet<string> = new Set()): string | null {
57
+ if (url.protocol !== 'https:' && url.protocol !== 'http:') return `${url.protocol} is not https: or http:`
58
+ if (url.port !== '') return `port ${url.port} is not the default port of ${url.protocol}`
59
+ if (url.username !== '' || url.password !== '') return 'the URL carries credentials, which a public request never sends'
60
+ const host = normalizedHost(url.hostname)
61
+ if (host.startsWith('[') || IPV4.test(host)) return `${host} is an IP address, not a public host name`
62
+ if (!host.includes('.')) return `${host} is a name of one label, as an internal service or a local machine has`
63
+ if (host.split('.').some((label) => label === '')) return `${host} has an empty label`
64
+ const suffix = PUBLIC_EGRESS_REFUSED_SUFFIXES.find((refused) => host === refused || host.endsWith(`.${refused}`))
65
+ if (suffix !== undefined) return `${host} is under .${suffix}, which names no public website`
66
+ if (refusedHosts.has(host)) return `${host} is a host of this installation`
67
+ return null
68
+ }
69
+
70
+ /**
71
+ * Whether `address` (an IPv4 or IPv6 address, as a resolver answers it) is a public unicast address: not private,
72
+ * loopback, link-local (which holds the cloud metadata address 169.254.169.254), shared, multicast, reserved,
73
+ * documentation, or an IPv6 form that embeds or tunnels an IPv4 address it cannot vouch for. A text that is no address
74
+ * is not public.
75
+ */
76
+ export function isPublicAddress(address: string): boolean {
77
+ const v4 = ipv4Octets(address)
78
+ if (v4 !== null) return isPublicIpv4(v4)
79
+ const words = ipv6Words(address)
80
+ if (words === null) return false
81
+ const [w0 = 0, w1 = 0, w2 = 0, w3 = 0, w4 = 0, w5 = 0, w6 = 0, w7 = 0] = words
82
+ // ::ffff:a.b.c.d, an IPv4 address in IPv6 form, is that IPv4 address.
83
+ if (w0 === 0 && w1 === 0 && w2 === 0 && w3 === 0 && w4 === 0 && w5 === 0xffff) {
84
+ return isPublicIpv4([w6 >> 8, w6 & 0xff, w7 >> 8, w7 & 0xff])
85
+ }
86
+ // Only global unicast (2000::/3) is public; every other block is local, multicast, reserved or a translation prefix.
87
+ if ((w0 & 0xe000) !== 0x2000) return false
88
+ // 2001::/32 Teredo, 2001:10::/28 ORCHID, 2001:20::/28 ORCHIDv2, 2001:db8::/32 documentation, 2002::/16 6to4.
89
+ if (w0 === 0x2001 && (w1 === 0 || (w1 & 0xfff0) === 0x10 || (w1 & 0xfff0) === 0x20 || w1 === 0x0db8)) return false
90
+ if (w0 === 0x2002) return false
91
+ // 3fff::/20 documentation (RFC 9637).
92
+ if (w0 === 0x3fff && (w1 & 0xf000) === 0) return false
93
+ return true
94
+ }
95
+
96
+ /** The non-public IPv4 blocks, each as its network (a 32-bit number) and its prefix length. */
97
+ const IPV4_REFUSED: readonly (readonly [number, number])[] = [
98
+ [0x00000000, 8], // 0.0.0.0/8 this network
99
+ [0x0a000000, 8], // 10.0.0.0/8 private
100
+ [0x64400000, 10], // 100.64.0.0/10 shared address space
101
+ [0x7f000000, 8], // 127.0.0.0/8 loopback
102
+ [0xa9fe0000, 16], // 169.254.0.0/16 link-local, the cloud metadata address
103
+ [0xa83f8110, 32], // 168.63.129.16 Azure's host endpoint (metadata, DNS), a public address answered inside the VM
104
+ [0xac100000, 12], // 172.16.0.0/12 private
105
+ [0xc0000000, 24], // 192.0.0.0/24 IETF protocol assignments
106
+ [0xc0000200, 24], // 192.0.2.0/24 documentation
107
+ [0xc0586300, 24], // 192.88.99.0/24 6to4 relay anycast
108
+ [0xc0a80000, 16], // 192.168.0.0/16 private
109
+ [0xc6120000, 15], // 198.18.0.0/15 benchmarking
110
+ [0xc6336400, 24], // 198.51.100.0/24 documentation
111
+ [0xcb007100, 24], // 203.0.113.0/24 documentation
112
+ [0xe0000000, 4], // 224.0.0.0/4 multicast
113
+ [0xf0000000, 4], // 240.0.0.0/4 reserved, broadcast
114
+ ]
115
+
116
+ function isPublicIpv4(octets: readonly number[]): boolean {
117
+ const [a = 0, b = 0, c = 0, d = 0] = octets
118
+ const value = ((a << 24) >>> 0) + (b << 16) + (c << 8) + d
119
+ return !IPV4_REFUSED.some(([network, prefix]) => {
120
+ const mask = prefix === 0 ? 0 : (0xffffffff << (32 - prefix)) >>> 0
121
+ return ((value & mask) >>> 0) === network
122
+ })
123
+ }
124
+
125
+ function ipv4Octets(text: string): number[] | null {
126
+ if (!IPV4.test(text)) return null
127
+ const octets = text.split('.').map((part) => Number.parseInt(part, 10))
128
+ return octets.every((octet) => octet >= 0 && octet <= 255) ? octets : null
129
+ }
130
+
131
+ const HEX_WORD = /^[0-9a-f]{1,4}$/i
132
+
133
+ /** The eight 16-bit words of an IPv6 address (brackets and a zone allowed, an embedded IPv4 tail too), or `null`. */
134
+ function ipv6Words(text: string): number[] | null {
135
+ let rest = text.startsWith('[') && text.endsWith(']') ? text.slice(1, -1) : text
136
+ const zone = rest.indexOf('%')
137
+ if (zone !== -1) rest = rest.slice(0, zone)
138
+ if (!rest.includes(':')) return null
139
+ const tailAt = rest.lastIndexOf(':')
140
+ const tail = ipv4Octets(rest.slice(tailAt + 1))
141
+ const embedded: number[] = []
142
+ if (tail !== null) {
143
+ const [a = 0, b = 0, c = 0, d = 0] = tail
144
+ embedded.push((a << 8) | b, (c << 8) | d)
145
+ rest = rest.slice(0, tailAt + 1) + '0'
146
+ }
147
+ const halves = rest.split('::')
148
+ if (halves.length > 2) return null
149
+ const parse = (half: string | undefined): number[] | null => {
150
+ if (half === undefined || half === '') return []
151
+ const parts = half.split(':')
152
+ if (!parts.every((part) => HEX_WORD.test(part))) return null
153
+ return parts.map((part) => Number.parseInt(part, 16))
154
+ }
155
+ const head = parse(halves[0])
156
+ const back = parse(halves[1])
157
+ if (head === null || back === null) return null
158
+ if (tail !== null) {
159
+ // The placeholder word stands for the two words of the IPv4 tail.
160
+ const last = halves.length === 2 ? back : head
161
+ last.pop()
162
+ last.push(...embedded)
163
+ }
164
+ const missing = 8 - head.length - back.length
165
+ if (halves.length === 1) return missing === 0 ? head : null
166
+ if (missing < 1) return null
167
+ return [...head, ...Array.from({ length: missing }, () => 0), ...back]
168
+ }
package/src/sha256.ts CHANGED
@@ -76,21 +76,60 @@ function rotateRight(value: number, bits: number): number {
76
76
 
77
77
  /** The SHA-256 of `text`'s UTF-8 bytes, as 64 lower-case hex digits. */
78
78
  export function sha256Hex(text: string): string {
79
- const bytes = new TextEncoder().encode(text)
80
- // The message, a 0x80 byte, zero padding and the 64-bit bit length fill whole 64-byte blocks.
81
- const padded = new Uint8Array(Math.ceil((bytes.length + 9) / 64) * 64)
82
- padded.set(bytes)
83
- padded[bytes.length] = 0x80
84
- const view = new DataView(padded.buffer)
85
- const bitLength = bytes.length * 8
86
- view.setUint32(padded.length - 8, Math.floor(bitLength / 0x1_0000_0000))
87
- view.setUint32(padded.length - 4, bitLength >>> 0)
79
+ return new Sha256().update(text).hex()
80
+ }
81
+
82
+ /**
83
+ * SHA-256 over text fed in pieces, so a digest of a large serialization never needs the whole text in memory. Each
84
+ * piece is whole text: a surrogate pair split across two pieces encodes as two replacement characters.
85
+ */
86
+ export class Sha256 {
87
+ readonly #hash = new Uint32Array(INITIAL_HASH)
88
+ readonly #schedule = new Uint32Array(64)
89
+ readonly #block = new Uint8Array(64)
90
+ readonly #blockView = new DataView(this.#block.buffer)
91
+ readonly #encoder = new TextEncoder()
92
+ #filled = 0
93
+ #length = 0
94
+
95
+ update(text: string): this {
96
+ const bytes = this.#encoder.encode(text)
97
+ this.#length += bytes.length
98
+ let offset = 0
99
+ while (offset < bytes.length) {
100
+ const taken = Math.min(64 - this.#filled, bytes.length - offset)
101
+ this.#block.set(bytes.subarray(offset, offset + taken), this.#filled)
102
+ this.#filled += taken
103
+ offset += taken
104
+ if (this.#filled === 64) {
105
+ this.#compress()
106
+ this.#filled = 0
107
+ }
108
+ }
109
+ return this
110
+ }
111
+
112
+ /** The digest of everything fed so far; the hash takes no piece after it. */
113
+ hex(): string {
114
+ const bitLength = this.#length * 8
115
+ // The message, a 0x80 byte, zero padding and the 64-bit bit length fill whole 64-byte blocks.
116
+ this.#block[this.#filled] = 0x80
117
+ this.#block.fill(0, this.#filled + 1)
118
+ if (this.#filled + 1 > 56) {
119
+ this.#compress()
120
+ this.#block.fill(0)
121
+ }
122
+ this.#blockView.setUint32(56, Math.floor(bitLength / 0x1_0000_0000))
123
+ this.#blockView.setUint32(60, bitLength >>> 0)
124
+ this.#compress()
125
+ return Array.from(this.#hash, (word) => word.toString(16).padStart(8, '0')).join('')
126
+ }
88
127
 
89
- const hash = new Uint32Array(INITIAL_HASH)
90
- const schedule = new Uint32Array(64)
91
- for (let offset = 0; offset < padded.length; offset += 64) {
128
+ #compress(): void {
129
+ const hash = this.#hash
130
+ const schedule = this.#schedule
92
131
  for (let index = 0; index < 16; index++) {
93
- schedule[index] = view.getUint32(offset + index * 4)
132
+ schedule[index] = this.#blockView.getUint32(index * 4)
94
133
  }
95
134
  for (let index = 16; index < 64; index++) {
96
135
  const early = schedule[index - 15] ?? 0
@@ -121,5 +160,4 @@ export function sha256Hex(text: string): string {
121
160
  hash[index] = (hash[index] ?? 0) + value
122
161
  }
123
162
  }
124
- return Array.from(hash, (word) => word.toString(16).padStart(8, '0')).join('')
125
163
  }
package/src/types.ts CHANGED
@@ -52,6 +52,45 @@ export interface Scope {
52
52
  */
53
53
  export const RELATION_SCOPE_TYPE = '~rel'
54
54
 
55
+ /**
56
+ * The pseudo-scope of a relation entry held inside one node: `{ type: '~relin', value: '<relation>:<dimension>:<node>' }`
57
+ * means the action is held where a row names the principal in that relation, on rows that lie inside `node` of
58
+ * `dimension`. IAM gives it a grant at that node of a role with `via`. Its own type, never `~rel`: a release that reads
59
+ * `~rel` as "the relation anywhere" ignores this one and reaches less.
60
+ */
61
+ export const RELATION_INSIDE_SCOPE_TYPE = '~relin'
62
+
63
+ /** A relation held inside one node of a dimension, as a `~relin` entry names it. */
64
+ export interface RelationInside {
65
+ readonly relation: string
66
+ readonly dimension: string
67
+ readonly node: string
68
+ }
69
+
70
+ /**
71
+ * The `~relin` scope of `relation` inside `node` of `dimension`. A relation or dimension name never holds `:` (the
72
+ * contract's names do not), so the node, last, is read back verbatim, colons included; a name that holds one is refused.
73
+ */
74
+ export function relationInsideScope(inside: RelationInside): Scope {
75
+ if (inside.relation === '' || inside.dimension === '' || inside.relation.includes(':') || inside.dimension.includes(':')) {
76
+ throw new Error('a relation held inside a node names a relation and a dimension without ":"')
77
+ }
78
+ return { type: RELATION_INSIDE_SCOPE_TYPE, value: `${inside.relation}:${inside.dimension}:${inside.node}` }
79
+ }
80
+
81
+ /** The relation, dimension and node of a `~relin` scope, or null for any other scope or a malformed value. */
82
+ export function parseRelationInside(scope: Scope): RelationInside | null {
83
+ if (scope.type !== RELATION_INSIDE_SCOPE_TYPE) {
84
+ return null
85
+ }
86
+ const first = scope.value.indexOf(':')
87
+ const second = first === -1 ? -1 : scope.value.indexOf(':', first + 1)
88
+ if (first <= 0 || second <= first + 1 || second === scope.value.length - 1) {
89
+ return null
90
+ }
91
+ return { relation: scope.value.slice(0, first), dimension: scope.value.slice(first + 1, second), node: scope.value.slice(second + 1) }
92
+ }
93
+
55
94
  /** A scope type no dimension, grant or key may name: IAM derives a `~` entry itself and never stores one. */
56
95
  export function isReservedScopeType(type: string): boolean {
57
96
  return type.startsWith('~')
@@ -94,8 +133,9 @@ export interface RoleDef {
94
133
  external?: true
95
134
  /**
96
135
  * Relation → exact actions. A GLOBAL grant of this role also carries `{ action, scope: { type: '~rel', value:
97
- * relation } }`: the application holds the action where one of its rows names the principal in that relation.
98
- * Only an application-wide internal role declares it.
136
+ * relation } }`: the application holds the action where one of its rows names the principal in that relation. A
137
+ * grant at a node carries `~relin` instead (`relationInsideScope`): the relation holds only inside that node. Only an
138
+ * internal role declares it.
99
139
  */
100
140
  via?: Record<string, string[]>
101
141
  }
@@ -22,3 +22,8 @@ export declare function canonicalAdmission(admission: BodyAdmission): BodyAdmiss
22
22
  export declare function canonicalOutput(shape: OutputShape): OutputShape;
23
23
  /** A schema shape with its enum values sorted; tuple items and union options keep their order. */
24
24
  export declare function canonicalShape(shape: SchemaShape): SchemaShape;
25
+ /**
26
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
27
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
28
+ */
29
+ export declare function writeCanonicalJson(value: unknown, write: (piece: string) => void): void;
@@ -0,0 +1,18 @@
1
+ import type { ContractArtifact } from './contract';
2
+ /** The `encoding` of an encoded artifact; a plain artifact has no such key. */
3
+ export declare const SHARED_SHAPES_ENCODING = "shared-shapes";
4
+ /** In place of a shape: `shapes[index]` of the encoded artifact, which is always written before it is referenced. */
5
+ export interface SharedShapeReference {
6
+ readonly type: 'shared';
7
+ readonly index: number;
8
+ }
9
+ /** An artifact in the shared encoding, as JSON. */
10
+ export interface EncodedArtifact {
11
+ readonly encoding: typeof SHARED_SHAPES_ENCODING;
12
+ readonly shapes: readonly object[];
13
+ readonly artifact: object;
14
+ }
15
+ /** The canonical artifact in the shared encoding. */
16
+ export declare function encodeArtifact(artifact: ContractArtifact): EncodedArtifact;
17
+ /** The encoded artifact as text, keys sorted: what a build bundles. */
18
+ export declare function encodedArtifactJson(artifact: ContractArtifact): string;
@@ -1,5 +1,6 @@
1
1
  import type { Locale } from './locale';
2
2
  import type { MailTemplates } from './mail';
3
+ import type { DeclaredEgress } from './public-egress';
3
4
  import type { TerminalArtifact } from './terminal';
4
5
  /**
5
6
  * The artifact format this release writes. A release that changes the artifact raises it, and Control upcasts every
@@ -717,9 +718,11 @@ export interface DeclaredReach {
717
718
  readonly signs?: readonly string[];
718
719
  /**
719
720
  * The HTTPS origins this site's code calls (`fetch`), sorted, each an exact origin or a one-label pattern
720
- * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Absent unless declared, so the digest stays.
721
+ * (`parseEgressEntry`): a credentialed procedure, a webhook or a job. Or `'public'` (a cron job only): every public
722
+ * host over HTTPS or HTTP, never the installation or a private network (ADR-0075). Absent unless declared, so the
723
+ * digest stays.
721
724
  */
722
- readonly egress?: readonly string[];
725
+ readonly egress?: DeclaredEgress;
723
726
  /**
724
727
  * A public procedure's workload actions, sorted: all its handler holds, through the key Control issues for the
725
728
  * endpoint (`contractWorkloads`). Present only on a public procedure's entry, so every other digest stays.
@@ -795,6 +798,12 @@ export interface TablePolicyArtifact {
795
798
  readonly confers?: Readonly<Record<string, ConfersArtifact>>;
796
799
  /** Action → the condition a row must meet for it, narrowing what any grant of it reaches. Absent unless declared. */
797
800
  readonly when?: Readonly<Record<string, ConditionArtifact>>;
801
+ /**
802
+ * Relation → action → the condition a row the relation reaches must meet for it; it narrows that relation's reach only.
803
+ * Absent unless declared, so the digest stays. A reader that ignores it reaches more: Control refuses to publish it to
804
+ * an application pinned below the release that enforces it.
805
+ */
806
+ readonly relationWhen?: Readonly<Record<string, Readonly<Record<string, ConditionArtifact>>>>;
798
807
  /**
799
808
  * Relation of the table's own dimension → the ancestor its rows reveal. Absent unless declared, so the digest stays.
800
809
  * A reader that ignores it reaches less, never more.
@@ -805,17 +814,45 @@ export interface TablePolicyArtifact {
805
814
  * digest stays. A reader that ignores it reaches less, never more.
806
815
  */
807
816
  readonly readThrough?: Readonly<Record<string, string>>;
817
+ /**
818
+ * Dimension of `readThrough` → the actions a `Ref` held through that path holds, writes included; whoever inserts the
819
+ * path's column must hold each at the node it names. Absent unless declared, so the digest stays. A reader that
820
+ * ignores it reaches less, never more.
821
+ */
822
+ readonly writeThrough?: Readonly<Record<string, readonly string[]>>;
808
823
  /**
809
824
  * The table's own dimension → the ancestor its rows reveal to a grant at their node, for a `Within`'s reads. Absent
810
825
  * unless declared, so the digest stays. A reader that ignores it reaches less, never more.
811
826
  */
812
827
  readonly memberReveals?: Readonly<Record<string, MemberRevealsArtifact>>;
828
+ /**
829
+ * Relation → the access view that lists the rows it reaches (ADR-0076). Absent unless declared, so the digest stays.
830
+ * A reader that ignores it reaches less, never more.
831
+ */
832
+ readonly access?: Readonly<Record<string, AccessArtifact>>;
833
+ }
834
+ /** An access view: its `row` column names the table's key; `principal` is compared to the caller, `member` to its nodes. */
835
+ export interface AccessArtifact {
836
+ readonly view: string;
837
+ readonly row: string;
838
+ readonly principal: string | null;
839
+ readonly member: string | null;
813
840
  }
814
- /** A row reveals its node in `to` for `actions` to a grant of them at the row's own node, while `when` admits the row. */
841
+ /**
842
+ * 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
843
+ * key's dimension names, while `when` admits the row.
844
+ */
815
845
  export interface MemberRevealsArtifact {
816
846
  readonly to: string;
817
847
  readonly actions: readonly string[];
818
848
  readonly when?: ConditionArtifact;
849
+ /**
850
+ * Through a path, on a table with an insert: the writer picks the node, and `self` lets it pick one where it holds a
851
+ * grant the reveal counts. Absent otherwise; only a reader that refuses a path's key reads it.
852
+ */
853
+ readonly assign?: {
854
+ readonly self: boolean;
855
+ };
819
856
  }
820
857
  /** A row the relation reaches reveals its node in `to` for `actions`, while `when` admits the row. */
821
858
  export interface RevealsArtifact {
@@ -38,6 +38,11 @@ export declare function endpointDigest(artifact: Pick<ContractArtifact, 'dimensi
38
38
  export declare function requirementDigest(rules: EndpointRules): string;
39
39
  /** The digest of the whole artifact, over its one canonical serialization. */
40
40
  export declare function contractDigest(artifact: ContractArtifact): string;
41
+ /**
42
+ * `contractDigest` of an artifact that already is canonical (`canonicalizeArtifact`'s, as a decoded artifact is),
43
+ * hashed as it is serialized: neither a canonical copy nor its text is built. A shared shape is hashed at each place.
44
+ */
45
+ export declare function canonicalArtifactDigest(canonical: ContractArtifact): string;
41
46
  /**
42
47
  * The digest of an installation service's table: each row's id and `requirementDigest`, and the reserved prefixes. A
43
48
  * composition writes it beside the service from the table its proxy publishes, so the service refuses to start under
@@ -12,6 +12,11 @@ export declare const FABRIKA_TOKEN_KEYS = "FABRIKA_TOKEN_KEYS";
12
12
  export declare const FABRIKA_APP_ORIGIN = "FABRIKA_APP_ORIGIN";
13
13
  /** The digests of the environment's ops keys, which the object checks Control's key against (`parseOpsKeyDigests`, ADR-0069). */
14
14
  export declare const FABRIKA_OPS_KEY_DIGESTS = "FABRIKA_OPS_KEY_DIGESTS";
15
+ /**
16
+ * The installation's own hosts, which a cron job's public egress refuses (ADR-0075): Control's, IAM's, Operations' and
17
+ * every application environment's domain, normalized and joined by `,`. Written only for a contract with such a job.
18
+ */
19
+ export declare const FABRIKA_EGRESS_REFUSED_HOSTS = "FABRIKA_EGRESS_REFUSED_HOSTS";
15
20
  /** The name of the object that serves an environment's ordinary traffic on Cloudflare; `application` without it. */
16
21
  export declare const FABRIKA_APPLICATION_OBJECT = "FABRIKA_APPLICATION_OBJECT";
17
22
  /** The object names an ops request may target, all in the environment's own namespace (`parseApplicationObjects`). */
@@ -22,7 +27,7 @@ export declare const FABRIKA_APPLICATION_OBJECTS = "FABRIKA_APPLICATION_OBJECTS"
22
27
  * application variable or secret under one of them, and so does every provider, for every surface that writes one.
23
28
  * A work unit that gives an application a new credential adds its name here.
24
29
  */
25
- export declare const FRAMEWORK_VARIABLE_NAMES: readonly ["FABRIKA_RELEASE", "FABRIKA_CONTRACT_DIGEST", "FABRIKA_IAM_ISSUER", "FABRIKA_IAM_APP_ID", "FABRIKA_OPERATIONS_DSN", "FABRIKA_APP_ID", "FABRIKA_ENVIRONMENT", "FABRIKA_SERVICE_KEY", "FABRIKA_APP_DATABASE_URL", "FABRIKA_APP_RUNTIME_DATABASE_URL", "FABRIKA_APP_DATABASE_CONNECTIONS", "FABRIKA_APP_STORAGE_ENDPOINT", "FABRIKA_APP_STORAGE_BUCKET", "FABRIKA_APP_STORAGE_ACCESS_KEY_ID", "FABRIKA_APP_STORAGE_SECRET_ACCESS_KEY", "FABRIKA_STORAGE_PROVENANCE", "FABRIKA_PROXY_SECRET", "FABRIKA_IAM_RPC_URL", "FABRIKA_IAM_RPC_KEY", "FABRIKA_SOURCE_MAP_UPLOAD", "FABRIKA_SOURCE_MAP_UPLOAD_KEY", "FABRIKA_TOKEN_KEYS", "FABRIKA_APP_ORIGIN", "FABRIKA_OPS_KEY_DIGESTS", "FABRIKA_APPLICATION_OBJECT", "FABRIKA_APPLICATION_OBJECTS"];
30
+ export declare const FRAMEWORK_VARIABLE_NAMES: readonly ["FABRIKA_RELEASE", "FABRIKA_CONTRACT_DIGEST", "FABRIKA_IAM_ISSUER", "FABRIKA_IAM_APP_ID", "FABRIKA_OPERATIONS_DSN", "FABRIKA_APP_ID", "FABRIKA_ENVIRONMENT", "FABRIKA_SERVICE_KEY", "FABRIKA_APP_DATABASE_URL", "FABRIKA_APP_RUNTIME_DATABASE_URL", "FABRIKA_APP_DATABASE_CONNECTIONS", "FABRIKA_APP_STORAGE_ENDPOINT", "FABRIKA_APP_STORAGE_BUCKET", "FABRIKA_APP_STORAGE_ACCESS_KEY_ID", "FABRIKA_APP_STORAGE_SECRET_ACCESS_KEY", "FABRIKA_STORAGE_PROVENANCE", "FABRIKA_PROXY_SECRET", "FABRIKA_IAM_RPC_URL", "FABRIKA_IAM_RPC_KEY", "FABRIKA_SOURCE_MAP_UPLOAD", "FABRIKA_SOURCE_MAP_UPLOAD_KEY", "FABRIKA_TOKEN_KEYS", "FABRIKA_APP_ORIGIN", "FABRIKA_OPS_KEY_DIGESTS", "FABRIKA_EGRESS_REFUSED_HOSTS", "FABRIKA_APPLICATION_OBJECT", "FABRIKA_APPLICATION_OBJECTS"];
26
31
  export type FrameworkVariableName = (typeof FRAMEWORK_VARIABLE_NAMES)[number];
27
32
  /**
28
33
  * The name families only the platform writes: one variable per job, webhook or public procedure, named after it
@@ -3,6 +3,7 @@ export * from './canonical-path';
3
3
  export * from './client-address';
4
4
  export * from './contract';
5
5
  export * from './contract-canonical';
6
+ export * from './contract-encoding';
6
7
  export * from './dev-environment';
7
8
  export * from './device';
8
9
  export * from './egress';
@@ -20,6 +21,7 @@ export * from './membership';
20
21
  export * from './oauth';
21
22
  export * from './ops';
22
23
  export * from './permissions';
24
+ export * from './public-egress';
23
25
  export * from './requirement';
24
26
  export * from './rpc';
25
27
  export { sha256Hex } from './sha256';
@@ -2,7 +2,7 @@
2
2
  * The framework names Control hands every deploy, each with a value or `null` (the deploy removes it). Beside them, a
3
3
  * deploy carries the families of `FRAMEWORK_VARIABLE_PREFIXES`, one variable per workload, import or receiver.
4
4
  */
5
- export declare const MANAGED_VARIABLE_NAMES: readonly ["FABRIKA_RELEASE", "FABRIKA_OPERATIONS_DSN", "FABRIKA_IAM_ISSUER", "FABRIKA_IAM_APP_ID", "FABRIKA_APP_ID", "FABRIKA_ENVIRONMENT", "FABRIKA_SERVICE_KEY", "FABRIKA_PROXY_SECRET", "FABRIKA_IAM_RPC_URL", "FABRIKA_IAM_RPC_KEY", "FABRIKA_APP_ORIGIN", "FABRIKA_TOKEN_KEYS", "FABRIKA_OPS_KEY_DIGESTS"];
5
+ export declare const MANAGED_VARIABLE_NAMES: readonly ["FABRIKA_RELEASE", "FABRIKA_OPERATIONS_DSN", "FABRIKA_IAM_ISSUER", "FABRIKA_IAM_APP_ID", "FABRIKA_APP_ID", "FABRIKA_ENVIRONMENT", "FABRIKA_SERVICE_KEY", "FABRIKA_PROXY_SECRET", "FABRIKA_IAM_RPC_URL", "FABRIKA_IAM_RPC_KEY", "FABRIKA_APP_ORIGIN", "FABRIKA_TOKEN_KEYS", "FABRIKA_OPS_KEY_DIGESTS", "FABRIKA_EGRESS_REFUSED_HOSTS"];
6
6
  export type ManagedVariableName = (typeof MANAGED_VARIABLE_NAMES)[number];
7
7
  /**
8
8
  * Whether a managed variable carries a credential, so a provider writes it as a secret and never reads it back. Fail
@@ -0,0 +1,31 @@
1
+ /** The declared form of public egress: every public host, over HTTPS or HTTP, on its default port. */
2
+ export declare const PUBLIC_EGRESS = "public";
3
+ export type PublicEgress = typeof PUBLIC_EGRESS;
4
+ /** What a site declares in `egress`: its exact HTTPS origins, sorted, or every public host (a cron job only). */
5
+ export type DeclaredEgress = readonly string[] | PublicEgress;
6
+ /**
7
+ * The name suffixes public egress refuses, each with every name under it: local and special-use names (RFC 6761,
8
+ * RFC 6762, RFC 8375, RFC 9476), the names private networks conventionally use (`.internal` holds Google's metadata
9
+ * host and Control's own `operations.internal`), and the platform subdomains an installation is served on beside its
10
+ * own domains: Cloudflare's `workers.dev`, where its Workers have their default routes, and Zerops' `zerops.app`, where
11
+ * its proxies, Control and IAM have their subdomains (a namespace proxy's `proxy-…-8080.<region>.zerops.app`), with the
12
+ * `zerops` suffix of a Zerops project's private network. Control knows no list of those subdomains, so every one is
13
+ * refused, another installation's too.
14
+ */
15
+ export declare const PUBLIC_EGRESS_REFUSED_SUFFIXES: readonly ["localhost", "local", "internal", "intranet", "lan", "home", "corp", "private", "arpa", "test", "invalid", "example", "onion", "alt", "zerops", "zerops.app", "workers.dev"];
16
+ /** A host name without its trailing dots, lowercased: the form every comparison here uses. */
17
+ export declare function normalizedHost(hostname: string): string;
18
+ /**
19
+ * Why public egress refuses `url`, or `null` when the URL alone admits it: a scheme other than `https:` and `http:`, a
20
+ * port other than the scheme's default, credentials in the URL, an IP literal, a name of one label, a name under a
21
+ * refused suffix, or one of `refusedHosts` (normalized names). A host it admits may still resolve to a private address,
22
+ * which only a runtime that resolves names refuses.
23
+ */
24
+ export declare function publicEgressRefusal(url: URL, refusedHosts?: ReadonlySet<string>): string | null;
25
+ /**
26
+ * Whether `address` (an IPv4 or IPv6 address, as a resolver answers it) is a public unicast address: not private,
27
+ * loopback, link-local (which holds the cloud metadata address 169.254.169.254), shared, multicast, reserved,
28
+ * documentation, or an IPv6 form that embeds or tunnels an IPv4 address it cannot vouch for. A text that is no address
29
+ * is not public.
30
+ */
31
+ export declare function isPublicAddress(address: string): boolean;
@@ -1,2 +1,12 @@
1
1
  /** The SHA-256 of `text`'s UTF-8 bytes, as 64 lower-case hex digits. */
2
2
  export declare function sha256Hex(text: string): string;
3
+ /**
4
+ * SHA-256 over text fed in pieces, so a digest of a large serialization never needs the whole text in memory. Each
5
+ * piece is whole text: a surrogate pair split across two pieces encodes as two replacement characters.
6
+ */
7
+ export declare class Sha256 {
8
+ #private;
9
+ update(text: string): this;
10
+ /** The digest of everything fed so far; the hash takes no piece after it. */
11
+ hex(): string;
12
+ }
@@ -40,6 +40,26 @@ export interface Scope {
40
40
  * scopes by `(type, value)` mistakes one for a dimension value, and none resolves it but the framework.
41
41
  */
42
42
  export declare const RELATION_SCOPE_TYPE = "~rel";
43
+ /**
44
+ * The pseudo-scope of a relation entry held inside one node: `{ type: '~relin', value: '<relation>:<dimension>:<node>' }`
45
+ * means the action is held where a row names the principal in that relation, on rows that lie inside `node` of
46
+ * `dimension`. IAM gives it a grant at that node of a role with `via`. Its own type, never `~rel`: a release that reads
47
+ * `~rel` as "the relation anywhere" ignores this one and reaches less.
48
+ */
49
+ export declare const RELATION_INSIDE_SCOPE_TYPE = "~relin";
50
+ /** A relation held inside one node of a dimension, as a `~relin` entry names it. */
51
+ export interface RelationInside {
52
+ readonly relation: string;
53
+ readonly dimension: string;
54
+ readonly node: string;
55
+ }
56
+ /**
57
+ * The `~relin` scope of `relation` inside `node` of `dimension`. A relation or dimension name never holds `:` (the
58
+ * contract's names do not), so the node, last, is read back verbatim, colons included; a name that holds one is refused.
59
+ */
60
+ export declare function relationInsideScope(inside: RelationInside): Scope;
61
+ /** The relation, dimension and node of a `~relin` scope, or null for any other scope or a malformed value. */
62
+ export declare function parseRelationInside(scope: Scope): RelationInside | null;
43
63
  /** A scope type no dimension, grant or key may name: IAM derives a `~` entry itself and never stores one. */
44
64
  export declare function isReservedScopeType(type: string): boolean;
45
65
  export interface PermissionEntry {
@@ -80,8 +100,9 @@ export interface RoleDef {
80
100
  external?: true;
81
101
  /**
82
102
  * Relation → exact actions. A GLOBAL grant of this role also carries `{ action, scope: { type: '~rel', value:
83
- * relation } }`: the application holds the action where one of its rows names the principal in that relation.
84
- * Only an application-wide internal role declares it.
103
+ * relation } }`: the application holds the action where one of its rows names the principal in that relation. A
104
+ * grant at a node carries `~relin` instead (`relationInsideScope`): the relation holds only inside that node. Only an
105
+ * internal role declares it.
85
106
  */
86
107
  via?: Record<string, string[]>;
87
108
  }