@fnndsc/calypso 0.29.15 → 0.30.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 (79) hide show
  1. package/dist/calypso.js +19 -8
  2. package/dist/calypso.js.map +1 -1
  3. package/dist/daemon/attachFile.d.ts +26 -19
  4. package/dist/daemon/attachFile.js +42 -51
  5. package/dist/daemon/attachFile.js.map +1 -1
  6. package/dist/daemon/attachOrigin.d.ts +69 -0
  7. package/dist/daemon/attachOrigin.js +125 -0
  8. package/dist/daemon/attachOrigin.js.map +1 -0
  9. package/dist/daemon/berth.d.ts +265 -26
  10. package/dist/daemon/berth.js +521 -158
  11. package/dist/daemon/berth.js.map +1 -1
  12. package/dist/daemon/claims.js +19 -9
  13. package/dist/daemon/claims.js.map +1 -1
  14. package/dist/daemon/commandLane.d.ts +317 -0
  15. package/dist/daemon/commandLane.js +409 -0
  16. package/dist/daemon/commandLane.js.map +1 -0
  17. package/dist/daemon/console.d.ts +0 -2
  18. package/dist/daemon/console.js +7 -10
  19. package/dist/daemon/console.js.map +1 -1
  20. package/dist/daemon/consoleSession.js +4 -1
  21. package/dist/daemon/consoleSession.js.map +1 -1
  22. package/dist/daemon/elevation.d.ts +0 -3
  23. package/dist/daemon/elevation.js +1 -3
  24. package/dist/daemon/elevation.js.map +1 -1
  25. package/dist/daemon/face.d.ts +18 -4
  26. package/dist/daemon/face.js +77 -32
  27. package/dist/daemon/face.js.map +1 -1
  28. package/dist/daemon/hostControl.d.ts +114 -1
  29. package/dist/daemon/hostControl.js +104 -4
  30. package/dist/daemon/hostControl.js.map +1 -1
  31. package/dist/daemon/hostPtyRelay.d.ts +118 -0
  32. package/dist/daemon/hostPtyRelay.js +186 -0
  33. package/dist/daemon/hostPtyRelay.js.map +1 -0
  34. package/dist/daemon/httpRoutes.d.ts +257 -0
  35. package/dist/daemon/httpRoutes.js +537 -0
  36. package/dist/daemon/httpRoutes.js.map +1 -0
  37. package/dist/daemon/instance.d.ts +37 -0
  38. package/dist/daemon/instance.js +59 -0
  39. package/dist/daemon/instance.js.map +1 -0
  40. package/dist/daemon/launch.d.ts +17 -0
  41. package/dist/daemon/launch.js +198 -194
  42. package/dist/daemon/launch.js.map +1 -1
  43. package/dist/daemon/launchBanner.d.ts +76 -0
  44. package/dist/daemon/launchBanner.js +80 -0
  45. package/dist/daemon/launchBanner.js.map +1 -0
  46. package/dist/daemon/rival.d.ts +65 -0
  47. package/dist/daemon/rival.js +67 -0
  48. package/dist/daemon/rival.js.map +1 -0
  49. package/dist/daemon/server.d.ts +104 -190
  50. package/dist/daemon/server.js +358 -866
  51. package/dist/daemon/server.js.map +1 -1
  52. package/dist/daemon/settings.d.ts +42 -0
  53. package/dist/daemon/settings.js +43 -0
  54. package/dist/daemon/settings.js.map +1 -0
  55. package/dist/daemon/surface.d.ts +103 -0
  56. package/dist/daemon/surface.js +71 -0
  57. package/dist/daemon/surface.js.map +1 -0
  58. package/dist/daemon/surfaceReplies.d.ts +109 -0
  59. package/dist/daemon/surfaceReplies.js +108 -0
  60. package/dist/daemon/surfaceReplies.js.map +1 -0
  61. package/dist/daemon/terminals.js +5 -2
  62. package/dist/daemon/terminals.js.map +1 -1
  63. package/dist/daemon/token.d.ts +41 -5
  64. package/dist/daemon/token.js +43 -12
  65. package/dist/daemon/token.js.map +1 -1
  66. package/dist/daemon/uploadHold.d.ts +85 -0
  67. package/dist/daemon/uploadHold.js +205 -0
  68. package/dist/daemon/uploadHold.js.map +1 -0
  69. package/dist/daemon/vfsHeaders.d.ts +11 -0
  70. package/dist/daemon/vfsHeaders.js +60 -0
  71. package/dist/daemon/vfsHeaders.js.map +1 -0
  72. package/dist/index.d.ts +5 -5
  73. package/dist/index.js +3 -4
  74. package/dist/index.js.map +1 -1
  75. package/dist/notes.json +1 -1
  76. package/package.json +9 -4
  77. package/dist/daemon/discovery.d.ts +0 -23
  78. package/dist/daemon/discovery.js +0 -57
  79. package/dist/daemon/discovery.js.map +0 -1
@@ -21,12 +21,18 @@
21
21
  *
22
22
  * @module
23
23
  */
24
- import { writeFileSync, readFileSync, existsSync, mkdirSync, readdirSync, unlinkSync, rmSync } from 'fs';
25
- import { dirname, join } from 'path';
26
- import { CLOSING_CAUSES } from '@fnndsc/menu';
27
- import { homedir, tmpdir } from 'os';
28
- import { createHash } from 'node:crypto';
24
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
25
+ import { readdirSync } from 'node:fs';
26
+ import { get as httpGet } from 'node:http';
27
+ import { get as httpsGet } from 'node:https';
29
28
  import { connect as net_connect } from 'node:net';
