@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/package.json CHANGED
@@ -1,7 +1,8 @@
1
1
  {
2
2
  "name": "@fabrika/auth-core",
3
- "version": "0.9.0-dev.5",
3
+ "version": "0.9.0-dev.50",
4
4
  "type": "module",
5
+ "sideEffects": false,
5
6
  "repository": {
6
7
  "type": "git",
7
8
  "url": "git+https://github.com/contember/fabrika-platform.git",
@@ -23,7 +24,7 @@
23
24
  }
24
25
  },
25
26
  "scripts": {
26
- "typecheck": "tsc --noEmit",
27
+ "typecheck": "tsrs --build tsconfig.test.json",
27
28
  "test": "bun test"
28
29
  }
29
30
  }
package/src/agent.ts ADDED
@@ -0,0 +1,89 @@
1
+ // An agent's device grant at an application environment (ADR-0090): the client, the caller its exchanged token
2
+ // presents, the scope it approved and the narrowing of the person's permissions to one scope value.
3
+
4
+ import type { CredentialedEndpointKind } from './contract'
5
+ import { isScopeParameterText } from './oauth'
6
+ import { narrowPermissions, uniquePermissions } from './permissions'
7
+ import { DIMENSION_NAME, parseRelationInside, type PermissionEntry, type Scope } from './types'
8
+
9
+ export { AGENT_CLIENT_ID } from './oauth'
10
+
11
+ /** The caller a person's application token presents when the proxy exchanged an agent's grant for it. */
12
+ export const AGENT_CALLER = 'agent'
13
+
14
+ export const AGENT_SCOPE_MODES = ['read', 'write'] as const
15
+ export type AgentScopeMode = (typeof AGENT_SCOPE_MODES)[number]
16
+
17
+ /** The mode a grant gets when the client asks for no scope. */
18
+ export const DEFAULT_AGENT_SCOPE_MODE: AgentScopeMode = 'read'
19
+
20
+ /** The endpoint kinds each mode admits. Neither admits an SPA: an agent calls procedures. */
21
+ export const AGENT_SCOPE_KINDS: Readonly<Record<AgentScopeMode, readonly CredentialedEndpointKind[]>> = Object.freeze({
22
+ read: Object.freeze(['query', 'download'] as const),
23
+ write: Object.freeze(['query', 'mutation', 'upload', 'download'] as const),
24
+ })
25
+
26
+ /** The scope one grant holds: its mode, and the one scope value it is narrowed to, or null for none. */
27
+ export interface AgentScope {
28
+ readonly mode: AgentScopeMode
29
+ readonly within: Scope | null
30
+ }
31
+
32
+ /**
33
+ * Read one scope token: `read`, `write`, or either narrowed to one value of a dimension, `read:<dimension>=<value>`.
34
+ * The dimension is a contract's dimension name; the value is opaque text of a parameterized scope
35
+ * (`isScopeParameterText`). Anything else is null.
36
+ */
37
+ export function parseAgentScope(token: string): AgentScope | null {
38
+ const colon = token.indexOf(':')
39
+ const mode = colon === -1 ? token : token.slice(0, colon)
40
+ if (!isAgentScopeMode(mode)) return null
41
+ if (colon === -1) return { mode, within: null }
42
+ const rest = token.slice(colon + 1)
43
+ const equals = rest.indexOf('=')
44
+ if (equals === -1) return null
45
+ const type = rest.slice(0, equals)
46
+ const value = rest.slice(equals + 1)
47
+ if (!DIMENSION_NAME.test(type) || !isScopeParameterText(type) || !isScopeParameterText(value)) return null
48
+ return { mode, within: { type, value } }
49
+ }
50
+
51
+ /** The scope token of `scope`; `parseAgentScope` reads it back to the same scope. */
52
+ export function agentScopeToken(scope: AgentScope): string {
53
+ return scope.within === null ? scope.mode : `${scope.mode}:${scope.within.type}=${scope.within.value}`
54
+ }
55
+
56
+ export function isAgentScopeMode(value: string): value is AgentScopeMode {
57
+ return value === 'read' || value === 'write'
58
+ }
59
+
60
+ /** Whether a grant of `mode` reaches an endpoint of `kind`. */
61
+ export function agentScopeAdmits(mode: AgentScopeMode, kind: string): boolean {
62
+ return AGENT_SCOPE_KINDS[mode].some((admitted) => admitted === kind)
63
+ }
64
+
65
+ /**
66
+ * The person's entries narrowed to the one scope value `within` (ADR-0090 §3): `narrowPermissions` under `*` at `within`
67
+ * (a global entry becomes the same action there, an entry at `within` stays, every other scope is dropped), plus the
68
+ * relations the person holds inside `within`. A relation held anywhere (`~rel`) is dropped: an access view bound to
69
+ * its member reaches rows for a node that a hold anywhere does not reach (ADR-0076), so moving it inside `within` would
70
+ * widen it. Never adds an action or a reach the person does not hold.
71
+ */
72
+ export function narrowToValue(entries: readonly PermissionEntry[], within: Scope): PermissionEntry[] {
73
+ if (!DIMENSION_NAME.test(within.type)) throw new Error('a grant is narrowed to a value of a dimension')
74
+ const scope = { type: within.type, value: within.value }
75
+ const inside = entries.filter((entry) => entry.scope !== null && relationInside(entry.scope, within))
76
+ return uniquePermissions([...narrowPermissions(entries, [{ action: '*', scope }]), ...inside])
77
+ }
78
+
79
+ /** Whether every entry lies within `within`, as `narrowToValue` leaves them: a check a token's reader repeats. */
80
+ export function liesWithinValue(entries: readonly PermissionEntry[], within: Scope): boolean {
81
+ return entries.every((entry) =>
82
+ entry.scope !== null && ((entry.scope.type === within.type && entry.scope.value === within.value) || relationInside(entry.scope, within))
83
+ )
84
+ }
85
+
86
+ function relationInside(scope: Scope, within: Scope): boolean {
87
+ const inside = parseRelationInside(scope)
88
+ return inside !== null && inside.dimension === within.type && inside.node === within.value
89
+ }
@@ -50,6 +50,24 @@ export function rawRequestTarget(url: string): RequestTarget {
50
50
  return target.pathname === '' ? { pathname: '/', search: target.search } : target
51
51
  }
