homecubbie-server 0.1.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 (111) hide show
  1. package/LICENSE +75 -0
  2. package/README.md +241 -0
  3. package/dist/crypto.js +135 -0
  4. package/dist/home-network.js +103 -0
  5. package/dist/household.js +912 -0
  6. package/dist/http-server.js +604 -0
  7. package/dist/https-listener.js +92 -0
  8. package/dist/main.js +11 -0
  9. package/dist/quiet-warnings.js +34 -0
  10. package/dist/start.js +104 -0
  11. package/dist/store.js +400 -0
  12. package/dist/web-app.js +138 -0
  13. package/package.json +30 -0
  14. package/web/(now)/index.html +474 -0
  15. package/web/(now)/month.html +474 -0
  16. package/web/+not-found.html +474 -0
  17. package/web/_expo/.routes.json +3 -0
  18. package/web/_expo/static/css/global-31a95f46f0d26533c432758949249e15.css +1 -0
  19. package/web/_expo/static/js/web/entry-0f771d01e242dad2ff9cf31c003ad963.js +2839 -0
  20. package/web/_expo/static/js/web/worker-d922322f88a7f1ead9d277776b9d9ebb.js +22 -0
  21. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/arrow_down.017bc6ba3fc25503e5eb5e53826d48a8.png +0 -0
  22. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/error.d1ea1496f9057eb392d5bbf3732a61b7.png +0 -0
  23. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/file.19eeb73b9593a38f8e9f418337fc7d10.png +0 -0
  24. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/forward.d8b800c443b8972542883e0b9de2bdc6.png +0 -0
  25. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/pkg.ab19f4cbc543357183a20571f68380a3.png +0 -0
  26. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/back-icon-mask.0a328cd9c1afd0afe8e3b1ec5165b1b4.png +0 -0
  27. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/back-icon.35ba0eaec5a4f5ed12ca16fabeae451d.png +0 -0
  28. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55.png +0 -0
  29. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@2x.png +0 -0
  30. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@3x.png +0 -0
  31. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/clear-icon.c94f6478e7ae0cdd9f15de1fcb9e5e55@4x.png +0 -0
  32. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7.png +0 -0
  33. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@2x.png +0 -0
  34. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@3x.png +0 -0
  35. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/close-icon.808e1b1b9b53114ec2838071a7e6daa7@4x.png +0 -0
  36. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/react-navigation/elements/search-icon.286d67d3f74808a60a78d3ebf1a5fb57.png +0 -0
  37. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/sitemap.412dd9275b6b48ad28f5e3d81bb1f626.png +0 -0
  38. package/web/assets/__HomeCubbie/node_modules/expo-router/assets/unmatched.20e71bdf79e3a97bf55fd9e164041578.png +0 -0
  39. package/web/assets/__HomeCubbie/node_modules/expo-sqlite/web/wa-sqlite/wa-sqlite.7ca566fbbc2ec2a172c5aefa63a20f4b.wasm +0 -0
  40. package/web/assets/assets/fonts/BricolageGrotesque_600SemiBold.e5b5fc505484ff3ca24da73cba67c660.ttf +0 -0
  41. package/web/assets/assets/images/icon.51a3d296cef4a538e85170017fc2f169.png +0 -0
  42. package/web/costs/[year].html +474 -0
  43. package/web/costs/index.html +474 -0
  44. package/web/favicon.ico +0 -0
  45. package/web/first-run.html +474 -0
  46. package/web/form/account/bill/edit/[id].html +474 -0
  47. package/web/form/account/bill/new.html +474 -0
  48. package/web/form/account/edit/[id].html +474 -0
  49. package/web/form/account/new.html +474 -0
  50. package/web/form/activity/new.html +474 -0
  51. package/web/form/event/edit/[id].html +474 -0
  52. package/web/form/event/new.html +474 -0
  53. package/web/form/note/edit/[id].html +474 -0
  54. package/web/form/note/new.html +474 -0
  55. package/web/form/person/edit/[id].html +474 -0
  56. package/web/form/person/new.html +474 -0
  57. package/web/form/place/edit/[id].html +474 -0
  58. package/web/form/place/new.html +474 -0
  59. package/web/form/policy/correct/[id].html +474 -0
  60. package/web/form/policy/new.html +474 -0
  61. package/web/form/policy/renew/[id].html +474 -0
  62. package/web/form/policy/term/[id].html +474 -0
  63. package/web/form/schedule/edit/[id].html +474 -0
  64. package/web/form/schedule/new.html +474 -0
  65. package/web/form/task/edit/[id].html +474 -0
  66. package/web/form/task/new.html +474 -0
  67. package/web/form/thing/edit/[id].html +474 -0
  68. package/web/form/thing/new.html +474 -0
  69. package/web/home/about/[category].html +474 -0
  70. package/web/home/about/index.html +474 -0
  71. package/web/home/arrange.html +474 -0
  72. package/web/home/index.html +474 -0
  73. package/web/home/place/[id].html +474 -0
  74. package/web/home/thing/[id].html +474 -0
  75. package/web/homecubbie-web.json +5 -0
  76. package/web/index.html +474 -0
  77. package/web/month.html +474 -0
  78. package/web/records/account/[id].html +474 -0
  79. package/web/records/accounts.html +474 -0
  80. package/web/records/document/[id].html +474 -0
  81. package/web/records/documents.html +474 -0
  82. package/web/records/events.html +474 -0
  83. package/web/records/history.html +474 -0
  84. package/web/records/index.html +474 -0
  85. package/web/records/people.html +474 -0
  86. package/web/records/person/[id].html +474 -0
  87. package/web/records/policies.html +474 -0
  88. package/web/records/policy/[id].html +474 -0
  89. package/web/records/supplies.html +474 -0
  90. package/web/records/year/[year].html +474 -0
  91. package/web/scan/[id].html +474 -0
  92. package/web/scan/index.html +474 -0
  93. package/web/search.html +474 -0
  94. package/web/settings/app-lock.html +474 -0
  95. package/web/settings/backup.html +474 -0
  96. package/web/settings/categories.html +474 -0
  97. package/web/settings/index.html +474 -0
  98. package/web/settings/open-source.html +474 -0
  99. package/web/settings/privacy.html +474 -0
  100. package/web/settings/property.html +474 -0
  101. package/web/settings/recently-deleted.html +474 -0
  102. package/web/settings/reminders.html +474 -0
  103. package/web/settings/restore.html +474 -0
  104. package/web/settings/sharing-guide.html +474 -0
  105. package/web/settings/sharing.html +474 -0
  106. package/web/settings/start-over.html +474 -0
  107. package/web/settings/storage.html +474 -0
  108. package/web/settings/tags.html +474 -0
  109. package/web/settings/who-uses-this-phone.html +474 -0
  110. package/web/tasks/[id].html +474 -0
  111. package/web/tasks/index.html +474 -0
