@ghostlytools/cli 1.7.2 → 1.7.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +37 -24
- package/SKILL.md +10 -4
- package/dist/assets/{api-CcuCtc1H.js → api-Chhvpwok.js} +2 -2
- package/dist/assets/{api-tSZELCPQ.js → api-D3i2hwy0.js} +340 -155
- package/dist/assets/api-D3i2hwy0.js.map +1 -0
- package/dist/assets/{apiKit-BFk7GAk9.js → apiKit-BtsHrnoo.js} +60 -8
- package/dist/assets/apiKit-BtsHrnoo.js.map +1 -0
- package/dist/assets/{apps-D6THreq_.js → apps-BFJTqvAt.js} +1 -1
- package/dist/assets/{apps-C5Mi6x9Q.js → apps-BHl97rHs.js} +11 -9
- package/dist/assets/apps-BHl97rHs.js.map +1 -0
- package/dist/assets/{arkade-Cz0B9bJ0.js → arkade-BFE8KkEE.js} +2 -2
- package/dist/assets/{arkade-Cz0B9bJ0.js.map → arkade-BFE8KkEE.js.map} +1 -1
- package/dist/assets/{backup-A0hIa9GE.js → backup-Bbsr6nDi.js} +1 -1
- package/dist/assets/{backup-Wb2sm2dd.js → backup-CxACdtQX.js} +7 -7
- package/dist/assets/{backup-Wb2sm2dd.js.map → backup-CxACdtQX.js.map} +1 -1
- package/dist/assets/{blobFiles-Bckz9fjp.js → blobFiles-DOQDRdDI.js} +3 -3
- package/dist/assets/{blobFiles-Bckz9fjp.js.map → blobFiles-DOQDRdDI.js.map} +1 -1
- package/dist/assets/{buttons-Cf70NVYq.js → buttons-CieBtXEO.js} +35 -9
- package/dist/assets/buttons-CieBtXEO.js.map +1 -0
- package/dist/assets/buttons-YtAj3R_E.js +2 -0
- package/dist/assets/{daemonProof-Bp9lJDxf.js → daemonProof-QmtwDj-N.js} +2 -2
- package/dist/assets/{daemonProof-Bp9lJDxf.js.map → daemonProof-QmtwDj-N.js.map} +1 -1
- package/dist/assets/{envelope-kQ5kYjVE.js → envelope-DYiGwzq_.js} +2 -2
- package/dist/assets/{envelope-kQ5kYjVE.js.map → envelope-DYiGwzq_.js.map} +1 -1
- package/dist/assets/{errors-mnjSQlbX.js → errors-QUGP-jIF.js} +2 -2
- package/dist/assets/errors-QUGP-jIF.js.map +1 -0
- package/dist/assets/{fileBytes-OolN5cSY.js → fileBytes-BPDKufla.js} +1 -1
- package/dist/assets/{fileBytes-BD0v3rRG.js → fileBytes-DNgrRL0R.js} +3 -3
- package/dist/assets/{fileBytes-BD0v3rRG.js.map → fileBytes-DNgrRL0R.js.map} +1 -1
- package/dist/assets/{fileBytes-_fd-2JRY.js → fileBytes-Q3ehcEr8.js} +2 -2
- package/dist/assets/{fileBytes-_fd-2JRY.js.map → fileBytes-Q3ehcEr8.js.map} +1 -1
- package/dist/assets/fileBytesIdb-DZcESfTt.js +2 -0
- package/dist/assets/{fileBytesIdb-NtA8r9EM.js → fileBytesIdb-Dm1EyEbT.js} +3 -3
- package/dist/assets/{fileBytesIdb-NtA8r9EM.js.map → fileBytesIdb-Dm1EyEbT.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-B8fJwkwM.js → fileBytesOpfs-ZGD21c4Q.js} +3 -3
- package/dist/assets/{fileBytesOpfs-B8fJwkwM.js.map → fileBytesOpfs-ZGD21c4Q.js.map} +1 -1
- package/dist/assets/{groupFiles-D9Ttlm3M.js → groupFiles-CBJIEvCE.js} +572 -6
- package/dist/assets/groupFiles-CBJIEvCE.js.map +1 -0
- package/dist/assets/{host-DpypH-fR.js → host-Va-r_KJz.js} +84 -23
- package/dist/assets/host-Va-r_KJz.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-D1rj84v2.js → hyperdhtRelay-B2uK9tJv.js} +2 -2
- package/dist/assets/{hyperdhtRelay-D1rj84v2.js.map → hyperdhtRelay-B2uK9tJv.js.map} +1 -1
- package/dist/assets/{idb-BlH8-O3R.js → idb-BkOJES5_.js} +5 -3
- package/dist/assets/idb-BkOJES5_.js.map +1 -0
- package/dist/assets/{irohWeb-BTSlWgEX.js → irohWeb-DxeEgQ-W.js} +2 -2
- package/dist/assets/{irohWeb-BTSlWgEX.js.map → irohWeb-DxeEgQ-W.js.map} +1 -1
- package/dist/assets/{main-BwgoQZVu.js → main-BX4oPWCJ.js} +589 -192
- package/dist/assets/main-BX4oPWCJ.js.map +1 -0
- package/dist/assets/{mainline-B1urhbEZ.js → mainline-IfWQOB-J.js} +39 -12
- package/dist/assets/mainline-IfWQOB-J.js.map +1 -0
- package/dist/assets/{networkReason-D2Z0BdIj.js → networkReason-N2vAaoth.js} +3 -3
- package/dist/assets/{networkReason-D2Z0BdIj.js.map → networkReason-N2vAaoth.js.map} +1 -1
- package/dist/assets/{nwc-T2aUK6bi.js → nwc-CzyCtNK2.js} +3 -3
- package/dist/assets/{nwc-T2aUK6bi.js.map → nwc-CzyCtNK2.js.map} +1 -1
- package/dist/assets/{nwcProvider-Dz-ty_DE.js → nwcProvider-DjWmEn3j.js} +2 -2
- package/dist/assets/{nwcProvider-Dz-ty_DE.js.map → nwcProvider-DjWmEn3j.js.map} +1 -1
- package/dist/assets/{profiles-C6XWqre5.js → profiles-DcCeOi7J.js} +104 -10
- package/dist/assets/profiles-DcCeOi7J.js.map +1 -0
- package/dist/assets/{registry-BlSTJlbv.js → registry-BmS02J5h.js} +1 -1
- package/dist/assets/{registry-Bazitl0a.js → registry-CeW8XEQc.js} +45 -14
- package/dist/assets/registry-CeW8XEQc.js.map +1 -0
- package/dist/assets/{resolve-Bx1Eeg-w.js → resolve-BvHkAhDH.js} +66 -29
- package/dist/assets/resolve-BvHkAhDH.js.map +1 -0
- package/dist/assets/{restoredRows-Fv-MuY45.js → restoredRows-mTTp3XNs.js} +2 -2
- package/dist/assets/{restoredRows-Fv-MuY45.js.map → restoredRows-mTTp3XNs.js.map} +1 -1
- package/dist/assets/{server-CnPj9wWh.js → server-BUcJo4vz.js} +1033 -821
- package/dist/assets/server-BUcJo4vz.js.map +1 -0
- package/dist/assets/{src-BsznF3XG.js → src-BB5-5P3s.js} +645 -196
- package/dist/assets/src-BB5-5P3s.js.map +1 -0
- package/dist/assets/{translate-cDBotA-b.js → translate-2WyaRVCr.js} +11 -9
- package/dist/assets/translate-2WyaRVCr.js.map +1 -0
- package/dist/assets/{usdt-DxxLdG60.js → usdt-BLazHiaP.js} +3 -3
- package/dist/assets/{usdt-DxxLdG60.js.map → usdt-BLazHiaP.js.map} +1 -1
- package/dist/assets/{words-qH8gGtmc.js → words-BaumxjXe.js} +5 -3
- package/dist/assets/words-BaumxjXe.js.map +1 -0
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-tSZELCPQ.js.map +0 -1
- package/dist/assets/apiKit-BFk7GAk9.js.map +0 -1
- package/dist/assets/apps-C5Mi6x9Q.js.map +0 -1
- package/dist/assets/buttons-Bxxu3lSk.js +0 -2
- package/dist/assets/buttons-Cf70NVYq.js.map +0 -1
- package/dist/assets/errors-mnjSQlbX.js.map +0 -1
- package/dist/assets/fileBytesIdb-CsSQcSxD.js +0 -2
- package/dist/assets/groupFiles-D9Ttlm3M.js.map +0 -1
- package/dist/assets/host-DpypH-fR.js.map +0 -1
- package/dist/assets/idb-BlH8-O3R.js.map +0 -1
- package/dist/assets/main-BwgoQZVu.js.map +0 -1
- package/dist/assets/mainline-B1urhbEZ.js.map +0 -1
- package/dist/assets/profiles-C6XWqre5.js.map +0 -1
- package/dist/assets/registry-Bazitl0a.js.map +0 -1
- package/dist/assets/resolve-Bx1Eeg-w.js.map +0 -1
- package/dist/assets/server-CnPj9wWh.js.map +0 -1
- package/dist/assets/src-BsznF3XG.js.map +0 -1
- package/dist/assets/translate-cDBotA-b.js.map +0 -1
- package/dist/assets/words-qH8gGtmc.js.map +0 -1
|
@@ -1,6 +1,7 @@
|
|
|
1
|
-
import { t as CliError } from "./errors-
|
|
1
|
+
import { t as CliError } from "./errors-QUGP-jIF.js";
|
|
2
2
|
import { chmodSync, closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readFileSync, readdirSync, renameSync, rmSync, statSync, writeFileSync, writeSync } from "node:fs";
|
|
3
3
|
import { isAbsolute, join, resolve } from "node:path";
|
|
4
|
+
import { execFileSync } from "node:child_process";
|
|
4
5
|
import { createHash } from "node:crypto";
|
|
5
6
|
import { homedir, tmpdir } from "node:os";
|
|
6
7
|
//#region src/privateFolder.ts
|
|
@@ -133,6 +134,23 @@ function profilePaths(home, name) {
|
|
|
133
134
|
function lockPath(dir) {
|
|
134
135
|
return join(dir, "daemon.lock");
|
|
135
136
|
}
|
|
137
|
+
/** The file in which a daemon says it is starting: its pid, from the lock it took until its socket listens. */
|
|
138
|
+
function startingPath(dir) {
|
|
139
|
+
return join(dir, "daemon.starting");
|
|
140
|
+
}
|
|
141
|
+
/**
|
|
142
|
+
* The pid of the profile's daemon while it starts (its engine, before its socket listens): the lock's holder, when it
|
|
143
|
+
* marked its start. Null otherwise: nobody holds the profile, a one-shot command does, or the mark is a dead daemon's.
|
|
144
|
+
*/
|
|
145
|
+
function startingDaemon(paths) {
|
|
146
|
+
let pid;
|
|
147
|
+
try {
|
|
148
|
+
pid = Number(readFileSync(startingPath(paths.dir), "utf8").trim());
|
|
149
|
+
} catch {
|
|
150
|
+
return null;
|
|
151
|
+
}
|
|
152
|
+
return Number.isInteger(pid) && pid > 0 && pid === lockOwner(paths) ? pid : null;
|
|
153
|
+
}
|
|
136
154
|
/**
|
|
137
155
|
* The daemon's socket: in the profile's folder, unless that path is longer than a Unix socket may be (104 bytes on
|
|
138
156
|
* macOS); then in a folder of the user's runtime folder named after the profile's (`runtimePath`), which the daemon
|
|
@@ -186,21 +204,35 @@ function selectProfile(home, name) {
|
|
|
186
204
|
* owner. An empty lock younger than `EMPTY_LOCK_GRACE_MS` is still an older release's being written: busy. A stale
|
|
187
205
|
* lock is moved aside before it is removed, and only when what was moved is the file judged stale: one that vanished,
|
|
188
206
|
* or that another process made since, is no longer removed.
|
|
207
|
+
*
|
|
208
|
+
* The lock stays the bare pid, as older releases read it; beside it, `<lock>.<pid>.start` holds when that process
|
|
209
|
+
* started (`processStart`). A lock left by a process that died without releasing it (kill -9, Ctrl-C of a one-shot, a
|
|
210
|
+
* reboot) whose pid now belongs to another process is then stale too: it held the profile for good, every command busy
|
|
211
|
+
* until someone found the file. It is written before the lock is placed, so a lock of this release never lacks it for
|
|
212
|
+
* a moment; one without it (an older release's) is held while its pid is alive, as before.
|
|
189
213
|
*/
|
|
190
214
|
function acquireLock(paths) {
|
|
191
215
|
const mine = String(process.pid);
|
|
192
216
|
const draft = `${paths.lock}.${mine}`;
|
|
217
|
+
const start = startPath(paths.lock, process.pid);
|
|
218
|
+
const started = processStart(process.pid);
|
|
219
|
+
let placed = false;
|
|
193
220
|
writeFileSync(draft, mine, { mode: 384 });
|
|
221
|
+
if (started !== null) writeFileSync(start, started, { mode: 384 });
|
|
194
222
|
try {
|
|
195
223
|
for (let attempt = 0; attempt < 3; attempt++) {
|
|
196
224
|
if (placeLock(draft, paths.lock, mine)) {
|
|
225
|
+
placed = true;
|
|
226
|
+
heldHere.add(paths.lock);
|
|
197
227
|
let released = false;
|
|
198
228
|
return () => {
|
|
199
229
|
if (released) return;
|
|
200
230
|
released = true;
|
|
231
|
+
heldHere.delete(paths.lock);
|
|
201
232
|
try {
|
|
202
233
|
if (readFileSync(paths.lock, "utf8").trim() === mine) rmSync(paths.lock, { force: true });
|
|
203
234
|
} catch {}
|
|
235
|
+
rmSync(start, { force: true });
|
|
204
236
|
};
|
|
205
237
|
}
|
|
206
238
|
let seen;
|
|
@@ -216,9 +248,51 @@ function acquireLock(paths) {
|
|
|
216
248
|
}
|
|
217
249
|
} finally {
|
|
218
250
|
rmSync(draft, { force: true });
|
|
251
|
+
if (!placed) rmSync(start, { force: true });
|
|
219
252
|
}
|
|
220
253
|
throw new CliError("busy", `Profile ${paths.name} is in use`);
|
|
221
254
|
}
|
|
255
|
+
/** The locks this process holds: a lock naming this pid that is not one of them is a dead holder's whose pid it has now. */
|
|
256
|
+
var heldHere = /* @__PURE__ */ new Set();
|
|
257
|
+
function startPath(lock, pid) {
|
|
258
|
+
return `${lock}.${pid}.start`;
|
|
259
|
+
}
|
|
260
|
+
/**
|
|
261
|
+
* When the process `pid` started, as a text that is the same for as long as it runs and another for the next process
|
|
262
|
+
* given that pid; null where it cannot be read (Windows, a `/proc` that hides others' processes, no `ps`). On Linux the
|
|
263
|
+
* boot's id and `/proc/<pid>/stat`'s start time (clock ticks since boot); elsewhere `ps -o lstart=`.
|
|
264
|
+
*/
|
|
265
|
+
function processStart(pid) {
|
|
266
|
+
try {
|
|
267
|
+
if (process.platform === "linux") {
|
|
268
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
269
|
+
const ticks = stat.slice(stat.lastIndexOf(")") + 2).split(" ")[19];
|
|
270
|
+
if (!ticks || !/^\d+$/.test(ticks)) return null;
|
|
271
|
+
return `${readFileSync("/proc/sys/kernel/random/boot_id", "utf8").trim()} ${ticks}`;
|
|
272
|
+
}
|
|
273
|
+
if (process.platform === "win32") return null;
|
|
274
|
+
return execFileSync("ps", [
|
|
275
|
+
"-o",
|
|
276
|
+
"lstart=",
|
|
277
|
+
"-p",
|
|
278
|
+
String(pid)
|
|
279
|
+
], {
|
|
280
|
+
encoding: "utf8",
|
|
281
|
+
stdio: [
|
|
282
|
+
"ignore",
|
|
283
|
+
"pipe",
|
|
284
|
+
"ignore"
|
|
285
|
+
],
|
|
286
|
+
timeout: 2e3,
|
|
287
|
+
env: {
|
|
288
|
+
...process.env,
|
|
289
|
+
LC_ALL: "C"
|
|
290
|
+
}
|
|
291
|
+
}).trim() || null;
|
|
292
|
+
} catch {
|
|
293
|
+
return null;
|
|
294
|
+
}
|
|
295
|
+
}
|
|
222
296
|
/** How long an empty lock is taken for one an older release is still writing its pid into. */
|
|
223
297
|
var EMPTY_LOCK_GRACE_MS = 1e3;
|
|
224
298
|
/**
|
|
@@ -263,7 +337,11 @@ function removeStaleLock(lock, seen) {
|
|
|
263
337
|
}
|
|
264
338
|
try {
|
|
265
339
|
const moved = lstatSync(aside);
|
|
266
|
-
if (moved.ino === seen.ino && moved.dev === seen.dev && holder(aside) === null && moved.size === seen.size)
|
|
340
|
+
if (moved.ino === seen.ino && moved.dev === seen.dev && holder(aside, lock) === null && moved.size === seen.size) {
|
|
341
|
+
const pid = lockPid(aside);
|
|
342
|
+
if (pid !== null && pid !== process.pid) rmSync(startPath(lock, pid), { force: true });
|
|
343
|
+
return;
|
|
344
|
+
}
|
|
267
345
|
try {
|
|
268
346
|
linkSync(aside, lock);
|
|
269
347
|
} catch {}
|
|
@@ -271,26 +349,42 @@ function removeStaleLock(lock, seen) {
|
|
|
271
349
|
rmSync(aside, { force: true });
|
|
272
350
|
}
|
|
273
351
|
}
|
|
274
|
-
/**
|
|
352
|
+
/**
|
|
353
|
+
* The pid holding the profile, or null when nobody does: the lock's process is gone, or its pid is another process's
|
|
354
|
+
* now (it started at another time than the lock's holder, or it is this process, which does not hold the lock).
|
|
355
|
+
*/
|
|
275
356
|
function lockOwner(paths) {
|
|
276
|
-
return holder(paths.lock);
|
|
357
|
+
return holder(paths.lock, paths.lock);
|
|
277
358
|
}
|
|
278
|
-
function
|
|
359
|
+
function lockPid(file) {
|
|
279
360
|
let pid;
|
|
280
361
|
try {
|
|
281
362
|
pid = Number(readFileSync(file, "utf8").trim());
|
|
282
363
|
} catch {
|
|
283
364
|
return null;
|
|
284
365
|
}
|
|
285
|
-
|
|
366
|
+
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
367
|
+
}
|
|
368
|
+
/** `file`: the lock, or the stale one moved aside; `lock`: the lock's own path, beside which its start is. */
|
|
369
|
+
function holder(file, lock) {
|
|
370
|
+
const pid = lockPid(file);
|
|
371
|
+
if (pid === null) return null;
|
|
372
|
+
if (pid === process.pid) return heldHere.has(lock) ? pid : null;
|
|
286
373
|
try {
|
|
287
374
|
process.kill(pid, 0);
|
|
288
|
-
return pid;
|
|
289
375
|
} catch (error) {
|
|
290
|
-
|
|
376
|
+
if (error.code !== "EPERM") return null;
|
|
377
|
+
}
|
|
378
|
+
let recorded;
|
|
379
|
+
try {
|
|
380
|
+
recorded = readFileSync(startPath(lock, pid), "utf8").trim();
|
|
381
|
+
} catch {
|
|
382
|
+
return pid;
|
|
291
383
|
}
|
|
384
|
+
const now = processStart(pid);
|
|
385
|
+
return recorded && now !== null && now !== recorded ? null : pid;
|
|
292
386
|
}
|
|
293
387
|
//#endregion
|
|
294
|
-
export {
|
|
388
|
+
export { userPath as _, checkShownName as a, privateFolder as b, ghostlyHome as c, lockPath as d, profileExists as f, startingPath as g, startingDaemon as h, checkProfileName as i, listProfiles as l, selectProfile as m, RESTORED_MARK as n, createProfile as o, profilePaths as p, acquireLock as r, currentProfile as s, DEFAULT_PROFILE as t, lockOwner as u, ownFolder as v, runtimePath as x, ownSocket as y };
|
|
295
389
|
|
|
296
|
-
//# sourceMappingURL=profiles-
|
|
390
|
+
//# sourceMappingURL=profiles-DcCeOi7J.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"profiles-DcCeOi7J.js","names":[],"sources":["../../src/privateFolder.ts","../../src/profiles.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { chmodSync, lstatSync, mkdirSync, statSync } from \"node:fs\";\nimport { tmpdir } from \"node:os\";\nimport { isAbsolute, join } from \"node:path\";\n\n/**\n * Where a socket goes when its path in the profile is longer than a Unix socket may be: `<base>/<prefix>-<hash of the\n * profile>/<leaf>`, in `$XDG_RUNTIME_DIR` or else the temp folder (macOS gives each user one) when that folder is the\n * user's alone, so no other user can make the folder first. When neither is, or the path would still be too long:\n * `/tmp/<prefix>-<uid>-<hash>/<leaf>`. Either way `privateFolder` checks the folder before use.\n */\nexport function runtimePath(prefix: string, profileDir: string, leaf: string): string {\n const hash = createHash(\"sha256\").update(profileDir).digest(\"hex\").slice(0, 24);\n for (const base of [process.env.XDG_RUNTIME_DIR, tmpdir()]) {\n if (!base || !isAbsolute(base) || !usersAlone(base)) continue;\n const path = join(base, `${prefix}-${hash}`, leaf);\n if (Buffer.byteLength(path) <= 100) return path;\n }\n return join(\"/tmp\", `${prefix}-${process.getuid?.() ?? 0}-${hash}`, leaf);\n}\n\nfunction usersAlone(path: string): boolean {\n try {\n const info = statSync(path);\n return info.isDirectory() && (!process.getuid || info.uid === process.getuid()) && (info.mode & 0o077) === 0;\n } catch {\n return false;\n }\n}\n\n/**\n * A folder for a socket outside the profile (when the profile's path is too long for one): made owner-only, and\n * refused when it is a link, someone else made it, or anyone else may enter it.\n */\nexport function privateFolder(path: string, what: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0) {\n throw new Error(`${path} is not a folder of this user's alone: ${what}`);\n }\n}\n\n/**\n * The profile's own folder, made owner-only again before the daemon's socket goes in it: a folder made by an older\n * release, or opened up by hand, is closed rather than trusted. Refused when it is a link or someone else's.\n */\nexport function ownFolder(path: string, what: string): void {\n const info = lstatSync(path);\n if (!info.isDirectory() || (process.getuid && info.uid !== process.getuid())) throw new Error(`${path} is not a folder of this user's: ${what}`);\n if ((info.mode & 0o077) !== 0) chmodSync(path, 0o700);\n}\n\n/** False when `path` is there but is not a socket of this user's: nothing to connect to. */\nexport function ownSocket(path: string): boolean {\n if (process.platform === \"win32\") return true;\n let info;\n try { info = lstatSync(path); } catch { return true; }\n return info.isSocket() && (!process.getuid || info.uid === process.getuid());\n}\n","import { execFileSync } from \"node:child_process\";\nimport { closeSync, existsSync, linkSync, lstatSync, mkdirSync, openSync, readdirSync, readFileSync, renameSync, rmSync, statSync, writeFileSync, writeSync, type Stats } from \"node:fs\";\nimport { createHash } from \"node:crypto\";\nimport { homedir } from \"node:os\";\nimport { join, resolve } from \"node:path\";\nimport { CliError } from \"./errors\";\nimport { runtimePath } from \"./privateFolder\";\n\n/**\n * Profiles on disk (WISP 1100 § Profiles and files): `<home>/profiles/<name>/`, 0700, one engine store each.\n * `<home>/current` names the profile commands use when none is given.\n */\nexport const DEFAULT_PROFILE = \"default\";\nconst NAME = /^[a-z0-9][a-z0-9._-]{0,63}$/i;\n\n/**\n * An empty `--home` or `--profile` (an unset variable in a script) is a usage error: taken as not given, it ran the\n * command in the current folder, or as the current profile. An empty variable of the environment counts as unset.\n */\nexport function ghostlyHome(option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--home needs a folder\");\n return userPath(option ?? (process.env.GHOSTLY_HOME || join(homedir(), \".ghostly\")), true);\n}\n\n/**\n * A path the CLI was given, made absolute. A `~` the shell left alone (`--home=~/bots`, a quoted variable, a unit\n * file's `Environment=` line) is the user's home, as the shell reads it: it was a folder named `~` in the current one.\n * `~user/…` is a usage error, not a guess at another user's home, unless it is there under this folder. Any other name\n * that starts with `~` is a file here, as the shell and every other tool read it (`~notes.txt`, Office's\n * `~$report.docx`, a new `~cursor`): all of them were refused (agents#1604). `home`: the profiles' folder, where a bare\n * `~bob` that is not there is refused too, as a new profile would be made in a folder of that name.\n */\nexport function userPath(path: string, home = false): string {\n if (path === \"~\" || path.startsWith(\"~/\")) return join(homedir(), path.slice(1));\n if (path.startsWith(\"~\") && (home || path.includes(\"/\")) && !existsSync(resolve(path))) {\n throw new CliError(\"usage\", `${path}: ~user is not read here: write the ${home || path.endsWith(\"/\") ? \"folder\" : \"path\"} in full`);\n }\n return resolve(path);\n}\n\nexport function checkProfileName(name: string): string {\n if (!NAME.test(name) || name.includes(\"..\")) throw new CliError(\"usage\", `Not a profile name: ${JSON.stringify(name)} (letters, digits, \".\", \"_\" and \"-\", up to 64)`);\n return name;\n}\n\n/**\n * The name a profile shows its contacts, whichever command sets it (`--name`, `profile.set`, `settings set nick`):\n * trimmed, up to 64 characters on one line, as a group's name; empty is no name. `settings set nick` took any length\n * and every one took a line break, printed whole by `status`. `field` names it in the refusal.\n */\nexport function checkShownName(name: unknown, field = \"name\"): string {\n const shown = typeof name === \"string\" ? name.trim() : undefined;\n // Core's MAX_NICK_LENGTH: this file loads before any command, without the engine.\n if (shown === undefined || [...shown].length > 64 || /\\p{Cc}/u.test(shown)) {\n throw new CliError(\"bad_request\", `${field} must be up to 64 characters on one line`);\n }\n return shown;\n}\n\nexport function currentProfile(home: string, option?: string): string {\n if (option === \"\") throw new CliError(\"usage\", \"--profile needs a profile name\");\n if (option !== undefined) return checkProfileName(option);\n if (process.env.GHOSTLY_PROFILE) return checkProfileName(process.env.GHOSTLY_PROFILE);\n const file = join(home, \"current\");\n if (existsSync(file)) {\n const name = readFileSync(file, \"utf8\").trim();\n if (name) return checkProfileName(name);\n }\n return DEFAULT_PROFILE;\n}\n\nexport function profileDir(home: string, name: string): string {\n return join(home, \"profiles\", checkProfileName(name));\n}\n\nexport interface ProfilePaths { name: string; dir: string; db: string; socket: string; lock: string; events: string; files: string; log: string }\nexport function profilePaths(home: string, name: string): ProfilePaths {\n const dir = profileDir(home, name);\n return {\n name, dir, db: join(dir, \"db\"), socket: socketPath(dir), lock: lockPath(dir),\n events: join(dir, \"events.jsonl\"), files: join(dir, \"files\"), log: join(dir, \"daemon.log\"),\n };\n}\n\n/** The file that says which process holds the profile (`acquireLock`). */\nexport function lockPath(dir: string): string {\n return join(dir, \"daemon.lock\");\n}\n\n/** The file in which a daemon says it is starting: its pid, from the lock it took until its socket listens. */\nexport function startingPath(dir: string): string {\n return join(dir, \"daemon.starting\");\n}\n\n/**\n * The pid of the profile's daemon while it starts (its engine, before its socket listens): the lock's holder, when it\n * marked its start. Null otherwise: nobody holds the profile, a one-shot command does, or the mark is a dead daemon's.\n */\nexport function startingDaemon(paths: ProfilePaths): number | null {\n let pid: number;\n try { pid = Number(readFileSync(startingPath(paths.dir), \"utf8\").trim()); } catch { return null; }\n // Alive, and this profile's: the lock's holder is.\n return Number.isInteger(pid) && pid > 0 && pid === lockOwner(paths) ? pid : null;\n}\n\n/**\n * The daemon's socket: in the profile's folder, unless that path is longer than a Unix socket may be (104 bytes on\n * macOS); then in a folder of the user's runtime folder named after the profile's (`runtimePath`), which the daemon\n * makes owner-only and checks before use (`privateFolder`), and whose socket a client connects to only when it is this\n * user's (`ownSocket`).\n */\nfunction socketPath(dir: string): string {\n const inside = join(dir, \"daemon.sock\");\n if (process.platform === \"win32\") return `\\\\\\\\.\\\\pipe\\\\ghostly-${createHash(\"sha256\").update(dir).digest(\"hex\").slice(0, 24)}`;\n if (Buffer.byteLength(inside) <= 100) return inside;\n return runtimePath(\"ghostly\", dir, \"daemon.sock\");\n}\n\nfunction ensureFolder(path: string): void {\n mkdirSync(path, { recursive: true, mode: 0o700 });\n}\n\n/** Makes the profile's folder; refused when it exists and `existing` is not allowed. */\nexport function createProfile(home: string, name: string, { existing = false } = {}): ProfilePaths {\n const paths = profilePaths(home, name);\n if (existsSync(paths.dir) && !existing) throw new CliError(\"refused\", `Profile ${name} exists`);\n ensureFolder(join(home, \"profiles\"));\n ensureFolder(paths.dir);\n return paths;\n}\n\n/**\n * A file in the folder of a profile a restore made, until its engine starts for the first time: the store came back\n * whole, as the backup held it, and the money in it is then treated as every restore treats it (WISP 05 § Restoring).\n */\nexport const RESTORED_MARK = \"restored\";\n\nexport function profileExists(home: string, name: string): boolean {\n return existsSync(profileDir(home, name));\n}\n\nexport function listProfiles(home: string): string[] {\n const root = join(home, \"profiles\");\n if (!existsSync(root)) return [];\n return readdirSync(root).filter((name) => NAME.test(name) && statSync(join(root, name)).isDirectory()).sort();\n}\n\nexport function selectProfile(home: string, name: string): void {\n if (!profileExists(home, name)) throw new CliError(\"not_found\", `No profile ${name}`);\n ensureFolder(home);\n writeFileSync(join(home, \"current\"), name + \"\\n\", { mode: 0o600 });\n}\n\n/**\n * One process per profile: the daemon or a one-shot command. The lock holds the owner's pid; a lock whose\n * process is gone is taken over.\n *\n * The lock is a link to a file that already holds the pid, so it never exists empty (agents#1642): one made by\n * `openSync` + `writeSync` was empty for a moment, and another process read that as nobody's and removed it under its\n * owner. An empty lock younger than `EMPTY_LOCK_GRACE_MS` is still an older release's being written: busy. A stale\n * lock is moved aside before it is removed, and only when what was moved is the file judged stale: one that vanished,\n * or that another process made since, is no longer removed.\n *\n * The lock stays the bare pid, as older releases read it; beside it, `<lock>.<pid>.start` holds when that process\n * started (`processStart`). A lock left by a process that died without releasing it (kill -9, Ctrl-C of a one-shot, a\n * reboot) whose pid now belongs to another process is then stale too: it held the profile for good, every command busy\n * until someone found the file. It is written before the lock is placed, so a lock of this release never lacks it for\n * a moment; one without it (an older release's) is held while its pid is alive, as before.\n */\nexport function acquireLock(paths: ProfilePaths): () => void {\n const mine = String(process.pid);\n const draft = `${paths.lock}.${mine}`;\n const start = startPath(paths.lock, process.pid);\n const started = processStart(process.pid);\n let placed = false;\n writeFileSync(draft, mine, { mode: 0o600 });\n if (started !== null) writeFileSync(start, started, { mode: 0o600 });\n try {\n for (let attempt = 0; attempt < 3; attempt++) {\n if (placeLock(draft, paths.lock, mine)) {\n placed = true;\n heldHere.add(paths.lock);\n let released = false;\n return () => {\n if (released) return;\n released = true;\n heldHere.delete(paths.lock);\n try { if (readFileSync(paths.lock, \"utf8\").trim() === mine) rmSync(paths.lock, { force: true }); } catch { /* gone already */ }\n rmSync(start, { force: true });\n };\n }\n let seen: Stats;\n try { seen = lstatSync(paths.lock); } catch { continue; }\n const owner = lockOwner(paths);\n if (owner !== null) throw new CliError(\"busy\", `Profile ${paths.name} is in use by process ${owner}`, { pid: owner });\n if (seen.size === 0 && Date.now() - seen.mtimeMs < EMPTY_LOCK_GRACE_MS) break;\n removeStaleLock(paths.lock, seen);\n }\n } finally {\n rmSync(draft, { force: true });\n if (!placed) rmSync(start, { force: true });\n }\n throw new CliError(\"busy\", `Profile ${paths.name} is in use`);\n}\n\n/** The locks this process holds: a lock naming this pid that is not one of them is a dead holder's whose pid it has now. */\nconst heldHere = new Set<string>();\n\nfunction startPath(lock: string, pid: number): string {\n return `${lock}.${pid}.start`;\n}\n\n/**\n * When the process `pid` started, as a text that is the same for as long as it runs and another for the next process\n * given that pid; null where it cannot be read (Windows, a `/proc` that hides others' processes, no `ps`). On Linux the\n * boot's id and `/proc/<pid>/stat`'s start time (clock ticks since boot); elsewhere `ps -o lstart=`.\n */\nexport function processStart(pid: number): string | null {\n try {\n if (process.platform === \"linux\") {\n const stat = readFileSync(`/proc/${pid}/stat`, \"utf8\");\n // Fields after the command, which may hold spaces and parentheses: the start time is field 22.\n const ticks = stat.slice(stat.lastIndexOf(\")\") + 2).split(\" \")[19];\n if (!ticks || !/^\\d+$/.test(ticks)) return null;\n return `${readFileSync(\"/proc/sys/kernel/random/boot_id\", \"utf8\").trim()} ${ticks}`;\n }\n if (process.platform === \"win32\") return null;\n const lstart = execFileSync(\"ps\", [\"-o\", \"lstart=\", \"-p\", String(pid)], {\n encoding: \"utf8\", stdio: [\"ignore\", \"pipe\", \"ignore\"], timeout: 2_000, env: { ...process.env, LC_ALL: \"C\" },\n }).trim();\n return lstart || null;\n } catch {\n return null;\n }\n}\n\n/** How long an empty lock is taken for one an older release is still writing its pid into. */\nconst EMPTY_LOCK_GRACE_MS = 1_000;\n\n/**\n * Links `draft` (which holds `mine`) as the lock; false when there is a lock already. Where the file system has no\n * hard links, the lock is made in place, as before.\n */\nfunction placeLock(draft: string, lock: string, mine: string): boolean {\n try {\n linkSync(draft, lock);\n return true;\n } catch (error) {\n const code = (error as NodeJS.ErrnoException).code;\n if (code === \"EEXIST\") return false;\n if (![\"EPERM\", \"ENOTSUP\", \"EOPNOTSUPP\", \"ENOSYS\"].includes(code ?? \"\")) throw error;\n }\n let fd: number;\n try { fd = openSync(lock, \"wx\", 0o600); } catch (error) {\n if ((error as NodeJS.ErrnoException).code === \"EEXIST\") return false;\n throw error;\n }\n writeSync(fd, mine);\n closeSync(fd);\n return true;\n}\n\n/**\n * Removes the lock judged stale (`seen`): it is moved aside first, and removed only when what was moved is that same\n * file and holds no live pid (a freed inode is soon reused). A lock another process made in the meantime is put back.\n */\nfunction removeStaleLock(lock: string, seen: Stats): void {\n const aside = `${lock}.stale.${process.pid}`;\n try { renameSync(lock, aside); } catch { return; }\n try {\n const moved = lstatSync(aside);\n if (moved.ino === seen.ino && moved.dev === seen.dev && holder(aside, lock) === null && moved.size === seen.size) {\n const pid = lockPid(aside);\n if (pid !== null && pid !== process.pid) rmSync(startPath(lock, pid), { force: true });\n return;\n }\n try { linkSync(aside, lock); } catch { /* another lock is there already */ }\n } finally {\n rmSync(aside, { force: true });\n }\n}\n\n/**\n * The pid holding the profile, or null when nobody does: the lock's process is gone, or its pid is another process's\n * now (it started at another time than the lock's holder, or it is this process, which does not hold the lock).\n */\nexport function lockOwner(paths: ProfilePaths): number | null {\n return holder(paths.lock, paths.lock);\n}\n\nfunction lockPid(file: string): number | null {\n let pid: number;\n try { pid = Number(readFileSync(file, \"utf8\").trim()); } catch { return null; }\n return Number.isInteger(pid) && pid > 0 ? pid : null;\n}\n\n/** `file`: the lock, or the stale one moved aside; `lock`: the lock's own path, beside which its start is. */\nfunction holder(file: string, lock: string): number | null {\n const pid = lockPid(file);\n if (pid === null) return null;\n if (pid === process.pid) return heldHere.has(lock) ? pid : null;\n try { process.kill(pid, 0); } catch (error) { if ((error as NodeJS.ErrnoException).code !== \"EPERM\") return null; }\n let recorded: string;\n try { recorded = readFileSync(startPath(lock, pid), \"utf8\").trim(); } catch { return pid; }\n const now = processStart(pid);\n return recorded && now !== null && now !== recorded ? null : pid;\n}\n"],"mappings":";;;;;;;;;;;;;AAWA,SAAgB,YAAY,QAAgB,YAAoB,MAAsB;CACpF,MAAM,OAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,UAAU,CAAC,CAAC,OAAO,KAAK,CAAC,CAAC,MAAM,GAAG,EAAE;CAC9E,KAAK,MAAM,QAAQ,CAAC,QAAQ,IAAI,iBAAiB,OAAO,CAAC,GAAG;EAC1D,IAAI,CAAC,QAAQ,CAAC,WAAW,IAAI,KAAK,CAAC,WAAW,IAAI,GAAG;EACrD,MAAM,OAAO,KAAK,MAAM,GAAG,OAAO,GAAG,QAAQ,IAAI;EACjD,IAAI,OAAO,WAAW,IAAI,KAAK,KAAK,O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AAQ,QAAQ,KAAK,OAAO,UAAU,MAAM,GAAG,GAAG,EAAE,OAAO,KAAK,CAAC;GACrF;EACF;EACA,IAAI;GAAE,SAAS,OAAO,IAAI;EAAG,QAAQ,CAAsC;CAC7E,UAAU;EACR,OAAO,OAAO,EAAE,OAAO,KAAK,CAAC;CAC/B;AACF;;;;;AAMA,SAAgB,UAAU,OAAoC;CAC5D,OAAO,OAAO,MAAM,MAAM,MAAM,IAAI;AACtC;AAEA,SAAS,QAAQ,MAA6B;CAC5C,IAAI;CACJ,IAAI;EAAE,MAAM,OAAO,aAAa,MAAM,MAAM,CAAC,CAAC,KAAK,CAAC;CAAG,QAAQ;EAAE,OAAO;CAAM;CAC9E,OAAO,OAAO,UAAU,GAAG,KAAK,MAAM,IAAI,MAAM;AAClD;;AAGA,SAAS,OAAO,MAAc,MAA6B;CACzD,MAAM,MAAM,QAAQ,IAAI;CACxB,IAAI,QAAQ,MAAM,OAAO;CACzB,IAAI,QAAQ,QAAQ,KAAK,OAAO,SAAS,IAAI,IAAI,IAAI,MAAM;CAC3D,IAAI;EAAE,QAAQ,KAAK,KAAK,CAAC;CAAG,SAAS,OAAO;EAAE,IAAK,MAAgC,SAAS,SAAS,OAAO;CAAM;CAClH,IAAI;CACJ,IAAI;EAAE,WAAW,aAAa,UAAU,MAAM,GAAG,GAAG,MAAM,CAAC,CAAC,KAAK;CAAG,QAAQ;EAAE,OAAO;CAAK;CAC1F,MAAM,MAAM,aAAa,GAAG;CAC5B,OAAO,YAAY,QAAQ,QAAQ,QAAQ,WAAW,OAAO;AAC/D"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { n as identityProvider, r as identityProviders, t as IDENTITY_PROVIDERS } from "./registry-
|
|
1
|
+
import { n as identityProvider, r as identityProviders, t as IDENTITY_PROVIDERS } from "./registry-CeW8XEQc.js";
|
|
2
2
|
export { IDENTITY_PROVIDERS, identityProvider, identityProviders };
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { $ as
|
|
2
|
-
import { _ as reserveAdapterIds, a as DomainCheckError, b as testBuild, c as assertPublicHost, d as ownDid, i as verifiedAtprotoHandle, l as chosenResolver, m as registeredIdentityProviders, n as resolveAtprotoDid, o as assertDomainRecord, r as resolveAtprotoHandle, s as assertNip05, t as assertPublicServer, u as resolverById, v as boundedIdentityFetch } from "./resolve-
|
|
1
|
+
import { $ as SshSigError, At as didSignedMessages, Bi as IdentityCheckUnavailable, Bt as signingKeys, Ci as domainWellKnownFile, Cn as homeserverWebEndpoint, Ct as DID_FILE_MAX_BYTES, Cu as randomBytes, Di as normalizeDomain, Dt as checkDidSignature, Du as utf8Encode, Et as checkDidJws, Eu as utf8Decode, Ft as didWebHost, Ht as strictBase64Url, It as normalizeDid, Lt as parseDid, Mi as wellKnownUrl, Mt as didWebFile, Nt as didWebFileNames, Ot as didGhostlyServiceEntry, Pt as didWebFileUrl, Q as SSHSIG_NAMESPACE, Rt as parseDidDocument, Si as domainTxtRecord, Sn as pubkyProofPath, St as DID_DOCUMENT_MAX_BYTES, Tt as DidError, Vt as staticDidDocument, _n as isPubkyProofFolder, _t as normalizeAtprotoHandle, at as verifyBitcoinMessage, bn as pubkyProofCapability, bt as AtprotoProofError, ct as ATPROTO_DECLARED_SCOPE, dt as ATPROTO_PROOF_SCOPE, et as parseSshPublicKey, gn as isPubkyKey, gt as isAtprotoDid, hn as PUBKY_PROOF_MAX_BYTES, ht as checkAtprotoProofRecord, it as verifySshSignature, jt as didWebDocumentUrl, kt as didJwsAlg, lt as ATPROTO_FULL_SCOPE, mt as atprotoProofRkey, nt as sameSshKey, ot as BitcoinAddressError, pt as atprotoProofRecord, qt as resolveDidDht, rt as sshSignCommand, st as decodeAnyBitcoinAddress, su as RELAY_PAYLOAD_MAX_BYTES, tt as parseSshSignature, ut as ATPROTO_PROOF_COLLECTION, uu as openRelayPayload, vn as newPubkyProofFolder, wn as pubkyHomeserverOf, wu as toBase64Url, xi as dnsProofName, xn as pubkyProofFile, xt as verifyAtprotoRecordProof, xu as fromBase64Url, yn as normalizePubkyKey, yt as shortAtprotoDid, zt as parseDidSignaturePaste } from "./src-BB5-5P3s.js";
|
|
2
|
+
import { _ as reserveAdapterIds, a as DomainCheckError, b as testBuild, c as assertPublicHost, d as ownDid, i as verifiedAtprotoHandle, l as chosenResolver, m as registeredIdentityProviders, n as resolveAtprotoDid, o as assertDomainRecord, r as resolveAtprotoHandle, s as assertNip05, t as assertPublicServer, u as resolverById, v as boundedIdentityFetch } from "./resolve-BvHkAhDH.js";
|
|
3
3
|
import { ed25519 } from "@noble/curves/ed25519.js";
|
|
4
4
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
5
5
|
import { schnorr } from "@noble/curves/secp256k1.js";
|
|
@@ -496,6 +496,20 @@ var nostr = {
|
|
|
496
496
|
};
|
|
497
497
|
//#endregion
|
|
498
498
|
//#region ../browser/src/proofs/providers/domain.ts
|
|
499
|
+
/**
|
|
500
|
+
* A long domain as a card shows it: its end, the part that names who owns it (`…ghostly.tools`), never its start, which
|
|
501
|
+
* is whatever the owner chose (`github.com.account-…` under any domain they own). Whole labels from the end, as many as
|
|
502
|
+
* fit in `room` characters; when they leave less than half of it (`…co.uk`, one long label before it), the end's
|
|
503
|
+
* characters instead.
|
|
504
|
+
*/
|
|
505
|
+
function shortDomain(domain, room = 24) {
|
|
506
|
+
if (domain.length <= room) return domain;
|
|
507
|
+
const labels = domain.split(".");
|
|
508
|
+
let end = labels.pop() ?? "";
|
|
509
|
+
while (labels.length && end.length + 1 + labels[labels.length - 1].length <= room - 1) end = `${labels.pop()}.${end}`;
|
|
510
|
+
if (end.length < room / 2) end = domain.slice(-(room - 1));
|
|
511
|
+
return `…${end}`;
|
|
512
|
+
}
|
|
499
513
|
var recordFor = (s) => ({
|
|
500
514
|
key: s.binding.key,
|
|
501
515
|
proof: s.id
|
|
@@ -608,7 +622,8 @@ var domain = {
|
|
|
608
622
|
label: "Domain",
|
|
609
623
|
placeholder: "example.com",
|
|
610
624
|
help: "A domain or subdomain you control. A proof for alice.example.com is published under alice.example.com.",
|
|
611
|
-
normalize: normalizeDomain
|
|
625
|
+
normalize: normalizeDomain,
|
|
626
|
+
short: (domain) => shortDomain(domain)
|
|
612
627
|
},
|
|
613
628
|
publicUri: (domain) => `https://${domain}`,
|
|
614
629
|
validity: {
|
|
@@ -1864,7 +1879,7 @@ async function verifyIdToken(token, options) {
|
|
|
1864
1879
|
const iat = claims.iat, exp = claims.exp, nbf = claims.nbf;
|
|
1865
1880
|
if (typeof iat !== "number" || typeof exp !== "number" || !Number.isFinite(iat) || !Number.isFinite(exp)) return refuse("Token has no validity window");
|
|
1866
1881
|
if (exp <= iat || exp - iat > MAX_LIFETIME) refuse("Token validity window refused");
|
|
1867
|
-
if (iat > now + 60) refuse("Token is not valid yet");
|
|
1882
|
+
if (iat > now + (options.issuedWithin ? 300 : 60)) refuse("Token is not valid yet");
|
|
1868
1883
|
if (options.issuedWithin) {
|
|
1869
1884
|
const [from, to] = options.issuedWithin;
|
|
1870
1885
|
if (iat < from || iat > to) refuse("The sign-in does not belong to this proof: it happened at another time");
|
|
@@ -2208,11 +2223,12 @@ async function fetchDidWeb(did, url, maxBytes, options) {
|
|
|
2208
2223
|
});
|
|
2209
2224
|
} catch (e) {
|
|
2210
2225
|
if (options.signal?.aborted) throw e;
|
|
2211
|
-
|
|
2226
|
+
if (/too large/i.test(String(e))) throw new DidError(`${url} is too large`);
|
|
2227
|
+
throw new IdentityCheckUnavailable(`${host} could not be reached. It must serve ${url} over HTTPS, without a redirect, with the header Access-Control-Allow-Origin: *`);
|
|
2212
2228
|
}
|
|
2213
2229
|
if (response.status === 404 || response.status === 410) return void 0;
|
|
2214
|
-
if (response.status >= 300 && response.status < 400) throw new
|
|
2215
|
-
if (response.status !== 200) throw new
|
|
2230
|
+
if (response.status >= 300 && response.status < 400) throw new IdentityCheckUnavailable(`${host} answered with a redirect; it must serve exactly ${url}`);
|
|
2231
|
+
if (response.status !== 200) throw new IdentityCheckUnavailable(`${host} answered ${response.status} for ${url}`);
|
|
2216
2232
|
try {
|
|
2217
2233
|
return new TextDecoder("utf-8", { fatal: true }).decode(response.bytes);
|
|
2218
2234
|
} catch {
|
|
@@ -2858,6 +2874,12 @@ function currentHost() {
|
|
|
2858
2874
|
}
|
|
2859
2875
|
}
|
|
2860
2876
|
var hostOf = (url) => new URL(url).host;
|
|
2877
|
+
/** Why the card shows the DID and no handle. */
|
|
2878
|
+
var HANDLE_NOT_SHOWN = {
|
|
2879
|
+
none: "The account's DID document names no handle",
|
|
2880
|
+
elsewhere: "The account's handle does not point back to it, so it is not shown",
|
|
2881
|
+
unchecked: "The account's handle could not be checked, so it is not shown"
|
|
2882
|
+
};
|
|
2861
2883
|
function createAtprotoIdentityProvider(options = {}) {
|
|
2862
2884
|
const host = options.host ?? currentHost;
|
|
2863
2885
|
const uiFetch = () => options.fetch ?? boundedIdentityFetch({ online: () => true });
|
|
@@ -2977,7 +2999,8 @@ function createAtprotoIdentityProvider(options = {}) {
|
|
|
2977
2999
|
redirect: "error"
|
|
2978
3000
|
});
|
|
2979
3001
|
} catch (e) {
|
|
2980
|
-
|
|
3002
|
+
if (/too large/i.test(String(e))) throw new Error("The account's server sent a proof that is too large");
|
|
3003
|
+
throw new IdentityCheckUnavailable(`The account's server (${hostOf(doc.pds)}) could not be reached`);
|
|
2981
3004
|
}
|
|
2982
3005
|
if (response.status !== 200) {
|
|
2983
3006
|
let code = "";
|
|
@@ -2986,7 +3009,7 @@ function createAtprotoIdentityProvider(options = {}) {
|
|
|
2986
3009
|
} catch {}
|
|
2987
3010
|
if (code === "RecordNotFound") throw new Error("The record is no longer in the account's repository");
|
|
2988
3011
|
if (/^Repo(NotFound|Deactivated|Takendown|Suspended)$/.test(code)) throw new Error("The account is no longer on its server");
|
|
2989
|
-
throw new
|
|
3012
|
+
throw new IdentityCheckUnavailable(`The account's server (${hostOf(doc.pds)}) did not send the record`);
|
|
2990
3013
|
}
|
|
2991
3014
|
let proof;
|
|
2992
3015
|
try {
|
|
@@ -3001,14 +3024,14 @@ function createAtprotoIdentityProvider(options = {}) {
|
|
|
3001
3024
|
}
|
|
3002
3025
|
if (!proof.record) throw new Error("The record is no longer in the account's repository");
|
|
3003
3026
|
checkAtprotoProofRecord(proof.record.value, statement);
|
|
3004
|
-
const handle = await verifiedAtprotoHandle(doc, resolve);
|
|
3027
|
+
const { handle, missing } = await verifiedAtprotoHandle(doc, resolve);
|
|
3005
3028
|
return {
|
|
3006
3029
|
subject: did,
|
|
3007
3030
|
source: `Record signed with the account's key, from ${hostOf(doc.pds)}`,
|
|
3008
3031
|
display: {
|
|
3009
3032
|
...handle ? { name: `@${handle}` } : {},
|
|
3010
3033
|
url: `https://bsky.app/profile/${did}`,
|
|
3011
|
-
source:
|
|
3034
|
+
source: missing ? HANDLE_NOT_SHOWN[missing] : "Handle checked both ways: it points to this account",
|
|
3012
3035
|
fetchedAt: ctx.now
|
|
3013
3036
|
}
|
|
3014
3037
|
};
|
|
@@ -3069,14 +3092,22 @@ async function pubkyRecords(key, fetch, signal, relays = PUBKY_RELAYS) {
|
|
|
3069
3092
|
}
|
|
3070
3093
|
}))).filter((a) => !!a).sort((a, b) => b.seq > a.seq ? 1 : b.seq < a.seq ? -1 : 0)[0];
|
|
3071
3094
|
if (!newest && failed.length === relays.length && failed[0] instanceof Error) throw failed[0];
|
|
3072
|
-
if (!newest) throw new
|
|
3095
|
+
if (!newest) throw new NoPkarrRecords("This Pubky key has no records on the Pkarr relays");
|
|
3073
3096
|
return newest.dnsPacket;
|
|
3074
3097
|
}
|
|
3098
|
+
var NoPkarrRecords = class extends Error {};
|
|
3075
3099
|
/** Where `key`'s homeserver answers browsers: its `_pubky` record, then the homeserver's own HTTPS record. */
|
|
3076
3100
|
async function pubkyHomeserver(key, fetch, signal, relays) {
|
|
3077
3101
|
const homeserver = pubkyHomeserverOf(await pubkyRecords(key, fetch, signal, relays), key);
|
|
3078
3102
|
if (!homeserver) throw new Error("This Pubky key names no homeserver");
|
|
3079
|
-
|
|
3103
|
+
let records;
|
|
3104
|
+
try {
|
|
3105
|
+
records = await pubkyRecords(homeserver, fetch, signal, relays);
|
|
3106
|
+
} catch (e) {
|
|
3107
|
+
if (e instanceof NoPkarrRecords) throw new Error("The homeserver of this Pubky key has no records on the Pkarr relays");
|
|
3108
|
+
throw e;
|
|
3109
|
+
}
|
|
3110
|
+
const endpoint = homeserverWebEndpoint(records, homeserver);
|
|
3080
3111
|
if (!endpoint) throw new Error("The homeserver of this Pubky key publishes no address a browser can reach");
|
|
3081
3112
|
return {
|
|
3082
3113
|
homeserver,
|
|
@@ -3775,4 +3806,4 @@ function identityProvider(id, providers = identityProviders()) {
|
|
|
3775
3806
|
//#endregion
|
|
3776
3807
|
export { identityProvider as n, identityProviders as r, IDENTITY_PROVIDERS as t };
|
|
3777
3808
|
|
|
3778
|
-
//# sourceMappingURL=registry-
|
|
3809
|
+
//# sourceMappingURL=registry-CeW8XEQc.js.map
|