29
+ import { homedir, tmpdir } from 'node:os';
30
+ import { basename, dirname, join } from 'node:path';
31
+ import { identityName_spell } from '@fnndsc/cumin/identity-epoch';
32
+ import { ownFile_read, ownFile_take, ownFile_write, ownFolder_settle, trustedRoot_settle, xdgDir_resolve } from '@fnndsc/fond';
33
+ import { CLOSING_CAUSES } from '@fnndsc/menu';
34
+ // A host that keeps berth folders under a root of its own asks this before it starts (porter's state root).
35
+ export { trustedRoot_settle } from '@fnndsc/fond';
30
36
  /** The prefix of every berth filename, so a directory scan finds only berths. */
31
37
  const BERTH_FILE_PREFIX = 'berth-';
32
38
  /** The owned subdirectory berths live under, inside the runtime directory. */
@@ -46,22 +52,7 @@ const BERTH_SUBDIR = 'calypso';
46
52
  * @returns The normalised identity string used as the berth key input.
47
53
  */
48
54
  export function identity_normalise(user, cubeUrl) {
49
- const schemeSplit = cubeUrl.indexOf('://');
50
- let normalisedUrl;
51
- if (schemeSplit === -1) {
52
- normalisedUrl = cubeUrl;
53
- }
54
- else {
55
- const scheme = cubeUrl.slice(0, schemeSplit).toLowerCase();
56
- const rest = cubeUrl.slice(schemeSplit + 3);
57
- // Lowercase only the authority (host[:port]); leave the path exactly as
58
- // written, including the trailing slash CUBE requires.
59
- const pathStart = rest.indexOf('/');
60
- const authority = pathStart === -1 ? rest : rest.slice(0, pathStart);
61
- const path = pathStart === -1 ? '' : rest.slice(pathStart);
62
- normalisedUrl = `${scheme}://${authority.toLowerCase()}${path}`;
63
- }
64
- return `${user}@${normalisedUrl}`;
55
+ return identityName_spell(user, cubeUrl);
65
56
  }
66
57
  /** The reserved identity for a daemon started with no restored CUBE session. */
67
58
  export const DISCONNECTED_IDENTITY = 'disconnected@no-cube';
