@join-pantheon/cli 0.33.9 → 0.33.10-rc.1

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/dist/relay.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createServer } from "node:http";
2
2
  import { createHash, randomBytes, timingSafeEqual as timingSafeEqualBuf } from "node:crypto";
3
- import { copyFileSync, readdirSync, readFileSync, statSync, existsSync, writeFileSync, openSync, readSync, closeSync, fstatSync, promises as fsp } from "node:fs";
3
+ import { copyFileSync, readdirSync, readFileSync, renameSync, rmSync, statSync, existsSync, writeFileSync, openSync, readSync, closeSync, fstatSync, promises as fsp } from "node:fs";
4
4
  import { spawn } from "node:child_process";
5
5
  import { monitorEventLoopDelay } from "node:perf_hooks";
6
6
  import { basename, join } from "node:path";
@@ -16,7 +16,7 @@ import { emailSenderFromEnv, maskEmail } from "./email.js";
16
16
  import { Allowlist, RosterUnreadable } from "./roster-file.js";
17
17
  import { StateStore, ensurePrivateDir, setWaitForDisk, takeSlowestDiskWait, waitsForDisk } from "./store.js";
18
18
  import { countGoal, countMessage, emptyUsage, parseUsage, usageAnswer, USAGE_KEEP_DAYS, USAGE_SHOW_DAYS } from "./usage.js";
19
- import { busyWriter, DiskBusy, flushWrites, onWriteError, pendingView, readLatest, recordWrites, whenLanded, writerFor } from "./disk-writer.js";
19
+ import { busyWriter, DiskBusy, flushWrites, onWriteError, pendingView, recordWrites, whenLanded, writerFor } from "./disk-writer.js";
20
20
  import { activity, mergeActivity, feed, noteRefusal, refusalsSince, countActs, spaceHealth, fleetReport, ESCALATIONS, MESSAGE_ACTS, ACT_TONE, DAY } from "./admin-stats.js";
21
21
  import { fmtLimit, inviteLimit, parseLimits, planLimits, PLAN_NAME } from "./plans.js";
22
22
  import { FEEDBACK_ADDRESS } from "./feedback.js";
@@ -436,6 +436,27 @@ export function upgradeHoldFrom(raw, relayVersion, log = () => { }) {
436
436
  export function advertisedPkg(hold, relayVersion) {
437
437
  return hold ?? (relayVersion.includes("-") ? null : relayVersion);
438
438
  }
439
+ export const TOMB_TEAMS_KEPT = 50;
440
+ export class TombstoneUnsafe extends Error {
441
+ }
442
+ export function tombTeams(t) {
443
+ if (t.teams?.length)
444
+ return t.teams;
445
+ const hashes = [...(t.tokenHash ? [t.tokenHash] : []), ...(t.retiredTokenHashes ?? [])];
446
+ return [{ name: t.name, at: t.at, hashes, ...(t.by ? { by: t.by } : {}), ...(t.how ? { how: t.how } : {}), ...(t.id ? { id: t.id } : {}) }];
447
+ }
448
+ export const DELETED_NAME_HOLD_MS = 3_600_000;
449
+ const UTC_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
450
+ const dayOf = (at) => { const d = new Date(at); return `${d.getUTCDate()} ${UTC_MONTHS[d.getUTCMonth()]}, ${String(d.getUTCHours()).padStart(2, "0")}:${String(d.getUTCMinutes()).padStart(2, "0")} UTC`; };
451
+ export function goneAnswer(t) {
452
+ return { gone: "deleted", by: t.by ?? null, at: t.at, ...(t.id ? { space_id: t.id } : {}) };
453
+ }
454
+ export function deletedWords(t) {
455
+ const who = t.by && t.by !== "operator" ? ` by its founder ${t.by}` : t.how === "operator" || t.by === "operator" ? " by the relay operator" : "";
456
+ return `the team "${t.name}" was deleted${who} on ${dayOf(t.at)}; it no longer exists on this relay. Remove it from this computer: pantheon leave ${t.id ?? relayShellArg(t.name)}`;
457
+ }
458
+ const deletedNameWords = (name) => `the space "${name}" was deleted. Start a new one with a different name, or contact the relay operator.`;
459
+ const removedWords = (member, name, by) => `"${member}" was removed from "${name}"${by ? ` by ${by}` : ""}. Only a member of the team can let you back in.`;
439
460
  export class Relay {
440
461
  opts;
441
462
  advertisedPkg() { return advertisedPkg(this.upgradeHold, VERSION); }
@@ -758,7 +779,7 @@ export class Relay {
758
779
  if (!gate.ok && gate.notice)
759
780
  return this.upgradeAnswer(res, url.pathname, url, gate.notice, gate.error);
760
781
  if (!gate.ok)
761
- return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}) });
782
+ return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}), ...(gate.gone ?? {}) });
762
783
  const space = gate.space;
763
784
  const act = space.ledger.find(url.searchParams.get("id") ?? "");
764
785
  if (!act)