@@ -0,0 +1,912 @@
1
+ /**
2
+ * What the household server does, with no HTTP in it.
3
+ *
4
+ * Every operation here either succeeds or throws a `Refusal` carrying a code
5
+ * the app turns into one plain sentence (board #294, "Test connection names
6
+ * the problem"). The server never interprets the house: it orders blobs it
7
+ * can't read, hands them back, and enforces the handful of rules that need no
8
+ * reading — who may talk to it, which key epoch is current, and which schema
9
+ * version the house is on.
10
+ */
11
+ import { randomUUID } from "node:crypto";
12
+ import { chmodSync, existsSync, readFileSync, writeFileSync } from "node:fs";
13
+ import { join } from "node:path";
14
+ import { exportPrivateKey, generateServerKeyPair, importPhoneKey, importServerKeyPair, linkKey, newSetupCode, open, sha256Hex, transportKey, } from "./crypto.js";
15
+ import { Store } from "./store.js";
16
+ /** Bumped when a phone and a server stop understanding each other: 2 since every key change is signed (#442). */
17
+ export const PROTOCOL = 2;
18
+ /** This server's version, as `package.json` has it; a test keeps the two equal. The setup guide names it (#294). */
19
+ export const SERVER_VERSION = "0.1.0";
20
+ export const LIMITS = {
21
+ /** A wrong setup code this many times prints a new one. */
22
+ claimFailures: 5,
23
+ /** A wrong invite proof this many times deletes the invite. */
24
+ inviteFailures: 5,
25
+ /** How long an invite lives. */
26
+ inviteMaxMs: 10 * 60 * 1000,
27
+ /** A wrong recovery proof this many times shuts the code for `recoveryShutMs`. */
28
+ recoveryFailures: 5,
29
+ /**
30
+ * Shut, not deleted: its id crosses the Wi-Fi when it's used, and someone
31
+ * listening could otherwise throw away the household's only way back.
32
+ */
33
+ recoveryShutMs: 10 * 60 * 1000,
34
+ /** How far a request's clock may be from the server's. */
35
+ clockSkewMs: 5 * 60 * 1000,
36
+ /** How long a used nonce is remembered; must exceed twice `clockSkewMs`. */
37
+ nonceKeepMs: 11 * 60 * 1000,
38
+ /** Change batches returned by one sync. */
39
+ batchesPerSync: 500,
40
+ /** Change batches accepted in one sync. */
41
+ batchesPerPush: 500,
42
+ /** Pieces in one file: 1 MiB each, so 4 GiB. */
43
+ piecesPerFile: 4096,
44
+ };
45
+ const STATUS = {
46
+ "not-set-up": 409,
47
+ "already-set-up": 409,
48
+ "bad-setup-code": 401,
49
+ "bad-proof": 401,
50
+ "unknown-phone": 401,
51
+ removed: 403,
52
+ clock: 401,
53
+ replay: 401,
54
+ "invite-gone": 410,
55
+ "recovery-exists": 409,
56
+ "recovery-shut": 429,
57
+ "app-too-old": 409,
58
+ "copy-first": 409,
59
+ "copy-behind": 409,
60
+ "key-changed": 409,
61
+ "identity-in-use": 409,
62
+ "server-behind": 409,
63
+ "not-found": 404,
64
+ "bad-request": 400,
65
+ "too-large": 413,
66
+ "host-not-allowed": 421,
67
+ };
68
+ export class Refusal extends Error {
69
+ code;
70
+ status;
71
+ details;
72
+ constructor(code, details = {}) {
73
+ super(code);
74
+ this.code = code;
75
+ this.status = STATUS[code];
76
+ this.details = details;
77
+ }
78
+ }
79
+ export const systemClock = { now: () => Date.now() };
80
+ const ID = /^[A-Za-z0-9_-]{16,64}$/;
81
+ export function isId(value) {
82
+ return typeof value === "string" && ID.test(value);
83
+ }
84
+ export class Household {
85
+ store;
86
+ keys;
87
+ clock;
88
+ log;
89
+ constructor(dataDir, options = {}) {
90
+ this.store = new Store(dataDir);
91
+ this.clock = options.clock ?? systemClock;
92
+ this.log = options.log ?? { info: () => undefined };
93
+ this.keys = loadOrCreateKeys(join(dataDir, "server-key"));
94
+ if (!this.isSetUp() && this.store.getMeta("setup_code") === null)
95
+ this.store.setMeta("setup_code", newSetupCode());
96
+ }
97
+ close() {
98
+ this.store.close();
99
+ }
100
+ nowIso() {
101
+ return new Date(this.clock.now()).toISOString();
102
+ }
103
+ isSetUp() {
104
+ return this.store.getMeta("household_id") !== null;
105
+ }
106
+ householdId() {
107
+ const id = this.store.getMeta("household_id");
108
+ if (id === null)
109
+ throw new Refusal("not-set-up");
110
+ return id;
111
+ }
112
+ /** The code printed in the server's own log until a phone claims it. Never sent over the network. */
113
+ setupCode() {
114
+ return this.isSetUp() ? null : this.store.getMeta("setup_code");
115
+ }
116
+ epoch() {
117
+ return this.store.getNumber("epoch", 1);
118
+ }
119
+ schemaVersion() {
120
+ return this.store.getNumber("schema_version", 0);
121
+ }
122
+ /**
123
+ * The oldest version whose changes the house takes (board #452, decision
124
+ * 384): what the phone that put the copy in use said, and never above the
125
+ * house's own. A copy from a phone before it says nothing, and then only the
126
+ * house's own version is taken, as before.
127
+ */
128
+ schemaFloor() {
129
+ const house = this.schemaVersion();
130
+ const floor = this.store.activeCopy()?.schema_floor;
131
+ return floor === null || floor === undefined ? house : Math.min(floor, house);
132
+ }
133
+ hello() {
134
+ return {
135
+ app: "homecubbie",
136
+ protocol: PROTOCOL,
137
+ version: SERVER_VERSION,
138
+ // The server's clock, so "Test connection" can say this phone's is wrong
139
+ // before a proof is refused for it (#294 item 7).
140
+ time: this.clock.now(),
141
+ setUp: this.isSetUp(),
142
+ householdId: this.store.getMeta("household_id"),
143
+ serverKey: this.keys.publicKey.toString("base64url"),
144
+ // The house's database version, which the server holds in clear to
145
+ // order copies and changes. A browser compares its own with it before it
146
+ // spends an invite (#376, #425). 0 until the first copy is in.
147
+ schemaVersion: this.schemaVersion(),
148
+ // The household key's epoch, which already travels in clear beside every
149
+ // change. A phone joining its household again compares it with its own
150
+ // before it spends anything, to know whether it can check the key
151
+ // change (#419 package 2, decision 364). Null until a phone sets it up.
152
+ epoch: this.isSetUp() ? this.epoch() : null,
153
+ // Which phone moved the household here, and which made the key change
154
+ // to the current epoch (#442): a phone joining again says beforehand
155
+ // whether it can check them, and then checks their signatures.
156
+ movedBy: this.movedBy(),
157
+ keyChangedBy: this.isSetUp() ? (this.store.findRekey(this.epoch())?.signed_by ?? null) : null,
158
+ };
159
+ }
160
+ movedBy() {
161
+ const first = this.store.firstRekey();
162
+ return first?.kind === "move" ? first.signed_by : null;
163
+ }
164
+ /** The proof the key change to the current epoch carried, or null: epoch 1 has none (#419 package 2). */
165
+ currentRekeyProof() {
166
+ const row = this.store.findRekey(this.epoch());
167
+ return row === undefined ? null : Buffer.from(row.proof).toString("base64url");
168
+ }
169
+ /**
170
+ * Every key change this server holds, each with its signed statement and
171
+ * its proof, for a phone joining again to check from what it held (#442).
172
+ */
173
+ keyChanges() {
174
+ return this.store.listRekeys().flatMap((row) => row.statement === null || row.signature === null
175
+ ? []
176
+ : [
177
+ {
178
+ epoch: row.epoch,
179
+ statement: row.statement,
180
+ signature: Buffer.from(row.signature).toString("base64url"),
181
+ rekeyProof: Buffer.from(row.proof).toString("base64url"),
182
+ },
183
+ ]);
184
+ }
185
+ /** A phone's link key, for checking its proofs and signing replies to it. */
186
+ linkKeyFor(phone) {
187
+ return linkKey(this.keys, Buffer.from(phone.public_key), this.householdId());
188
+ }
189
+ /**
190
+ * Refuses a phone key that can't make a link key: the wrong length, or a
191
+ * small-order point built so the shared secret would be predictable.
192
+ * OpenSSL refuses those when deriving, so trying is the check.
193
+ */
194
+ requireUsablePhoneKey(phoneKey, householdId) {
195
+ try {
196
+ linkKey(this.keys, phoneKey, householdId);
197
+ }
198
+ catch {
199
+ throw new Refusal("bad-request");
200
+ }
201
+ if (this.store.listPhones().some((phone) => Buffer.from(phone.public_key).equals(phoneKey))) {
202
+ throw new Refusal("identity-in-use");
203
+ }
204
+ }
205
+ /** The phone behind a request, or a refusal saying why there isn't one. */
206
+ requirePhone(phoneId) {
207
+ if (!this.isSetUp())
208
+ throw new Refusal("not-set-up");
209
+ const phone = isId(phoneId) ? this.store.findPhone(phoneId) : undefined;
210
+ if (phone === undefined)
211
+ throw new Refusal("unknown-phone");
212
+ return phone;
213
+ }
214
+ /** Refused for a removed phone. Called after its proof has been checked, so the answer can be signed. */
215
+ requireActive(phone) {
216
+ if (phone.removed_at !== null)
217
+ throw new Refusal("removed");
218
+ this.store.markPhoneSeen(phone.id, this.nowIso());
219
+ }
220
+ checkFresh(timeMs, nonce) {
221
+ const now = this.clock.now();
222
+ if (!Number.isFinite(timeMs) || Math.abs(now - timeMs) > LIMITS.clockSkewMs) {
223
+ throw new Refusal("clock", { serverTime: now });
224
+ }
225
+ if (!this.store.rememberNonce(nonce, now, LIMITS.nonceKeepMs))
226
+ throw new Refusal("replay");
227
+ }
228
+ // ── setting up ────────────────────────────────────────────────────────
229
+ /**
230
+ * The first phone takes the server. The caller has already checked the
231
+ * request's proof against the setup code; this counts a failure when it
232
+ * hasn't, and prints a new code after `LIMITS.claimFailures` of them.
233
+ */
234
+ countClaimFailure() {
235
+ const failures = this.store.getNumber("claim_failures", 0) + 1;
236
+ if (failures >= LIMITS.claimFailures) {
237
+ this.store.setMeta("setup_code", newSetupCode());
238
+ this.store.setMeta("claim_failures", "0");
239
+ this.log.info("Too many wrong setup codes. A new one is below; the old one no longer works.");
240
+ this.printSetupCode();
241
+ }
242
+ else {
243
+ this.store.setMeta("claim_failures", String(failures));
244
+ }
245
+ }
246
+ printSetupCode() {
247
+ const code = this.setupCode();
248
+ if (code !== null)
249
+ this.log.info(`Setup code: ${code.replace(/(.{4})(?=.)/g, "$1-")}`);
250
+ }
251
+ /**
252
+ * A household moving here from a server that was lost (#419 package 2,
253
+ * decision 364) starts at the epoch after its last, with the proof every
254
+ * key change carries: `HMAC` under the data key before (§357). The server
255
+ * can't check it; it keeps it, and a phone joining again that holds the
256
+ * key before checks it, as it checks any key change. A new household
257
+ * starts at 1, with no proof. A move is also signed by the phone that moves
258
+ * it (#442), which the server keeps as it came, as it keeps the proof.
259
+ */
260
+ claim(input) {
261
+ if (this.isSetUp())
262
+ throw new Refusal("already-set-up");
263
+ if (!isId(input.householdId) || !isId(input.phoneId))
264
+ throw new Refusal("bad-request");
265
+ // The phone says which server key it saw. If someone on the Wi-Fi swapped
266
+ // it, the proof covered the swap and this refuses it.
267
+ if (!input.serverKey.equals(this.keys.publicKey))
268
+ throw new Refusal("bad-proof");
269
+ const epoch = input.epoch ?? 1;
270
+ const proof = input.rekeyProof ?? null;
271
+ if (!Number.isInteger(epoch) || epoch < 1)
272
+ throw new Refusal("bad-request");
273
+ // A household's first epoch has no key before it, and every later one has a proof.
274
+ if (epoch === 1 ? proof !== null : proof === null || proof.length !== 32)
275
+ throw new Refusal("bad-request");
276
+ const signed = input.signed ?? null;
277
+ if ((proof === null) !== (signed === null))
278
+ throw new Refusal("bad-request");
279
+ this.requireUsablePhoneKey(input.phoneKey, input.householdId);
280
+ return this.store.transaction(() => {
281
+ this.store.setMeta("household_id", input.householdId);
282
+ this.store.setMeta("epoch", String(epoch));
283
+ if (proof !== null && signed !== null) {
284
+ this.store.insertRekey({ epoch, proof, ...signed, signedBy: input.phoneId, kind: "move" });
285
+ }
286
+ this.store.deleteMeta("setup_code");
287
+ this.store.deleteMeta("claim_failures");
288
+ this.store.insertPhone({
289
+ id: input.phoneId,
290
+ publicKey: input.phoneKey,
291
+ nameBlob: input.nameBlob,
292
+ kind: "phone",
293
+ now: this.nowIso(),
294
+ signingKey: input.signingKey,
295
+ door: null,
296
+ });
297
+ this.log.info("A phone set this server up. The setup code no longer works.");
298
+ return this.requirePhone(input.phoneId);
299
+ });
300
+ }
301
+ // ── invites ───────────────────────────────────────────────────────────
302
+ /**
303
+ * An invite, with the door key its maker worked out from the invite's
304
+ * secret and its maker's vouch for it (#442). Kept as they came: the phones
305
+ * check them, and the server can make neither.
306
+ */
307
+ createInvite(from, input) {
308
+ if (!isId(input.inviteId))
309
+ throw new Refusal("bad-request");
310
+ if (input.expiresInMs <= 0 || input.expiresInMs > LIMITS.inviteMaxMs)
311
+ throw new Refusal("bad-request");
312
+ // The join verifier is the one secret a phone sends the server. It comes
313
+ // sealed under that phone's link key, so the Wi-Fi never sees it.
314
+ let verifier;
315
+ try {
316
+ verifier = open(transportKey(this.linkKeyFor(from)), input.sealedVerifier, `invite ${input.inviteId}`);
317
+ }
318
+ catch {
319
+ throw new Refusal("bad-request");
320
+ }
321
+ if (verifier.length !== 32)
322
+ throw new Refusal("bad-request");
323
+ this.store.deleteExpiredInvites(this.clock.now());
324
+ this.store.insertInvite({
325
+ id: input.inviteId,
326
+ verifier,
327
+ packet: input.packet,
328
+ createdBy: from.id,
329
+ expiresAt: this.clock.now() + input.expiresInMs,
330
+ door: doorOf(input),
331
+ });
332
+ }
333
+ /**
334
+ * The verifier a join's proof is checked against, or a refusal if the invite
335
+ * is gone. The id is an invite's or the recovery code's (#419): the code is
336
+ * an invite with no time limit, so it comes in by the same door.
337
+ */
338
+ inviteVerifier(inviteId) {
339
+ if (!isId(inviteId))
340
+ throw new Refusal("bad-request");
341
+ this.store.deleteExpiredInvites(this.clock.now());
342
+ const invite = this.store.findInvite(inviteId);
343
+ if (invite !== undefined)
344
+ return Buffer.from(invite.verifier);
345
+ const recovery = this.store.findRecoveryById(inviteId);
346
+ if (recovery === undefined)
347
+ throw new Refusal("invite-gone");
348
+ if (recovery.shut_until > this.clock.now())
349
+ throw new Refusal("recovery-shut", { until: recovery.shut_until });
350
+ return Buffer.from(recovery.verifier);
351
+ }
352
+ countJoinFailure(inviteId) {
353
+ if (this.store.findInvite(inviteId) !== undefined) {
354
+ if (this.store.countInviteFailure(inviteId) >= LIMITS.inviteFailures)
355
+ this.store.deleteInvite(inviteId);
356
+ return;
357
+ }
358
+ if (this.store.findRecoveryById(inviteId) === undefined)
359
+ return;
360
+ if (this.store.countRecoveryFailure(inviteId) >= LIMITS.recoveryFailures) {
361
+ this.store.shutRecovery(inviteId, this.clock.now() + LIMITS.recoveryShutMs);
362
+ }
363
+ }
364
+ /**
365
+ * Uses up the invite, or the recovery code: its packet is returned once and
366
+ * deleted. The phone is kept with how it came in (#442): the door, its
367
+ * maker's vouch for it, and the arrival the phone signed with the door's
368
+ * key and with its own.
369
+ */
370
+ join(input) {
371
+ if (!isId(input.phoneId))
372
+ throw new Refusal("bad-request");
373
+ this.requireUsablePhoneKey(input.phoneKey, this.householdId());
374
+ return this.store.transaction(() => {
375
+ const now = this.clock.now();
376
+ const invite = this.store.findInvite(input.inviteId);
377
+ const recovery = invite === undefined ? this.store.findRecoveryById(input.inviteId) : undefined;
378
+ let packet;
379
+ let door;
380
+ if (invite !== undefined && invite.expires_at > now) {
381
+ packet = invite.packet;
382
+ door = invite;
383
+ }
384
+ else if (recovery !== undefined && recovery.shut_until <= now) {
385
+ packet = recovery.packet;
386
+ door = recovery;
387
+ }
388
+ else {
389
+ throw new Refusal("invite-gone");
390
+ }
391
+ if (this.store.findPhone(input.phoneId) !== undefined)
392
+ throw new Refusal("identity-in-use");
393
+ if (invite !== undefined) {
394
+ this.store.deleteInvite(invite.id);
395
+ }
396
+ else {
397
+ // Used once. Every phone's Sharing screen then says when, and which
398
+ // phone came in with it.
399
+ this.store.deleteRecovery();
400
+ this.store.deleteMeta("recovery_ended_at");
401
+ this.store.setMeta("recovery_used_at", this.nowIso());
402
+ this.store.setMeta("recovery_used_by", input.phoneId);
403
+ }
404
+ this.store.insertPhone({
405
+ id: input.phoneId,
406
+ publicKey: input.phoneKey,
407
+ nameBlob: input.nameBlob,
408
+ kind: "phone",
409
+ now: this.nowIso(),
410
+ signingKey: input.signingKey,
411
+ door: arrivalOf(door, input),
412
+ });
413
+ return { phone: this.requirePhone(input.phoneId), packet: Buffer.from(packet) };
414
+ });
415
+ }
416
+ // ── the recovery code ─────────────────────────────────────────────────
417
+ /**
418
+ * Board #419 (decision 362): a recovery code, made by a phone in the
419
+ * household. It is an invite with no time limit, used once through `join`.
420
+ * It is never a phone, nothing is wrapped for it, and any key change deletes
421
+ * it, so its packet always holds the key in force.
422
+ *
423
+ * One at a time. A phone replaces one by changing the key first, which ends
424
+ * the old code, so a code someone may have seen can't stay good.
425
+ */
426
+ createRecovery(from, input) {
427
+ if (!isId(input.recoveryId))
428
+ throw new Refusal("bad-request");
429
+ if (input.epoch !== this.epoch())
430
+ throw new Refusal("key-changed", { epoch: this.epoch() });
431
+ let verifier;
432
+ try {
433
+ verifier = open(transportKey(this.linkKeyFor(from)), input.sealedVerifier, `recovery ${input.recoveryId}`);
434
+ }
435
+ catch {
436
+ throw new Refusal("bad-request");
437
+ }
438
+ if (verifier.length !== 32)
439
+ throw new Refusal("bad-request");
440
+ this.store.transaction(() => {
441
+ if (this.store.findRecovery() !== undefined)
442
+ throw new Refusal("recovery-exists");
443
+ if (this.store.findInvite(input.recoveryId) !== undefined)
444
+ throw new Refusal("bad-request");
445
+ this.store.insertRecovery({
446
+ id: input.recoveryId,
447
+ verifier,
448
+ packet: input.packet,
449
+ epoch: input.epoch,
450
+ createdBy: from.id,
451
+ now: this.nowIso(),
452
+ door: doorOf({ ...input, doorEpoch: input.epoch }),
453
+ });
454
+ this.store.deleteMeta("recovery_used_at");
455
+ this.store.deleteMeta("recovery_used_by");
456
+ this.store.deleteMeta("recovery_ended_at");
457
+ });
458
+ this.log.info("A phone made a recovery code.");
459
+ }
460
+ /** What every phone's Sharing screen says about the recovery code. Never its id, verifier or packet. */
461
+ recoveryStatus() {
462
+ const row = this.store.findRecovery();
463
+ const usedAt = this.store.getMeta("recovery_used_at");
464
+ const endedAt = this.store.getMeta("recovery_ended_at");
465
+ return {
466
+ recovery: row === undefined ? null : { epoch: row.epoch, madeBy: row.created_by, madeAt: row.created_at },
467
+ used: usedAt === null ? null : { at: usedAt, by: this.store.getMeta("recovery_used_by") },
468
+ // A printed code that stopped working at a key change, so every phone
469
+ // can say so (decision 362) rather than "none yet".
470
+ ended: endedAt === null ? null : { at: endedAt },
471
+ };
472
+ }
473
+ /** Any key change, and any removal, ends the recovery code (#419). Recorded, so the phones can say when. */
474
+ endRecovery() {
475
+ if (!this.store.deleteRecovery())
476
+ return;
477
+ this.store.deleteMeta("recovery_used_at");
478
+ this.store.deleteMeta("recovery_used_by");
479
+ this.store.setMeta("recovery_ended_at", this.nowIso());
480
+ }
481
+ /**
482
+ * A phone replaces its own sealed name. A phone that joined by invite can only
483
+ * seal its name once it has opened the invite's packet, after the join.
484
+ */
485
+ renamePhone(phone, nameBlob) {
486
+ this.store.renamePhone(phone.id, nameBlob);
487
+ }
488
+ removePhone(by, phoneId) {
489
+ if (!isId(phoneId))
490
+ throw new Refusal("bad-request");
491
+ const target = this.store.findPhone(phoneId);
492
+ if (target === undefined)
493
+ throw new Refusal("not-found");
494
+ this.store.transaction(() => {
495
+ this.store.removePhone(target.id, this.nowIso());
496
+ this.store.deleteInvitesBy(target.id);
497
+ // A removal ends the recovery code, on this path as in a key change
498
+ // (#419): whoever is removed may have seen it. Leaving doesn't: the
499
+ // phone that leaves deletes its own keys, and the key doesn't change.
500
+ if (by.id !== target.id)
501
+ this.endRecovery();
502
+ });
503
+ this.log.info(by.id === target.id ? "A phone left the household." : "A phone was removed from the household.");
504
+ }
505
+ phones() {
506
+ return this.store.listPhones().map((phone) => ({
507
+ phoneId: phone.id,
508
+ phoneKey: Buffer.from(phone.public_key).toString("base64url"),
509
+ nameBlob: Buffer.from(phone.name_blob).toString("base64url"),
510
+ kind: phone.kind,
511
+ joinedAt: phone.joined_at,
512
+ lastSeenAt: phone.last_seen_at,
513
+ removed: phone.removed_at !== null,
514
+ // What it signed, and how it came in, for the phones to check (#442).
515
+ signingKey: phone.signing_key === null ? null : Buffer.from(phone.signing_key).toString("base64url"),
516
+ door: phone.door === null ? null : JSON.parse(phone.door),
517
+ }));
518
+ }
519
+ // ── changes ───────────────────────────────────────────────────────────
520
+ /**
521
+ * Stores what the phone sent, then returns what it hasn't seen.
522
+ *
523
+ * All of `batches` lands or none of it does. Sending the same batch again
524
+ * is harmless, which is what lets a phone retry after a dropped reply. A
525
+ * different blob under a batch number this phone already used means two
526
+ * installs share one identity — the case an iPhone transfer produces —
527
+ * and is refused rather than silently kept.
528
+ *
529
+ * A batch this server already holds is recognised before its epoch is
530
+ * looked at (#439): one that arrived just before a key change, whose reply
531
+ * was lost, is the same bytes under the old epoch. Refused as `key-changed`
532
+ * it would go again sealed under the new key, as other bytes under its old
533
+ * number, and read as a copied phone. So a request of held batches only is
534
+ * answered as usual, and a `key-changed` refusal names the batches in it
535
+ * this server already holds, for the phone to stop sending rather than
536
+ * seal again.
537
+ */
538
+ sync(phone, input) {
539
+ if (!Number.isInteger(input.since) || input.since < 0)
540
+ throw new Refusal("bad-request");
541
+ if (input.batches.length > LIMITS.batchesPerPush)
542
+ throw new Refusal("too-large");
543
+ const epoch = this.epoch();
544
+ const house = this.schemaVersion();
545
+ const floor = this.schemaFloor();
546
+ const copy = this.store.activeCopy();
547
+ // Changes up to a reset were dropped, and the copy it made is the whole
548
+ // truth. A phone that hasn't loaded that copy yet starts again from it,
549
+ // and what it sends now isn't stored: it was made against a house that no
550
+ // longer exists. The app says so before anyone resets (#292 item 9).
551
+ const droppedThrough = this.store.getNumber("dropped_through", 0);
552
+ const mustLoadCopy = copy !== undefined && (phone.must_reload === 1 || input.since < droppedThrough);
553
+ if (mustLoadCopy)
554
+ return this.syncReply(phone, copy, copy.through_seq, true);
555
+ this.store.transaction(() => {
556
+ const held = [];
557
+ const fresh = new Map();
558
+ for (const batch of input.batches) {
559
+ if (!Number.isInteger(batch.batch) || batch.batch < 1)
560
+ throw new Refusal("bad-request");
561
+ if (!Number.isInteger(batch.schemaVersion) || batch.schemaVersion < 1)
562
+ throw new Refusal("bad-request");
563
+ const hash = sha256Hex(batch.blob);
564
+ const existing = this.store.findChange(phone.id, batch.batch)?.blob_hash ?? fresh.get(batch.batch)?.hash;
565
+ if (existing === undefined)
566
+ fresh.set(batch.batch, { batch, hash });
567
+ else if (existing !== hash)
568
+ throw new Refusal("identity-in-use");
569
+ else if (!fresh.has(batch.batch))
570
+ held.push(batch.batch);
571
+ }
572
+ for (const { batch, hash } of fresh.values()) {
573
+ if (batch.epoch !== epoch)
574
+ throw new Refusal("key-changed", { epoch, held });
575
+ // A phone a version behind keeps sharing, down to the floor (#452).
576
+ if (batch.schemaVersion < floor)
577
+ throw new Refusal("app-too-old", { schemaVersion: house, schemaFloor: floor });
578
+ if (batch.schemaVersion > house)
579
+ throw new Refusal("copy-first", { schemaVersion: house });
580
+ this.store.insertChange({
581
+ phoneId: phone.id,
582
+ batch: batch.batch,
583
+ epoch,
584
+ schemaVersion: batch.schemaVersion,
585
+ blob: batch.blob,
586
+ blobHash: hash,
587
+ now: this.nowIso(),
588
+ });
589
+ }
590
+ });
591
+ // The phone has seen changes this server no longer has: it was restored
592
+ // from an old backup, or its folder was replaced. The server says so
593
+ // rather than quietly numbering new changes over the gap, and the app
594
+ // offers a reset from the phone, whose house is whole (#292 item 12).
595
+ if (input.since > this.store.lastSeq())
596
+ throw new Refusal("server-behind", { lastSeq: this.store.lastSeq() });
597
+ return this.syncReply(phone, copy, input.since, false);
598
+ }
599
+ syncReply(phone, copy, from, mustLoadCopy) {
600
+ const lastSeq = this.store.lastSeq();
601
+ const changes = this.store.changesAfter(from, LIMITS.batchesPerSync);
602
+ const last = changes.at(-1);
603
+ return {
604
+ epoch: this.epoch(),
605
+ schemaVersion: this.schemaVersion(),
606
+ // A phone behind the house reads this to know it may keep sharing (#452).
607
+ schemaFloor: this.schemaFloor(),
608
+ lastSeq,
609
+ // The last batch this server holds from this phone. More than the phone
610
+ // itself has numbered means a second install is using its identity: a
611
+ // phone copied to a new handset by the system's transfer (#292 item 12).
612
+ lastBatch: this.store.lastBatchOf(phone.id),
613
+ copy: copy === undefined ? null : describeCopy(copy),
614
+ mustLoadCopy,
615
+ next: last?.seq ?? from,
616
+ more: last !== undefined && last.seq < lastSeq,
617
+ changes: changes.map((row) => ({
618
+ seq: row.seq,
619
+ phoneId: row.phone_id,
620
+ batch: row.batch,
621
+ epoch: row.epoch,
622
+ schemaVersion: row.schema_version,
623
+ blob: Buffer.from(row.blob).toString("base64url"),
624
+ })),
625
+ };
626
+ }
627
+ // ── full copies ───────────────────────────────────────────────────────
628
+ /**
629
+ * Stores a full copy of the house, not yet in use. It becomes the copy every
630
+ * new phone starts from when `activateCopy` or `changeKey` names it.
631
+ *
632
+ * Only a phone on the house's version makes one: a phone behind it shares,
633
+ * but holds a newer phone's details only as changes waiting for its update
634
+ * (#452), so its copy would leave them out.
635
+ */
636
+ uploadCopy(phone, input) {
637
+ const epoch = this.epoch();
638
+ if (input.epoch !== epoch && input.epoch !== epoch + 1)
639
+ throw new Refusal("key-changed", { epoch });
640
+ if (!Number.isInteger(input.schemaVersion) || input.schemaVersion < this.schemaVersion()) {
641
+ throw new Refusal("app-too-old", { schemaVersion: this.schemaVersion(), schemaFloor: this.schemaFloor() });
642
+ }
643
+ if (!Number.isInteger(input.throughSeq) || input.throughSeq < 0 || input.throughSeq > this.store.lastSeq()) {
644
+ throw new Refusal("bad-request");
645
+ }
646
+ const floor = input.schemaFloor;
647
+ if (floor !== undefined && (!Number.isInteger(floor) || floor < 1 || floor > input.schemaVersion)) {
648
+ throw new Refusal("bad-request");
649
+ }
650
+ const id = randomUUID();
651
+ this.store.writeCopyBytes(id, input.bytes);
652
+ this.store.insertCopy({
653
+ id,
654
+ epoch: input.epoch,
655
+ schema_version: input.schemaVersion,
656
+ through_seq: input.throughSeq,
657
+ byte_size: input.bytes.length,
658
+ phone_id: phone.id,
659
+ schema_floor: floor ?? null,
660
+ now: this.nowIso(),
661
+ });
662
+ return id;
663
+ }
664
+ /**
665
+ * Puts an uploaded copy in use, under the current key. This is how the
666
+ * first phone's house arrives and how an updated app raises the house's
667
+ * schema version. A new phone starts from it; the changes it holds stay,
668
+ * so a phone that hasn't synced lately carries on from where it was.
669
+ */
670
+ activateCopy(copyId) {
671
+ const copy = this.pendingCopy(copyId);
672
+ if (copy.epoch !== this.epoch())
673
+ throw new Refusal("key-changed", { epoch: this.epoch() });
674
+ this.requireCopyPastEarlierKeys(copy);
675
+ this.store.transaction(() => {
676
+ this.store.activateCopy(copy.id);
677
+ this.store.setMeta("schema_version", String(Math.max(copy.schema_version, this.schemaVersion())));
678
+ });
679
+ }
680
+ /**
681
+ * A new household key, after a phone is removed or on "Reset sharing from
682
+ * this phone". It lands in one step with the copy made under it, so no phone
683
+ * ever sees the new epoch without a copy it can read.
684
+ *
685
+ * A reset also drops every change on the server, including other phones'
686
+ * that the copy doesn't hold. The app says so first.
687
+ */
688
+ changeKey(phone, input) {
689
+ const next = this.epoch() + 1;
690
+ if (input.epoch !== next)
691
+ throw new Refusal("key-changed", { epoch: this.epoch() });
692
+ if (input.rekeyProof.length !== 32)
693
+ throw new Refusal("bad-request");
694
+ const copy = this.pendingCopy(input.copyId);
695
+ if (copy.epoch !== next)
696
+ throw new Refusal("bad-request");
697
+ // A reset's copy covers everything there is, whatever it said (below).
698
+ if (!input.reset)
699
+ this.requireCopyPastEarlierKeys(copy);
700
+ let removing;
701
+ if (input.remove !== undefined) {
702
+ if (!isId(input.remove) || input.remove === phone.id)
703
+ throw new Refusal("bad-request");
704
+ removing = this.store.findPhone(input.remove);
705
+ if (removing === undefined || removing.removed_at !== null)
706
+ throw new Refusal("not-found");
707
+ }
708
+ const active = this.store.listPhones().filter((row) => row.removed_at === null && row.id !== removing?.id);
709
+ const wrapped = new Set(input.wraps.map((wrap) => wrap.phoneId));
710
+ // Every phone still in the household must be able to read the new key,
711
+ // or it would be locked out by a phone that forgot it.
712
+ for (const row of active) {
713
+ if (row.id !== phone.id && !wrapped.has(row.id))
714
+ throw new Refusal("bad-request", { missing: row.id });
715
+ }
716
+ for (const wrap of input.wraps) {
717
+ if (!active.some((row) => row.id === wrap.phoneId))
718
+ throw new Refusal("bad-request");
719
+ importPhoneKey(wrap.ephemeralKey);
720
+ }
721
+ this.store.transaction(() => {
722
+ if (removing !== undefined) {
723
+ this.store.removePhone(removing.id, this.nowIso());
724
+ this.store.deleteInvitesBy(removing.id);
725
+ }
726
+ // Any key change ends the recovery code (#419, decision 362). Its packet
727
+ // holds the key before, and nothing is wrapped for it, so it could only
728
+ // be a key someone removed still had.
729
+ this.endRecovery();
730
+ this.store.insertRekey({
731
+ epoch: next,
732
+ proof: input.rekeyProof,
733
+ statement: input.statement,
734
+ signature: input.signature,
735
+ signedBy: phone.id,
736
+ kind: input.reset ? "reset" : "change",
737
+ });
738
+ for (const wrap of input.wraps)
739
+ this.store.insertWrap({ epoch: next, ...wrap });
740
+ this.store.setMeta("epoch", String(next));
741
+ this.store.activateCopy(copy.id);
742
+ this.store.setMeta("schema_version", String(Math.max(copy.schema_version, this.schemaVersion())));
743
+ // Only a reset drops changes: the copy is the whole truth then, and a
744
+ // phone behind it starts again from it. A key change keeps them, sealed
745
+ // under the old key, which every phone still in the household holds.
746
+ if (input.reset) {
747
+ const through = this.store.lastSeq();
748
+ this.store.dropChangesThrough(through);
749
+ this.store.setMeta("dropped_through", String(through));
750
+ // The copy holds everything up to now, whatever the phone said it
751
+ // had seen: after a server restored from a backup, the phone has
752
+ // seen numbers this server never gave out.
753
+ this.store.setCopyThrough(copy.id, through);
754
+ // Every other phone starts again from it, including one that was
755
+ // fully up to date: its house may not be the one this phone reset to.
756
+ this.store.markMustReload(phone.id);
757
+ this.store.clearMustReload(phone.id);
758
+ }
759
+ // Older wraps stay: a phone that missed several key changes walks
760
+ // forward one epoch at a time, checking each against the key before.
761
+ });
762
+ this.log.info(input.reset ? "Sharing was reset from a phone." : "The household key was changed.");
763
+ return { epoch: next, lastSeq: this.store.lastSeq() };
764
+ }
765
+ /**
766
+ * A phone that joins from a copy holds only that copy's key, and reads on
767
+ * from where the copy stops. So a copy must run past every change sealed
768
+ * under a key before its own, or that phone could never open them, and
769
+ * would stop syncing for good (#435). The changes stay: the phones already
770
+ * in the household still hold those keys, and read them.
771
+ */
772
+ requireCopyPastEarlierKeys(copy) {
773
+ const needed = this.store.lastSeqSealedBefore(copy.epoch);
774
+ if (copy.through_seq < needed)
775
+ throw new Refusal("copy-behind", { lastSeq: needed });
776
+ }
777
+ /** A phone has loaded the active copy after a reset, so what it sends counts again. */
778
+ copyLoaded(phone, copyId) {
779
+ const copy = this.store.activeCopy();
780
+ if (copy === undefined || copy.id !== copyId)
781
+ throw new Refusal("not-found");
782
+ this.store.clearMustReload(phone.id);
783
+ }
784
+ /** This phone's wrap of the key at `epoch` (the current one when not given), with that key change's proof. */
785
+ wrapFor(phone, epoch = this.epoch()) {
786
+ if (!Number.isInteger(epoch) || epoch < 1 || epoch > this.epoch())
787
+ throw new Refusal("bad-request");
788
+ const wrap = this.store.findWrap(epoch, phone.id);
789
+ if (wrap === undefined)
790
+ throw new Refusal("not-found");
791
+ const rekey = this.store.findRekey(wrap.epoch);
792
+ return {
793
+ epoch: wrap.epoch,
794
+ current: this.epoch(),
795
+ ephemeralKey: Buffer.from(wrap.ephemeral_key).toString("base64url"),
796
+ blob: Buffer.from(wrap.blob).toString("base64url"),
797
+ rekeyProof: rekey === undefined ? null : Buffer.from(rekey.proof).toString("base64url"),
798
+ // Who made the change, signed, for the phone to check (#442).
799
+ statement: rekey?.statement ?? null,
800
+ signature: rekey?.signature === null || rekey?.signature === undefined ? null : Buffer.from(rekey.signature).toString("base64url"),
801
+ };
802
+ }
803
+ activeCopyBytes() {
804
+ const copy = this.store.activeCopy();
805
+ if (copy === undefined)
806
+ throw new Refusal("not-found");
807
+ return { copy: describeCopy(copy), bytes: this.store.readCopyBytes(copy.id) };
808
+ }
809
+ pendingCopy(copyId) {
810
+ if (typeof copyId !== "string")
811
+ throw new Refusal("bad-request");
812
+ const copy = this.store.findCopy(copyId);
813
+ if (copy === undefined)
814
+ throw new Refusal("not-found");
815
+ return copy;
816
+ }
817
+ // ── files ─────────────────────────────────────────────────────────────
818
+ putPiece(fileId, piece, bytes) {
819
+ requireFileId(fileId);
820
+ requirePiece(piece);
821
+ const file = this.store.findFile(fileId);
822
+ if (file?.pieces != null)
823
+ throw new Refusal("bad-request", { reason: "file-complete" });
824
+ this.store.ensureFile(fileId, this.nowIso());
825
+ this.store.writePiece(fileId, piece, bytes);
826
+ }
827
+ getPiece(fileId, piece) {
828
+ requireFileId(fileId);
829
+ requirePiece(piece);
830
+ const bytes = this.store.readPiece(fileId, piece);
831
+ if (bytes === null)
832
+ throw new Refusal("not-found");
833
+ return bytes;
834
+ }
835
+ /** Marks a file whole once every piece from 0 to `pieces - 1` is stored. */
836
+ completeFile(fileId, pieces) {
837
+ requireFileId(fileId);
838
+ if (!Number.isInteger(pieces) || pieces < 1 || pieces > LIMITS.piecesPerFile) {
839
+ throw new Refusal("bad-request");
840
+ }
841
+ const count = pieces;
842
+ if (this.store.findFile(fileId) === undefined)
843
+ throw new Refusal("not-found");
844
+ const stored = new Set(this.store.storedPieces(fileId));
845
+ for (let piece = 0; piece < count; piece += 1) {
846
+ if (!stored.has(piece))
847
+ throw new Refusal("bad-request", { missingPiece: piece });
848
+ }
849
+ this.store.completeFile(fileId, count);
850
+ }
851
+ fileStatus(fileId) {
852
+ requireFileId(fileId);
853
+ const file = this.store.findFile(fileId);
854
+ if (file === undefined)
855
+ throw new Refusal("not-found");
856
+ return { fileId, complete: file.pieces !== null, pieces: file.pieces, stored: this.store.storedPieces(fileId) };
857
+ }
858
+ /** Only a phone decides a file is no longer needed: the server can't read which records use it. */
859
+ deleteFile(fileId) {
860
+ requireFileId(fileId);
861
+ this.store.deleteFile(fileId);
862
+ }
863
+ }
864
+ /** A door as an invite or the recovery code keeps it: its public key, the epoch it was made at, and its maker's vouch (#442). */
865
+ function doorOf(input) {
866
+ if (input.doorKey.length !== 32 || input.vouch.length !== 64 || !Number.isInteger(input.doorEpoch))
867
+ throw new Refusal("bad-request");
868
+ return JSON.stringify({ key: input.doorKey.toString("base64url"), epoch: input.doorEpoch, vouch: input.vouch.toString("base64url") });
869
+ }
870
+ /** How a phone came in, as `phones()` lists it: the door, who made it, the vouch, and the arrival's two signatures. */
871
+ function arrivalOf(row, input) {
872
+ if (row.door === null)
873
+ return null;
874
+ if (input.arrival.length !== 64 || input.arrivalOwn.length !== 64)
875
+ throw new Refusal("bad-request");
876
+ const door = JSON.parse(row.door);
877
+ return JSON.stringify({
878
+ id: row.id,
879
+ key: door.key,
880
+ epoch: door.epoch,
881
+ by: row.created_by,
882
+ vouch: door.vouch,
883
+ arrival: input.arrival.toString("base64url"),
884
+ arrivalOwn: input.arrivalOwn.toString("base64url"),
885
+ });
886
+ }
887
+ function describeCopy(copy) {
888
+ return {
889
+ copyId: copy.id,
890
+ epoch: copy.epoch,
891
+ schemaVersion: copy.schema_version,
892
+ throughSeq: copy.through_seq,
893
+ byteSize: copy.byte_size,
894
+ };
895
+ }
896
+ /** A file is named by a random id the phone made, never by its contents' hash (#419). */
897
+ function requireFileId(fileId) {
898
+ if (!/^[0-9a-f]{32}$/.test(fileId))
899
+ throw new Refusal("bad-request");
900
+ }
901
+ function requirePiece(piece) {
902
+ if (!Number.isInteger(piece) || piece < 0 || piece >= LIMITS.piecesPerFile)
903
+ throw new Refusal("bad-request");
904
+ }
905
+ function loadOrCreateKeys(path) {
906
+ if (existsSync(path))
907
+ return importServerKeyPair(readFileSync(path));
908
+ const keys = generateServerKeyPair();
909
+ writeFileSync(path, exportPrivateKey(keys.privateKey), { mode: 0o600 });
910
+ chmodSync(path, 0o600);
911
+ return keys;
912
+ }