52
52
 
53
+ /**
54
+ * The absolute URL of `path` on `origin`, or `null` when `path` is not a path of that origin: the one rule for a
55
+ * redirect or return target that must stay on its own origin. A leading `//` or any `\` would make a browser read a
56
+ * host from it, and a browser strips a tab or newline before parsing, so no control character is admitted.
57
+ */
58
+ export function sameOriginTarget(origin: string, path: string): string | null {
59
+ if (!path.startsWith('/') || path.startsWith('//') || path.includes('\\') || [...path].some(isControl)) {
60
+ return null
61
+ }
62
+ const target = new URL(path, origin)
63
+ return target.origin === origin ? target.toString() : null
64
+ }
65
+
66
+ function isControl(character: string): boolean {
67
+ const code = character.charCodeAt(0)
68
+ return code < 0x20 || code === 0x7f
69
+ }
70
+
53
71
  /** A segment one reader decodes and another refuses would route differently, so a malformed escape is refused. */
54
72
  function isDecodable(segment: string): boolean {
55
73
  try {
@@ -0,0 +1,74 @@
1
+ // The client a per-client abuse bucket counts, derived from the address an ingress wrote. IAM and the application
2
+ // runtime both key on it, so one client is one bucket on either side.
3
+
4
+ /** Longest header value read; an IPv6 address with a zone id fits with room to spare. */
5
+ const MAX_ADDRESS_LENGTH = 64
6
+
7
+ const IPV4 = /^(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(?:\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}$/
8
+ const HEXTET = /^[0-9a-f]{1,4}$/
9
+
10
+ /**
11
+ * The eight groups of an IPv6 address, or `null`. An embedded IPv4 tail (`::ffff:192.0.2.1`) counts as two groups,
12
+ * and a zone id (`%eth0`) is dropped.
13
+ */
14
+ function ipv6Groups(text: string): number[] | null {
15
+ const address = text.split('%')[0] ?? ''
16
+ const halves = address.split('::')
17
+ if (halves.length > 2) {
18
+ return null
19
+ }
20
+ const groupsOf = (half: string): number[] | null => {
21
+ if (half === '') {
22
+ return []
23
+ }
24
+ const groups: number[] = []
25
+ const parts = half.split(':')
26
+ for (const [index, part] of parts.entries()) {
27
+ if (index === parts.length - 1 && IPV4.test(part)) {
28
+ const [a = 0, b = 0, c = 0, d = 0] = part.split('.').map(Number)
29
+ groups.push(a * 256 + b, c * 256 + d)
30
+ } else if (HEXTET.test(part)) {
31
+ groups.push(Number.parseInt(part, 16))
32
+ } else {
33
+ return null
34
+ }
35
+ }
36
+ return groups
37
+ }
38
+ const head = groupsOf(halves[0] ?? '')
39
+ const tail = halves.length === 2 ? groupsOf(halves[1] ?? '') : []
40
+ if (head === null || tail === null) {
41
+ return null
42
+ }
43
+ if (halves.length === 1) {
44
+ return head.length === 8 ? head : null
45
+ }
46
+ const missing = 8 - head.length - tail.length
47
+ return missing < 1 ? null : [...head, ...Array.from({ length: missing }, () => 0), ...tail]
48
+ }
49
+
50
+ /**
51
+ * The client a client-address header value counts as: an IPv4 address, or an IPv6 address's /64 (one subscriber's
52
+ * prefix, of which it may hold every address); an IPv4-mapped IPv6 address counts as its IPv4 address. Only the first
53
+ * value counts, so a caller that appends a second copy cannot change the key. `null` when the value is absent or no
54
+ * IP address.
55
+ */
56
+ export function clientAddressKey(header: string | null): string | null {
57
+ const value = (header ?? '').split(',')[0]?.trim().toLowerCase() ?? ''
58
+ if (value === '' || value.length > MAX_ADDRESS_LENGTH) {
59
+ return null
60
+ }
61
+ if (IPV4.test(value)) {
62
+ return value
63
+ }
64
+ const groups = ipv6Groups(value.startsWith('[') && value.endsWith(']') ? value.slice(1, -1) : value)
65
+ if (groups === null) {
66
+ return null
67
+ }
68
+ const mapped = groups.slice(0, 5).every((group) => group === 0) && groups[5] === 0xffff
69
+ if (mapped) {
70
+ const [high = 0, low = 0] = groups.slice(6)
71
+ return [high >> 8, high & 0xff, low >> 8, low & 0xff].join('.')
72
+ }
73
+ return `${groups.slice(0, 4).map((group) => group.toString(16)).join(':')}::/64`
74
+ }
@@ -4,12 +4,20 @@
4
4
  import type {
5
5
  BodyAdmission,
6
6
  Caller,
7
+ ColumnPolicyArtifact,
8
+ ColumnTestArtifact,
9
+ ConditionArtifact,
10
+ ConditionLiteralArtifact,
11
+ ConfersArtifact,
7
12
  ContractArtifact,
8
13
  CspSource,
9
14
  EndpointRow,
15
+ MemberRevealsArtifact,
10
16
  MountArtifact,
11
17
  OutputShape,
18
+ RevealsArtifact,
12
19
  RoleArtifact,
20
+ RowsTestArtifact,
13
21
  SchemaShape,
14
22
  TableActionArtifact,
15
23
  TablePolicyArtifact,
@@ -24,9 +32,14 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
24
32
  return {
25
33
  format: artifact.format,
26
34
  app: artifact.app,
27
- dimensions: artifact.dimensions,
35
+ dimensions: mapValues(
36
+ artifact.dimensions,
37
+ (dimension) =>
38
+ dimension.values === undefined ? dimension : { ...dimension, values: [...dimension.values].sort((a, b) => compare(a.value, b.value)) },
39
+ ),
28
40
  actions: artifact.actions,
29
41
  roles: mapValues(artifact.roles, canonicalRole),
42
+ ...(artifact.relations === undefined ? {} : { relations: artifact.relations }),
30
43
  mounts: mapValues(artifact.mounts, canonicalMount),
31
44
  files: mapValues(artifact.files, (collection) => ({
32
45
  ...collection,
@@ -65,7 +78,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
65
78
  ...(reach.actions === undefined ? {} : { actions: sorted(reach.actions) }),
66
79
  ...(reach.kicks === undefined ? {} : { kicks: sorted(reach.kicks) }),
67
80
  ...(reach.signs === undefined ? {} : { signs: sorted(reach.signs) }),
68
- ...(reach.egress === undefined ? {} : { egress: sorted(reach.egress) }),
81
+ ...(reach.egress === undefined ? {} : { egress: typeof reach.egress === 'string' ? reach.egress : sorted(reach.egress) }),
69
82
  })),
70
83
  }),
71
84
  ...(artifact.directories === undefined ? {} : { directories: artifact.directories }),
@@ -75,6 +88,7 @@ export function canonicalizeArtifact(artifact: ContractArtifact): ContractArtifa
75
88
  ...(artifact.members === undefined ? {} : { members: artifact.members }),
76
89
  ...(artifact.directory === undefined ? {} : { directory: artifact.directory }),
77
90
  ...(artifact.terminal === undefined ? {} : { terminal: { identify: artifact.terminal.identify } }),
91
+ ...(artifact.notifications === undefined ? {} : { notifications: artifact.notifications }),
78
92
  ...(artifact.procedures === undefined
79
93
  ? {}
80
94
  : {
@@ -101,6 +115,7 @@ function canonicalRole(role: RoleArtifact): RoleArtifact {
101
115
  grants: sorted(role.grants),
102
116
  member: role.member === null ? null : { scope: role.member.scope, assignableBy: sorted(role.member.assignableBy) },
103
117
  ...(role.external === true ? { external: true } : {}),
118
+ ...(role.via === undefined ? {} : { via: mapValues(role.via, sorted) }),
104
119
  }
105
120
  }
106
121
 
@@ -151,7 +166,120 @@ function canonicalTable(table: TablePolicyArtifact): TablePolicyArtifact {
151
166
  scope: table.scope.mode === 'child' ? { ...table.scope, inherit: sorted(table.scope.inherit) } : table.scope,
152
167
  insert: sorted(table.insert),
153
168
  update: sorted(table.update),
169
+ columns: mapValues(table.columns, canonicalColumn),
170
+ ...(table.when === undefined ? {} : { when: mapValues(table.when, canonicalCondition) }),
171
+ ...(table.relationWhen === undefined
172
+ ? {}
173
+ : { relationWhen: mapValues(table.relationWhen, (conditions) => mapValues(conditions, canonicalCondition)) }),
174
+ ...(table.confers === undefined ? {} : { confers: mapValues(table.confers, canonicalConfers) }),
175
+ ...(table.reveals === undefined ? {} : { reveals: mapValues(table.reveals, canonicalReveals) }),
176
+ ...(table.memberReveals === undefined ? {} : { memberReveals: mapValues(table.memberReveals, canonicalMemberReveals) }),
177
+ }
178
+ }
179
+
180
+ /** A column's lists of read and write actions sorted; one action, and an absent one, as they are. */
181
+ function canonicalColumn(column: ColumnPolicyArtifact): ColumnPolicyArtifact {
182
+ return {
183
+ ...column,
184
+ ...(column.read === undefined || typeof column.read === 'string' ? {} : { read: sorted(column.read) }),
185
+ ...(column.write === undefined || typeof column.write === 'string' ? {} : { write: sorted(column.write) }),
186
+ }
187
+ }
188
+
189
+ function canonicalConfers(confers: ConfersArtifact): ConfersArtifact {
190
+ return confers.when === undefined ? confers : { ...confers, when: canonicalCondition(confers.when) }
191
+ }
192
+
193
+ function canonicalReveals(reveals: RevealsArtifact): RevealsArtifact {
194
+ return {
195
+ ...reveals,
196
+ actions: sorted(reveals.actions),
197
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
198
+ }
199
+ }
200
+
201
+ function canonicalMemberReveals(reveals: MemberRevealsArtifact): MemberRevealsArtifact {
202
+ return {
203
+ ...reveals,
204
+ actions: sorted(reveals.actions),
205
+ ...(reveals.when === undefined ? {} : { when: canonicalCondition(reveals.when) }),
206
+ }
207
+ }
208
+
209
+ /**
210
+ * A condition with its connectives' operands and its `in` / `notIn` lists sorted by their canonical JSON: AND and OR
211
+ * commute and a list is a set, so neither order changes which rows it admits.
212
+ */
213
+ export function canonicalCondition(condition: ConditionArtifact): ConditionArtifact {
214
+ if ('allOf' in condition && isConditionList(condition.allOf)) {
215
+ return { allOf: sortedConditions(condition.allOf) }
216
+ }
217
+ if ('anyOf' in condition && isConditionList(condition.anyOf)) {
218
+ return { anyOf: sortedConditions(condition.anyOf) }
219
+ }
220
+ if ('not' in condition && isCondition(condition.not)) {
221
+ return { not: canonicalCondition(condition.not) }
222
+ }
223
+ const rows = canonicalRows(condition)
224
+ if (rows !== undefined) return rows
225
+ const tests: Record<string, ColumnTestArtifact | RowsTestArtifact> = {}
226
+ for (const [path, test] of Object.entries(condition)) {
227
+ const after = isCondition(test) ? canonicalRows(test) : undefined
228
+ if (after !== undefined) {
229
+ tests[path] = after
230
+ continue
231
+ }
232
+ // A parsed artifact holds nothing else here; dropping an unknown test would widen what the condition admits.
233
+ if (!isColumnTest(test)) throw new Error(`the condition test of ${path} is not a column test`)
234
+ tests[path] = canonicalTest(test)
235
+ }
236
+ return tests
237
+ }
238
+
239
+ /** `some` or `none` with its condition canonical, or `undefined` for any other form: one beside another key is no rows test. */
240
+ function canonicalRows(condition: object): RowsTestArtifact | undefined {
241
+ if (Object.keys(condition).length !== 1) return undefined
242
+ if ('some' in condition && isConditionRecord(condition.some)) {
243
+ return { some: mapValues(condition.some, canonicalCondition) }
154
244
  }
245
+ if ('none' in condition && isConditionRecord(condition.none)) {
246
+ return { none: mapValues(condition.none, canonicalCondition) }
247
+ }
248
+ return undefined
249
+ }
250
+
251
+ function canonicalTest(test: ColumnTestArtifact): ColumnTestArtifact {
252
+ return {
253
+ ...test,
254
+ ...(test.in === undefined ? {} : { in: sortedLiterals(test.in) }),
255
+ ...(test.notIn === undefined ? {} : { notIn: sortedLiterals(test.notIn) }),
256
+ }
257
+ }
258
+
259
+ function sortedConditions(conditions: readonly ConditionArtifact[]): ConditionArtifact[] {
260
+ return conditions.map(canonicalCondition).sort((a, b) => compare(canonicalJson(a), canonicalJson(b)))
261
+ }
262
+
263
+ function sortedLiterals(values: readonly ConditionLiteralArtifact[]): ConditionLiteralArtifact[] {
264
+ return [...values].sort((a, b) => compare(JSON.stringify(a), JSON.stringify(b)))
265
+ }
266
+
267
+ function isCondition(value: unknown): value is ConditionArtifact {
268
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
269
+ }
270
+
271
+ function isConditionRecord(value: unknown): value is Readonly<Record<string, ConditionArtifact>> {
272
+ return isCondition(value) && Object.values(value).every(isCondition)
273
+ }
274
+
275
+ function isConditionList(value: unknown): value is readonly ConditionArtifact[] {
276
+ return Array.isArray(value) && value.every(isCondition)
277
+ }
278
+
279
+ const COLUMN_TEST_OPERATORS: ReadonlySet<string> = new Set(['eq', 'notEq', 'in', 'notIn', 'isNull', 'lt', 'lte', 'gt', 'gte'])
280
+
281
+ function isColumnTest(value: unknown): value is ColumnTestArtifact {
282
+ return isCondition(value) && Object.keys(value).every((operator) => COLUMN_TEST_OPERATORS.has(operator))
155
283
  }
156
284
 
157
285
  function canonicalizeEndpoint(row: EndpointRow): EndpointRow {
@@ -234,3 +362,41 @@ function sortKeys(_key: string, value: unknown): unknown {
234
362
  }
235
363
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
236
364
  }
365
+
366
+ /**
367
+ * `canonicalJson(value)` written in pieces to `write`, so a digest of a large value never holds its whole text. Each
368
+ * object is rebuilt as `sortKeys` rebuilds it, so integer-like keys come first exactly as `JSON.stringify` orders them.
369
+ */
370
+ export function writeCanonicalJson(value: unknown, write: (piece: string) => void): void {
371
+ if (Array.isArray(value)) {
372
+ write('[')
373
+ for (const [index, item] of value.entries()) {
374
+ if (index > 0) write(',')
375
+ if (isOmitted(item)) write('null')
376
+ else writeCanonicalJson(item, write)
377
+ }
378
+ write(']')
379
+ return
380
+ }
381
+ if (typeof value === 'object' && value !== null) {
382
+ write('{')
383
+ let first = true
384
+ const rebuilt = Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
385
+ for (const [key, item] of Object.entries(rebuilt)) {
386
+ if (isOmitted(item)) continue
387
+ if (!first) write(',')
388
+ first = false
389
+ write(JSON.stringify(key))
390
+ write(':')
391
+ writeCanonicalJson(item, write)
392
+ }
393
+ write('}')
394
+ return
395
+ }
396
+ write(JSON.stringify(value) ?? 'null')
397
+ }
398
+
399
+ /** What `JSON.stringify` leaves out of an object and writes as `null` in an array. */
400
+ function isOmitted(value: unknown): boolean {
401
+ return value === undefined || typeof value === 'function' || typeof value === 'symbol'
402
+ }
@@ -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
+ }