@@ -771,7 +792,7 @@ export class Relay {
771
792
  if (!gate.ok && gate.notice)
772
793
  return this.upgradeAnswer(res, url.pathname, url, gate.notice, gate.error);
773
794
  if (!gate.ok)
774
- return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}) });
795
+ return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}), ...(gate.gone ?? {}) });
775
796
  const space = gate.space;
776
797
  const goal = url.searchParams.get("goal");
777
798
  const sinceRaw = url.searchParams.get("since");
@@ -785,7 +806,7 @@ export class Relay {
785
806
  return this.json(res, 401, { ...v, code: "SIGNED_ONLY", error: "a team's usage is read signed, by its founder: pantheon usage" });
786
807
  const gate = this.readGate(req, url, ip);
787
808
  if (!gate.ok)
788
- return this.json(res, gate.status, { ...v, error: gate.error, ...(gate.code ? { code: gate.code } : {}) });
809
+ return this.json(res, gate.status, { ...v, error: gate.error, ...(gate.code ? { code: gate.code } : {}), ...(gate.gone ?? {}) });
789
810
  const space = gate.space;
790
811
  if (url.searchParams.has("dpub"))
791
812
  return this.json(res, 403, { ...v, code: "NOT_FOR_A_RUN", error: "an unattended run cannot read the team's usage" });
@@ -801,7 +822,7 @@ export class Relay {
801
822
  if (!gate.ok && gate.notice)
802
823
  return this.upgradeAnswer(res, url.pathname, url, gate.notice, gate.error);
803
824
  if (!gate.ok)
804
- return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}) });
825
+ return this.json(res, gate.status, { error: gate.error, ...(gate.code ? { code: gate.code } : {}), ...(gate.gone ?? {}) });
805
826
  const space = gate.space;
806
827
  const member = url.searchParams.get("member");
807
828
  const now = Date.now();
@@ -1640,34 +1661,162 @@ button:hover{background:#1d4ed8}.err{color:var(--bad);margin-top:12px}
1640
1661
  const { goals } = st.load();
1641
1662
  return { goals, refusals: st.refusals };
1642
1663
  }