@@ -95,14 +86,51 @@ export function berthKey_compute(identity) {
95
86
  * @returns The absolute berth directory path (not guaranteed to exist yet).
96
87
  */
97
88
  export function berthDir_path() {
98
- const runtimeDir = process.env.XDG_RUNTIME_DIR || tmpdir();
99
- return join(runtimeDir, BERTH_SUBDIR);
89
+ const runtimeDir = process.env.XDG_RUNTIME_DIR;
90
+ // Joined as spelled, not normalised: a `..` in it is refused by the folder check, never folded away first.
91
+ if (runtimeDir)
92
+ return berthFolder_pathIn(runtimeDir);
93
+ // No runtime directory: a folder of this account's own name under the shared temporary folder, so no other
94
+ // account can hold the name for everyone (held to this account by ownFolder_settle before use).
95
+ // Read as os.tmpdir() reads it on Linux (TMPDIR, TMP, TEMP, else the platform's), but from this process's own
96
+ // environment and as spelled.
97
+ const temporary = process.env.TMPDIR || process.env.TMP || process.env.TEMP || tmpdir();
98
+ return spelled_join(temporary, `${BERTH_SUBDIR}-${String(process.getuid?.() ?? 'user')}`);
99
+ }
100
+ /**
101
+ * Joins names onto a configured folder as spelled, never normalising it: a `..` the configuration holds reaches the
102
+ * owner-only check (`ownFolder_settle`), which refuses it, instead of being folded into another folder first.
103
+ *
104
+ * @param base - The folder as configured.
105
+ * @param names - Plain names to append.
106
+ * @returns The joined path.
107
+ *
108
+ * @example
109
+ * ```ts
110
+ * spelled_join('/run/user/1000/x/..', 'calypso'); // '/run/user/1000/x/../calypso'
111
+ * ```
112
+ */
113
+ export function spelled_join(base, ...names) {
114
+ // An empty base stays relative (as join gave); a base of only slashes is the root.
115
+ if (base === '')
116
+ return names.join('/');
117
+ const trimmed = base.replace(/\/+$/, '');
118
+ return trimmed === '' ? `/${names.join('/')}` : [trimmed, ...names].join('/');
100
119
  }
120
+ /** The most a berth record may hold. */
121
+ const BERTH_MAX_BYTES = 64 * 1024;
122
+ /** The paths already said to be refused, so each is said once per process. */
123
+ const refusalsSaid = new Set();
101
124
  /**
102
- * Ensures the berth directory exists, owner-only (`0700`).
125
+ * Says, once, why a berth folder or record was refused: its path and what was wrong, never what it holds.
126
+ *
127
+ * @param refused - The refusal.
103
128
  */
104
- function berthDir_ensure() {
105
- mkdirSync(berthDir_path(), { recursive: true, mode: 0o700 });
129
+ function refusal_say(refused) {
130
+ if (refusalsSaid.has(refused.reason))
131
+ return;
132
+ refusalsSaid.add(refused.reason);
133
+ console.error(`[!] berth record refused: ${refused.reason}`);
106
134
  }
107
135
  /**
108
136
  * The absolute path of one identity's berth file.
@@ -111,7 +139,7 @@ function berthDir_ensure() {
111
139
  * @returns The berth file path (may not exist).
112
140
  */
113
141
  export function berth_path(identity) {
114
- return berth_pathIn(process.env.XDG_RUNTIME_DIR || tmpdir(), identity);
142
+ return spelled_join(berthDir_path(), `${BERTH_FILE_PREFIX}${berthKey_compute(identity)}.json`);
115
143
  }
116
144
  /**
117
145
  * The path of one identity's berth file under a given runtime directory.
@@ -125,16 +153,35 @@ export function berth_path(identity) {
125
153
  * @returns The berth file path (may not exist).
126
154
  */
127
155
  export function berth_pathIn(runtimeDir, identity) {
128
- return join(runtimeDir, BERTH_SUBDIR, `${BERTH_FILE_PREFIX}${berthKey_compute(identity)}.json`);
156
+ return spelled_join(berthFolder_pathIn(runtimeDir), `${BERTH_FILE_PREFIX}${berthKey_compute(identity)}.json`);
129
157
  }
130
158
  /**
131
159
  * Writes a berth to its identity-keyed file, readable only by the current user.
132
160
  *
133
161
  * @param berth - The berth to advertise; its `identity` must be normalised.
162
+ * @throws {Error} When the berth folder is not this account's own, or a record that is not stands at the name.
134
163
  */
135
164
  export function berth_write(berth) {
136
- berthDir_ensure();
137
- writeFileSync(berth_path(berth.identity), JSON.stringify(berth), { mode: 0o600 });
165
+ const held = ownFolder_settle(berthDir_path(), true);
166
+ if (!held.ok)
167
+ throw new Error(`the berth folder is not this account's own: ${held.reason}`);
168
+ // In the folder as held (its resolved path), by rename over the name: a valid standing record is replaced whole,
169
+ // anything else at the name refused untouched.
170
+ const written = ownFile_write(held.path, basename(berth_path(berth.identity)), JSON.stringify(berth));
171
+ if (!written.ok)
172
+ throw new Error(`the berth record could not be written: ${written.reason}`);
173
+ }
174
+ /**
175
+ * Whether a record that carries a probe key carries all an instance proof is made over: a key of 32 hex bytes, a
176
+ * pid and a boot time. An earlier release's record carries no key and is whole as it is.
177
+ *
178
+ * @param berth - The record.
179
+ * @returns True when whole.
180
+ */
181
+ function keyedFacts_areWhole(berth) {
182
+ if (berth.probeKey === undefined)
183
+ return true;
184
+ return typeof berth.probeKey === 'string' && HEX_32.test(berth.probeKey) && Number.isSafeInteger(berth.pid) && typeof berth.booted === 'string';
138
185
  }
139
186
  /**
140
187
  * Validates that an unknown parsed value is a well-formed {@link Berth}.
@@ -146,7 +193,9 @@ function berth_validate(parsed) {
146
193
  if (typeof parsed === 'object' && parsed !== null &&
147
194
  typeof parsed.identity === 'string' &&
148
195
  typeof parsed.url === 'string' &&
149
- typeof parsed.token === 'string') {
196
+ typeof parsed.token === 'string' &&
197
+ berthUrl_target(parsed.url) !== null &&
198
+ keyedFacts_areWhole(parsed)) {
150
199
  return parsed;
151
200
  }
152
201
  return null;
@@ -180,6 +229,62 @@ export function berth_read(identity) {
180
229
  export function berthOwn_read(identity) {
181
230
  return berthFile_read(berth_path(identity), identity);
182
231
  }
232
+ /** The folder of porter's state root a session's runtime is kept in: `<root>/<key>/run` (porter's own layout). */
233
+ const PORTER_SESSION_RUNTIME = 'run';
234
+ /**
235
+ * Where a porter keeps its sessions' state, from the environment alone: `PORTER_STATE_DIR` when it is set,
236
+ * else `porter` under the XDG state folder (`xdgDir_resolve`). The one reading porter starts by and a client
237
+ * looks for sessions by.
238
+ *
239
+ * Spelled, not normalised: a `..` in either reaches the state root's check (`trustedRoot_settle`), never
240
+ * folded away first. An empty `PORTER_STATE_DIR` is unset, as an empty XDG variable is, and a trailing `/`
241
+ * is trimmed, so both sides name one root by one string.
242
+ *
243
+ * @param env - The environment; `process.env` in production.
244
+ * @param home - The account's home as spelled; `HOME`, else the account's.
245
+ * @returns The state root.
246
+ *
247
+ * @example
248
+ * ```ts
249
+ * porterStateRoot_resolve({ XDG_STATE_HOME: '/state' }); // '/state/porter'
250
+ * porterStateRoot_resolve({ PORTER_STATE_DIR: '/srv/porter/' }); // '/srv/porter'
251
+ * ```
252
+ */
253
+ export function porterStateRoot_resolve(env = process.env, home = process.env.HOME || homedir()) {
254
+ const configured = env['PORTER_STATE_DIR'];
255
+ if (configured !== undefined && configured !== '')
256
+ return configured.replace(/(.)\/+$/, '$1');
257
+ return spelled_join(xdgDir_resolve('state', { XDG_STATE_HOME: env['XDG_STATE_HOME'] }, () => home), 'porter');
258
+ }
259
+ /**
260
+ * A porter session's runtime folder: `<root>/<session>/run`, where its calypso writes its berth.
261
+ *
262
+ * @param root - The porter state root.
263
+ * @param session - The session's folder under it: its identity's `berthKey_compute`.
264
+ * @returns The runtime folder.
265
+ *
266
+ * @example
267
+ * ```ts
268
+ * porterSessionRuntime_path('/srv/porter', berthKey_compute(identity)); // '/srv/porter/<key>/run'
269
+ * ```
270
+ */
271
+ export function porterSessionRuntime_path(root, session) {
272
+ return spelled_join(root, session, PORTER_SESSION_RUNTIME);
273
+ }
274
+ /**
275
+ * The folder a daemon started with a runtime folder keeps its berth and closing files in.
276
+ *
277
+ * @param runtimeDir - The runtime folder.
278
+ * @returns `<runtimeDir>/calypso`.
279
+ *
280
+ * @example
281
+ * ```ts
282
+ * berthFolder_pathIn('/run/mise'); // '/run/mise/calypso'
283
+ * ```
284
+ */
285
+ export function berthFolder_pathIn(runtimeDir) {
286
+ return spelled_join(runtimeDir, BERTH_SUBDIR);
287
+ }
183
288
  /**
184
289
  * The state directories a porter on this machine keeps its sessions under,
185
290
  * in the order looked: the porter's own setting, the user's state directory
@@ -188,10 +293,9 @@ export function berthOwn_read(identity) {
188
293
  * @returns The candidate roots.
189
294
  */
190
295
  export function porterStateRoots_get() {
191
- const roots = [];
192
- if (process.env.PORTER_STATE_DIR)
193
- roots.push(process.env.PORTER_STATE_DIR);
194
- roots.push(join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'porter'));
296
+ const roots = [porterStateRoot_resolve(process.env)];
297
+ // A porter run as this user without the setting, when this process has it.
298
+ roots.push(porterStateRoot_resolve({ XDG_STATE_HOME: process.env.XDG_STATE_HOME }));
195
299
  roots.push('/var/lib/porter/sessions');
196
300
  return [...new Set(roots)];
197
301
  }
@@ -205,9 +309,27 @@ export function porterStateRoots_get() {
205
309
  export function berthPaths_list(identity) {
206
310
  return [
207
311
  berth_path(identity),
208
- ...porterStateRoots_get().map((root) => berth_pathIn(join(root, berthKey_compute(identity), 'run'), identity)),
312
+ ...porterRootsHeld_get().map((root) => berth_pathIn(porterSessionRuntime_path(root, berthKey_compute(identity)), identity)),
209
313
  ];
210
314
  }
315
+ /**
316
+ * The porter state roots a client may read sessions from: each held as porter holds its own (`trustedRoot_settle`:
317
+ * on a trusted path, and not itself open to other accounts), by its resolved path. A refused root is said once and
318
+ * passed over; the roots after it still count. A root not made yet holds no sessions and is passed over quietly.
319
+ *
320
+ * @returns The held roots' resolved paths.
321
+ */
322
+ function porterRootsHeld_get() {
323
+ const held = [];
324
+ for (const root of porterStateRoots_get()) {
325
+ const settled = trustedRoot_settle(root);
326
+ if (settled.ok)
327
+ held.push(settled.path);
328
+ else if (settled.missing !== true)
329
+ refusal_say(settled);
330
+ }
331
+ return held;
332
+ }
211
333
  /**
212
334
  * Reads one berth file, when it exists and names the identity.
213
335
  *
@@ -216,20 +338,56 @@ export function berthPaths_list(identity) {
216
338
  * @returns The berth, or null.
217
339
  */
218
340
  function berthFile_read(path, identity) {
219
- if (!existsSync(path)) {
341
+ const berth = berthRecord_read(path);
342
+ return berth !== null && berth.identity === identity ? berth : null;
343
+ }
344
+ /**
345
+ * Reads a berth record held to this account: its folder through a trusted path, owner-only, never made by a
346
+ * reader; the record a regular 0600 file of this account's, bounded. A missing folder or record is no berth; one
347
+ * refused is said once (its path and why) and is no berth either.
348
+ *
349
+ * @param path - The record.
350
+ * @returns The berth, or null.
351
+ *
352
+ * @example
353
+ * ```ts
354
+ * const berth: Berth | null = berthRecord_read(berth_path(identity));
355
+ * ```
356
+ */
357
+ export function berthRecord_read(path) {
358
+ const folder = ownFolder_settle(dirname(path), false);
359
+ if (!folder.ok) {
360
+ if (folder.missing !== true)
361
+ refusal_say(folder);
362
+ return null;
363
+ }
364
+ return berthRecordIn_read(folder.path, basename(path));
365
+ }
366
+ /**
367
+ * Reads one berth record in a folder already held (`ownFolder_settle`), by the held folder's resolved path.
368
+ *
369
+ * @param folder - The held folder's `path`.
370
+ * @param name - The record's name.
371
+ * @returns The berth, or null (a refusal other than absence said once).
372
+ */
373
+ function berthRecordIn_read(folder, name) {
374
+ const path = join(folder, name);
375
+ const read = ownFile_read(path, BERTH_MAX_BYTES);
376
+ if (!read.ok) {
377
+ if (read.missing !== true)
378
+ refusal_say(read);
220
379
  return null;
221
380
  }
381
+ let berth;
222
382
  try {
223
- const berth = berth_validate(JSON.parse(readFileSync(path, 'utf-8')));
224
- return berth && berth.identity === identity ? berth : null;
383
+ berth = berth_validate(JSON.parse(read.text));
225
384
  }
226
- catch (error) {
227
- // A corrupt berth file reading as "no daemon" sends the user down a
228
- // confusing start-a-new-daemon path; name the file so it can be removed.
229
- const msg = error instanceof Error ? error.message : String(error);
230
- console.error(`[!] Ignoring unreadable berth file ${path}: ${msg}`);
231
- return null;
385
+ catch {
386
+ berth = null;
232
387
  }
388
+ if (berth === null)
389
+ refusal_say({ ok: false, reason: `${path}: not a berth record` });
390
+ return berth;
233
391
  }
234
392
  /**
235
393
  * Reads every advertised berth in the berth directory.
@@ -238,15 +396,44 @@ function berthFile_read(path, identity) {
238
396
  * or holds none.
239
397
  */
240
398
  export function berthAll_read() {
241
- const berths = [];
399
+ return berthAllLocated_read().map((located) => located.berth);
400
+ }
401
+ /**
402
+ * Reads every advertised berth with the file each was read from.
403
+ *
404
+ * A berth is found in this runtime's directory or in a porter session's,
405
+ * so the file is not something an identity alone gives back: a listing
406
+ * that must name where a berth's token is kept names this path.
407
+ *
408
+ * @returns All well-formed berths, one per identity, each with its record's path.
409
+ */
410
+ export function berthAllLocated_read() {
411
+ const found = [];
242
412
  // This runtime's berths, then each porter session's, one per identity.
243
413
  for (const dir of [berthDir_path(), ...porterSessionDirs_get()]) {
244
- for (const berth of berthDir_read(dir)) {
245
- if (!berths.some((one) => one.identity === berth.identity))
246
- berths.push(berth);
414
+ for (const located of berthFolder_read(dir)) {
415
+ if (!found.some((one) => one.berth.identity === located.berth.identity))
416
+ found.push(located);
247
417
  }
248
418
  }
249
- return berths;
419
+ return found;
420
+ }
421
+ /**
422
+ * Appends every session berth directory inside one porter root to `dirs`.
423
+ *
424
+ * @param root - Porter state root directory.
425
+ * @param dirs - Output list of berth directories.
426
+ */
427
+ function porterRootDirs_collect(root, dirs) {
428
+ try {
429
+ for (const entry of readdirSync(root, { withFileTypes: true })) {
430
+ if (entry.isDirectory())
431
+ dirs.push(berthFolder_pathIn(porterSessionRuntime_path(root, entry.name)));
432
+ }
433
+ }
434
+ catch {
435
+ // No porter here, or not one this user may read.
436
+ }
250
437
  }
251
438
  /**
252
439
  * The berth directories of every porter session this user can read.
@@ -255,148 +442,314 @@ export function berthAll_read() {
255
442
  */
256
443
  function porterSessionDirs_get() {
257
444
  const dirs = [];
258
- for (const root of porterStateRoots_get()) {
259
- try {
260
- for (const entry of readdirSync(root, { withFileTypes: true })) {
261
- if (entry.isDirectory())
262
- dirs.push(join(root, entry.name, 'run', BERTH_SUBDIR));
263
- }
264
- }
265
- catch {
266
- // No porter here, or not one this user may read.
267
- }
268
- }
445
+ for (const root of porterRootsHeld_get())
446
+ porterRootDirs_collect(root, dirs);
269
447
  return dirs;
270
448
  }
271
449
  /**
272
- * Reads every well-formed berth in one directory.
450
+ * Reads every well-formed berth in one folder, held to this account first (`ownFolder_settle`); a refused
451
+ * folder, a folder that cannot be listed, and a refused record are each said once and passed over.
273
452
  *
274
- * @param dir - The directory.
275
- * @returns Its berths.
453
+ * @param dir - The folder.
454
+ * @returns Its berths, each with its file (by the folder's resolved path).
455
+ *
456
+ * @example
457
+ * ```ts
458
+ * const found: LocatedBerth[] = berthFolder_read(join(runtime, 'calypso'));
459
+ * ```
276
460
  */
277
- function berthDir_read(dir) {
278
- if (!existsSync(dir)) {
461
+ export function berthFolder_read(dir) {
462
+ const folder = ownFolder_settle(dir, false);
463
+ if (!folder.ok) {
464
+ if (folder.missing !== true)
465
+ refusal_say(folder);
279
466
  return [];
280
467
  }
281
468
  const berths = [];
282
- for (const name of readdirSync(dir)) {
283
- if (!name.startsWith(BERTH_FILE_PREFIX) || !name.endsWith('.json')) {
469
+ let names;
470
+ try {
471
+ names = readdirSync(folder.path);
472
+ }
473
+ catch (error) {
474
+ refusal_say({ ok: false, reason: `${folder.path}: could not be listed (${error instanceof Error ? error.message : String(error)})` });
475
+ return [];
476
+ }
477
+ for (const name of names) {
478
+ if (!name.startsWith(BERTH_FILE_PREFIX) || !name.endsWith('.json'))
284
479
  continue;
285
- }
286
- try {
287
- const berth = berth_validate(JSON.parse(readFileSync(join(dir, name), 'utf-8')));
288
- if (berth) {
289
- berths.push(berth);
290
- }
291
- }
292
- catch (error) {
293
- // Skipped, but named: a corrupted berth silently vanishing from the
294
- // --remote picker is indistinguishable from a stopped daemon.
295
- const msg = error instanceof Error ? error.message : String(error);
296
- console.error(`[!] Skipping unreadable berth file ${join(dir, name)}: ${msg}`);
297
- }
480
+ // Skipped, but said (once): a refused or unreadable record vanishing silently is indistinguishable from a stopped daemon.
481
+ const berth = berthRecordIn_read(folder.path, name);
482
+ if (berth !== null)
483
+ berths.push({ berth, path: join(folder.path, name) });
298
484
  }
299
485
  return berths;
300
486
  }
487
+ /** What the instance proof covers, and its version. */
488
+ const INSTANCE_PROOF_LABEL = 'calypso-instance-v1';
489
+ /** A probe's nonce, and a launch's probe key: 32 bytes, lowercase hex. */
490
+ const HEX_32 = /^[0-9a-f]{64}$/;
491
+ /** How long a probe waits for an answer. */
492
+ const PROBE_TIMEOUT_MS = 1500;
301
493
  /**
302
- * Removes an identity's berth file if present (used to reap a berth whose
303
- * daemon a liveness probe found dead).
494
+ * A fresh key for this launch's instance proof.
304
495
  *
305
- * @param identity - A normalised identity from {@link identity_normalise}.
496
+ * @returns 32 random bytes, lowercase hex.
497
+ *
498
+ * @example
499
+ * ```ts
500
+ * const berth: Berth = { ...facts, probeKey: probeKey_generate() };
501
+ * ```
306
502
  */
307
- export function berth_remove(identity) {
308
- const path = berth_path(identity);
309
- if (existsSync(path)) {
310
- try {
311
- unlinkSync(path);
312
- }
313
- catch {
314
- // Already gone: the reap is a best-effort convenience.
315
- }
503
+ export function probeKey_generate() {
504
+ return randomBytes(32).toString('hex');
505
+ }
506
+ /**
507
+ * The proof that a daemon is the instance a record names: HMAC-SHA256 under the launch's probe key over the label,
508
+ * the nonce, the identity, the pid and the boot time, one per line. Neither the key nor the token travels.
509
+ *
510
+ * @param facts - The instance's facts.
511
+ * @param nonce - The probe's nonce.
512
+ * @returns The proof, hex.
513
+ *
514
+ * @example
515
+ * ```ts
516
+ * const proof: string = instanceProof_compute(facts, nonce);
517
+ * ```
518
+ */
519
+ export function instanceProof_compute(facts, nonce) {
520
+ return createHmac('sha256', Buffer.from(facts.probeKey, 'hex'))
521
+ .update(`${INSTANCE_PROOF_LABEL}\n${nonce}\n${facts.identity}\n${String(facts.pid)}\n${facts.booted}`)
522
+ .digest('hex');
523
+ }
524
+ /**
525
+ * A record's instance facts, when it holds a key to prove by.
526
+ *
527
+ * @param berth - The record.
528
+ * @returns Its facts, or null for an earlier release's record.
529
+ */
530
+ function instanceFacts_read(berth) {
531
+ if (berth.probeKey === undefined || berth.pid === undefined || berth.booted === undefined)
532
+ return null;
533
+ return { probeKey: berth.probeKey, identity: berth.identity, pid: berth.pid, booted: berth.booted };
534
+ }
535
+ /**
536
+ * A berth URL's address: a `ws:` or `wss:` URL with a host and no credentials, its scheme's default port filled
537
+ * in. Anything else names no daemon a berth could record.
538
+ *
539
+ * @param url - The URL.
540
+ * @returns The address, or null.
541
+ *
542
+ * @example
543
+ * ```ts
544
+ * berthUrl_target('ws://[::1]:4000'); // { host: '::1', port: 4000, secure: false, origin: 'http://[::1]:4000' }
545
+ * ```
546
+ */
547
+ export function berthUrl_target(url) {
548
+ let parsed;
549
+ try {
550
+ parsed = new URL(url);
316
551
  }
552
+ catch {
553
+ return null;
554
+ }
555
+ if (parsed.protocol !== 'ws:' && parsed.protocol !== 'wss:')
556
+ return null;
557
+ if (parsed.username !== '' || parsed.password !== '' || parsed.hostname === '')
558
+ return null;
559
+ const secure = parsed.protocol === 'wss:';
560
+ const port = parsed.port === '' ? (secure ? 443 : 80) : Number(parsed.port);
561
+ if (!Number.isInteger(port) || port <= 0 || port > 65535)
562
+ return null;
563
+ const bracketed = parsed.hostname.startsWith('[') && parsed.hostname.endsWith(']');
564
+ const host = bracketed ? parsed.hostname.slice(1, -1) : parsed.hostname;
565
+ return { host, port, secure, origin: `${secure ? 'https' : 'http'}://${parsed.host}` };
317
566
  }
318
567
  /**
319
- * Reports whether something is listening at a berth's WebSocket address, by a
320
- * plain TCP connect — no WebSocket handshake, so this stays within the daemon
321
- * package (which has no client). It is the liveness check `daemon_launch` uses
322
- * to refuse starting a rival for an identity that is already hosted; a surface's
323
- * resolver uses a stronger handshake probe for attach.
568
+ * Connects to a berth's address and says how it went, no handshake, within one deadline. Only a refusal means
569
+ * nothing is there; a timeout, a name that does not resolve, an address that names no daemon, or any other failure
570
+ * is inconclusive.
324
571
  *
325
572
  * @param url - A `ws://host:port` berth URL.
326
- * @param timeoutMs - How long to wait for the TCP connect (default 500 ms).
327
- * @returns True when the port accepts a connection.
573
+ * @param timeoutMs - The deadline for the whole attempt.
574
+ * @returns How it went.
575
+ *
576
+ * @example
577
+ * ```ts
578
+ * if ((await berthUrl_connect(berth.url)) === 'refused') startHere();
579
+ * ```
328
580
  */
329
- export function berthUrl_isAlive(url, timeoutMs = 500) {
581
+ export function berthUrl_connect(url, timeoutMs = 500) {
330
582
  return new Promise((resolve) => {
331
- let host;
332
- let port;
333
- try {
334
- const parsed = new URL(url);
335
- host = parsed.hostname;
336
- port = Number(parsed.port);
337
- }
338
- catch {
339
- resolve(false);
340
- return;
341
- }
342
- if (!port) {
343
- resolve(false);
583
+ const target = berthUrl_target(url);
584
+ if (target === null) {
585
+ resolve('inconclusive');
344
586
  return;
345
587
  }
346
- const socket = net_connect({ host, port });
347
- const settle = (alive) => {
588
+ const socket = net_connect({ host: target.host, port: target.port });
589
+ const deadline = setTimeout(() => { outcome_settle('inconclusive'); }, timeoutMs);
590
+ /**
591
+ * Settles once: the deadline cleared, the socket closed.
592
+ *
593
+ * @param outcome - How it went.
594
+ */
595
+ function outcome_settle(outcome) {
596
+ clearTimeout(deadline);
348
597
  socket.destroy();
349
- resolve(alive);
350
- };
351
- socket.setTimeout(timeoutMs);
352
- socket.once('connect', () => settle(true));
353
- socket.once('timeout', () => settle(false));
354
- socket.once('error', () => settle(false));
598
+ resolve(outcome);
599
+ }
600
+ socket.once('connect', () => { outcome_settle('accepted'); });
601
+ socket.once('error', (error) => { outcome_settle(error.code === 'ECONNREFUSED' ? 'refused' : 'inconclusive'); });
602
+ });
603
+ }
604
+ /** The most an instance answer may hold; a proof answer is under 100 bytes. */
605
+ const INSTANCE_BODY_MAX = 1024;
606
+ /**
607
+ * Asks an address for its instance proof: `GET <origin>/instance?nonce=<nonce>`, built from the address's origin
608
+ * and the nonce alone, with no pooled socket, within one deadline for the whole exchange, the body bounded (more
609
+ * is no answer).
610
+ *
611
+ * @param target - The address.
612
+ * @param nonce - The nonce.
613
+ * @returns The answer, or how the connection failed.
614
+ */
615
+ function instance_ask(target, nonce) {
616
+ return new Promise((resolve) => {
617
+ const request_get = target.secure ? httpsGet : httpGet;
618
+ let request = null;
619
+ const deadline = setTimeout(() => { answer_settle({ failed: 'inconclusive' }); }, PROBE_TIMEOUT_MS);
620
+ /**
621
+ * Settles once: the deadline cleared, the request ended.
622
+ *
623
+ * @param answer - What was had.
624
+ */
625
+ function answer_settle(answer) {
626
+ clearTimeout(deadline);
627
+ request?.destroy();
628
+ resolve(answer);
629
+ }
630
+ request = request_get(`${target.origin}/instance?nonce=${nonce}`, { agent: false }, (response) => {
631
+ const chunks = [];
632
+ let size = 0;
633
+ response.on('data', (chunk) => {
634
+ size += chunk.length;
635
+ if (size > INSTANCE_BODY_MAX) {
636
+ answer_settle({ failed: 'inconclusive' });
637
+ return;
638
+ }
639
+ chunks.push(chunk);
640
+ });
641
+ response.on('end', () => {
642
+ if (size > INSTANCE_BODY_MAX)
643
+ return;
644
+ answer_settle({ status: response.statusCode ?? 0, body: Buffer.concat(chunks).toString('utf8') });
645
+ });
646
+ // Cut short: no answer. A settled promise ignores this after an end.
647
+ response.on('close', () => { answer_settle({ failed: 'inconclusive' }); });
648
+ });
649
+ request.on('error', (error) => { answer_settle({ failed: error.code === 'ECONNREFUSED' ? 'refused' : 'inconclusive' }); });
355
650
  });
356
651
  }
357
652
  /**
358
- * The tier-1 resolver: reads identity-keyed berth files and, when given a
359
- * liveness probe, reaps any berth whose daemon has gone (passive cleanup — the
360
- * next read of a stale berth removes it). Without a probe it returns berths as
361
- * recorded, trusting the caller's own attach to surface a dead one.
653
+ * Whether a berth's recorded daemon is running. A keyed record is live only when its address answers a fresh nonce
654
+ * with the proof the record's key gives for that instance (identity, pid, boot time); anything else is dead. An
655
+ * earlier release's record has no key: a refused connection means it is gone, anything else leaves it unverified
656
+ * (never grounds to start beside it or adopt it).
657
+ *
658
+ * @param berth - The record.
659
+ * @returns What was learnt.
660
+ *
661
+ * @example
662
+ * ```ts
663
+ * if ((await berthInstance_probe(berth)) === 'live') attach(berth);
664
+ * ```
665
+ */
666
+ export async function berthInstance_probe(berth) {
667
+ const facts = instanceFacts_read(berth);
668
+ if (facts === null)
669
+ return (await berthUrl_connect(berth.url)) === 'refused' ? 'dead' : 'unverified';
670
+ const target = berthUrl_target(berth.url);
671
+ if (target === null)
672
+ return 'dead';
673
+ const nonce = randomBytes(32).toString('hex');
674
+ const answer = await instance_ask(target, nonce);
675
+ if ('failed' in answer || answer.status !== 200)
676
+ return 'dead';
677
+ let proof;
678
+ try {
679
+ proof = JSON.parse(answer.body).proof;
680
+ }
681
+ catch {
682
+ return 'dead';
683
+ }
684
+ if (typeof proof !== 'string' || !HEX_32.test(proof))
685
+ return 'dead';
686
+ return timingSafeEqual(Buffer.from(proof, 'hex'), Buffer.from(instanceProof_compute(facts, nonce), 'hex')) ? 'live' : 'dead';
687
+ }
688
+ /**
689
+ * The tier-1 resolver: reads identity-keyed berth records and, given a probe, walks every record of an identity in
690
+ * order (this runtime's, then each porter session's), probing each before one is chosen, so a dead record never
691
+ * hides a live one behind it. Nothing is removed: a dead record is passed over and the next daemon of its identity
692
+ * replaces it. Without a probe it returns records as written, trusting the caller's own attach to find a dead one.
362
693
  */
363
694
  export class LocalBerthResolver {
364
695
  liveness_probe;
365
696
  /**
366
- * @param liveness_probe - Optional reachability probe; when present, dead
367
- * berths are reaped and never returned.
697
+ * @param liveness_probe - Optional probe; when present, only live berths are returned.
368
698
  */
369
699
  constructor(liveness_probe) {
370
700
  this.liveness_probe = liveness_probe;
371
701
  }
372
702
  /** @inheritdoc */
373
703
  async resolve(identity) {
374
- const berth = berth_read(identity);
375
- if (!berth) {
376
- return null;
377
- }
378
- if (this.liveness_probe && !(await this.liveness_probe(berth))) {
379
- berth_remove(berth.identity);
380
- return null;
704
+ for (const path of berthPaths_list(identity)) {
705
+ const berth = berthFile_read(path, identity);
706
+ if (berth === null)
707
+ continue;
708
+ if (!this.liveness_probe || (await this.liveness_probe(berth)) === 'live')
709
+ return berth;
381
710
  }
382
- return berth;
711
+ return null;
383
712
  }
384
713
  /** @inheritdoc */
385
714
  async list() {
386
- const berths = berthAll_read();
387
- if (!this.liveness_probe) {
388
- return berths;
389
- }
390
- const live = [];
391
- for (const berth of berths) {
392
- if (await this.liveness_probe(berth)) {
393
- live.push(berth);
394
- }
395
- else {
396
- berth_remove(berth.identity);
715
+ return (await this.listLocated()).map((located) => located.berth);
716
+ }
717
+ /**
718
+ * Every live berth with the record it was read from, one per identity.
719
+ *
720
+ * @returns The berths and their files.
721
+ */
722
+ async listLocated() {
723
+ return (await this.probed_list())
724
+ .filter((one) => one.liveness === 'live')
725
+ .map((one) => ({ berth: one.berth, path: one.path }));
726
+ }
727
+ /**
728
+ * Every record with what a probe learnt of it, one per identity: the first live record of each identity, else
729
+ * its first unverified one (an earlier release's daemon that may still run), else none. Without a probe, the
730
+ * first record of each identity, as written, counted live.
731
+ *
732
+ * @returns The probed berths.
733
+ *
734
+ * @example
735
+ * ```ts
736
+ * const rows: ProbedBerth[] = await new LocalBerthResolver(berthInstance_probe).probed_list();
737
+ * ```
738
+ */
739
+ async probed_list() {
740
+ const chosen = new Map();
741
+ for (const dir of [berthDir_path(), ...porterSessionDirs_get()]) {
742
+ for (const located of berthFolder_read(dir)) {
743
+ const held = chosen.get(located.berth.identity);
744
+ if (held?.liveness === 'live')
745
+ continue;
746
+ const liveness = this.liveness_probe ? await this.liveness_probe(located.berth) : 'live';
747
+ if (liveness === 'dead' || (held !== undefined && liveness !== 'live'))
748
+ continue;
749
+ chosen.set(located.berth.identity, { ...located, liveness });
397
750
  }
398
751
  }
399
- return live;
752
+ return [...chosen.values()];
400
753
  }
401
754
  }
402
755
  /** The file beside a berth that says why its daemon is being ended. */
@@ -410,7 +763,7 @@ const CLOSING_FILE_PREFIX = 'closing-';
410
763
  * @returns The path.
411
764
  */
412
765
  export function closing_pathIn(runtimeDir, identity) {
413
- return join(runtimeDir, BERTH_SUBDIR, `${CLOSING_FILE_PREFIX}${berthKey_compute(identity)}.json`);
766
+ return spelled_join(berthFolder_pathIn(runtimeDir), `${CLOSING_FILE_PREFIX}${berthKey_compute(identity)}.json`);
414
767
  }
415
768
  /**
416
769
  * Leaves the reason an identity's daemon is about to be ended, for the
@@ -419,26 +772,36 @@ export function closing_pathIn(runtimeDir, identity) {
419
772
  * @param runtimeDir - The daemon's runtime directory.
420
773
  * @param identity - The normalised identity.
421
774
  * @param cause - Why: `restart` or `end`.
775
+ * @throws {Error} When the folder is not this account's own, or a note that is not stands at the name.
422
776
  */
423
777
  export function closing_write(runtimeDir, identity, cause) {
424
778
  const path = closing_pathIn(runtimeDir, identity);
425
- mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
426
- writeFileSync(path, `${JSON.stringify({ cause, at: Date.now() })}\n`, { mode: 0o600 });
779
+ const held = ownFolder_settle(dirname(path), true);
780
+ if (!held.ok)
781
+ throw new Error(`the berth folder is not this account's own: ${held.reason}`);
782
+ const written = ownFile_write(held.path, basename(path), `${JSON.stringify({ cause, at: Date.now() })}\n`);
783
+ if (!written.ok)
784
+ throw new Error(`the closing note could not be written: ${written.reason}`);
427
785
  }
428
786
  /** How long a left reason stays believable; an older one is a leftover. */
429
787
  const CLOSING_FRESH_MS = 60_000;
430
788
  /**
431
- * Takes the reason a host left for this daemon's ending, removing it.
789
+ * Takes the reason a host left for this daemon's ending: renamed aside and read once, never put back.
432
790
  *
433
791
  * @param identity - The daemon's normalised identity.
434
- * @param runtimeDir - Its runtime directory; this process's by default.
435
- * @returns The cause, or null when none was left (or it is stale).
792
+ * @param runtimeDir - Its runtime directory; by default this process's berth folder's.
793
+ * @returns The cause, or null when none was left (or it is stale, or refused).
436
794
  */
437
- export function closing_take(identity, runtimeDir = process.env.XDG_RUNTIME_DIR || tmpdir()) {
438
- const path = closing_pathIn(runtimeDir, identity);
795
+ export function closing_take(identity, runtimeDir) {
796
+ const path = runtimeDir !== undefined ? closing_pathIn(runtimeDir, identity) : spelled_join(berthDir_path(), basename(closing_pathIn('', identity)));
797
+ const held = ownFolder_settle(dirname(path), false);
798
+ if (!held.ok)
799
+ return null;
800
+ const taken = ownFile_take(held.path, basename(path), 4096);
801
+ if (!taken.ok)
802
+ return null;
439
803
  try {
440
- const left = JSON.parse(readFileSync(path, 'utf-8'));
441
- rmSync(path, { force: true });
804
+ const left = JSON.parse(taken.text);
442
805
  const fresh = typeof left.at === 'number' && Date.now() - left.at < CLOSING_FRESH_MS;
443
806
  return fresh && CLOSING_CAUSES.includes(left.cause) ? left.cause : null;
444
807
  }