nervur 0.19.2 → 0.20.0

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 (205) hide show
  1. package/README.md +66 -101
  2. package/dist/being/being.d.ts +7 -15
  3. package/dist/being/being.js +16 -67
  4. package/dist/being/digest.d.ts +1 -1
  5. package/dist/being/digest.js +7 -27
  6. package/dist/being/faculty.d.ts +9 -0
  7. package/dist/being/faculty.js +68 -0
  8. package/dist/being/index.d.ts +4 -5
  9. package/dist/being/index.js +5 -5
  10. package/dist/being/types.d.ts +35 -62
  11. package/dist/being/types.js +3 -57
  12. package/dist/being/words.d.ts +13 -0
  13. package/dist/being/words.js +14 -0
  14. package/dist/contract/index.d.ts +26 -0
  15. package/dist/contract/index.js +19 -0
  16. package/dist/crypto/aes.d.ts +3 -0
  17. package/dist/crypto/aes.js +24 -0
  18. package/dist/crypto/bytes.d.ts +6 -0
  19. package/dist/crypto/bytes.js +33 -0
  20. package/dist/crypto/ed25519.d.ts +3 -0
  21. package/dist/crypto/ed25519.js +85 -0
  22. package/dist/crypto/hash.d.ts +2 -0
  23. package/dist/crypto/hash.js +11 -0
  24. package/dist/crypto/index.d.ts +7 -0
  25. package/dist/crypto/index.js +10 -0
  26. package/dist/crypto/json.d.ts +8 -0
  27. package/dist/crypto/json.js +250 -0
  28. package/dist/crypto/mlkem.d.ts +12 -0
  29. package/dist/crypto/mlkem.js +36 -0
  30. package/dist/crypto/subtle.d.ts +10 -0
  31. package/dist/crypto/subtle.js +29 -0
  32. package/dist/crypto/x25519.d.ts +2 -0
  33. package/dist/crypto/x25519.js +21 -0
  34. package/dist/folder/index.d.ts +13 -0
  35. package/dist/folder/index.js +125 -0
  36. package/dist/harbor/dock.d.ts +19 -0
  37. package/dist/harbor/dock.js +92 -0
  38. package/dist/harbor/harbor.d.ts +22 -0
  39. package/dist/harbor/harbor.js +84 -0
  40. package/dist/harbor/index.d.ts +4 -10
  41. package/dist/harbor/index.js +5 -18
  42. package/dist/harbor/registry.d.ts +7 -0
  43. package/dist/harbor/registry.js +13 -0
  44. package/dist/harbor/terrain.d.ts +8 -0
  45. package/dist/harbor/terrain.js +2 -0
  46. package/dist/index.d.ts +7 -0
  47. package/dist/index.js +14 -0
  48. package/dist/pointer/bodies.d.ts +20 -0
  49. package/dist/pointer/bodies.js +45 -0
  50. package/dist/pointer/index.d.ts +2 -0
  51. package/dist/pointer/index.js +4 -0
  52. package/dist/pointer/world.d.ts +34 -0
  53. package/dist/pointer/world.js +76 -0
  54. package/dist/quo/door.d.ts +34 -0
  55. package/dist/quo/door.js +172 -0
  56. package/dist/quo/index.d.ts +8 -0
  57. package/dist/quo/index.js +11 -0
  58. package/dist/quo/invitation.d.ts +7 -0
  59. package/dist/quo/invitation.js +15 -0
  60. package/dist/quo/keys.d.ts +40 -0
  61. package/dist/quo/keys.js +79 -0
  62. package/dist/quo/payload.d.ts +15 -0
  63. package/dist/quo/payload.js +55 -0
  64. package/dist/quo/relations.d.ts +40 -0
  65. package/dist/quo/relations.js +33 -0
  66. package/dist/quo/reply.d.ts +13 -0
  67. package/dist/quo/reply.js +35 -0
  68. package/dist/quo/seal.d.ts +42 -0
  69. package/dist/quo/seal.js +78 -0
  70. package/dist/quo/standing.d.ts +39 -0
  71. package/dist/quo/standing.js +90 -0
  72. package/dist/ward/allowance.d.ts +13 -9
  73. package/dist/ward/allowance.js +28 -67
  74. package/dist/ward/cells.d.ts +6 -6
  75. package/dist/ward/cells.js +67 -179
  76. package/dist/ward/index.d.ts +5 -10
  77. package/dist/ward/index.js +6 -13
  78. package/dist/ward/partition.d.ts +44 -60
  79. package/dist/ward/partition.js +56 -285
  80. package/dist/ward/stance.d.ts +29 -20
  81. package/dist/ward/stance.js +173 -406
  82. package/dist/ward/ward-being.d.ts +33 -0
  83. package/dist/ward/ward-being.js +76 -0
  84. package/dist/ward/ward.d.ts +43 -11
  85. package/dist/ward/ward.js +215 -363
  86. package/package.json +19 -33
  87. package/src/being/being.ts +31 -78
  88. package/src/being/digest.ts +7 -35
  89. package/src/being/faculty.ts +66 -0
  90. package/src/being/index.ts +5 -6
  91. package/src/being/types.ts +47 -145
  92. package/src/being/words.ts +31 -0
  93. package/src/contract/index.ts +44 -0
  94. package/src/crypto/aes.ts +26 -0
  95. package/src/crypto/bytes.ts +37 -0
  96. package/src/crypto/ed25519.ts +84 -0
  97. package/src/crypto/hash.ts +14 -0
  98. package/src/crypto/index.ts +10 -0
  99. package/src/crypto/json.ts +241 -0
  100. package/src/crypto/mlkem.ts +38 -0
  101. package/src/crypto/subtle.ts +33 -0
  102. package/src/crypto/x25519.ts +21 -0
  103. package/src/folder/index.ts +134 -0
  104. package/src/harbor/dock.ts +101 -0
  105. package/src/harbor/harbor.ts +105 -0
  106. package/src/harbor/index.ts +5 -19
  107. package/src/harbor/registry.ts +20 -0
  108. package/src/harbor/terrain.ts +13 -0
  109. package/src/index.ts +20 -0
  110. package/src/pointer/bodies.ts +47 -0
  111. package/src/pointer/index.ts +4 -0
  112. package/src/pointer/world.ts +91 -0
  113. package/src/quo/door.ts +178 -0
  114. package/src/quo/index.ts +11 -0
  115. package/src/quo/invitation.ts +15 -0
  116. package/src/quo/keys.ts +91 -0
  117. package/src/quo/payload.ts +61 -0
  118. package/src/quo/relations.ts +62 -0
  119. package/src/quo/reply.ts +38 -0
  120. package/src/quo/seal.ts +101 -0
  121. package/src/quo/standing.ts +111 -0
  122. package/src/stand/main.ts +19 -0
  123. package/src/stand/stand.ts +178 -0
  124. package/src/ward/allowance.ts +37 -75
  125. package/src/ward/cells.ts +63 -176
  126. package/src/ward/index.ts +6 -17
  127. package/src/ward/partition.ts +86 -326
  128. package/src/ward/stance.ts +185 -420
  129. package/src/ward/ward-being.ts +97 -0
  130. package/src/ward/ward.ts +229 -363
  131. package/dist/being/lent.d.ts +0 -32
  132. package/dist/being/lent.js +0 -72
  133. package/dist/being/silence.d.ts +0 -12
  134. package/dist/being/silence.js +0 -41
  135. package/dist/conformance/assert.d.ts +0 -11
  136. package/dist/conformance/assert.js +0 -106
  137. package/dist/conformance/beings.d.ts +0 -199
  138. package/dist/conformance/beings.js +0 -188
  139. package/dist/conformance/estate.d.ts +0 -5
  140. package/dist/conformance/estate.js +0 -388
  141. package/dist/conformance/index.d.ts +0 -80
  142. package/dist/conformance/index.js +0 -819
  143. package/dist/conformance/reach.d.ts +0 -10
  144. package/dist/conformance/reach.js +0 -72
  145. package/dist/conformance/store.d.ts +0 -5
  146. package/dist/conformance/store.js +0 -113
  147. package/dist/harbor/box.d.ts +0 -121
  148. package/dist/harbor/box.js +0 -121
  149. package/dist/harbor/core.d.ts +0 -55
  150. package/dist/harbor/core.js +0 -662
  151. package/dist/harbor/dial.d.ts +0 -9
  152. package/dist/harbor/dial.js +0 -81
  153. package/dist/harbor/memory.d.ts +0 -29
  154. package/dist/harbor/memory.js +0 -104
  155. package/dist/harbor/reach.d.ts +0 -36
  156. package/dist/harbor/reach.js +0 -199
  157. package/dist/harbor/store.d.ts +0 -35
  158. package/dist/harbor/store.js +0 -62
  159. package/dist/vector/cases.d.ts +0 -42
  160. package/dist/vector/cases.js +0 -223
  161. package/dist/vector/index.d.ts +0 -6
  162. package/dist/vector/index.js +0 -8
  163. package/dist/vector/stand.d.ts +0 -9
  164. package/dist/vector/stand.js +0 -77
  165. package/dist/vector/world.d.ts +0 -144
  166. package/dist/vector/world.js +0 -209
  167. package/dist/ward/arithmetic.d.ts +0 -31
  168. package/dist/ward/arithmetic.js +0 -249
  169. package/dist/ward/door.d.ts +0 -18
  170. package/dist/ward/door.js +0 -186
  171. package/dist/ward/ground.d.ts +0 -29
  172. package/dist/ward/ground.js +0 -56
  173. package/dist/ward/heirs.d.ts +0 -13
  174. package/dist/ward/heirs.js +0 -117
  175. package/dist/ward/json.d.ts +0 -2
  176. package/dist/ward/json.js +0 -163
  177. package/dist/ward/owner.d.ts +0 -13
  178. package/dist/ward/owner.js +0 -220
  179. package/dist/ward/seal.d.ts +0 -52
  180. package/dist/ward/seal.js +0 -150
  181. package/src/being/lent.ts +0 -72
  182. package/src/being/silence.ts +0 -46
  183. package/src/conformance/assert.ts +0 -100
  184. package/src/conformance/beings.ts +0 -188
  185. package/src/conformance/estate.ts +0 -412
  186. package/src/conformance/index.ts +0 -965
  187. package/src/conformance/reach.ts +0 -83
  188. package/src/conformance/store.ts +0 -125
  189. package/src/harbor/box.ts +0 -131
  190. package/src/harbor/core.ts +0 -699
  191. package/src/harbor/dial.ts +0 -112
  192. package/src/harbor/memory.ts +0 -123
  193. package/src/harbor/reach.ts +0 -221
  194. package/src/harbor/store.ts +0 -91
  195. package/src/vector/cases.ts +0 -257
  196. package/src/vector/index.ts +0 -11
  197. package/src/vector/stand.ts +0 -76
  198. package/src/vector/world.ts +0 -232
  199. package/src/ward/arithmetic.ts +0 -251
  200. package/src/ward/door.ts +0 -186
  201. package/src/ward/ground.ts +0 -142
  202. package/src/ward/heirs.ts +0 -116
  203. package/src/ward/json.ts +0 -144
  204. package/src/ward/owner.ts +0 -214
  205. package/src/ward/seal.ts +0 -178