1643
- deleteSpace(name) {
1644
- const sp = this.spaces.get(spaceKey(name));
1664
+ resolveTeam(typed) {
1665
+ const read = (stem) => { try {
1666
+ return new Allowlist(this.dataDir, stem);
1667
+ }
1668
+ catch {
1669
+ return null;
1670
+ } };
1671
+ const named = (stem) => {
1672
+ const roster = read(stem);
1673
+ let recorded = roster?.recordedName() ?? null;
1674
+ if (!recorded && this.accounts) {
1675
+ const rows = this.accounts.spaceRowsWithStem(stem);
1676
+ if (rows.length === 1)
1677
+ recorded = rows[0];
1678
+ }
1679
+ return { name: recorded ?? stem, stem, id: roster?.peekId() ?? null };
1680
+ };
1681
+ const live = this.live(typed);
1682
+ if (live)
1683
+ return { team: { name: live.name, stem: safeName(live.name), id: live.allow.peekId() } };
1684
+ const exact = safeName(typed);
1685
+ const queued = (stem) => [".members.json", ".jsonl", ".state.json"].some((suf) => {
1686
+ const f = join(this.dataDir, `${stem}${suf}`);
1687
+ const q = pendingView(this.dataDir, stem, f);
1688
+ return q !== undefined && q !== null;
1689
+ });
1690
+ let stems = [];
1691
+ try {
1692
+ stems = [...new Set(readdirSync(this.dataDir).flatMap((f) => { const m = /^(.*)\.(members\.json|jsonl)$/.exec(f); return m && m[1].toLowerCase() === exact.toLowerCase() ? [m[1]] : []; }))];
1693
+ }
1694
+ catch { }
1695
+ if (stems.includes(exact) || (!stems.length && queued(exact))) {
1696
+ const recorded = read(exact)?.recordedName() ?? null;
1697
+ const t = named(exact);
1698
+ if (recorded && recorded !== typed) {
1699
+ const dup = this.accounts ? this.accounts.spaceRowsWithStem(exact).filter((n) => n !== recorded) : [];
1700
+ return { refused: `"${typed}" is the file name of the team "${recorded}"${t.id ? ` (${t.id})` : ""} — type its exact name or id. Nothing changed.${dup.length ? ` ${dup.length} plan record${dup.length === 1 ? " is" : "s are"} spelled like its file name (${dup.join(", ")}), left as ${dup.length === 1 ? "it is" : "they are"}.` : ""}` };
1701
+ }
1702
+ return { team: { ...t, name: recorded ?? (t.name === exact && typed !== exact ? typed : t.name) } };
1703
+ }
1704
+ if (/^sp_[A-Za-z0-9_-]{8,64}$/.test(typed)) {
1705
+ for (const sp of this.spaces.values())
1706
+ if (sp.allow.peekId() === typed)
1707
+ return { team: { name: sp.name, stem: safeName(sp.name), id: typed } };
1708
+ try {
1709
+ for (const f of readdirSync(this.dataDir)) {
1710
+ if (!f.endsWith(".members.json"))
1711
+ continue;
1712
+ const stem = f.slice(0, -".members.json".length);
1713
+ if (read(stem)?.peekId() === typed)
1714
+ return { team: named(stem) };
1715
+ }
1716
+ }
1717
+ catch { }
1718
+ }
1719
+ for (const sp of this.spaces.values())
1720
+ if (spaceKey(sp.name) === spaceKey(typed) && !stems.includes(safeName(sp.name)))
1721
+ stems.push(safeName(sp.name));
1722
+ const others = stems.map((st) => { const sp = [...this.spaces.values()].find((x) => safeName(x.name) === st); return sp ? { name: sp.name, stem: st, id: sp.allow.peekId() } : named(st); });
1723
+ if (others.length === 1 && !this.accounts?.liveSpaceRow(typed) && this.diskIgnoresCase(others[0].stem))
1724
+ return { team: others[0] };
1725
+ return { others: others.map(({ name, id }) => ({ name, id })) };
1726
+ }
1727
+ diskIgnoresCase(stem) {
1728
+ const f = [".members.json", ".jsonl"].map((suf) => `${stem}${suf}`).find((x) => existsSync(join(this.dataDir, x)));
1729
+ return !!f && this.fileIgnoresCase(f);
1730
+ }
1731
+ fileIgnoresCase(f) {
1732
+ const flipped = f.replace(/[a-z]/gi, (c) => (c === c.toLowerCase() ? c.toUpperCase() : c.toLowerCase()));
1733
+ if (flipped === f)
1734
+ return false;
1735
+ try {
1736
+ return statSync(join(this.dataDir, flipped)).ino === statSync(join(this.dataDir, f)).ino;
1737
+ }
1738
+ catch {
1739
+ return false;
1740
+ }
1741
+ }
1742
+ deleteSpace(name, who = { by: "operator", how: "operator" }, o = {}) {
1743
+ const found = this.resolveTeam(name);
1744
+ if ("refused" in found)
1745
+ throw new TombstoneUnsafe(found.refused);
1746
+ if (!("team" in found))
1747
+ return null;
1748
+ const team = found.team;
1749
+ const sp = this.live(team.name) ?? [...this.spaces.values()].find((x) => safeName(x.name) === team.stem);
1750
+ let roster = sp?.allow ?? null;
1751
+ if (!roster) {
1752
+ try {
1753
+ roster = new Allowlist(this.dataDir, team.stem);
1754
+ }
1755
+ catch (e) {
1756
+ throw new TombstoneUnsafe(`the member list of "${team.name}" cannot be read (${e.message.slice(0, 120)}), so it was not deleted — try again once it can be`);
1757
+ }
1758
+ }
1759
+ const id = roster.peekId();
1760
+ const latest = {
1761
+ name: team.name, at: Date.now(), hashes: roster.everyTokenHash(), by: who.by, how: who.how, ...(id ? { id } : {}),
1762
+ members: roster.all().filter((e) => e.admitted || e.revoked_at).map((e) => ({ member: e.member, publicKey: e.publicKey, ...(e.admitted ? {} : { removed_by: e.revoked_by ?? null }) })),
1763
+ };
1764
+ const tombFile = join(this.dataDir, `${team.stem}.deleted.json`);
1765
+ const before = this.tombstoneRecord(team.stem);
1766
+ if (before?.unreadable)
1767
+ throw new TombstoneUnsafe(`what this relay keeps about earlier teams called "${team.name}" cannot be read right now (${before.unreadable}), so "${team.name}" was not deleted — try again in a moment`);
1768
+ const teams = [latest, ...(before && !before.corrupt ? tombTeams(before) : [])].slice(0, TOMB_TEAMS_KEPT);
1769
+ const all = [...new Set(teams.flatMap((t) => t.hashes))];
1770
+ const tomb = {
1771
+ name: team.name, at: latest.at, tokenHash: latest.hashes[0] ?? all[0] ?? null,
1772
+ ...(all.length > 1 ? { retiredTokenHashes: all.filter((h) => h !== (latest.hashes[0] ?? all[0])) } : {}),
1773
+ by: who.by, how: who.how, ...(id ? { id } : {}), teams,
1774
+ ...(before?.corrupt || before?.sealed ? { sealed: true } : {}),
1775
+ };
1776
+ try {
1777
+ if (before?.corrupt || before?.diskCorrupt) {
1778
+ try {
1779
+ renameSync(tombFile, `${tombFile}.corrupt-${Date.now()}`);
1780
+ }
1781
+ catch { }
1782
+ }
1783
+ const tmp = `${tombFile}.${randomBytes(6).toString("hex")}.tmp`;
1784
+ try {
1785
+ writeFileSync(tmp, JSON.stringify(tomb), { flag: "wx" });
1786
+ renameSync(tmp, tombFile);
1787
+ }
1788
+ catch (e) {
1789
+ try {
1790
+ rmSync(tmp, { force: true });
1791
+ }
1792
+ catch { }
1793
+ throw e;
1794
+ }
1795
+ this.noteTombstoneStem(team.stem);
1796
+ }
1797
+ catch (e) {
1798
+ if (o.durable) {
1799
+ this.noteStorageFailure(`[${team.name}] delete`, e);
1800
+ return null;
1801
+ }
1802
+ this.deletedSpaces.set(team.stem, tomb);
1803
+ if (this.deletedSpaces.size > 1000)
1804
+ for (const [k, t] of this.deletedSpaces)
1805
+ if (Date.now() - t.at > DELETED_NAME_HOLD_MS)
1806
+ this.deletedSpaces.delete(k);
1807
+ }
1808
+ o.first?.();
1645
1809
  if (sp) {
1646
1810
  sp.deleted = true;
1647
1811
  sp.store.discardUsage();
1648
1812
  for (const m of sp.members.values())
1649
1813
  for (const s of m.sessions.values())
1650
1814
  this.hangUp(s.ws, "SPACE_DELETED");
1651
- this.spaces.delete(spaceKey(name));
1815
+ this.spaces.delete(spaceKey(sp.name));
1652
1816
  }
1653
- setTimeout(() => this.deleteSpaceFiles(name), 600).unref?.();
1654
- const safe = name.replace(/[^a-z0-9._-]/gi, "_");
1655
- try {
1656
- const hash = sp?.allow ? JSON.parse(readLatest(this.dataDir, safe, join(this.dataDir, `${safe}.members.json`))).tokenHash ?? null : null;
1657
- const earlier = sp?.allow ? sp.allow.tokenHashes().filter((h) => h !== hash) : [];
1658
- writeFileSync(join(this.dataDir, `${safe}.deleted.json`), JSON.stringify({ name, at: Date.now(), tokenHash: hash, ...(earlier.length ? { retiredTokenHashes: earlier } : {}) }));
1659
- this.tombstoneFile(name);
1660
- this.tombstoneStems.set(spaceKey(name), safe);
1661
- }
1662
- catch { }
1663
- const existed = !!sp || [".jsonl", ".state.json", ".members.json"].some((suf) => existsSync(join(this.dataDir, `${safe}${suf}`)));
1664
- this.deleteSpaceFiles(name);
1665
- this.deletedSpaces.set(spaceKey(name), Date.now());
1666
- if (this.deletedSpaces.size > 1000)
1667
- for (const [k, t] of this.deletedSpaces)
1668
- if (Date.now() - t > 3_600_000)
1669
- this.deletedSpaces.delete(k);
1670
- return existed;
1817
+ setTimeout(() => this.deleteSpaceFiles(team.stem), 600).unref?.();
1818
+ this.deleteSpaceFiles(team.stem);
1819
+ return team.name;
1671
1820
  }
1672
1821
  adminAction(res, A, body, ip) {
1673
1822
  if (body.csrf !== this.adminCsrf())
@@ -1732,11 +1881,42 @@ button:hover{background:#1d4ed8}.err{color:var(--bad);margin-top:12px}
1732
1881
  case "delete_space": {
1733
1882
  if ((body.confirm ?? "").trim() !== id)
1734
1883
  return done(`not deleted: type the space name exactly ("${id}") to confirm`);
1735
- const existed = this.deleteSpace(id);
1736
- A.markSpaceDeleted(id);
1737
- A.audit({ event: "admin_space_deleted", space: id, ip });
1738
- this.log(`[admin] deleted space "${id}" from ${ip}`);
1739
- return done(existed ? `space "${id}" deleted — its members were disconnected` : `no space "${id}"`);
1884
+ const describe = (t) => `"${t.name}"${t.id ? ` (${t.id})` : ""}`;
1885
+ const found = this.resolveTeam(id);
1886
+ if ("refused" in found)
1887
+ return done(found.refused);
1888
+ if (!("team" in found)) {
1889
+ const row = A.liveSpaceRow(id);
1890
+ const left = found.others.length ? ` (left alone: ${found.others.map(describe).join(", ")}, spelled differently)` : "";
1891
+ if (row) {
1892
+ A.markSpaceDeleted(row);
1893
+ A.audit({ event: "admin_space_deleted", space: row, detail: "no team files; plan slot freed", ip });
1894
+ this.log(`[admin] freed the plan slot of "${row}" (no team files) from ${ip}`);
1895
+ return done(`no team files for "${row}"; plan slot freed${left}`);
1896
+ }
1897
+ if (found.others.length)
1898
+ return done(`no team "${id}" here — did you mean ${found.others.map(describe).join(" or ")}? Nothing changed: type its exact name, or its id`);
1899
+ return done(`no such team "${id}" on this relay — nothing deleted`);
1900
+ }
1901
+ const t = found.team;
1902
+ let deleted;
1903
+ try {
1904
+ deleted = this.deleteSpace(t.id && id === t.id ? t.id : t.name);
1905
+ }
1906
+ catch (e) {
1907
+ if (e instanceof TombstoneUnsafe)
1908
+ return done(e.message);
1909
+ throw e;
1910
+ }
1911
+ if (!deleted)
1912
+ return done(`nothing deleted: ${describe(t)} could not be found again — reload and try once more`);
1913
+ const rows = A.spaceRowsWithStem(t.stem);
1914
+ const row = A.liveSpaceRow(deleted) ?? (rows.length === 1 ? rows[0] : null);
1915
+ if (row)
1916
+ A.markSpaceDeleted(row);
1917
+ A.audit({ event: "admin_space_deleted", space: deleted, detail: t.id ?? undefined, ip });
1918
+ this.log(`[admin] deleted team ${describe(t)} from ${ip}`);
1919
+ return done(`deleted team ${describe(t)} — its members were disconnected${row ? `; plan slot "${row}" freed` : rows.length > 1 ? `; ${rows.length} plan records could be it (${rows.join(", ")}), so none was changed` : "; it had no plan record"}`);
1740
1920
  }
1741
1921
  case "set_plan": {
1742
1922
  const target = A.accountById(id);
@@ -2182,8 +2362,31 @@ button:hover{background:#1d4ed8}.err{color:var(--bad);margin-top:12px}
2182
2362
  return { ok: false, status: 404, error: "no such space" };
2183
2363
  return { ok: true, space, reader: null };
2184
2364
  }
2185
- if (!target)
2365
+ if (!target) {
2366
+ const tt = this.tombstoneTeamFor(name, token);
2367
+ const reader = params.reader ?? "", ts = Number(params.ts);
2368
+ const kept = tt?.members?.find((e) => e.member === reader)?.publicKey ?? null;
2369
+ if (tt?.members && kept && Number.isFinite(ts) && Math.abs(Date.now() - ts) < LIMITS.activityFreshMs) {
2370
+ const { sig, ...signed } = params;
2371
+ let ok = false;
2372
+ {
2373
+ let signer = kept;
2374
+ if (signed.dpub) {
2375
+ const cert = { pub: signed.dpub, run: signed.drun ?? "", expires: Number(signed.dexp), sig: signed.dcert ?? "" };
2376
+ signer = [tt.id, name].some((x) => x && verifyDelegate(kept, x, reader, cert)) ? signed.dpub : "";
2377
+ }
2378
+ ok = !!signer && verifyRead(signer, req.method ?? "GET", url.pathname, signed, sig);
2379
+ }
2380
+ if (ok) {
2381
+ const a = this.deletedAnswerFor(tt, reader, kept);
2382
+ if (a.kind === "member")
2383
+ return { ok: false, status: 410, code: "SPACE_DELETED", error: deletedWords(tt), gone: goneAnswer(tt) };
2384
+ if (a.kind === "removed")
2385
+ return { ok: false, status: 403, code: "REVOKED", error: removedWords(reader, tt.name, a.removedBy) };
2386
+ }
2387
+ }
2186
2388
  return { ok: false, status: 404, error: "no such space" };
2389
+ }
2187
2390
  const reader = params.reader ?? "";
2188
2391
  const ts = Number(params.ts);
2189
2392
  const refused = { ok: false, status: 403, error: "a read must be signed, recently, by the key of a member admitted to this team" };
@@ -2220,48 +2423,135 @@ button:hover{background:#1d4ed8}.err{color:var(--bad);margin-top:12px}
2220
2423
  return { ok: true, space, reader };
2221
2424
  }
2222
2425
  tombstoneStems = null;
2223
- tombstoneFile(name) {
2426
+ tombstoneIndex() {
2224
2427
  if (!this.tombstoneStems) {
2225
2428
  this.tombstoneStems = new Map();
2226
2429
  try {
2227
2430
  for (const f of readdirSync(this.dataDir)) {
2228
2431
  if (!f.endsWith(".deleted.json"))
2229
2432
  continue;
2230
- const stem = f.slice(0, -".deleted.json".length);
2231
- this.tombstoneStems.set(stem.toLowerCase(), stem);
2433
+ this.noteTombstoneStem(f.slice(0, -".deleted.json".length));
2232
2434
  }
2233
2435
  }
2234
2436
  catch { }
2235
2437
  }
2236
- const stem = this.tombstoneStems.get(spaceKey(name));
2237
- return stem ? join(this.dataDir, `${stem}.deleted.json`) : null;
2438
+ return this.tombstoneStems;
2238
2439
  }
2239
- tombstone(name, _token) {
2240
- const f = this.tombstoneFile(name);
2241
- if (!f)
2440
+ noteTombstoneStem(stem) {
2441
+ const idx = this.tombstoneStems ?? this.tombstoneIndex();
2442
+ const k = stem.toLowerCase();
2443
+ let set = idx.get(k);
2444
+ if (!set) {
2445
+ set = new Set();
2446
+ idx.set(k, set);
2447
+ }
2448
+ set.add(stem);
2449
+ }
2450
+ tombstoneFile(name) {
2451
+ const exact = safeName(name);
2452
+ const set = this.tombstoneIndex().get(exact.toLowerCase());
2453
+ if (!set?.size)
2242
2454
  return null;
2455
+ if (set.has(exact))
2456
+ return join(this.dataDir, `${exact}.deleted.json`);
2457
+ let ino;
2243
2458
  try {
2244
- return JSON.parse(readFileSync(f, "utf8")).at;
2459
+ ino = statSync(join(this.dataDir, `${exact}.deleted.json`)).ino;
2245
2460
  }
2246
2461
  catch {
2247
2462
  return null;
2248
2463
  }
2464
+ for (const st of set) {
2465
+ const f = join(this.dataDir, `${st}.deleted.json`);
2466
+ try {
2467
+ if (statSync(f).ino === ino)
2468
+ return f;
2469
+ }
2470
+ catch { }
2471
+ }
2472
+ return null;
2249
2473
  }
2250
- tombstoneMatches(name, token) {
2474
+ tombstoneRecord(name) {
2475
+ const mem = this.deletedSpaces.get(safeName(name)) ?? null;
2476
+ const disk = this.tombstoneFromDisk(name);
2477
+ if (!mem)
2478
+ return disk;
2479
+ if (!disk)
2480
+ return mem;
2481
+ if (disk.corrupt)
2482
+ return { ...mem, sealed: true, diskCorrupt: true };
2483
+ if (disk.unreadable)
2484
+ return { ...mem, unreadable: disk.unreadable };
2485
+ const seen = new Set();
2486
+ const teams = [...tombTeams(mem), ...tombTeams(disk)].filter((t) => { const k = `${t.at}|${t.id ?? ""}|${t.hashes[0] ?? ""}`; if (seen.has(k))
2487
+ return false; seen.add(k); return true; })
2488
+ .slice(0, TOMB_TEAMS_KEPT);
2489
+ return { ...mem, at: Math.max(mem.at, disk.at), teams, ...(mem.sealed || disk.sealed ? { sealed: true } : {}) };
2490
+ }
2491
+ tombstoneFromDisk(name) {
2251
2492
  const f = this.tombstoneFile(name);
2252
2493
  if (!f)
2253
- return false;
2494
+ return null;
2495
+ let text;
2254
2496
  try {
2255
- const t = JSON.parse(readFileSync(f, "utf8"));
2256
- if (!token)
2257
- return false;
2258
- const h = createHash("sha256").update(token).digest("hex");
2259
- return (!!t.tokenHash && h === t.tokenHash) || (Array.isArray(t.retiredTokenHashes) && t.retiredTokenHashes.includes(h));
2497
+ text = readFileSync(f, "utf8");
2260
2498
  }
2261
- catch {
2262
- return false;
2499
+ catch (e) {
2500
+ const code = e.code ?? "EIO";
2501
+ if (code === "ENOENT") {
2502
+ const st = basename(f).slice(0, -".deleted.json".length);
2503
+ this.tombstoneStems?.get(st.toLowerCase())?.delete(st);
2504
+ return null;
2505
+ }
2506
+ return { name, at: 0, tokenHash: null, unreadable: code };
2507
+ }
2508
+ try {
2509
+ const t = JSON.parse(text);
2510
+ if (!t || typeof t !== "object" || typeof t.at !== "number")
2511
+ throw new Error("not a tombstone");
2512
+ const str = (x) => (typeof x === "string" ? x : undefined);
2513
+ const how = (x) => (x === "founder" || x === "operator" ? x : undefined);
2514
+ const teams = Array.isArray(t.teams) ? t.teams.flatMap((x) => {
2515
+ if (!x || typeof x !== "object" || typeof x.at !== "number" || !Array.isArray(x.hashes))
2516
+ return [];
2517
+ const members = Array.isArray(x.members) ? x.members.filter((e) => e && typeof e.member === "string" && typeof e.publicKey === "string") : undefined;
2518
+ return [{ name: str(x.name) ?? name, at: x.at, hashes: x.hashes.filter((h) => typeof h === "string"),
2519
+ ...(str(x.by) ? { by: str(x.by) } : {}), ...(how(x.how) ? { how: how(x.how) } : {}), ...(str(x.id) ? { id: str(x.id) } : {}), ...(members ? { members } : {}) }];
2520
+ }) : undefined;
2521
+ return {
2522
+ name: str(t.name) ?? name, at: t.at,
2523
+ tokenHash: str(t.tokenHash) ?? null,
2524
+ ...(Array.isArray(t.retiredTokenHashes) ? { retiredTokenHashes: t.retiredTokenHashes.filter((h) => typeof h === "string") } : {}),
2525
+ ...(str(t.by) ? { by: str(t.by) } : {}), ...(how(t.how) ? { how: how(t.how) } : {}), ...(str(t.id) ? { id: str(t.id) } : {}),
2526
+ ...(teams?.length ? { teams } : {}),
2527
+ ...(t.sealed === true ? { sealed: true } : {}),
2528
+ };
2529
+ }
2530
+ catch (e) {
2531
+ if (!this.corruptSaid.has(f)) {
2532
+ this.corruptSaid.add(f);
2533
+ this.log(`! tombstone ${basename(f)} does not parse (${e.message.slice(0, 80)}) — "${name}" stays deleted`);
2534
+ }
2535
+ return { name, at: 0, tokenHash: null, corrupt: true };
2263
2536
  }
2264
2537
  }
2538
+ corruptSaid = new Set();
2539
+ tombstoneTeamFor(name, token, who) {
2540
+ const t = this.tombstoneRecord(name);
2541
+ if (!t || t.corrupt)
2542
+ return null;
2543
+ const h = token ? createHash("sha256").update(token).digest("hex") : null;
2544
+ return tombTeams(t).find((x) => (h && x.hashes.includes(h))
2545
+ || (!x.hashes.length && who && x.members?.some((e) => e.member === who.member && e.publicKey === who.publicKey))) ?? null;
2546
+ }
2547
+ deletedAnswerFor(t, member, publicKey) {
2548
+ if (!t.members)
2549
+ return { kind: "stranger" };
2550
+ const e = t.members.find((x) => x.member === member && x.publicKey === publicKey);
2551
+ if (!e)
2552
+ return { kind: "stranger" };
2553
+ return "removed_by" in e ? { kind: "removed", removedBy: e.removed_by ?? null } : { kind: "member" };
2554
+ }
2265
2555
  nameCollides(name) {
2266
2556
  const stem = safeName(name).toLowerCase();
2267
2557
  try {
@@ -2360,11 +2650,15 @@ button:hover{background:#1d4ed8}.err{color:var(--bad);margin-top:12px}
2360
2650
  for (const f of files) {
2361
2651
  if (!f.endsWith(".members.json"))
2362
2652
  continue;
2363
- const name = f.slice(0, -".members.json".length);
2364
- if (this.accounts.hasSpaceRecord(name))
2653
+ const stem = f.slice(0, -".members.json".length);
2654
+ if (this.accounts.hasSpaceRecord(stem) || this.accounts.spaceRowsWithStem(stem, true).length)
2365
2655
  continue;
2366
2656
  try {
2367
- const founder = new Allowlist(this.dataDir, name).founder();
2657
+ const roster = new Allowlist(this.dataDir, stem);
2658
+ const name = roster.recordedName() ?? stem;
2659
+ if (name !== stem && this.accounts.hasSpaceRecord(name))
2660
+ continue;
2661
+ const founder = roster.founder();
2368
2662
  const owner = founder ? this.accounts.accountByUsername(founder) : null;
2369
2663
  this.accounts.recordSpace(name, owner?.id ?? null);
2370
2664
  this.log(`[${name}] owner recorded: ${owner ? owner.username : "unknown (no plan limits apply)"}`);
@@ -2583,7 +2877,8 @@ ${done ? `<div class=done role=status>${esc(done)}</div>` : ""}
2583
2877
  adminSpace(res, url, name) {
2584
2878
  const safe = name.replace(/[^a-z0-9._-]/gi, "_");
2585
2879
  const sp = this.spaces.get(spaceKey(name)) ?? null;
2586
- const tomb = this.deletedSpaces.get(spaceKey(name));
2880
+ const rec = this.tombstoneRecord(name);
2881
+ const tomb = rec && !rec.corrupt && !rec.unreadable ? rec.at : undefined;
2587
2882
  const onDisk = [".jsonl", ".state.json", ".members.json"].some((suf) => {
2588
2883
  const f = join(this.dataDir, `${safe}${suf}`);
2589
2884
  const queued = pendingView(this.dataDir, safe, f);
@@ -2930,7 +3225,7 @@ pantheon start</code></pre>
2930
3225
  probe._clear = () => { alive = false; };
2931
3226
  let refusalStamps = [];
2932
3227
  let refusedOut = false;
2933
- const fail = (code, message, cid) => {
3228
+ const fail = (code, message, cid, extra = {}) => {
2934
3229
  if (refusedOut)
2935
3230
  return;
2936
3231
  const now = Date.now();
@@ -2949,10 +3244,10 @@ pantheon start</code></pre>
2949
3244
  noteRefusal(space.store.refusals, { ts: now, member: me.id, act: lastMsg || "?", code });
2950
3245
  space.store.save(space.goals, space.obligations, space.profiles);
2951
3246
  }
2952
- this.send(ws, { t: "error", code, message, ...(cid ? { cid } : {}) });
3247
+ this.send(ws, { t: "error", code, message, ...(cid ? { cid } : {}), ...extra });
2953
3248
  };
2954
- const reject = (code, message) => {
2955
- fail(code, message);
3249
+ const reject = (code, message, extra = {}) => {
3250
+ fail(code, message, undefined, extra);
2956
3251
  setTimeout(() => { try {
2957
3252
  ws.close(1008, code);
2958
3253
  }
@@ -3039,9 +3334,25 @@ pantheon start</code></pre>
3039
3334
  return reject("NO_SUCH_SPACE", `no space "${m.space}" on this relay`);
3040
3335
  }
3041
3336
  else {
3042
- const tomb = this.deletedSpaces.get(spaceKey(m.space)) ?? this.tombstone(m.space, m.token ?? "");
3043
- if (tomb && Date.now() - tomb < 3_600_000 || (tomb && this.tombstoneMatches(m.space, m.token ?? ""))) {
3044
- return reject("SPACE_DELETED", `the space "${m.space}" was removed by the relay operator. Start a new one with a different name, or contact them.`);
3337
+ const found = this.tombstoneRecord(m.space);
3338
+ const otherSpelling = !!found && !found.corrupt && !found.unreadable && safeName(found.name) !== safeName(m.space);
3339
+ const tomb = otherSpelling && (this.live(m.space) || this.spaceOnDisk(m.space)) ? null : found;
3340
+ if (tomb) {
3341
+ const own = this.tombstoneTeamFor(m.space, m.token ?? "", { member: m.member, publicKey: m.pubkey });
3342
+ if (own) {
3343
+ const a = this.deletedAnswerFor(own, m.member, m.pubkey);
3344
+ this.log(`! REFUSED ${m.member}: "${m.space}" was deleted (${own.by ?? "?"}, ${new Date(own.at).toISOString()}) — told as ${a.kind}`);
3345
+ if (a.kind === "member")
3346
+ return reject("SPACE_DELETED", deletedWords(own), { gone: goneAnswer(own) });
3347
+ if (a.kind === "removed")
3348
+ return reject("REVOKED", removedWords(m.member, own.name, a.removedBy));
3349
+ return reject("SPACE_DELETED", deletedNameWords(m.space), { gone: null });
3350
+ }
3351
+ const making = !this.live(m.space) && !this.spaceOnDisk(m.space);
3352
+ if (tomb.unreadable && making)
3353
+ return reject("STORAGE", `the relay cannot read what it keeps about the name "${m.space}" right now — try again in a moment`);
3354
+ if (Date.now() - tomb.at < DELETED_NAME_HOLD_MS || ((tomb.corrupt || tomb.sealed) && making))
3355
+ return reject("SPACE_DELETED", deletedNameWords(m.space), { gone: null });
3045
3356
  }
3046
3357
  if (this.aliasOf(m.space)) {
3047
3358
  return reject("NAME_TAKEN", `a team with a name too close to "${m.space}" already exists here — use its exact name, or pick another`);
@@ -3414,19 +3725,39 @@ pantheon start</code></pre>
3414
3725
  const isOwner = owner ? owner.id === acct?.id : space.allow.founder() === me.id;
3415
3726
  if (!isOwner)
3416
3727
  return fail("NOT_OWNER", `only the founder of "${space.name}" can delete it${owner ? ` (that is ${owner.username})` : ""}`, m.cid);
3417
- const name = space.name;
3418
- this.accounts?.audit({ event: "space_deleted", actor_account: acct?.id ?? null, space: name, detail: `by its founder ${me.id}`, ip });
3419
- this.log(`[${name}] * DELETED by its founder ${me.id}`);
3420
- this.send(ws, { t: "ack", ...(m.cid ? { cid: m.cid } : {}), id: name, seq: space.ledger.head });
3421
- setTimeout(() => {
3728
+ const name = space.name, by = me.id, del = space, cid = m.cid;
3729
+ const refused = JSON.stringify({ t: "error", code: "STORAGE", message: `the relay's disk is refusing writes, so "${name}" was NOT deleted — try again in a moment`, ...(cid ? { cid } : {}) });
3730
+ const ack = JSON.stringify({ t: "ack", ...(cid ? { cid } : {}), id: name, seq: space.ledger.head });
3731
+ const send = (frame) => { if (ws.readyState === 1) {
3732
+ try {
3733
+ ws.send(frame);
3734
+ }
3735
+ catch { }
3736
+ } };
3737
+ this.out(del, () => {
3738
+ if (del.deleted) {
3739
+ send(ack);
3740
+ return;
3741
+ }
3742
+ let deleted = null;
3743
+ let unsafe = null;
3422
3744
  try {
3423
- this.deleteSpace(name);
3424
- this.accounts?.markSpaceDeleted(name);
3745
+ deleted = this.deleteSpace(name, { by, how: "founder" }, { durable: true, first: () => send(ack) });
3425
3746
  }
3426
3747
  catch (e) {
3427
- this.noteStorageFailure(`[${name}] delete`, e);
3748
+ if (e instanceof TombstoneUnsafe)
3749
+ unsafe = e.message;
3750
+ else
3751
+ this.noteStorageFailure(`[${name}] delete`, e);
3752
+ }
3753
+ if (!deleted) {
3754
+ send(unsafe ? JSON.stringify({ t: "error", code: "STORAGE", message: unsafe, ...(cid ? { cid } : {}) }) : refused);
3755
+ return;
3428
3756
  }
3429
- }, 50).unref?.();
3757
+ this.accounts?.markSpaceDeleted(deleted);
3758
+ this.accounts?.audit({ event: "space_deleted", actor_account: acct?.id ?? null, space: deleted, detail: `by its founder ${by}`, ip });
3759
+ this.log(`[${deleted}] * DELETED by its founder ${by}`);
3760
+ }, { ws, payload: refused, hangUp: false });
3430
3761
  return;
3431
3762
  }
3432
3763
  if (m.t === "invite") {