@fabrika/auth-core 0.9.0-dev.14 → 0.9.0-dev.16

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.14",
3
+ "version": "0.9.0-dev.16",
4
4
  "type": "module",
5
5
  "repository": {
6
6
  "type": "git",
@@ -346,3 +346,41 @@ function sortKeys(_key: string, value: unknown): unknown {
346
346
  }
347
347
  return Object.fromEntries(Object.entries(value).sort(([a], [b]) => compare(a, b)))
348
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
+ }
@@ -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
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'
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
  }
@@ -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;
@@ -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
@@ -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';
@@ -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
+ }