@@ -0,0 +1,178 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The door: an ask's box in, a reply's box out, judged by the thirteen cases
3
+ // of the spec in their order. A stranger hears one silence whatever the
4
+ // case. The case is handed back beside the bytes, for the kit's own eyes,
5
+ // with `heard`: whether a key the door holds or keeps spoke.
6
+ import { decapsulate, hex, unhex, utf8, x25519Public, zero } from '../crypto/index.ts';
7
+ import { drawLock, SigningKey, type Draw, type WardKey } from './keys.ts';
8
+ import type { Invitation } from './invitation.ts';
9
+ import { readPayload, type Payload } from './payload.ts';
10
+ import type { HeirRecord, Keys, Relations } from './relations.ts';
11
+ import { writeReply, type Reply } from './reply.ts';
12
+ import { checkBody, follow, HEAD, knockEdge, openBody, openHead, replyKey, sealReply, signBody, SIZE, splitBody, splitKnock, ZERO_EDGE, type OpenedHead, type ReplyKey } from './seal.ts';
13
+
14
+ // The count numbers below the highest a door still honours: those within
15
+ // this span that it has not seen.
16
+ export const SPAN = 64;
17
+
18
+ export type Choice = { readonly object: string; readonly seen: string | null } | { readonly silence: true };
19
+
20
+ // What stands behind the door. `zero` says whether anything answers the
21
+ // zero head.
22
+ export interface Behind {
23
+ readonly zero: boolean;
24
+ answer(heir: string | null, payload: Payload): Promise<Choice>;
25
+ }
26
+
27
+ export type Judged = { bytes: Uint8Array; case: number; heard: boolean };
28
+
29
+ type Body = { edge: Uint8Array; text: Uint8Array; signature: Uint8Array };
30
+
31
+ export class Door {
32
+ readonly key: WardKey;
33
+ readonly relations: Relations;
34
+ readonly behind: Behind;
35
+ readonly draw: Draw;
36
+
37
+ constructor(key: WardKey, relations: Relations, behind: Behind, draw: Draw) {
38
+ this.key = key;
39
+ this.relations = relations;
40
+ this.behind = behind;
41
+ this.draw = draw;
42
+ }
43
+
44
+ // A new heir, held fresh, and its invitation. The lock is drawn at the
45
+ // first invitation that names a heir, before the heir's secret.
46
+ async invite(): Promise<{ heir: string; invitation: Invitation }> {
47
+ let lock = this.relations.lock();
48
+ if (!lock) this.relations.setLock((lock = drawLock(this.draw)));
49
+ const heir = await SigningKey.draw(this.draw);
50
+ this.relations.set(heir.id, { state: 'fresh' });
51
+ return { heir: heir.id, invitation: { ward: this.key.pk, heir: heir.id, secret: hex(heir.secret), lock: hex(lock.ek) } };
52
+ }
53
+
54
+ // The door stops holding a heir. A fresh one leaves nothing, a spent one
55
+ // leaves the keys kept at removal.
56
+ remove(heir: string): boolean {
57
+ const record = this.relations.get(heir);
58
+ if (record === undefined || record.state === 'kept') return false;
59
+ if (record.state === 'fresh') this.relations.delete(heir);
60
+ else this.relations.set(heir, { state: 'kept', held: record.held, vouched: record.vouched, open: record.open, offered: record.offered });
61
+ return true;
62
+ }
63
+
64
+ async arrive(bytes: Uint8Array): Promise<Judged> {
65
+ const stranger = async (n: number): Promise<Judged> => ({ bytes: await this.#silence(bytes), case: n, heard: false });
66
+ if (bytes.length > SIZE || bytes.length < HEAD) return stranger(1);
67
+ const agreement = await this.key.open(bytes.subarray(0, HEAD));
68
+ const opened = agreement && (await openHead(bytes, agreement));
69
+ if (!opened) return stranger(1);
70
+ const isZero = zero(opened.head);
71
+ const heir = hex(opened.head);
72
+ const record = isZero ? undefined : this.relations.get(heir);
73
+ const body = await this.#body(opened, record);
74
+ if (!body) return stranger(1);
75
+ const read = readPayload(body.text);
76
+ if ('fault' in read) return stranger(read.fault === 'not an object' ? 2 : 3);
77
+ const p = read.payload;
78
+ if (isZero ? p.to !== null : p.to !== heir) return stranger(3);
79
+
80
+ if (isZero) {
81
+ if (!this.behind.zero) return stranger(4);
82
+ if (!(await checkBody(unhex(p.by), body))) return stranger(5);
83
+ const choice = await this.#choose(null, p);
84
+ return { bytes: await this.#sealed(opened, choice), case: 'object' in choice ? 12 : 13, heard: false };
85
+ }
86
+
87
+ if (record === undefined) return stranger(6);
88
+ if (!admits(record, heir, p.by)) return stranger(7);
89
+ if (!(await checkBody(unhex(p.by), body))) return stranger(8);
90
+ const reply = await replyKey(this.draw, opened.lid);
91
+ if (!reply) return stranger(1);
92
+ const offered = await follow(body.edge, reply.agreement);
93
+
94
+ // Checked again, since another arrival may have moved the keys while
95
+ // this one was checking its signature.
96
+ const now = this.relations.get(heir);
97
+ if (now === undefined || !admits(now, heir, p.by) || !opensUnder(now, body.edge)) return stranger(7);
98
+ if (now.state === 'kept') return this.#heard(reply, { quo: 'removed' }, 9);
99
+ if (now.state === 'fresh' && (p.next === null || p.next === heir)) return this.#heard(reply, { quo: 'unannounced' }, 10);
100
+ if (now.state === 'spent' && !honours(now, p.seq)) return this.#heard(reply, { quo: 'repeated' }, 11);
101
+
102
+ this.relations.set(heir, move(now, heir, p, hex(body.edge), hex(offered)));
103
+ const choice = await this.#choose(heir, p);
104
+ const kept = await this.relations.kept().catch(() => false);
105
+ return this.#heard(reply, kept ? choice : { silence: true }, kept && 'object' in choice ? 12 : 13);
106
+ }
107
+
108
+ async #heard(key: ReplyKey, reply: Reply, n: number): Promise<Judged> {
109
+ return { bytes: await sealReply(key, await this.#signed(reply)), case: n, heard: true };
110
+ }
111
+
112
+ #signed(reply: Reply): Promise<Uint8Array> {
113
+ return signBody(utf8(writeReply(reply)), this.key.signing);
114
+ }
115
+
116
+ async #choose(heir: string | null, p: Payload): Promise<Choice> {
117
+ try {
118
+ return await this.behind.answer(heir, p);
119
+ } catch {
120
+ return { silence: true };
121
+ }
122
+ }
123
+
124
+ async #sealed(opened: OpenedHead, reply: Reply): Promise<Uint8Array> {
125
+ const key = await replyKey(this.draw, opened.lid);
126
+ return key ? sealReply(key, await this.#signed(reply)) : this.#silence(opened.lid);
127
+ }
128
+
129
+ // The body, opened under the edge keys the door takes for this head.
130
+ async #body(opened: OpenedHead, record: HeirRecord | undefined): Promise<Body | null> {
131
+ const tries: { edge: Uint8Array; sealed: Uint8Array }[] = [];
132
+ if (record?.state === 'fresh') {
133
+ const knock = splitKnock(opened.rest);
134
+ const lock = this.relations.lock();
135
+ const shared = knock && lock ? decapsulate(lock.dk, knock.ciphertext) : null;
136
+ if (!knock || !shared) return null;
137
+ tries.push({ edge: await knockEdge(shared), sealed: knock.sealedBody });
138
+ } else if (record === undefined) tries.push({ edge: ZERO_EDGE, sealed: opened.rest });
139
+ else for (const edge of [record.open, record.offered]) tries.push({ edge: unhex(edge), sealed: opened.rest });
140
+ for (const { edge, sealed } of tries) {
141
+ const plain = await openBody(opened, edge, sealed);
142
+ if (plain === null) continue;
143
+ const body = splitBody(plain);
144
+ return body && { edge, ...body };
145
+ }
146
+ return null;
147
+ }
148
+
149
+ // A stranger's silence: sealed to the first thirty-two bytes that arrived
150
+ // when they take a seal, and otherwise to a lid nobody holds.
151
+ async #silence(arrived: Uint8Array): Promise<Uint8Array> {
152
+ const text = await this.#signed({ silence: true });
153
+ const candidates = [arrived.length >= HEAD ? arrived.subarray(0, HEAD) : null, this.draw(HEAD)];
154
+ for (const lid of candidates) {
155
+ const key = lid && (await replyKey(this.draw, lid));
156
+ if (key) return sealReply(key, text);
157
+ }
158
+ return sealReply((await replyKey(this.draw, await x25519Public(this.draw(HEAD))))!, text);
159
+ }
160
+ }
161
+
162
+ const admits = (record: HeirRecord, heir: string, by: string): boolean => (record.state === 'fresh' ? by === heir : by === record.held || by === record.vouched);
163
+
164
+ const opensUnder = (record: HeirRecord, edge: Uint8Array): boolean => record.state === 'fresh' || hex(edge) === record.open || hex(edge) === record.offered;
165
+
166
+ const honours = (record: { highest: number; honoured: readonly number[] }, seq: number): boolean =>
167
+ seq > record.highest || (seq > record.highest - SPAN && seq !== record.highest && !record.honoured.includes(seq));
168
+
169
+ // The move tables: the keys and edge keys after a choice, and the count.
170
+ const move = (record: HeirRecord, heir: string, p: Payload, edge: string, offered: string): HeirRecord => {
171
+ const announced = p.next !== null && p.next !== heir && p.next !== p.by ? p.next : null;
172
+ if (record.state === 'fresh') return { state: 'spent', held: announced!, vouched: null, open: edge, offered, highest: p.seq, honoured: [] };
173
+ if (record.state !== 'spent') return record;
174
+ if (p.seq < record.highest) return { ...record, honoured: [...record.honoured, p.seq] };
175
+ const keys: Keys = p.by === record.held ? { held: record.held, vouched: announced ?? record.vouched, open: edge, offered } : { held: p.by, vouched: announced, open: edge, offered };
176
+ const honoured = [...record.honoured, record.highest].filter((n) => n > p.seq - SPAN);
177
+ return { state: 'spent', ...keys, highest: p.seq, honoured };
178
+ };
@@ -0,0 +1,11 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // Quo's wire: keys, the invitation, the payload, the reply, the boxes, the
3
+ // door and the standing. It knows no being, no ward and no terrain.
4
+ export { Door, SPAN, type Behind, type Choice, type Judged } from './door.ts';
5
+ export { readInvitation, type Invitation } from './invitation.ts';
6
+ export { Ephemeral, SigningKey, WardKey, type Draw } from './keys.ts';
7
+ export { readPayload, writePayload, type Payload } from './payload.ts';
8
+ export { GONE, keptLock, lockOf, MemoryRelations, type HeirRecord, type KeptLock, type Relations } from './relations.ts';
9
+ export { readReply, SILENCE, WORDS, writeReply, type Reply, type Word } from './reply.ts';
10
+ export { SIZE } from './seal.ts';
11
+ export { freshStanding, Standing, type Read, type Sent, type StandingState } from './standing.ts';
@@ -0,0 +1,15 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The invitation: `{ ward, heir, secret, lock }`, a value with no route.
3
+ import { EK, encapsulate, isHex, unhex } from '../crypto/index.ts';
4
+
5
+ export type Invitation = { readonly ward: string; readonly heir: string; readonly secret: string; readonly lock: string };
6
+
7
+ // An invitation, or null for any other shape. A field beside the four is
8
+ // ignored, and the lock is held to the modulus check.
9
+ export const readInvitation = (value: unknown): Invitation | null => {
10
+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return null;
11
+ const { ward, heir, secret, lock } = value as Record<string, unknown>;
12
+ if (!isHex(ward, 64) || !isHex(heir, 32) || !isHex(secret, 32) || !isHex(lock, EK)) return null;
13
+ if (encapsulate(unhex(lock), new Uint8Array(32)) === null) return null;
14
+ return { ward, heir, secret, lock };
15
+ };
@@ -0,0 +1,91 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The keys of Quo: the ward key derived from a seed, and every other key
3
+ // drawn. A draw is the caller's, so this layer names no source of bytes.
4
+ import { agree, ed25519Public, hex, hkdf, lockFrom, sha256, utf8, x25519Public, type Lock } from '../crypto/index.ts';
5
+
6
+ // Drawn bytes, from whatever the caller's terrain gives.
7
+ export type Draw = (length: number) => Uint8Array;
8
+
9
+ export const LABEL = {
10
+ seal: utf8('quo-seal'),
11
+ edgeSeal: utf8('quo-edge-seal'),
12
+ lock: utf8('quo-lock'),
13
+ edge: utf8('quo-edge'),
14
+ wardSign: utf8('quo-ward-sign'),
15
+ wardSeal: utf8('quo-ward-seal'),
16
+ } as const;
17
+
18
+ // An Ed25519 pair: a heir, or a standing's own key.
19
+ export class SigningKey {
20
+ readonly secret: Uint8Array;
21
+ readonly pk: Uint8Array;
22
+ private constructor(secret: Uint8Array, pk: Uint8Array) {
23
+ this.secret = secret;
24
+ this.pk = pk;
25
+ }
26
+ static async from(secret: Uint8Array): Promise<SigningKey> {
27
+ return new SigningKey(secret, await ed25519Public(secret));
28
+ }
29
+ static draw(draw: Draw): Promise<SigningKey> {
30
+ return SigningKey.from(draw(32));
31
+ }
32
+ get id(): string {
33
+ return hex(this.pk);
34
+ }
35
+ }
36
+
37
+ // An X25519 pair used for one box.
38
+ export class Ephemeral {
39
+ readonly secret: Uint8Array;
40
+ readonly pk: Uint8Array;
41
+ private constructor(secret: Uint8Array, pk: Uint8Array) {
42
+ this.secret = secret;
43
+ this.pk = pk;
44
+ }
45
+ static async from(secret: Uint8Array): Promise<Ephemeral> {
46
+ return new Ephemeral(secret, await x25519Public(secret));
47
+ }
48
+ static draw(draw: Draw): Promise<Ephemeral> {
49
+ return Ephemeral.from(draw(32));
50
+ }
51
+ agree(pk: Uint8Array): Promise<Uint8Array | null> {
52
+ return agree(this.secret, pk);
53
+ }
54
+ }
55
+
56
+ // The ward key: a signing pair and a padlock, both from the seed.
57
+ export class WardKey {
58
+ readonly signing: SigningKey;
59
+ readonly sealSecret: Uint8Array;
60
+ readonly padlock: Uint8Array;
61
+ private constructor(signing: SigningKey, sealSecret: Uint8Array, padlock: Uint8Array) {
62
+ this.signing = signing;
63
+ this.sealSecret = sealSecret;
64
+ this.padlock = padlock;
65
+ }
66
+
67
+ // Thirty-two bytes are the seed. Text, and bytes of any other length, are
68
+ // hashed to it first.
69
+ static async from(seed: Uint8Array | string): Promise<WardKey> {
70
+ const bytes = typeof seed === 'string' ? await sha256(utf8(seed)) : seed.length === 32 ? seed : await sha256(seed);
71
+ const sealSecret = await hkdf(bytes, LABEL.wardSeal, 32);
72
+ return new WardKey(await SigningKey.from(await hkdf(bytes, LABEL.wardSign, 32)), sealSecret, await x25519Public(sealSecret));
73
+ }
74
+
75
+ get pk(): string {
76
+ return hex(this.signing.pk) + hex(this.padlock);
77
+ }
78
+
79
+ open(lid: Uint8Array): Promise<Uint8Array | null> {
80
+ return agree(this.sealSecret, lid);
81
+ }
82
+ }
83
+
84
+ // A ward pk's two halves.
85
+ export const wardHalves = (pk: string): { signing: string; padlock: string } => ({ signing: pk.slice(0, 64), padlock: pk.slice(64) });
86
+
87
+ // A lock from sixty-four drawn bytes.
88
+ export const drawLock = (draw: Draw): Lock => {
89
+ const bytes = draw(64);
90
+ return lockFrom(bytes.subarray(0, 32), bytes.subarray(32));
91
+ };
@@ -0,0 +1,61 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The payload: `{ to, by, next, seq, method?, args? }`. `args` is carried as
3
+ // the text it was written in, since Quo reads nothing inside it.
4
+ import { isCount, isHex, readObject } from '../crypto/index.ts';
5
+
6
+ export type Payload = {
7
+ readonly to: string | null;
8
+ readonly by: string;
9
+ readonly next: string | null;
10
+ readonly seq: number;
11
+ readonly method?: string;
12
+ readonly args?: string;
13
+ };
14
+
15
+ const OWED = ['to', 'by', 'next', 'seq'];
16
+ const ZERO = '0'.repeat(64);
17
+ const isPk = (text: string): boolean => isHex(text, 32) && text !== ZERO;
18
+
19
+ // A pk written as a JSON string, or null written as null.
20
+ const pkOrNull = (text: string, nullable: boolean): string | null | undefined => {
21
+ if (nullable && text === 'null') return null;
22
+ if (!/^"[0-9a-f]{64}"$/.test(text)) return undefined;
23
+ const pk = text.slice(1, -1);
24
+ return isPk(pk) ? pk : undefined;
25
+ };
26
+
27
+ export const writePayload = (p: Payload): string => {
28
+ const parts = [`"to":${JSON.stringify(p.to)}`, `"by":"${p.by}"`, `"next":${JSON.stringify(p.next)}`, `"seq":${p.seq}`];
29
+ if (p.method !== undefined) parts.push(`"method":${JSON.stringify(p.method)}`);
30
+ if (p.args !== undefined) parts.push(`"args":${p.args}`);
31
+ return `{${parts.join(',')}}`;
32
+ };
33
+
34
+ export type PayloadRead = { payload: Payload } | { fault: 'not an object' | 'not well formed' };
35
+
36
+ // Cases 2 and 3 of the door, before the head is compared.
37
+ export const readPayload = (bytes: Uint8Array): PayloadRead => {
38
+ const fields = readObject(bytes);
39
+ if (fields === null) return { fault: 'not an object' };
40
+ const bad = { fault: 'not well formed' } as const;
41
+ if (!OWED.every((f) => fields.has(f))) return bad;
42
+ const to = pkOrNull(fields.get('to')!, true);
43
+ const by = pkOrNull(fields.get('by')!, false);
44
+ const next = pkOrNull(fields.get('next')!, true);
45
+ const seq = fields.get('seq')!;
46
+ if (to === undefined || !by || next === undefined || !isCount(seq)) return bad;
47
+ const method = fields.get('method');
48
+ if (method !== undefined && !method.startsWith('"')) return bad;
49
+ const args = fields.get('args');
50
+ if (args !== undefined && !args.startsWith('{')) return bad;
51
+ return {
52
+ payload: {
53
+ to,
54
+ by,
55
+ next,
56
+ seq: Number(seq),
57
+ ...(method === undefined ? {} : { method: JSON.parse(method) as string }),
58
+ ...(args === undefined ? {} : { args }),
59
+ },
60
+ };
61
+ };
@@ -0,0 +1,62 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // What a door keeps: its lock, and for each heir it holds the keys and the
3
+ // count of the spec's relation chapter. Keys are written as hex, so a record
4
+ // is a value any memory can keep.
5
+ import type { Lock } from '../crypto/index.ts';
6
+ import { hex, unhex } from '../crypto/index.ts';
7
+
8
+ export type Keys = { readonly held: string; readonly vouched: string | null; readonly open: string; readonly offered: string };
9
+
10
+ export type HeirRecord =
11
+ | { readonly state: 'fresh' }
12
+ | ({ readonly state: 'spent'; readonly highest: number; readonly honoured: readonly number[] } & Keys)
13
+ | ({ readonly state: 'kept' } & Keys);
14
+
15
+ export type KeptLock = { readonly ek: string; readonly dk: string };
16
+
17
+ // The door's memory. A ward stands it on its partition; `MemoryRelations`
18
+ // is the one that lives in an object.
19
+ export interface Relations {
20
+ lock(): Lock | undefined;
21
+ setLock(lock: Lock): void;
22
+ get(heir: string): HeirRecord | undefined;
23
+ set(heir: string, record: HeirRecord): void;
24
+ delete(heir: string): void;
25
+ // Whether what was written during an arrival is kept, asked once before
26
+ // the reply is sealed.
27
+ kept(): Promise<boolean>;
28
+ }
29
+
30
+ export const lockOf = (kept: KeptLock | undefined): Lock | undefined => (kept ? { ek: unhex(kept.ek), dk: unhex(kept.dk) } : undefined);
31
+ export const keptLock = (lock: Lock): KeptLock => ({ ek: hex(lock.ek), dk: hex(lock.dk) });
32
+
33
+ // A bound on the kept records of removed relations, oldest out.
34
+ export const GONE = 256;
35
+
36
+ export class MemoryRelations implements Relations {
37
+ #lock: KeptLock | undefined;
38
+ readonly #heirs = new Map<string, HeirRecord>();
39
+ readonly #gone: string[] = [];
40
+
41
+ lock(): Lock | undefined {
42
+ return lockOf(this.#lock);
43
+ }
44
+ setLock(lock: Lock): void {
45
+ this.#lock = keptLock(lock);
46
+ }
47
+ get(heir: string): HeirRecord | undefined {
48
+ return this.#heirs.get(heir);
49
+ }
50
+ set(heir: string, record: HeirRecord): void {
51
+ this.#heirs.set(heir, record);
52
+ if (record.state !== 'kept') return;
53
+ this.#gone.push(heir);
54
+ while (this.#gone.length > GONE) this.#heirs.delete(this.#gone.shift()!);
55
+ }
56
+ delete(heir: string): void {
57
+ this.#heirs.delete(heir);
58
+ }
59
+ kept(): Promise<boolean> {
60
+ return Promise.resolve(true);
61
+ }
62
+ }
@@ -0,0 +1,38 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The reply text: `{ object, seen }`, `{ silence: true }` or `{ quo: word }`.
3
+ // `object` is carried as the text it was written in.
4
+ import { readObject } from '../crypto/index.ts';
5
+
6
+ export const WORDS = ['removed', 'unannounced', 'repeated'] as const;
7
+ export type Word = (typeof WORDS)[number];
8
+
9
+ export type Reply = { readonly object: string; readonly seen: string | null } | { readonly silence: true } | { readonly quo: Word };
10
+
11
+ export const SILENCE = '{"silence":true}';
12
+
13
+ export const writeReply = (reply: Reply): string => {
14
+ if ('silence' in reply) return SILENCE;
15
+ if ('quo' in reply) return `{"quo":"${reply.quo}"}`;
16
+ return `{"object":${reply.object},"seen":${JSON.stringify(reply.seen)}}`;
17
+ };
18
+
19
+ const exactly = (fields: ReadonlyMap<string, string>, ...keys: string[]): boolean => fields.size === keys.length && keys.every((k) => fields.has(k));
20
+
21
+ // A reply text of one of the three shapes, or null for anything else, which
22
+ // the reader takes as silence.
23
+ export const readReply = (bytes: Uint8Array): Reply | null => {
24
+ const fields = readObject(bytes);
25
+ if (fields === null) return null;
26
+ if (exactly(fields, 'silence')) return fields.get('silence') === 'true' ? { silence: true } : null;
27
+ if (exactly(fields, 'quo')) {
28
+ const text = fields.get('quo')!;
29
+ const word = text.startsWith('"') ? (JSON.parse(text) as string) : null;
30
+ return WORDS.find((w) => w === word) ? { quo: word as Word } : null;
31
+ }
32
+ if (exactly(fields, 'object', 'seen')) {
33
+ const seen = fields.get('seen')!;
34
+ if (seen === 'null') return { object: fields.get('object')!, seen: null };
35
+ return seen.startsWith('"') ? { object: fields.get('object')!, seen: JSON.parse(seen) as string } : null;
36
+ }
37
+ return null;
38
+ };
@@ -0,0 +1,101 @@
1
+ // SPDX-License-Identifier: Apache-2.0
2
+ // The three boxes and the keys between them.
3
+ //
4
+ // ask box lid (32) || AES( head ) || AES( body )
5
+ // knock box lid (32) || AES( head ) || ML-KEM ciphertext (1088) || AES( body )
6
+ // reply box ephemeral pk (32) || AES( body )
7
+ // body JSON text || signature (64)
8
+ //
9
+ // The head of an ask and the body of a reply are sealed under `quo-seal`
10
+ // over the agreement. The body of an ask is sealed under `quo-edge-seal`
11
+ // over the agreement and then the edge key. Every ciphertext's additional
12
+ // data is its own box's ephemeral pk.
13
+ import { CIPHERTEXT, concat, decrypt, encrypt, hkdf, sign, TAG, verify } from '../crypto/index.ts';
14
+ import { Ephemeral, LABEL, type Draw, type SigningKey } from './keys.ts';
15
+
16
+ export const SIZE = 1_048_576;
17
+ export const HEAD = 32;
18
+ export const SIGNATURE = 64;
19
+ export const SEALED_HEAD = HEAD + TAG;
20
+ export const ZERO_EDGE = new Uint8Array(32);
21
+ export const ZERO_HEAD = new Uint8Array(HEAD);
22
+
23
+ const cipher = async (label: Uint8Array, ...material: Uint8Array[]) => {
24
+ const out = await hkdf(concat(...material), label, 44);
25
+ return { key: out.subarray(0, 32), nonce: out.subarray(32) };
26
+ };
27
+ const seal = async (label: Uint8Array, material: Uint8Array[], lid: Uint8Array, plaintext: Uint8Array) => {
28
+ const { key, nonce } = await cipher(label, ...material);
29
+ return encrypt(key, nonce, lid, plaintext);
30
+ };
31
+ const open = async (label: Uint8Array, material: Uint8Array[], lid: Uint8Array, ciphertext: Uint8Array) => {
32
+ const { key, nonce } = await cipher(label, ...material);
33
+ return decrypt(key, nonce, lid, ciphertext);
34
+ };
35
+
36
+ // A knock's edge key, from the shared secret the lock decapsulates.
37
+ export const knockEdge = (shared: Uint8Array): Promise<Uint8Array> => hkdf(shared, LABEL.lock, 32);
38
+
39
+ // The edge key that follows `edge` after a reply of this agreement.
40
+ export const follow = (edge: Uint8Array, agreement: Uint8Array): Promise<Uint8Array> => hkdf(concat(edge, agreement), LABEL.edge, 32);
41
+
42
+ export const signBody = async (text: Uint8Array, key: SigningKey): Promise<Uint8Array> => concat(text, await sign(key.secret, text));
43
+
44
+ // The text and signature of a body, or null for a body of sixty-four bytes
45
+ // or fewer.
46
+ export const splitBody = (body: Uint8Array): { text: Uint8Array; signature: Uint8Array } | null =>
47
+ body.length <= SIGNATURE ? null : { text: body.subarray(0, -SIGNATURE), signature: body.subarray(-SIGNATURE) };
48
+
49
+ export const checkBody = (pk: Uint8Array, body: { text: Uint8Array; signature: Uint8Array }): Promise<boolean> => verify(pk, body.text, body.signature);
50
+
51
+ // An ask box sealed under `lid` to a padlock, or null for a padlock that
52
+ // takes no seal. `ciphertext` makes it a knock box.
53
+ export const sealAsk = async (lid: Ephemeral, padlock: Uint8Array, head: Uint8Array, edge: Uint8Array, body: Uint8Array, ciphertext?: Uint8Array): Promise<Uint8Array | null> => {
54
+ const agreement = await lid.agree(padlock);
55
+ if (agreement === null) return null;
56
+ const sealedHead = await seal(LABEL.seal, [agreement], lid.pk, head);
57
+ const sealedBody = await seal(LABEL.edgeSeal, [agreement, edge], lid.pk, body);
58
+ return concat(lid.pk, sealedHead, ciphertext ?? new Uint8Array(0), sealedBody);
59
+ };
60
+
61
+ // What a door reads before it knows which edge key to try.
62
+ export type OpenedHead = { lid: Uint8Array; agreement: Uint8Array; head: Uint8Array; rest: Uint8Array };
63
+
64
+ export const openHead = async (bytes: Uint8Array, agreement: Uint8Array): Promise<OpenedHead | null> => {
65
+ if (bytes.length < HEAD + SEALED_HEAD) return null;
66
+ const lid = bytes.subarray(0, HEAD);
67
+ const head = await open(LABEL.seal, [agreement], lid, bytes.subarray(HEAD, HEAD + SEALED_HEAD));
68
+ return head === null ? null : { lid, agreement, head, rest: bytes.subarray(HEAD + SEALED_HEAD) };
69
+ };
70
+
71
+ // A knock's rest split into its ciphertext and sealed body.
72
+ export const splitKnock = (rest: Uint8Array): { ciphertext: Uint8Array; sealedBody: Uint8Array } | null =>
73
+ rest.length < CIPHERTEXT ? null : { ciphertext: rest.subarray(0, CIPHERTEXT), sealedBody: rest.subarray(CIPHERTEXT) };
74
+
75
+ export const openBody = (opened: OpenedHead, edge: Uint8Array, sealedBody: Uint8Array): Promise<Uint8Array | null> =>
76
+ open(LABEL.edgeSeal, [opened.agreement, edge], opened.lid, sealedBody);
77
+
78
+ export type SealedReply = { bytes: Uint8Array; agreement: Uint8Array };
79
+
80
+ // The reply's ephemeral key and its agreement with the lid, drawn before the
81
+ // reply is written, since the edge keys move by that agreement.
82
+ export type ReplyKey = { ephemeral: Ephemeral; agreement: Uint8Array };
83
+
84
+ export const replyKey = async (draw: Draw, lid: Uint8Array): Promise<ReplyKey | null> => {
85
+ const ephemeral = await Ephemeral.draw(draw);
86
+ const agreement = await ephemeral.agree(lid);
87
+ return agreement === null ? null : { ephemeral, agreement };
88
+ };
89
+
90
+ export const sealReply = async (key: ReplyKey, body: Uint8Array): Promise<Uint8Array> =>
91
+ concat(key.ephemeral.pk, await seal(LABEL.seal, [key.agreement], key.ephemeral.pk, body));
92
+
93
+ // A reply's body and agreement, opened with the lid's secret, or null.
94
+ export const openReply = async (bytes: Uint8Array, lid: Ephemeral): Promise<SealedReply | null> => {
95
+ if (bytes.length > SIZE || bytes.length < HEAD + TAG) return null;
96
+ const pk = bytes.subarray(0, HEAD);
97
+ const agreement = await lid.agree(pk);
98
+ if (agreement === null) return null;
99
+ const body = await open(LABEL.seal, [agreement], pk, bytes.subarray(HEAD));
100
+ return body === null ? null : { bytes: body, agreement };
101
+ };