@getcirrus/pds 0.19.0 → 0.20.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/cli.js CHANGED
@@ -2,11 +2,11 @@
2
2
  import { defineCommand, runMain } from "citty";
3
3
  import * as p from "@clack/prompts";
4
4
  import { randomBytes } from "node:crypto";
5
- import { Secp256k1Keypair } from "@atproto/crypto";
5
+ import { P256Keypair, Secp256k1Keypair, bytesToMultibase, multibaseToBytes } from "@atproto/crypto";
6
6
  import bcrypt from "bcryptjs";
7
7
  import { spawn } from "node:child_process";
8
- import { experimental_patchConfig, experimental_readRawConfig } from "wrangler";
9
8
  import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
9
+ import { experimental_patchConfig, experimental_readRawConfig } from "wrangler";
10
10
  import { join, resolve } from "node:path";
11
11
  import { writeFile } from "node:fs/promises";
12
12
  import pc from "picocolors";
@@ -14,7 +14,9 @@ import QRCode from "qrcode";
14
14
  import { Client, ClientResponseError, ok } from "@atcute/client";
15
15
  import "@atcute/bluesky";
16
16
  import "@atcute/atproto";
17
- import { CompositeDidDocumentResolver, DohJsonHandleResolver, PlcDidDocumentResolver, WebDidDocumentResolver } from "@atcute/identity-resolver";
17
+ import { CompositeDidDocumentResolver, CompositeHandleResolver, DohJsonHandleResolver, PlcDidDocumentResolver, WebDidDocumentResolver, WellKnownHandleResolver } from "@atcute/identity-resolver";
18
+ import { encode } from "@atcute/cbor";
19
+ import { base64url } from "jose";
18
20
  import { getPdsEndpoint } from "@atcute/identity";
19
21
  import { decodeAll } from "@atproto/lex-cbor";
20
22
 
@@ -79,20 +81,27 @@ function runWrangler(args, options = {}) {
79
81
  });
80
82
  }
81
83
  /**
82
- * Set a var in wrangler.jsonc using experimental_patchConfig
84
+ * Patch the wrangler config, keeping the file's trailing newline as it was.
83
85
  */
84
- function setVar(name, value) {
86
+ function patchConfig(patch) {
85
87
  const { configPath } = experimental_readRawConfig({});
86
88
  if (!configPath) throw new Error("No wrangler config found");
87
- experimental_patchConfig(configPath, { vars: { [name]: value } });
89
+ const hadTrailingNewline = readFileSync(configPath, "utf-8").endsWith("\n");
90
+ experimental_patchConfig(configPath, patch);
91
+ const patched = readFileSync(configPath, "utf-8");
92
+ if (patched.endsWith("\n") !== hadTrailingNewline) writeFileSync(configPath, hadTrailingNewline ? patched + "\n" : patched.trimEnd());
93
+ }
94
+ /**
95
+ * Set a var in wrangler.jsonc using experimental_patchConfig
96
+ */
97
+ function setVar(name, value) {
98
+ patchConfig({ vars: { [name]: value } });
88
99
  }
89
100
  /**
90
101
  * Set multiple vars in wrangler.jsonc
91
102
  */
92
103
  function setVars(vars) {
93
- const { configPath } = experimental_readRawConfig({});
94
- if (!configPath) throw new Error("No wrangler config found");
95
- experimental_patchConfig(configPath, { vars });
104
+ patchConfig({ vars });
96
105
  }
97
106
  /**
98
107
  * Get current vars from wrangler config
@@ -112,9 +121,7 @@ function getWorkerName() {
112
121
  * Set worker name in wrangler config
113
122
  */
114
123
  function setWorkerName(name) {
115
- const { configPath } = experimental_readRawConfig({});
116
- if (!configPath) throw new Error("No wrangler config found");
117
- experimental_patchConfig(configPath, { name });
124
+ patchConfig({ name });
118
125
  }
119
126
  /**
120
127
  * Set a secret using wrangler secret put
@@ -140,17 +147,13 @@ function getAccountId() {
140
147
  * Set account_id in wrangler config
141
148
  */
142
149
  function setAccountId(accountId) {
143
- const { configPath } = experimental_readRawConfig({});
144
- if (!configPath) throw new Error("No wrangler config found");
145
- experimental_patchConfig(configPath, { account_id: accountId });
150
+ patchConfig({ account_id: accountId });
146
151
  }
147
152
  /**
148
153
  * Set custom domain routes in wrangler config
149
154
  */
150
155
  function setCustomDomains(domains) {
151
- const { configPath } = experimental_readRawConfig({});
152
- if (!configPath) throw new Error("No wrangler config found");
153
- experimental_patchConfig(configPath, { routes: domains.map((pattern) => ({
156
+ patchConfig({ routes: domains.map((pattern) => ({
154
157
  pattern,
155
158
  custom_domain: true
156
159
  })) });
@@ -397,12 +400,47 @@ async function is1PasswordAvailable() {
397
400
  child.on("close", (code) => resolve$1(code === 0));
398
401
  });
399
402
  }
403
+ const KEY_BACKUP_TEXT = {
404
+ signing: {
405
+ name: "signing key",
406
+ label: "Signing Key",
407
+ title: "Cirrus PDS Signing Key",
408
+ heading: "CIRRUS PDS SIGNING KEY",
409
+ filePrefix: "signing-key-backup",
410
+ tag: "signing-key",
411
+ warning: "WARNING: This key controls your identity!",
412
+ encoding: "hex-encoded secp256k1 private key"
413
+ },
414
+ recovery: {
415
+ name: "recovery key",
416
+ label: "Recovery Key",
417
+ title: "atproto Recovery Key",
418
+ heading: "ATPROTO RECOVERY KEY",
419
+ filePrefix: "recovery-key-backup",
420
+ tag: "recovery-key",
421
+ warning: "WARNING: This key can take control of your identity!",
422
+ encoding: "multibase private key, usable with goat"
423
+ }
424
+ };
400
425
  /**
401
426
  * Save a key to 1Password using the CLI
402
- * Creates a secure note with the signing key
427
+ * Creates a secure note with the key and any extra details
403
428
  */
404
- async function saveTo1Password(key, handle) {
405
- const itemName = `Cirrus PDS Signing Key - ${handle}`;
429
+ async function saveTo1Password(key, handle, kind = "signing", details = []) {
430
+ const text = KEY_BACKUP_TEXT[kind];
431
+ const itemName = `${text.title} - ${handle}`;
432
+ const notes = [
433
+ text.heading,
434
+ "",
435
+ `Handle: ${handle}`,
436
+ `Created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
437
+ ...details,
438
+ "",
439
+ text.warning,
440
+ "",
441
+ `${text.name.toUpperCase()}:`,
442
+ key
443
+ ].join("\n");
406
444
  return new Promise((resolve$1) => {
407
445
  const child = spawn("op", [
408
446
  "item",
@@ -411,9 +449,9 @@ async function saveTo1Password(key, handle) {
411
449
  "Secure Note",
412
450
  "--title",
413
451
  itemName,
414
- `notesPlain=CIRRUS PDS SIGNING KEY\n\nHandle: ${handle}\nCreated: ${(/* @__PURE__ */ new Date()).toISOString()}\n\nWARNING: This key controls your identity!\n\nSIGNING KEY:\n${key}`,
452
+ `notesPlain=${notes}`,
415
453
  "--tags",
416
- "cirrus,pds,signing-key"
454
+ `cirrus,pds,${text.tag}`
417
455
  ], { stdio: [
418
456
  "ignore",
419
457
  "pipe",
@@ -516,25 +554,27 @@ function runCommand(cmd, args, options = {}) {
516
554
  /**
517
555
  * Save a key backup file with appropriate warnings
518
556
  */
519
- async function saveKeyBackup(key, handle) {
520
- const filename = `signing-key-backup-${handle.replace(/[^a-z0-9]/gi, "-")}.txt`;
557
+ async function saveKeyBackup(key, handle, kind = "signing", details = []) {
558
+ const text = KEY_BACKUP_TEXT[kind];
559
+ const filename = `${text.filePrefix}-${handle.replace(/[^a-z0-9]/gi, "-")}.txt`;
521
560
  const filepath = join(process.cwd(), filename);
522
561
  await writeFile(filepath, [
523
562
  "=".repeat(60),
524
- "CIRRUS PDS SIGNING KEY BACKUP",
563
+ `${text.heading} BACKUP`,
525
564
  "=".repeat(60),
526
565
  "",
527
566
  `Handle: ${handle}`,
528
567
  `Created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
568
+ ...details,
529
569
  "",
530
- "WARNING: This key controls your identity!",
570
+ text.warning,
531
571
  "- Store this file in a secure location (password manager, encrypted drive)",
532
572
  "- Delete this file from your local disk after backing up",
533
573
  "- Never share this key with anyone",
534
574
  "- If compromised, your identity can be stolen",
535
575
  "",
536
576
  "=".repeat(60),
537
- "SIGNING KEY (hex-encoded secp256k1 private key)",
577
+ `${text.name.toUpperCase()} (${text.encoding})`,
538
578
  "=".repeat(60),
539
579
  "",
540
580
  key,
@@ -543,6 +583,83 @@ async function saveKeyBackup(key, handle) {
543
583
  ].join("\n"), { mode: 384 });
544
584
  return filepath;
545
585
  }
586
+ /**
587
+ * Ask how to back up a key (1Password, clipboard, file or on screen), do
588
+ * it, and ask the user to confirm it is saved. Returns whether they
589
+ * confirmed. With allowSkip, the user may decline to back it up.
590
+ */
591
+ async function promptKeyBackup(opts) {
592
+ const text = KEY_BACKUP_TEXT[opts.kind];
593
+ const details = opts.details ?? [];
594
+ const capitalised = text.name[0].toUpperCase() + text.name.slice(1);
595
+ const showKey = () => p.note([
596
+ `${text.name.toUpperCase()} (keep this secret!):`,
597
+ "",
598
+ opts.key,
599
+ "",
600
+ "Copy this to your password manager now."
601
+ ].join("\n"), `🔑 Your ${text.label}`);
602
+ const options = [];
603
+ if (await is1PasswordAvailable()) options.push({
604
+ value: "1password",
605
+ label: "Save to 1Password",
606
+ hint: "recommended - uses op CLI"
607
+ });
608
+ options.push({
609
+ value: "copy",
610
+ label: "Copy to clipboard",
611
+ hint: "paste into password manager"
612
+ }, {
613
+ value: "file",
614
+ label: "Save to file",
615
+ hint: `${text.filePrefix}.txt`
616
+ }, {
617
+ value: "show",
618
+ label: "Display it (I'll copy manually)",
619
+ hint: "shown in terminal"
620
+ });
621
+ if (opts.allowSkip) options.push({
622
+ value: "skip",
623
+ label: "Skip (I understand the risk)",
624
+ hint: "not recommended"
625
+ });
626
+ const choice = await promptSelect({
627
+ message: `How would you like to back up your ${text.name}?`,
628
+ options
629
+ });
630
+ if (choice === "1password") {
631
+ const spinner = p.spinner();
632
+ spinner.start("Saving to 1Password...");
633
+ const result = await saveTo1Password(opts.key, opts.handle, opts.kind, details);
634
+ if (result.success) {
635
+ spinner.stop("Saved to 1Password");
636
+ p.log.success(`Created: "${result.itemName}"`);
637
+ } else {
638
+ spinner.stop("Failed to save to 1Password");
639
+ p.log.error(result.error || "Unknown error");
640
+ p.log.info("Falling back to displaying the key...");
641
+ showKey();
642
+ }
643
+ } else if (choice === "copy") {
644
+ await copyToClipboard(opts.key);
645
+ p.log.success(`${capitalised} copied to clipboard`);
646
+ p.log.info("Paste it into your password manager now!");
647
+ } else if (choice === "file") {
648
+ const backupPath = await saveKeyBackup(opts.key, opts.handle, opts.kind, details);
649
+ p.log.success(`${capitalised} saved to: ${backupPath}`);
650
+ p.log.warn("Move this file to a secure location and delete the local copy!");
651
+ } else if (choice === "show") showKey();
652
+ if (choice === "skip") return false;
653
+ const confirmed = await promptConfirm({
654
+ message: `Have you saved your ${text.name} securely?`,
655
+ initialValue: true
656
+ });
657
+ if (!confirmed) {
658
+ p.log.warn("Please back up your key before continuing!");
659
+ p.note(opts.key, `🔑 ${text.label}`);
660
+ }
661
+ return confirmed;
662
+ }
546
663
 
547
664
  //#endregion
548
665
  //#region src/cli/utils/secrets.ts
@@ -560,6 +677,17 @@ async function generateSigningKeypair() {
560
677
  };
561
678
  }
562
679
  /**
680
+ * Generate a P-256 keypair for the spaces `#atproto_kem` verification
681
+ * method, which MACs space data for syncers.
682
+ */
683
+ async function generateKemKeypair() {
684
+ const keypair = await P256Keypair.create({ exportable: true });
685
+ return {
686
+ privateKey: Buffer.from(await keypair.export()).toString("hex"),
687
+ publicKey: keypair.did().replace("did:key:", "")
688
+ };
689
+ }
690
+ /**
563
691
  * Derive public key from an existing private key
564
692
  */
565
693
  async function derivePublicKey(privateKeyHex) {
@@ -1406,6 +1534,28 @@ var PDSClient = class PDSClient {
1406
1534
  };
1407
1535
  }
1408
1536
  /**
1537
+ * Get this PDS's recommended PLC credentials. The rotation key and
1538
+ * atproto verification method are both the deployed signing key.
1539
+ */
1540
+ async getRecommendedDidCredentials() {
1541
+ const result = await ok(this.client.get("com.atproto.identity.getRecommendedDidCredentials", {}));
1542
+ return {
1543
+ rotationKeys: result.rotationKeys ?? [],
1544
+ verificationMethods: result.verificationMethods ?? {}
1545
+ };
1546
+ }
1547
+ /**
1548
+ * Get this PDS to sign a PLC operation applying the given changes to the
1549
+ * DID's current state. Needs a token from getMigrationToken, and fails
1550
+ * unless the PDS's signing key is a rotation key.
1551
+ */
1552
+ async signPlcOperation(token, changes) {
1553
+ return (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
1554
+ token,
1555
+ ...changes
1556
+ } }))).operation;
1557
+ }
1558
+ /**
1409
1559
  * List notifications (proxied through PDS to AppView)
1410
1560
  */
1411
1561
  async listNotifications(limit = 25) {
@@ -2163,10 +2313,21 @@ const appPasswordCommand = defineCommand({
2163
2313
  /**
2164
2314
  * Utilities for resolving AT Protocol handles to DIDs
2165
2315
  */
2166
- const resolver = new DohJsonHandleResolver({ dohUrl: "https://cloudflare-dns.com/dns-query" });
2316
+ const currentFetch = (input, init) => globalThis.fetch(input, init);
2317
+ const resolver = new CompositeHandleResolver({
2318
+ strategy: "dns-first",
2319
+ methods: {
2320
+ dns: new DohJsonHandleResolver({
2321
+ dohUrl: "https://cloudflare-dns.com/dns-query",
2322
+ fetch: currentFetch
2323
+ }),
2324
+ http: new WellKnownHandleResolver({ fetch: currentFetch })
2325
+ }
2326
+ });
2167
2327
  /**
2168
- * Resolve a handle to a DID using the AT Protocol handle resolution methods.
2169
- * Uses DNS-over-HTTPS via Cloudflare for DNS resolution.
2328
+ * Resolve a handle to a DID using the AT Protocol handle resolution methods:
2329
+ * a DNS TXT record (via Cloudflare DNS-over-HTTPS), then
2330
+ * /.well-known/atproto-did on the handle's domain.
2170
2331
  */
2171
2332
  async function resolveHandleToDid(handle) {
2172
2333
  try {
@@ -2241,6 +2402,39 @@ var DidResolver = class {
2241
2402
  * Interactive PDS setup wizard
2242
2403
  */
2243
2404
  /**
2405
+ * Explain how the handle will be verified: automatically when it matches the
2406
+ * PDS hostname, otherwise with a DNS TXT record or a file on the handle's
2407
+ * domain. For a migration (didWeb false) the handle switches when
2408
+ * `pds identity` runs, so the record must exist by then.
2409
+ */
2410
+ function showHandleSetup(opts) {
2411
+ const { handle, hostname, did, didWeb } = opts;
2412
+ const didWebLines = (verb) => didWeb ? [
2413
+ `For did:web, your PDS ${verb} the DID document at:`,
2414
+ ` https://${hostname}/.well-known/did.json`,
2415
+ ""
2416
+ ] : [];
2417
+ if (handle === hostname) p.note([
2418
+ "Your handle matches your PDS hostname, so your PDS will",
2419
+ "automatically handle domain verification for you!",
2420
+ "",
2421
+ ...didWebLines("serves"),
2422
+ "For handle verification, it serves:",
2423
+ ` https://${hostname}/.well-known/atproto-did`,
2424
+ "",
2425
+ didWeb ? "No additional DNS or hosting setup needed. Easy! 🎉" : "No additional DNS setup needed. Your handle switches when you run 'pds identity'."
2426
+ ].join("\n"), "Identity Setup 🪪");
2427
+ else p.note([
2428
+ ...didWebLines("will serve"),
2429
+ didWeb ? "To verify your handle, create a DNS TXT record:" : "Before you run 'pds identity', verify your handle with a DNS TXT record:",
2430
+ ` _atproto.${handle} TXT "did=${did}"`,
2431
+ "",
2432
+ "Or serve a file at:",
2433
+ ` https://${handle}/.well-known/atproto-did`,
2434
+ ` containing: ${did}`
2435
+ ].join("\n"), "Identity Setup 🪪");
2436
+ }
2437
+ /**
2244
2438
  * Slugify a handle to create a worker name
2245
2439
  * e.g., "example.com" -> "example-com-pds"
2246
2440
  */
@@ -2407,7 +2601,7 @@ const initCommand = defineCommand({
2407
2601
  if (isHostedHandle(existingHandle)) {
2408
2602
  const theirDomain = hostedDomains.find((d) => existingHandle?.endsWith(d));
2409
2603
  const domainExample = theirDomain ? `*${theirDomain}` : "*.bsky.social";
2410
- p.log.warn(`You'll need a custom domain for your new handle (not ${domainExample}). You can set this up after transferring your data.`);
2604
+ p.log.warn(`Your handle needs to move to a domain you control (not ${domainExample}). Choose it below: 'pds identity' switches to it as part of the migration.`);
2411
2605
  }
2412
2606
  if (attempts >= MAX_ATTEMPTS) {
2413
2607
  p.log.error("Unable to resolve handle after 3 attempts.");
@@ -2437,6 +2631,12 @@ const initCommand = defineCommand({
2437
2631
  initialValue: currentVars.PDS_HOSTNAME || handle,
2438
2632
  validate: (v) => !v ? "Hostname is required" : void 0
2439
2633
  });
2634
+ if (handle !== existingHandle) showHandleSetup({
2635
+ handle,
2636
+ hostname,
2637
+ did,
2638
+ didWeb: false
2639
+ });
2440
2640
  workerName = await promptWorkerName(handle, currentWorkerName);
2441
2641
  initialActive = "false";
2442
2642
  await ensureAccountConfigured();
@@ -2467,29 +2667,12 @@ const initCommand = defineCommand({
2467
2667
  workerName = await promptWorkerName(handle, currentWorkerName);
2468
2668
  initialActive = "true";
2469
2669
  await ensureAccountConfigured();
2470
- if (handle === hostname) p.note([
2471
- "Your handle matches your PDS hostname, so your PDS will",
2472
- "automatically handle domain verification for you!",
2473
- "",
2474
- "For did:web, your PDS serves the DID document at:",
2475
- ` https://${hostname}/.well-known/did.json`,
2476
- "",
2477
- "For handle verification, it serves:",
2478
- ` https://${hostname}/.well-known/atproto-did`,
2479
- "",
2480
- "No additional DNS or hosting setup needed. Easy! 🎉"
2481
- ].join("\n"), "Identity Setup 🪪");
2482
- else p.note([
2483
- "For did:web, your PDS will serve the DID document at:",
2484
- ` https://${hostname}/.well-known/did.json`,
2485
- "",
2486
- "To verify your handle, create a DNS TXT record:",
2487
- ` _atproto.${handle} TXT "did=${did}"`,
2488
- "",
2489
- "Or serve a file at:",
2490
- ` https://${handle}/.well-known/atproto-did`,
2491
- ` containing: ${did}`
2492
- ].join("\n"), "Identity Setup 🪪");
2670
+ showHandleSetup({
2671
+ handle,
2672
+ hostname,
2673
+ did,
2674
+ didWeb: true
2675
+ });
2493
2676
  }
2494
2677
  let dataLocation;
2495
2678
  if (currentVars.DATA_LOCATION) dataLocation = currentVars.DATA_LOCATION;
@@ -2571,76 +2754,12 @@ const initCommand = defineCommand({
2571
2754
  "",
2572
2755
  "We strongly recommend backing it up now."
2573
2756
  ].join("\n"), "Critical: Back Up Your Signing Key");
2574
- const has1Password = await is1PasswordAvailable();
2575
- const backupOptions = [];
2576
- if (has1Password) backupOptions.push({
2577
- value: "1password",
2578
- label: "Save to 1Password",
2579
- hint: "recommended - uses op CLI"
2580
- });
2581
- backupOptions.push({
2582
- value: "copy",
2583
- label: "Copy to clipboard",
2584
- hint: "paste into password manager"
2585
- }, {
2586
- value: "file",
2587
- label: "Save to file",
2588
- hint: "signing-key-backup.txt"
2589
- }, {
2590
- value: "show",
2591
- label: "Display it (I'll copy manually)",
2592
- hint: "shown in terminal"
2593
- }, {
2594
- value: "skip",
2595
- label: "Skip (I understand the risk)",
2596
- hint: "not recommended"
2597
- });
2598
- const backupChoice = await promptSelect({
2599
- message: "How would you like to back up your signing key?",
2600
- options: backupOptions
2757
+ await promptKeyBackup({
2758
+ key: signingKey,
2759
+ kind: "signing",
2760
+ handle,
2761
+ allowSkip: true
2601
2762
  });
2602
- if (backupChoice === "1password") {
2603
- spinner.start("Saving to 1Password...");
2604
- const result = await saveTo1Password(signingKey, handle);
2605
- if (result.success) {
2606
- spinner.stop("Saved to 1Password");
2607
- p.log.success(`Created: "${result.itemName}"`);
2608
- } else {
2609
- spinner.stop("Failed to save to 1Password");
2610
- p.log.error(result.error || "Unknown error");
2611
- p.log.info("Falling back to displaying the key...");
2612
- p.note([
2613
- "SIGNING KEY (keep this secret!):",
2614
- "",
2615
- signingKey,
2616
- "",
2617
- "Copy this to your password manager now."
2618
- ].join("\n"), "🔑 Your Signing Key");
2619
- }
2620
- } else if (backupChoice === "copy") {
2621
- await copyToClipboard(signingKey);
2622
- p.log.success("Signing key copied to clipboard");
2623
- p.log.info("Paste it into your password manager now!");
2624
- } else if (backupChoice === "file") {
2625
- const backupPath = await saveKeyBackup(signingKey, handle);
2626
- p.log.success(`Signing key saved to: ${backupPath}`);
2627
- p.log.warn("Move this file to a secure location and delete the local copy!");
2628
- } else if (backupChoice === "show") p.note([
2629
- "SIGNING KEY (keep this secret!):",
2630
- "",
2631
- signingKey,
2632
- "",
2633
- "Copy this to your password manager now."
2634
- ].join("\n"), "🔑 Your Signing Key");
2635
- if (backupChoice !== "skip") {
2636
- if (!await promptConfirm({
2637
- message: "Have you saved your signing key securely?",
2638
- initialValue: true
2639
- })) {
2640
- p.log.warn("Please back up your key before continuing!");
2641
- p.note(signingKey, "🔑 Signing Key");
2642
- }
2643
- }
2644
2763
  }
2645
2764
  const jwtSecret = await getOrGenerateSecret("JWT_SECRET", devVars, async () => {
2646
2765
  spinner.start("Generating JWT secret...");
@@ -2793,86 +2912,484 @@ async function getOrGenerateSecret(name, devVars, generate) {
2793
2912
  }
2794
2913
 
2795
2914
  //#endregion
2796
- //#region src/cli/commands/migrate.ts
2797
- const brightNote$2 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
2915
+ //#region src/plc.ts
2916
+ const PLC_DIRECTORY = "https://plc.directory";
2798
2917
  /**
2799
- * Format number with commas
2918
+ * Headers for submitting a PLC operation (POST /{did}). An update (any
2919
+ * operation with a `prev`) carries `If-Match: *`, which tells the directory
2920
+ * the DID already exists, so it is rate-limited per identifier rather than
2921
+ * per IP. That matters on Workers, whose egress IPs are shared. A genesis
2922
+ * operation (`prev: null`) must not carry it. Directories that predate the
2923
+ * header ignore it.
2924
+ * https://discourse.atmosphere.community/t/plc-directory-and-rate-limits/1506
2800
2925
  */
2801
- function num(n) {
2802
- return n.toLocaleString();
2926
+ function plcSubmitHeaders(operation) {
2927
+ return {
2928
+ "Content-Type": "application/json",
2929
+ ...typeof operation.prev === "string" ? { "If-Match": "*" } : {}
2930
+ };
2803
2931
  }
2804
2932
  /**
2805
- * Format bytes to human-readable size
2933
+ * Set the account's handle in an alsoKnownAs list. Handles are verified
2934
+ * against the first at:// entry, so the handle replaces it, or is added
2935
+ * first if there is none. Any later copy of the handle is dropped, and
2936
+ * other entries are kept.
2806
2937
  */
2807
- function formatBytes(bytes) {
2808
- if (bytes < 1024) return `${bytes} B`;
2809
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
2810
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
2938
+ function withHandle(alsoKnownAs, handle) {
2939
+ const aka = `at://${handle}`;
2940
+ const first = alsoKnownAs.findIndex((uri) => uri.startsWith("at://"));
2941
+ if (first < 0) return [aka, ...alsoKnownAs];
2942
+ return alsoKnownAs.map((uri, i) => i === first ? aka : uri).filter((uri, i) => uri !== aka || i === first);
2811
2943
  }
2812
- const migrateCommand = defineCommand({
2813
- meta: {
2814
- name: "migrate",
2815
- description: "Migrate account from source PDS to your new PDS"
2816
- },
2817
- args: {
2818
- clean: {
2819
- type: "boolean",
2820
- description: "Reset migration and start fresh",
2821
- default: false
2822
- },
2823
- dev: {
2824
- type: "boolean",
2825
- description: "Target local development server instead of production",
2826
- default: false
2827
- }
2828
- },
2829
- async run({ args }) {
2830
- const pm = detectPackageManager();
2831
- const isDev = args.dev;
2832
- const vars = getVars();
2833
- let targetUrl;
2944
+ /**
2945
+ * Sign a PLC operation: DAG-CBOR encode the unsigned operation, sign the
2946
+ * bytes, and attach the signature as base64url.
2947
+ */
2948
+ async function signOperation(op, keypair) {
2949
+ const sig = await keypair.sign(encode(op));
2950
+ return {
2951
+ ...op,
2952
+ sig: base64url.encode(sig)
2953
+ };
2954
+ }
2955
+
2956
+ //#endregion
2957
+ //#region src/cli/utils/plc-client.ts
2958
+ /**
2959
+ * PLC Directory client for identity operations
2960
+ *
2961
+ * Handles communication with the PLC directory and source PDS
2962
+ * for DID document updates during migration.
2963
+ *
2964
+ * Uses @atcute/client for type-safe XRPC calls.
2965
+ */
2966
+ /**
2967
+ * Create a fetch handler that adds optional auth token
2968
+ */
2969
+ function createAuthHandler(baseUrl, token) {
2970
+ return async (pathname, init) => {
2971
+ const url = new URL(pathname, baseUrl);
2972
+ const headers = new Headers(init.headers);
2973
+ if (token) headers.set("Authorization", `Bearer ${token}`);
2974
+ return fetch(url, {
2975
+ ...init,
2976
+ headers
2977
+ });
2978
+ };
2979
+ }
2980
+ /**
2981
+ * Client for interacting with source PDS for PLC operations
2982
+ *
2983
+ * Uses @atcute/client for type-safe XRPC calls to:
2984
+ * - com.atproto.identity.requestPlcOperationSignature
2985
+ * - com.atproto.identity.signPlcOperation
2986
+ */
2987
+ var SourcePdsPlcClient = class {
2988
+ client;
2989
+ authToken;
2990
+ baseUrl;
2991
+ constructor(baseUrl, authToken) {
2992
+ this.baseUrl = baseUrl;
2993
+ this.authToken = authToken;
2994
+ this.client = new Client({ handler: createAuthHandler(baseUrl, authToken) });
2995
+ }
2996
+ setAuthToken(token) {
2997
+ this.authToken = token;
2998
+ this.client = new Client({ handler: createAuthHandler(this.baseUrl, token) });
2999
+ }
3000
+ /**
3001
+ * Request a PLC operation signature from the source PDS.
3002
+ * This triggers the source PDS to send an email token to the user.
3003
+ *
3004
+ * Uses: com.atproto.identity.requestPlcOperationSignature
3005
+ */
3006
+ async requestPlcOperationSignature() {
2834
3007
  try {
2835
- targetUrl = getTargetUrl(isDev, vars.PDS_HOSTNAME);
3008
+ await ok(this.client.post("com.atproto.identity.requestPlcOperationSignature", { as: null }));
3009
+ return {
3010
+ success: true,
3011
+ credentialInfo: { type: "email" }
3012
+ };
2836
3013
  } catch (err) {
2837
- p.log.error(err instanceof Error ? err.message : "Configuration error");
2838
- p.log.info("Run 'pds init' first to configure your PDS.");
2839
- process.exit(1);
2840
- }
2841
- const targetDomain = getDomain(targetUrl);
2842
- p.intro("🦋 PDS Migration");
2843
- const spinner = p.spinner();
2844
- spinner.start(`Checking PDS at ${targetDomain}...`);
2845
- const targetClient = new PDSClient(targetUrl);
2846
- if (!await targetClient.healthCheck()) {
2847
- spinner.stop(`PDS not responding at ${targetDomain}`);
2848
- if (isDev) {
2849
- p.log.error(`Your local PDS isn't running at ${targetUrl}`);
2850
- p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
2851
- } else {
2852
- p.log.error(`Your PDS isn't responding at ${targetUrl}`);
2853
- p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
2854
- p.log.info(`Or test locally first: ${formatCommand(pm, "pds", "migrate", "--dev")}`);
2855
- }
2856
- p.outro("Migration cancelled.");
2857
- process.exit(1);
3014
+ return {
3015
+ success: false,
3016
+ error: err instanceof Error ? err.message : "Network error"
3017
+ };
2858
3018
  }
2859
- spinner.stop(`Connected to ${targetDomain}`);
2860
- const wranglerVars = getVars();
2861
- const config = {
2862
- ...readDevVars(),
2863
- ...wranglerVars
2864
- };
2865
- const did = config.DID;
2866
- const handle = config.HANDLE;
2867
- const authToken = config.AUTH_TOKEN;
2868
- if (!did) {
2869
- p.log.error("No DID configured. Run 'pds init' first.");
2870
- p.outro("Migration cancelled.");
2871
- process.exit(1);
3019
+ }
3020
+ /**
3021
+ * Get the source PDS's recommended credentials for this account. Its
3022
+ * rotationKeys are the keys the source PDS holds.
3023
+ *
3024
+ * Uses: com.atproto.identity.getRecommendedDidCredentials
3025
+ */
3026
+ async getRecommendedDidCredentials() {
3027
+ return { rotationKeys: (await ok(this.client.get("com.atproto.identity.getRecommendedDidCredentials", {}))).rotationKeys ?? [] };
3028
+ }
3029
+ /**
3030
+ * Get the source PDS to sign a PLC operation applying the given changes
3031
+ * to the DID's current state.
3032
+ *
3033
+ * Uses: com.atproto.identity.signPlcOperation
3034
+ *
3035
+ * @param token - The email token received from the source PDS
3036
+ * @param changes - Fields to change; omitted fields keep their values
3037
+ */
3038
+ async signPlcOperation(token, changes) {
3039
+ try {
3040
+ return {
3041
+ success: true,
3042
+ signedOperation: (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
3043
+ token,
3044
+ ...changes
3045
+ } }))).operation
3046
+ };
3047
+ } catch (err) {
3048
+ const errorMessage = err instanceof Error ? err.message : "Network error";
3049
+ if (errorMessage.includes("expired") || errorMessage.includes("ExpiredToken")) return {
3050
+ success: false,
3051
+ error: "Token expired. Request a new one and try again."
3052
+ };
3053
+ if (errorMessage.includes("invalid") || errorMessage.includes("InvalidToken")) return {
3054
+ success: false,
3055
+ error: "Invalid token. Check you entered it correctly."
3056
+ };
3057
+ return {
3058
+ success: false,
3059
+ error: errorMessage
3060
+ };
2872
3061
  }
2873
- if (!authToken) {
2874
- p.log.error("No AUTH_TOKEN found. Run 'pds init' first.");
2875
- p.outro("Migration cancelled.");
3062
+ }
3063
+ };
3064
+ /**
3065
+ * Client for interacting with the PLC directory
3066
+ *
3067
+ * The PLC directory has its own REST API (not XRPC), so we use raw fetch here.
3068
+ * See: https://web.plc.directory/
3069
+ */
3070
+ var PlcDirectoryClient = class {
3071
+ constructor(plcUrl = PLC_DIRECTORY) {
3072
+ this.plcUrl = plcUrl;
3073
+ }
3074
+ /**
3075
+ * Get the audit log for a DID (list of all operations)
3076
+ */
3077
+ async getAuditLog(did) {
3078
+ const res = await fetch(`${this.plcUrl}/${did}/log/audit`);
3079
+ if (!res.ok) throw new Error(`Failed to fetch audit log: ${res.status}`);
3080
+ return res.json();
3081
+ }
3082
+ /**
3083
+ * Get the most recent non-nullified operation for a DID
3084
+ */
3085
+ async getLatestOperation(did) {
3086
+ return (await this.getAuditLog(did)).filter((entry) => !entry.nullified).pop() ?? null;
3087
+ }
3088
+ /**
3089
+ * Get the current DID document
3090
+ */
3091
+ async getDocument(did) {
3092
+ const res = await fetch(`${this.plcUrl}/${did}`);
3093
+ if (!res.ok) {
3094
+ if (res.status === 404) return null;
3095
+ throw new Error(`Failed to fetch DID document: ${res.status}`);
3096
+ }
3097
+ return res.json();
3098
+ }
3099
+ /**
3100
+ * Submit a signed PLC operation to the directory
3101
+ */
3102
+ async submitOperation(did, operation) {
3103
+ try {
3104
+ const res = await fetch(`${this.plcUrl}/${did}`, {
3105
+ method: "POST",
3106
+ headers: plcSubmitHeaders(operation),
3107
+ body: JSON.stringify(operation)
3108
+ });
3109
+ if (!res.ok) return {
3110
+ success: false,
3111
+ error: `PLC directory rejected operation: ${await res.text()}`
3112
+ };
3113
+ return { success: true };
3114
+ } catch (err) {
3115
+ return {
3116
+ success: false,
3117
+ error: err instanceof Error ? err.message : "Network error"
3118
+ };
3119
+ }
3120
+ }
3121
+ };
3122
+
3123
+ //#endregion
3124
+ //#region src/cli/utils/checks.ts
3125
+ /**
3126
+ * Check that handle resolves to the expected DID
3127
+ */
3128
+ async function checkHandleResolution(handle, expectedDid) {
3129
+ const resolvedDid = await resolveHandleToDid(handle);
3130
+ if (!resolvedDid) return {
3131
+ ok: false,
3132
+ message: `@${handle} does not resolve to any DID`,
3133
+ detail: "Update your DNS TXT record or .well-known/atproto-did file"
3134
+ };
3135
+ if (resolvedDid !== expectedDid) return {
3136
+ ok: false,
3137
+ message: `@${handle} resolves to wrong DID`,
3138
+ detail: `Expected: ${expectedDid}\n Got: ${resolvedDid}`
3139
+ };
3140
+ return {
3141
+ ok: true,
3142
+ message: `@${handle} → ${expectedDid.slice(0, 24)}...`
3143
+ };
3144
+ }
3145
+ /**
3146
+ * Check that handle resolves via DNS and/or HTTP, returning both methods
3147
+ */
3148
+ async function checkHandleResolutionDetailed(client, handle, expectedDid) {
3149
+ const [httpDid, dnsDid] = await Promise.all([client.checkHandleViaHttp(handle), client.checkHandleViaDns(handle)]);
3150
+ const httpValid = httpDid === expectedDid;
3151
+ const dnsValid = dnsDid === expectedDid;
3152
+ const methods = [];
3153
+ if (dnsValid) methods.push("DNS");
3154
+ if (httpValid) methods.push("HTTP");
3155
+ return {
3156
+ ok: httpValid || dnsValid,
3157
+ httpDid,
3158
+ dnsDid,
3159
+ methods
3160
+ };
3161
+ }
3162
+ /**
3163
+ * Check that DID document points to the expected PDS endpoint
3164
+ */
3165
+ async function checkDidDocument(did, expectedPdsUrl) {
3166
+ const didDoc = await new DidResolver().resolve(did);
3167
+ const expectedEndpoint = expectedPdsUrl.replace(/\/$/, "");
3168
+ if (!didDoc) return {
3169
+ ok: false,
3170
+ message: `Could not resolve DID document for ${did}`,
3171
+ detail: "Make sure your DID is published to the PLC directory or did:web endpoint"
3172
+ };
3173
+ const pdsService = didDoc.service?.find((s) => {
3174
+ return (Array.isArray(s.type) ? s.type : [s.type]).includes("AtprotoPersonalDataServer") || s.id === "#atproto_pds";
3175
+ });
3176
+ if (!pdsService?.serviceEndpoint) return {
3177
+ ok: false,
3178
+ message: "DID document has no PDS service endpoint",
3179
+ detail: "Update your DID document to include an AtprotoPersonalDataServer service"
3180
+ };
3181
+ const actualEndpoint = pdsService.serviceEndpoint.replace(/\/$/, "");
3182
+ if (actualEndpoint !== expectedEndpoint) return {
3183
+ ok: false,
3184
+ message: "DID document points to different PDS",
3185
+ detail: `Expected: ${expectedEndpoint}\n Got: ${actualEndpoint}`
3186
+ };
3187
+ return {
3188
+ ok: true,
3189
+ message: `PDS endpoint → ${expectedEndpoint}`
3190
+ };
3191
+ }
3192
+ /**
3193
+ * Check whether this PDS can update a did:plc identity: its signing key
3194
+ * must be one of the DID's rotation keys. Also reports whether any other
3195
+ * key is listed, such as a recovery key. Returns null if either side
3196
+ * can't be read.
3197
+ */
3198
+ async function checkPlcRotationKeys(client, did, plcClient = new PlcDirectoryClient()) {
3199
+ try {
3200
+ const [credentials, latest] = await Promise.all([client.getRecommendedDidCredentials(), plcClient.getLatestOperation(did)]);
3201
+ const pdsKey = credentials.rotationKeys[0];
3202
+ if (!pdsKey || latest?.operation.type !== "plc_operation") return null;
3203
+ const keys = latest.operation.rotationKeys;
3204
+ return {
3205
+ pdsCanSign: keys.includes(pdsKey),
3206
+ otherKeys: keys.filter((key) => key !== pdsKey).length
3207
+ };
3208
+ } catch {
3209
+ return null;
3210
+ }
3211
+ }
3212
+ /**
3213
+ * Check that DID resolves and returns the PDS endpoint (simpler version using PDSClient)
3214
+ */
3215
+ async function checkDidResolution(client, did, expectedPdsHostname) {
3216
+ const resolved = await client.resolveDid(did);
3217
+ const resolveMethod = did.startsWith("did:plc:") ? "plc.directory" : did.startsWith("did:web:") ? "/.well-known/did.json" : "unknown";
3218
+ if (!resolved.pdsEndpoint) return {
3219
+ ok: false,
3220
+ pdsEndpoint: null,
3221
+ resolveMethod
3222
+ };
3223
+ const expectedEndpoint = `https://${expectedPdsHostname}`;
3224
+ return {
3225
+ ok: resolved.pdsEndpoint === expectedEndpoint || resolved.pdsEndpoint === expectedPdsHostname,
3226
+ pdsEndpoint: resolved.pdsEndpoint,
3227
+ resolveMethod
3228
+ };
3229
+ }
3230
+ /**
3231
+ * Count the blobs that imported records reference but that have not been
3232
+ * uploaded.
3233
+ */
3234
+ async function countMissingBlobs(client) {
3235
+ const missing = /* @__PURE__ */ new Set();
3236
+ let cursor;
3237
+ do {
3238
+ const page = await client.listMissingBlobs(500, cursor);
3239
+ for (const blob of page.blobs) missing.add(blob.cid);
3240
+ cursor = page.cursor;
3241
+ } while (cursor);
3242
+ return missing.size;
3243
+ }
3244
+ /**
3245
+ * Check that every blob referenced by the imported repo has been uploaded.
3246
+ *
3247
+ * `expectedBlobs` counts blobs referenced by records at import time, while
3248
+ * `importedBlobs` counts every blob uploaded since, so the two only compare
3249
+ * until the account takes new uploads. `missingBlobs` comes from
3250
+ * `countMissingBlobs`.
3251
+ */
3252
+ function checkBlobsImported(status, missingBlobs) {
3253
+ if (missingBlobs > 0) return {
3254
+ ok: false,
3255
+ message: `${missingBlobs} of ${status.expectedBlobs} migrated blobs missing`,
3256
+ detail: "Run 'pds migrate' to import missing blobs before activating"
3257
+ };
3258
+ return {
3259
+ ok: true,
3260
+ message: `All ${status.expectedBlobs} migrated blobs imported`
3261
+ };
3262
+ }
3263
+ /**
3264
+ * Check that repository data exists and is properly initialised
3265
+ */
3266
+ function checkRepoInitialised(status) {
3267
+ if (!status.repoCommit) return {
3268
+ ok: false,
3269
+ message: "No repo data imported",
3270
+ detail: "Run 'pds migrate' to import your repository first"
3271
+ };
3272
+ if (status.indexedRecords === 0) return {
3273
+ ok: false,
3274
+ message: "Repository has no indexed records",
3275
+ detail: "Run 'pds migrate' to import your repository"
3276
+ };
3277
+ return {
3278
+ ok: true,
3279
+ message: `${status.repoBlocks.toLocaleString()} blocks, ${status.indexedRecords.toLocaleString()} records`
3280
+ };
3281
+ }
3282
+ /**
3283
+ * Check that repo is complete for activation (combines blob and repo checks)
3284
+ */
3285
+ async function checkRepoComplete(client, status) {
3286
+ const repoCheck = checkRepoInitialised(status);
3287
+ if (!repoCheck.ok) return repoCheck;
3288
+ if (status.expectedBlobs > 0) {
3289
+ const blobCheck = checkBlobsImported(status, await countMissingBlobs(client));
3290
+ if (!blobCheck.ok) return blobCheck;
3291
+ }
3292
+ return {
3293
+ ok: true,
3294
+ message: `${status.repoBlocks} blocks, ${status.importedBlobs} blobs`
3295
+ };
3296
+ }
3297
+ /**
3298
+ * Check if profile is indexed by AppView
3299
+ */
3300
+ async function checkAppViewIndexing(client, did) {
3301
+ if (!await client.checkAppViewIndexing(did)) return {
3302
+ ok: false,
3303
+ message: "Profile not found on AppView",
3304
+ detail: "This may be normal for new accounts"
3305
+ };
3306
+ return {
3307
+ ok: true,
3308
+ message: "Profile indexed by AppView"
3309
+ };
3310
+ }
3311
+
3312
+ //#endregion
3313
+ //#region src/cli/commands/migrate.ts
3314
+ const brightNote$3 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
3315
+ /**
3316
+ * Format number with commas
3317
+ */
3318
+ function num(n) {
3319
+ return n.toLocaleString();
3320
+ }
3321
+ /**
3322
+ * Format bytes to human-readable size
3323
+ */
3324
+ function formatBytes(bytes) {
3325
+ if (bytes < 1024) return `${bytes} B`;
3326
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
3327
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
3328
+ }
3329
+ const migrateCommand = defineCommand({
3330
+ meta: {
3331
+ name: "migrate",
3332
+ description: "Migrate account from source PDS to your new PDS"
3333
+ },
3334
+ args: {
3335
+ clean: {
3336
+ type: "boolean",
3337
+ description: "Reset migration and start fresh",
3338
+ default: false
3339
+ },
3340
+ dev: {
3341
+ type: "boolean",
3342
+ description: "Target local development server instead of production",
3343
+ default: false
3344
+ }
3345
+ },
3346
+ async run({ args }) {
3347
+ const pm = detectPackageManager();
3348
+ const isDev = args.dev;
3349
+ const vars = getVars();
3350
+ let targetUrl;
3351
+ try {
3352
+ targetUrl = getTargetUrl(isDev, vars.PDS_HOSTNAME);
3353
+ } catch (err) {
3354
+ p.log.error(err instanceof Error ? err.message : "Configuration error");
3355
+ p.log.info("Run 'pds init' first to configure your PDS.");
3356
+ process.exit(1);
3357
+ }
3358
+ const targetDomain = getDomain(targetUrl);
3359
+ p.intro("🦋 PDS Migration");
3360
+ const spinner = p.spinner();
3361
+ spinner.start(`Checking PDS at ${targetDomain}...`);
3362
+ const targetClient = new PDSClient(targetUrl);
3363
+ if (!await targetClient.healthCheck()) {
3364
+ spinner.stop(`PDS not responding at ${targetDomain}`);
3365
+ if (isDev) {
3366
+ p.log.error(`Your local PDS isn't running at ${targetUrl}`);
3367
+ p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
3368
+ } else {
3369
+ p.log.error(`Your PDS isn't responding at ${targetUrl}`);
3370
+ p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
3371
+ p.log.info(`Or test locally first: ${formatCommand(pm, "pds", "migrate", "--dev")}`);
3372
+ }
3373
+ p.outro("Migration cancelled.");
3374
+ process.exit(1);
3375
+ }
3376
+ spinner.stop(`Connected to ${targetDomain}`);
3377
+ const wranglerVars = getVars();
3378
+ const config = {
3379
+ ...readDevVars(),
3380
+ ...wranglerVars
3381
+ };
3382
+ const did = config.DID;
3383
+ const handle = config.HANDLE;
3384
+ const authToken = config.AUTH_TOKEN;
3385
+ if (!did) {
3386
+ p.log.error("No DID configured. Run 'pds init' first.");
3387
+ p.outro("Migration cancelled.");
3388
+ process.exit(1);
3389
+ }
3390
+ if (!authToken) {
3391
+ p.log.error("No AUTH_TOKEN found. Run 'pds init' first.");
3392
+ p.outro("Migration cancelled.");
2876
3393
  process.exit(1);
2877
3394
  }
2878
3395
  targetClient.setAuthToken(authToken);
@@ -2916,7 +3433,7 @@ const migrateCommand = defineCommand({
2916
3433
  p.outro("Migration cancelled.");
2917
3434
  process.exit(1);
2918
3435
  }
2919
- p.note(brightNote$2([
3436
+ p.note(brightNote$3([
2920
3437
  pc.bold("This will permanently delete from your new PDS:"),
2921
3438
  "",
2922
3439
  ` • ${num(status.repoBlocks)} repository blocks`,
@@ -2966,15 +3483,15 @@ const migrateCommand = defineCommand({
2966
3483
  const profileStats = await sourceClient.getProfileStats(did);
2967
3484
  spinner.stop("Account details fetched");
2968
3485
  const needsRepoImport = status.repoBlocks === 0 || status.indexedRecords === 0 && status.expectedBlobs === 0;
2969
- const needsBlobSync = status.expectedBlobs - status.importedBlobs > 0 || needsRepoImport;
2970
- if (!needsRepoImport && needsBlobSync) {
3486
+ const missingBlobs = needsRepoImport ? 0 : await countMissingBlobs(targetClient);
3487
+ if (!needsRepoImport && (missingBlobs > 0 || needsRepoImport)) {
2971
3488
  p.log.info("Welcome back!");
2972
3489
  p.log.info("Looks like you started packing earlier. Let's pick up where we left off.");
2973
3490
  p.note([
2974
3491
  `@${handle} (${did.slice(0, 20)}...)`,
2975
3492
  "",
2976
3493
  "✓ Repository imported",
2977
- `◐ Media: ${num(status.importedBlobs)}/${num(status.expectedBlobs)} images and videos transferred`
3494
+ `◐ Media: ${num(status.expectedBlobs - missingBlobs)}/${num(status.expectedBlobs)} images and videos transferred`
2978
3495
  ].join("\n"), "Migration Progress");
2979
3496
  const continueTransfer = await p.confirm({
2980
3497
  message: "Continue transferring images and video?",
@@ -2992,7 +3509,7 @@ const migrateCommand = defineCommand({
2992
3509
  ` 👥 ${num(profileStats.followsCount)} follows`,
2993
3510
  ` ...plus all your images, likes and preferences`
2994
3511
  ] : [` 📝 Posts, follows, images, likes and preferences`];
2995
- p.note(brightNote$2([
3512
+ p.note(brightNote$3([
2996
3513
  pc.bold(`@${handle}`) + ` (${did.slice(0, 20)}...)`,
2997
3514
  "",
2998
3515
  `Currently at: ${sourceDomain}`,
@@ -3055,7 +3572,6 @@ const migrateCommand = defineCommand({
3055
3572
  p.outro("Migration cancelled.");
3056
3573
  process.exit(1);
3057
3574
  }
3058
- status = await targetClient.getAccountStatus();
3059
3575
  }
3060
3576
  spinner.start("Migrating your preferences...");
3061
3577
  try {
@@ -3067,9 +3583,11 @@ const migrateCommand = defineCommand({
3067
3583
  } catch (err) {
3068
3584
  spinner.stop("Skipped preferences (not available)");
3069
3585
  }
3070
- if (status.expectedBlobs - status.importedBlobs > 0) {
3586
+ spinner.start("Counting images to transfer...");
3587
+ const totalBlobs = await countMissingBlobs(targetClient);
3588
+ if (totalBlobs === 0) spinner.stop("No images or videos to transfer");
3589
+ else {
3071
3590
  let synced = 0;
3072
- let totalBlobs = 0;
3073
3591
  let cursor;
3074
3592
  let failedBlobs = [];
3075
3593
  const progressBar = (current, total) => {
@@ -3079,26 +3597,24 @@ const migrateCommand = defineCommand({
3079
3597
  const empty = width - filled;
3080
3598
  return `${"█".repeat(filled)}${"░".repeat(empty)} ${current}/${total}`;
3081
3599
  };
3082
- spinner.start("Counting images to transfer...");
3083
- let countCursor;
3084
- do {
3085
- const page = await targetClient.listMissingBlobs(500, countCursor);
3086
- totalBlobs += page.blobs.length;
3087
- countCursor = page.cursor;
3088
- } while (countCursor);
3089
3600
  spinner.message(`Transferring media ${progressBar(0, totalBlobs)}`);
3601
+ const attempted = /* @__PURE__ */ new Set();
3090
3602
  do {
3091
3603
  const page = await targetClient.listMissingBlobs(100, cursor);
3092
3604
  cursor = page.cursor;
3093
- for (const blob of page.blobs) try {
3094
- const { bytes, mimeType } = await sourceClient.getBlob(did, blob.cid);
3095
- await targetClient.uploadBlob(bytes, mimeType);
3096
- synced++;
3097
- spinner.message(`Transferring media ${progressBar(synced, totalBlobs)}`);
3098
- } catch (err) {
3099
- synced++;
3100
- failedBlobs.push(blob.cid);
3101
- spinner.message(`Transferring media ${progressBar(synced, totalBlobs)}`);
3605
+ for (const blob of page.blobs) {
3606
+ if (attempted.has(blob.cid)) continue;
3607
+ attempted.add(blob.cid);
3608
+ try {
3609
+ const { bytes, mimeType } = await sourceClient.getBlob(did, blob.cid);
3610
+ await targetClient.uploadBlob(bytes, mimeType);
3611
+ synced++;
3612
+ spinner.message(`Transferring media ${progressBar(synced, totalBlobs)}`);
3613
+ } catch (err) {
3614
+ synced++;
3615
+ failedBlobs.push(blob.cid);
3616
+ spinner.message(`Transferring media ${progressBar(synced, totalBlobs)}`);
3617
+ }
3102
3618
  }
3103
3619
  } while (cursor);
3104
3620
  if (failedBlobs.length > 0) {
@@ -3107,11 +3623,11 @@ const migrateCommand = defineCommand({
3107
3623
  } else spinner.stop(`Transferred ${num(synced)} images and videos`);
3108
3624
  }
3109
3625
  spinner.start("Verifying migration...");
3110
- const finalStatus = await targetClient.getAccountStatus();
3626
+ const remainingBlobs = await countMissingBlobs(targetClient);
3111
3627
  spinner.stop("Verification complete");
3112
- if (finalStatus.importedBlobs >= finalStatus.expectedBlobs) p.log.success("All packed and moved!");
3628
+ if (remainingBlobs === 0) p.log.success("All packed and moved!");
3113
3629
  else {
3114
- p.log.warn(`Migration partially complete. ${finalStatus.expectedBlobs - finalStatus.importedBlobs} images remaining.`);
3630
+ p.log.warn(`Migration partially complete. ${remainingBlobs} images remaining.`);
3115
3631
  p.log.info("Run 'pds migrate' again to continue.");
3116
3632
  }
3117
3633
  showNextSteps(pm, pdsDisplayName);
@@ -3119,7 +3635,7 @@ const migrateCommand = defineCommand({
3119
3635
  }
3120
3636
  });
3121
3637
  function showNextSteps(pm, sourceDomain) {
3122
- p.note(brightNote$2([
3638
+ p.note(brightNote$3([
3123
3639
  pc.bold("Your data is safe in your new PDS."),
3124
3640
  "Two more steps to go live:",
3125
3641
  "",
@@ -3226,164 +3742,240 @@ const migrateTokenCommand = defineCommand({
3226
3742
  });
3227
3743
 
3228
3744
  //#endregion
3229
- //#region src/cli/utils/plc-client.ts
3745
+ //#region src/cli/utils/rotation-keys.ts
3230
3746
  /**
3231
- * PLC Directory client for identity operations
3747
+ * PLC rotation key helpers: ordering, labelling, and recovery keys.
3232
3748
  *
3233
- * Handles communication with the PLC directory and source PDS
3234
- * for DID document updates during migration.
3235
- *
3236
- * Uses @atcute/client for type-safe XRPC calls.
3749
+ * Rotation keys are listed in priority order. A higher-priority key can
3750
+ * override an operation signed by a lower one for 72 hours, so keys the
3751
+ * user holds offline come before the PDS key.
3237
3752
  */
3238
- const PLC_DIRECTORY = "https://plc.directory";
3753
+ /** plc.directory accepts at most this many rotation keys */
3754
+ const MAX_ROTATION_KEYS = 5;
3755
+ const SECP256K1_PRIV_PREFIX = [129, 38];
3756
+ const P256_PRIV_PREFIX = [134, 38];
3239
3757
  /**
3240
- * Create a fetch handler that adds optional auth token
3758
+ * Build the rotation key list: keys the user holds, in the order given,
3759
+ * followed by the PDS key.
3241
3760
  */
3242
- function createAuthHandler(baseUrl, token) {
3243
- return async (pathname, init) => {
3244
- const url = new URL(pathname, baseUrl);
3245
- const headers = new Headers(init.headers);
3246
- if (token) headers.set("Authorization", `Bearer ${token}`);
3247
- return fetch(url, {
3248
- ...init,
3249
- headers
3250
- });
3251
- };
3761
+ function buildRotationKeys(opts) {
3762
+ const keys = [...new Set([...opts.userKeys.filter((k) => k !== opts.pdsKey), opts.pdsKey])];
3763
+ const invalid = keys.find((k) => !k.startsWith("did:key:"));
3764
+ if (invalid) throw new Error(`Not a did:key: ${invalid}`);
3765
+ if (keys.length > MAX_ROTATION_KEYS) throw new Error(`A DID can have at most ${MAX_ROTATION_KEYS} rotation keys (got ${keys.length})`);
3766
+ return keys;
3252
3767
  }
3253
3768
  /**
3254
- * Client for interacting with source PDS for PLC operations
3255
- *
3256
- * Uses @atcute/client for type-safe XRPC calls to:
3257
- * - com.atproto.identity.requestPlcOperationSignature
3258
- * - com.atproto.identity.signPlcOperation
3769
+ * Tag each current rotation key with who holds it, where known.
3259
3770
  */
3260
- var SourcePdsPlcClient = class {
3261
- client;
3262
- authToken;
3263
- baseUrl;
3264
- constructor(baseUrl, authToken) {
3265
- this.baseUrl = baseUrl;
3266
- this.authToken = authToken;
3267
- this.client = new Client({ handler: createAuthHandler(baseUrl, authToken) });
3771
+ function labelRotationKeys(current, known) {
3772
+ return current.map((key) => ({
3773
+ key,
3774
+ owner: key === known.pdsKey ? "this-pds" : known.sourcePdsKeys?.includes(key) ? "source-pds" : "unknown"
3775
+ }));
3776
+ }
3777
+ /**
3778
+ * Find the PDS a DID pointed at before the current one, from its PLC audit
3779
+ * log. Returns null if it has never pointed anywhere else.
3780
+ */
3781
+ function findPreviousPdsEndpoint(log, currentEndpoint) {
3782
+ const current = currentEndpoint.replace(/\/$/, "");
3783
+ for (const entry of [...log].reverse()) {
3784
+ if (entry.nullified || entry.operation.type !== "plc_operation") continue;
3785
+ const endpoint = entry.operation.services.atproto_pds?.endpoint?.replace(/\/$/, "");
3786
+ if (endpoint && endpoint !== current) return endpoint;
3268
3787
  }
3269
- setAuthToken(token) {
3270
- this.authToken = token;
3271
- this.client = new Client({ handler: createAuthHandler(this.baseUrl, token) });
3788
+ return null;
3789
+ }
3790
+ /**
3791
+ * The server to log in to and ask for PLC signatures, given a PDS endpoint
3792
+ * from a DID's history. Bluesky's hosts forward PLC signing requests to
3793
+ * bsky.social with a service token signed by the account's repo key at that
3794
+ * host, which bsky.social rejects once the DID lists another PDS's key.
3795
+ */
3796
+ function entrywayFor(endpoint) {
3797
+ return hostnameOf(endpoint)?.endsWith(".host.bsky.network") ? "https://bsky.social" : endpoint;
3798
+ }
3799
+ /**
3800
+ * The hostname of a URL, or null if it doesn't parse as one.
3801
+ */
3802
+ function hostnameOf(url) {
3803
+ try {
3804
+ return new URL(url).hostname;
3805
+ } catch {
3806
+ return null;
3272
3807
  }
3273
- /**
3274
- * Request a PLC operation signature from the source PDS.
3275
- * This triggers the source PDS to send an email token to the user.
3276
- *
3277
- * Uses: com.atproto.identity.requestPlcOperationSignature
3278
- */
3279
- async requestPlcOperationSignature() {
3808
+ }
3809
+ /**
3810
+ * Generate a secp256k1 recovery key.
3811
+ */
3812
+ async function generateRecoveryKey() {
3813
+ const keypair = await Secp256k1Keypair.create({ exportable: true });
3814
+ const bytes = await keypair.export();
3815
+ return {
3816
+ privateKey: bytesToMultibase(new Uint8Array([...SECP256K1_PRIV_PREFIX, ...bytes]), "base58btc"),
3817
+ did: keypair.did()
3818
+ };
3819
+ }
3820
+ /**
3821
+ * Parse a private rotation key pasted by the user: multibase (from goat or
3822
+ * generateRecoveryKey, secp256k1 or P-256), or a hex secp256k1 key like
3823
+ * the PDS signing key.
3824
+ */
3825
+ async function importRotationKey(input) {
3826
+ const value = input.trim();
3827
+ if (/^[0-9a-f]{64}$/i.test(value)) return Secp256k1Keypair.import(value.toLowerCase());
3828
+ if (value.startsWith("z")) {
3829
+ let bytes;
3280
3830
  try {
3281
- await ok(this.client.post("com.atproto.identity.requestPlcOperationSignature", { as: null }));
3282
- return {
3283
- success: true,
3284
- credentialInfo: { type: "email" }
3285
- };
3286
- } catch (err) {
3287
- return {
3288
- success: false,
3289
- error: err instanceof Error ? err.message : "Network error"
3290
- };
3831
+ bytes = multibaseToBytes(value);
3832
+ } catch {
3833
+ throw new Error("Not a valid multibase key");
3291
3834
  }
3292
- }
3293
- /**
3294
- * Get a signed PLC operation from the source PDS.
3295
- * This builds and signs the operation to migrate to the new PDS.
3296
- *
3297
- * Uses: com.atproto.identity.signPlcOperation
3298
- *
3299
- * @param token - The email token received from the source PDS
3300
- * @param newPdsEndpoint - The endpoint URL of the new PDS
3301
- * @param newSigningKey - The new signing key DID (did:key:...)
3302
- */
3303
- async signPlcOperation(token, newPdsEndpoint, newSigningKey) {
3304
- try {
3305
- return {
3306
- success: true,
3307
- signedOperation: (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
3308
- token,
3309
- rotationKeys: void 0,
3310
- alsoKnownAs: void 0,
3311
- verificationMethods: { atproto: newSigningKey },
3312
- services: { atproto_pds: {
3313
- type: "AtprotoPersonalDataServer",
3314
- endpoint: newPdsEndpoint
3315
- } }
3316
- } }))).operation
3317
- };
3318
- } catch (err) {
3319
- const errorMessage = err instanceof Error ? err.message : "Network error";
3320
- if (errorMessage.includes("expired") || errorMessage.includes("ExpiredToken")) return {
3321
- success: false,
3322
- error: "Token expired. Request a new one and try again."
3323
- };
3324
- if (errorMessage.includes("invalid") || errorMessage.includes("InvalidToken")) return {
3325
- success: false,
3326
- error: "Invalid token. Check you entered it correctly."
3327
- };
3328
- return {
3329
- success: false,
3330
- error: errorMessage
3331
- };
3835
+ const prefix = [bytes[0], bytes[1]];
3836
+ const key = bytes.slice(2);
3837
+ if (key.length === 32) {
3838
+ if (samePrefix(prefix, SECP256K1_PRIV_PREFIX)) return Secp256k1Keypair.import(key);
3839
+ if (samePrefix(prefix, P256_PRIV_PREFIX)) return P256Keypair.import(key);
3332
3840
  }
3333
3841
  }
3334
- };
3842
+ throw new Error("Unrecognised key format. Expected a multibase private key (starting with z) or a 64-character hex key.");
3843
+ }
3844
+ function samePrefix(a, b) {
3845
+ return a[0] === b[0] && a[1] === b[1];
3846
+ }
3847
+
3848
+ //#endregion
3849
+ //#region src/cli/utils/rotation-key-prompts.ts
3335
3850
  /**
3336
- * Client for interacting with the PLC directory
3337
- *
3338
- * The PLC directory has its own REST API (not XRPC), so we use raw fetch here.
3339
- * See: https://web.plc.directory/
3851
+ * Interactive steps for choosing a DID's rotation keys, shared by
3852
+ * `pds identity` and `pds rotation-keys`.
3340
3853
  */
3341
- var PlcDirectoryClient = class {
3342
- constructor(plcUrl = PLC_DIRECTORY) {
3343
- this.plcUrl = plcUrl;
3854
+ /**
3855
+ * Get the key the deployed PDS signs with, from its recommended
3856
+ * credentials. The DID must name this key, which may not be the one in
3857
+ * .dev.vars, so a different local key is an error.
3858
+ */
3859
+ async function getPdsRotationKey(client, pdsName, localSigningKey) {
3860
+ const credentials = await client.getRecommendedDidCredentials();
3861
+ const pdsKey = credentials.rotationKeys[0];
3862
+ if (!pdsKey || credentials.verificationMethods.atproto !== pdsKey) throw new Error(`${pdsName} returned unexpected credentials`);
3863
+ if (localSigningKey) {
3864
+ const localKey = (await Secp256k1Keypair.import(localSigningKey)).did();
3865
+ if (localKey !== pdsKey) throw new Error(`The signing key in .dev.vars (${localKey}) is not the one ${pdsName} uses (${pdsKey}). Restore the deployed key to .dev.vars, or redeploy with the local one, then try again.`);
3344
3866
  }
3345
- /**
3346
- * Get the audit log for a DID (list of all operations)
3347
- */
3348
- async getAuditLog(did) {
3349
- const res = await fetch(`${this.plcUrl}/${did}/log/audit`);
3350
- if (!res.ok) throw new Error(`Failed to fetch audit log: ${res.status}`);
3351
- return res.json();
3867
+ return pdsKey;
3868
+ }
3869
+ /**
3870
+ * Decide the new rotation keys: keep the current keys the user holds, offer
3871
+ * to generate a recovery key if there are none, and put this PDS's key last.
3872
+ *
3873
+ * @param sourcePdsKeys - Keys held by the previous PDS, if known. Without
3874
+ * them, the user is asked about every key that isn't this PDS's.
3875
+ * @param sourceName - Display name for the previous PDS
3876
+ * @param heldKeys - Keys known to be the user's, kept without asking
3877
+ */
3878
+ async function chooseRotationKeys(opts) {
3879
+ const descriptions = new Map([[opts.pdsKey, `${opts.pdsName} (this PDS)`]]);
3880
+ const labelled = labelRotationKeys(opts.currentKeys, {
3881
+ pdsKey: opts.pdsKey,
3882
+ sourcePdsKeys: opts.sourcePdsKeys
3883
+ });
3884
+ const sourceKnown = opts.sourcePdsKeys !== void 0;
3885
+ const userKeys = [];
3886
+ for (const { key, owner } of labelled) {
3887
+ if (owner === "source-pds") {
3888
+ descriptions.set(key, opts.sourceName ?? "previous PDS");
3889
+ continue;
3890
+ }
3891
+ if (owner === "this-pds") continue;
3892
+ if (opts.heldKeys?.includes(key)) {
3893
+ userKeys.push(key);
3894
+ descriptions.set(key, "your key");
3895
+ continue;
3896
+ }
3897
+ if (await promptConfirm({
3898
+ message: sourceKnown ? `Keep ${pc.cyan(key)}? It isn't held by ${opts.sourceName ?? "your previous PDS"}, so it is probably a recovery key you added.` : `Keep ${pc.cyan(key)}? Answer no only if you don't hold this key, such as one belonging to your previous PDS.`,
3899
+ initialValue: true
3900
+ })) {
3901
+ userKeys.push(key);
3902
+ descriptions.set(key, "your key");
3903
+ } else descriptions.set(key, "not held by you");
3352
3904
  }
3353
- /**
3354
- * Get the current DID document
3355
- */
3356
- async getDocument(did) {
3357
- const res = await fetch(`${this.plcUrl}/${did}`);
3358
- if (!res.ok) {
3359
- if (res.status === 404) return null;
3360
- throw new Error(`Failed to fetch DID document: ${res.status}`);
3905
+ let createdRecoveryKey = false;
3906
+ if (userKeys.length === 0) {
3907
+ p.note([
3908
+ "A recovery key is a rotation key you keep offline.",
3909
+ "It ranks above your PDS's key, so for 72 hours after any",
3910
+ "identity change it can override it. If your PDS is lost or",
3911
+ "compromised, it is how you take your identity back."
3912
+ ].join("\n"), "Recovery key");
3913
+ if (await promptConfirm({
3914
+ message: "Create a recovery key? (recommended)",
3915
+ initialValue: true
3916
+ })) {
3917
+ const recoveryKey = await generateRecoveryKey();
3918
+ const backup = () => promptKeyBackup({
3919
+ key: recoveryKey.privateKey,
3920
+ kind: "recovery",
3921
+ handle: opts.handle,
3922
+ details: [`DID: ${opts.did}`, `Public key: ${recoveryKey.did}`],
3923
+ allowSkip: false
3924
+ });
3925
+ let saved = await backup();
3926
+ while (!saved) {
3927
+ if (!await promptConfirm({
3928
+ message: "Try saving it again? Choosing no continues without a recovery key.",
3929
+ initialValue: true
3930
+ })) break;
3931
+ saved = await backup();
3932
+ }
3933
+ if (saved) {
3934
+ userKeys.push(recoveryKey.did);
3935
+ descriptions.set(recoveryKey.did, "your new recovery key");
3936
+ createdRecoveryKey = true;
3937
+ }
3361
3938
  }
3362
- return res.json();
3363
3939
  }
3364
- /**
3365
- * Submit a signed PLC operation to the directory
3366
- */
3367
- async submitOperation(did, operation) {
3368
- try {
3369
- const res = await fetch(`${this.plcUrl}/${did}`, {
3370
- method: "POST",
3371
- headers: { "Content-Type": "application/json" },
3372
- body: JSON.stringify(operation)
3373
- });
3374
- if (!res.ok) return {
3375
- success: false,
3376
- error: `PLC directory rejected operation: ${await res.text()}`
3377
- };
3378
- return { success: true };
3379
- } catch (err) {
3380
- return {
3381
- success: false,
3382
- error: err instanceof Error ? err.message : "Network error"
3383
- };
3940
+ if (userKeys.length > MAX_ROTATION_KEYS - 1) throw new Error(`You chose ${userKeys.length} keys to keep, but a DID can have at most ${MAX_ROTATION_KEYS} rotation keys including this PDS's.`);
3941
+ const rotationKeys = buildRotationKeys({
3942
+ userKeys,
3943
+ pdsKey: opts.pdsKey
3944
+ });
3945
+ return {
3946
+ rotationKeys,
3947
+ descriptions,
3948
+ removed: opts.currentKeys.filter((k) => !rotationKeys.includes(k)),
3949
+ createdRecoveryKey
3950
+ };
3951
+ }
3952
+ /**
3953
+ * Lines describing a rotation key change, for a note.
3954
+ */
3955
+ function describeRotationKeys(choice) {
3956
+ const lines = [pc.bold("Rotation keys, highest priority first:")];
3957
+ choice.rotationKeys.forEach((key, i) => {
3958
+ lines.push(` ${i + 1}. ${key}`);
3959
+ lines.push(` ${pc.dim(choice.descriptions.get(key) ?? "")}`);
3960
+ });
3961
+ if (choice.removed.length > 0) {
3962
+ lines.push("", pc.bold("Removed:"));
3963
+ for (const key of choice.removed) {
3964
+ lines.push(` ${key}`);
3965
+ lines.push(` ${pc.dim(choice.descriptions.get(key) ?? "")}`);
3384
3966
  }
3385
3967
  }
3386
- };
3968
+ return lines;
3969
+ }
3970
+ /**
3971
+ * Read the DID's latest operation back and check its rotation keys.
3972
+ * Returns the keys plc.directory has, or null if they match.
3973
+ */
3974
+ async function checkRotationKeys(plcClient, did, expected) {
3975
+ const latest = await plcClient.getLatestOperation(did);
3976
+ const actual = latest?.operation.type === "plc_operation" ? latest.operation.rotationKeys : [];
3977
+ return actual.length === expected.length && actual.every((key, i) => key === expected[i]) ? null : actual;
3978
+ }
3387
3979
 
3388
3980
  //#endregion
3389
3981
  //#region src/cli/commands/identity.ts
@@ -3392,11 +3984,14 @@ var PlcDirectoryClient = class {
3392
3984
  *
3393
3985
  * This command handles the PLC operation flow for migrating identity
3394
3986
  * from source PDS to Cirrus. It:
3395
- * 1. Requests an email token from the source PDS
3396
- * 2. Gets the source PDS to sign a PLC operation with the new endpoint
3397
- * 3. Submits the signed operation to the PLC directory
3987
+ * 1. Chooses the rotation keys: keys the user holds, an optional new
3988
+ * recovery key, then this PDS's key. The source PDS's key is removed.
3989
+ * 2. Requests an email token from the source PDS
3990
+ * 3. Gets the source PDS to sign a PLC operation with the new endpoint,
3991
+ * signing key, rotation keys and handle
3992
+ * 4. Submits the signed operation to the PLC directory
3398
3993
  */
3399
- const brightNote$1 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
3994
+ const brightNote$2 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
3400
3995
  const identityCommand = defineCommand({
3401
3996
  meta: {
3402
3997
  name: "identity",
@@ -3410,7 +4005,7 @@ const identityCommand = defineCommand({
3410
4005
  },
3411
4006
  token: {
3412
4007
  type: "string",
3413
- description: "Email token (if you already have one)"
4008
+ description: "Confirmation code from your previous PDS's email, if you already have one"
3414
4009
  }
3415
4010
  },
3416
4011
  async run({ args }) {
@@ -3448,11 +4043,6 @@ const identityCommand = defineCommand({
3448
4043
  p.outro("Identity update cancelled.");
3449
4044
  process.exit(1);
3450
4045
  }
3451
- if (!signingKey) {
3452
- p.log.error("No SIGNING_KEY found. Run 'pds init' first.");
3453
- p.outro("Identity update cancelled.");
3454
- process.exit(1);
3455
- }
3456
4046
  if (!did.startsWith("did:plc:")) {
3457
4047
  p.log.error("Only did:plc identities are supported for now.");
3458
4048
  p.log.info("did:web identities don't use PLC operations.");
@@ -3486,14 +4076,10 @@ const identityCommand = defineCommand({
3486
4076
  const sourceDomain = getDomain(sourcePdsUrl);
3487
4077
  spinner.stop(`Current PDS: ${sourceDomain}`);
3488
4078
  const targetEndpoint = targetUrl.replace(/\/$/, "");
3489
- if (sourcePdsUrl.replace(/\/$/, "") === targetEndpoint) {
3490
- p.log.success("Your DID already points to your new PDS!");
3491
- p.log.info(`Next step: ${formatCommand(pm, "pds", "activate")}`);
3492
- p.outro("All set!");
3493
- return;
3494
- }
4079
+ const currentEndpoint = sourcePdsUrl.replace(/\/$/, "");
3495
4080
  spinner.start(`Checking ${targetDomain}...`);
3496
- if (!await new PDSClient(targetUrl, authToken).healthCheck()) {
4081
+ const targetClient = new PDSClient(targetUrl, authToken);
4082
+ if (!await targetClient.healthCheck()) {
3497
4083
  spinner.stop(`PDS not responding`);
3498
4084
  p.log.error(`Your new PDS isn't responding at ${targetUrl}`);
3499
4085
  if (isDev) p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
@@ -3502,44 +4088,130 @@ const identityCommand = defineCommand({
3502
4088
  process.exit(1);
3503
4089
  }
3504
4090
  spinner.stop(`New PDS is ready`);
3505
- spinner.start("Preparing signing key...");
3506
- const signingKeyDid = await getSigningKeyDid(signingKey);
3507
- if (!signingKeyDid) {
3508
- spinner.stop("Failed to derive signing key");
3509
- p.log.error("Could not convert signing key to did:key format");
4091
+ spinner.start("Fetching your PDS's signing key...");
4092
+ let pdsKey;
4093
+ try {
4094
+ pdsKey = await getPdsRotationKey(targetClient, targetDomain, signingKey);
4095
+ } catch (err) {
4096
+ spinner.stop("Failed to fetch signing key");
4097
+ p.log.error(err instanceof Error ? err.message : "Could not fetch credentials");
4098
+ p.outro("Identity update cancelled.");
4099
+ process.exit(1);
4100
+ }
4101
+ spinner.stop(`Signing key: ${pdsKey}`);
4102
+ const plcClient = new PlcDirectoryClient();
4103
+ spinner.start("Reading your PLC record...");
4104
+ const current = await plcClient.getLatestOperation(did).catch(() => null);
4105
+ if (!current || current.operation.type !== "plc_operation") {
4106
+ spinner.stop("Failed to read PLC record");
4107
+ p.log.error(`Could not read the current PLC operation for ${did}`);
3510
4108
  p.outro("Identity update cancelled.");
3511
4109
  process.exit(1);
3512
4110
  }
3513
- spinner.stop("Signing key ready");
4111
+ const currentKeys = current.operation.rotationKeys;
4112
+ const currentHandle = current.operation.alsoKnownAs.find((uri) => uri.startsWith("at://"))?.slice(5);
4113
+ const alsoKnownAs = withHandle(current.operation.alsoKnownAs, handle);
4114
+ spinner.stop("PLC record loaded");
4115
+ if (currentEndpoint === targetEndpoint) {
4116
+ p.log.success("Your DID already points to your new PDS!");
4117
+ if (!currentKeys.includes(pdsKey)) {
4118
+ p.log.warn("Your PDS can't update your identity, because its key isn't one of your rotation keys.");
4119
+ p.log.info(`Fix this with: ${formatCommand(pm, "pds", "rotation-keys")}`);
4120
+ }
4121
+ p.log.info(`Next step: ${formatCommand(pm, "pds", "activate")}`);
4122
+ p.outro("All set!");
4123
+ return;
4124
+ }
4125
+ if (currentHandle !== handle) {
4126
+ spinner.start(`Checking ${handle} resolves to your DID...`);
4127
+ const handleCheck = await checkHandleResolutionDetailed(targetClient, handle, did);
4128
+ if (handleCheck.ok) spinner.stop(`${handle} resolves to your DID (via ${handleCheck.methods.join(", ")})`);
4129
+ else {
4130
+ spinner.stop(`${handle} doesn't resolve to your DID yet`);
4131
+ p.note(brightNote$2(handle === pdsHostname ? [
4132
+ "Your handle is your PDS hostname, so your PDS verifies it at:",
4133
+ ` https://${handle}/.well-known/atproto-did`,
4134
+ "",
4135
+ "Check the PDS is deployed on that domain."
4136
+ ] : [
4137
+ "Add a DNS TXT record:",
4138
+ ` _atproto.${handle} TXT "did=${did}"`,
4139
+ "",
4140
+ "Or serve a file at:",
4141
+ ` https://${handle}/.well-known/atproto-did`,
4142
+ ` containing: ${did}`
4143
+ ]), "Handle not verified");
4144
+ if (!await promptConfirm({
4145
+ message: "Continue anyway? Apps will show your handle as invalid until it resolves.",
4146
+ initialValue: false
4147
+ })) {
4148
+ p.outro("Identity update cancelled. Set up your handle, then run this again.");
4149
+ process.exit(0);
4150
+ }
4151
+ }
4152
+ }
3514
4153
  const sourceDisplayName = sourceDomain.endsWith(".bsky.network") ? "bsky.social" : sourceDomain;
3515
- p.note(brightNote$1([
4154
+ const sourcePdsClient = new SourcePdsPlcClient(sourcePdsUrl);
4155
+ let token = args.token;
4156
+ let sourcePdsKeys;
4157
+ const password = await p.password({ message: `Your password for ${sourceDisplayName}:` });
4158
+ if (p.isCancel(password)) {
4159
+ p.cancel("Identity update cancelled.");
4160
+ process.exit(0);
4161
+ }
4162
+ spinner.start(`Logging in to ${sourceDisplayName}...`);
4163
+ const sourceClient = new PDSClient(sourcePdsUrl);
4164
+ try {
4165
+ const session = await sourceClient.createSession(did, password);
4166
+ sourcePdsClient.setAuthToken(session.accessJwt);
4167
+ spinner.stop("Authenticated");
4168
+ } catch (err) {
4169
+ spinner.stop("Login failed");
4170
+ p.log.error(err instanceof Error ? err.message : "Authentication failed");
4171
+ p.outro("Identity update cancelled.");
4172
+ process.exit(1);
4173
+ }
4174
+ try {
4175
+ sourcePdsKeys = (await sourcePdsClient.getRecommendedDidCredentials()).rotationKeys;
4176
+ } catch {
4177
+ p.log.warn(`Couldn't ask ${sourceDisplayName} which rotation keys it holds.`);
4178
+ }
4179
+ let choice;
4180
+ try {
4181
+ choice = await chooseRotationKeys({
4182
+ did,
4183
+ handle,
4184
+ currentKeys,
4185
+ pdsKey,
4186
+ pdsName: targetDomain,
4187
+ sourcePdsKeys,
4188
+ sourceName: sourceDisplayName
4189
+ });
4190
+ } catch (err) {
4191
+ p.log.error(err instanceof Error ? err.message : String(err));
4192
+ p.outro("Identity update cancelled.");
4193
+ process.exit(1);
4194
+ }
4195
+ p.note(brightNote$2([
3516
4196
  pc.bold("Updating your identity:"),
3517
4197
  "",
3518
4198
  `${pc.dim("From:")} ${sourceDisplayName}`,
3519
4199
  `${pc.dim("To:")} ${targetDomain}`,
4200
+ currentHandle && currentHandle !== handle ? `${pc.dim("Handle:")} ${currentHandle} → ${handle}` : `${pc.dim("Handle:")} ${handle}`,
3520
4201
  "",
3521
- pc.dim("This tells the network where to find you.")
4202
+ ...describeRotationKeys(choice),
4203
+ "",
4204
+ pc.dim("This tells the network where to find you, and gives"),
4205
+ pc.dim("your new PDS control of your identity.")
3522
4206
  ]), "🔄 DID Update");
3523
- const sourcePdsClient = new SourcePdsPlcClient(sourcePdsUrl);
3524
- let token = args.token;
4207
+ if (!await promptConfirm({
4208
+ message: "Update your identity?",
4209
+ initialValue: true
4210
+ })) {
4211
+ p.outro("Identity update cancelled.");
4212
+ process.exit(0);
4213
+ }
3525
4214
  if (!token) {
3526
- const password = await p.password({ message: `Your password for ${sourceDisplayName}:` });
3527
- if (p.isCancel(password)) {
3528
- p.cancel("Identity update cancelled.");
3529
- process.exit(0);
3530
- }
3531
- spinner.start(`Logging in to ${sourceDisplayName}...`);
3532
- const sourceClient = new PDSClient(sourcePdsUrl);
3533
- try {
3534
- const session = await sourceClient.createSession(did, password);
3535
- sourcePdsClient.setAuthToken(session.accessJwt);
3536
- spinner.stop("Authenticated");
3537
- } catch (err) {
3538
- spinner.stop("Login failed");
3539
- p.log.error(err instanceof Error ? err.message : "Authentication failed");
3540
- p.outro("Identity update cancelled.");
3541
- process.exit(1);
3542
- }
3543
4215
  spinner.start("Requesting identity update token...");
3544
4216
  const signatureRequest = await sourcePdsClient.requestPlcOperationSignature();
3545
4217
  if (!signatureRequest.success) {
@@ -3551,218 +4223,314 @@ const identityCommand = defineCommand({
3551
4223
  spinner.stop("Token requested");
3552
4224
  p.log.info("");
3553
4225
  p.log.info(pc.bold("📧 Check your email!"));
3554
- p.log.info(`${sourceDisplayName} has sent you a confirmation code.`);
3555
- p.log.info("");
3556
- token = await promptText({
3557
- message: "Enter the confirmation code from your email:",
3558
- placeholder: "XXXXX-XXXXX",
3559
- validate: (v) => {
3560
- if (!v || v.trim().length < 5) return "Please enter the confirmation code";
3561
- }
3562
- });
3563
- }
3564
- spinner.start("Signing identity update...");
3565
- const signResult = await sourcePdsClient.signPlcOperation(token.trim(), targetUrl, signingKeyDid);
3566
- if (!signResult.success || !signResult.signedOperation) {
3567
- spinner.stop("Failed to sign operation");
3568
- p.log.error(signResult.error ?? "Could not sign PLC operation");
3569
- if (signResult.error?.includes("expired")) p.log.info("Run the command again to request a new token.");
3570
- p.outro("Identity update cancelled.");
3571
- process.exit(1);
3572
- }
3573
- spinner.stop("Operation signed");
3574
- const plcClient = new PlcDirectoryClient();
3575
- spinner.start("Submitting to PLC directory...");
3576
- const submitResult = await plcClient.submitOperation(did, signResult.signedOperation);
3577
- if (!submitResult.success) {
3578
- spinner.stop("Failed to submit operation");
3579
- p.log.error(submitResult.error ?? "PLC directory rejected the operation");
3580
- p.outro("Identity update cancelled.");
3581
- process.exit(1);
3582
- }
3583
- spinner.stop("Identity updated!");
3584
- spinner.start("Verifying update...");
3585
- await new Promise((resolve$1) => setTimeout(resolve$1, 1e3));
3586
- const newDidDoc = await new DidResolver().resolve(did);
3587
- if ((newDidDoc ? getPdsEndpoint(newDidDoc) : null)?.replace(/\/$/, "") === targetEndpoint) spinner.stop("Verified! DID now points to new PDS");
3588
- else {
3589
- spinner.stop("Update submitted (verification pending)");
3590
- p.log.warn("It may take a moment for the update to propagate.");
3591
- }
3592
- p.log.success("Your identity now points to your new PDS!");
3593
- p.note(brightNote$1([
3594
- pc.bold("Final step:"),
3595
- "",
3596
- `Run: ${formatCommand(pm, "pds", "activate")}`,
3597
- "",
3598
- "This enables writes and notifies the network."
3599
- ]), "Almost done!");
3600
- p.outro("Identity updated! 🎉");
3601
- }
3602
- });
3603
- /**
3604
- * Convert a hex-encoded secp256k1 private key to a did:key
3605
- *
3606
- * This imports the private key and returns the did:key representation.
3607
- */
3608
- async function getSigningKeyDid(hexPrivateKey) {
3609
- try {
3610
- return (await Secp256k1Keypair.import(hexPrivateKey)).did();
3611
- } catch {
3612
- return null;
3613
- }
3614
- }
3615
-
3616
- //#endregion
3617
- //#region src/cli/utils/checks.ts
3618
- /**
3619
- * Check that handle resolves to the expected DID
3620
- */
3621
- async function checkHandleResolution(handle, expectedDid) {
3622
- const resolvedDid = await resolveHandleToDid(handle);
3623
- if (!resolvedDid) return {
3624
- ok: false,
3625
- message: `@${handle} does not resolve to any DID`,
3626
- detail: "Update your DNS TXT record or .well-known/atproto-did file"
3627
- };
3628
- if (resolvedDid !== expectedDid) return {
3629
- ok: false,
3630
- message: `@${handle} resolves to wrong DID`,
3631
- detail: `Expected: ${expectedDid}\n Got: ${resolvedDid}`
3632
- };
3633
- return {
3634
- ok: true,
3635
- message: `@${handle} → ${expectedDid.slice(0, 24)}...`
3636
- };
3637
- }
3638
- /**
3639
- * Check that handle resolves via DNS and/or HTTP, returning both methods
3640
- */
3641
- async function checkHandleResolutionDetailed(client, handle, expectedDid) {
3642
- const [httpDid, dnsDid] = await Promise.all([client.checkHandleViaHttp(handle), client.checkHandleViaDns(handle)]);
3643
- const httpValid = httpDid === expectedDid;
3644
- const dnsValid = dnsDid === expectedDid;
3645
- const methods = [];
3646
- if (dnsValid) methods.push("DNS");
3647
- if (httpValid) methods.push("HTTP");
3648
- return {
3649
- ok: httpValid || dnsValid,
3650
- httpDid,
3651
- dnsDid,
3652
- methods
3653
- };
3654
- }
3655
- /**
3656
- * Check that DID document points to the expected PDS endpoint
3657
- */
3658
- async function checkDidDocument(did, expectedPdsUrl) {
3659
- const didDoc = await new DidResolver().resolve(did);
3660
- const expectedEndpoint = expectedPdsUrl.replace(/\/$/, "");
3661
- if (!didDoc) return {
3662
- ok: false,
3663
- message: `Could not resolve DID document for ${did}`,
3664
- detail: "Make sure your DID is published to the PLC directory or did:web endpoint"
3665
- };
3666
- const pdsService = didDoc.service?.find((s) => {
3667
- return (Array.isArray(s.type) ? s.type : [s.type]).includes("AtprotoPersonalDataServer") || s.id === "#atproto_pds";
3668
- });
3669
- if (!pdsService?.serviceEndpoint) return {
3670
- ok: false,
3671
- message: "DID document has no PDS service endpoint",
3672
- detail: "Update your DID document to include an AtprotoPersonalDataServer service"
3673
- };
3674
- const actualEndpoint = pdsService.serviceEndpoint.replace(/\/$/, "");
3675
- if (actualEndpoint !== expectedEndpoint) return {
3676
- ok: false,
3677
- message: "DID document points to different PDS",
3678
- detail: `Expected: ${expectedEndpoint}\n Got: ${actualEndpoint}`
3679
- };
3680
- return {
3681
- ok: true,
3682
- message: `PDS endpoint → ${expectedEndpoint}`
3683
- };
3684
- }
3685
- /**
3686
- * Check that DID resolves and returns the PDS endpoint (simpler version using PDSClient)
3687
- */
3688
- async function checkDidResolution(client, did, expectedPdsHostname) {
3689
- const resolved = await client.resolveDid(did);
3690
- const resolveMethod = did.startsWith("did:plc:") ? "plc.directory" : did.startsWith("did:web:") ? "/.well-known/did.json" : "unknown";
3691
- if (!resolved.pdsEndpoint) return {
3692
- ok: false,
3693
- pdsEndpoint: null,
3694
- resolveMethod
3695
- };
3696
- const expectedEndpoint = `https://${expectedPdsHostname}`;
3697
- return {
3698
- ok: resolved.pdsEndpoint === expectedEndpoint || resolved.pdsEndpoint === expectedPdsHostname,
3699
- pdsEndpoint: resolved.pdsEndpoint,
3700
- resolveMethod
3701
- };
3702
- }
4226
+ p.log.info(`${sourceDisplayName} has sent you a confirmation code.`);
4227
+ p.log.info("");
4228
+ token = await promptText({
4229
+ message: "Enter the confirmation code from your email:",
4230
+ placeholder: "XXXXX-XXXXX",
4231
+ validate: (v) => {
4232
+ if (!v || v.trim().length < 5) return "Please enter the confirmation code";
4233
+ }
4234
+ });
4235
+ }
4236
+ spinner.start("Signing identity update...");
4237
+ const signResult = await sourcePdsClient.signPlcOperation(token.trim(), {
4238
+ rotationKeys: choice.rotationKeys,
4239
+ alsoKnownAs,
4240
+ verificationMethods: { atproto: pdsKey },
4241
+ services: { atproto_pds: {
4242
+ type: "AtprotoPersonalDataServer",
4243
+ endpoint: targetUrl
4244
+ } }
4245
+ });
4246
+ if (!signResult.success || !signResult.signedOperation) {
4247
+ spinner.stop("Failed to sign operation");
4248
+ p.log.error(signResult.error ?? "Could not sign PLC operation");
4249
+ if (signResult.error?.includes("expired")) p.log.info("Run the command again to request a new token.");
4250
+ p.outro("Identity update cancelled.");
4251
+ process.exit(1);
4252
+ }
4253
+ spinner.stop("Operation signed");
4254
+ const signed = signResult.signedOperation;
4255
+ const sameList = (a, b) => a.length === b.length && a.every((item, i) => item === b[i]);
4256
+ if (!sameList(signed.rotationKeys, choice.rotationKeys)) {
4257
+ p.log.error(`${sourceDisplayName} signed different rotation keys than requested: ${signed.rotationKeys.join(", ")}`);
4258
+ p.outro("Identity update cancelled. Nothing was submitted.");
4259
+ process.exit(1);
4260
+ }
4261
+ if (!sameList(signed.alsoKnownAs, alsoKnownAs)) {
4262
+ p.log.error(`${sourceDisplayName} signed a different handle than requested: ${signed.alsoKnownAs.join(", ")}`);
4263
+ p.outro("Identity update cancelled. Nothing was submitted.");
4264
+ process.exit(1);
4265
+ }
4266
+ spinner.start("Submitting to PLC directory...");
4267
+ const submitResult = await plcClient.submitOperation(did, signed);
4268
+ if (!submitResult.success) {
4269
+ spinner.stop("Failed to submit operation");
4270
+ p.log.error(submitResult.error ?? "PLC directory rejected the operation");
4271
+ p.outro("Identity update cancelled.");
4272
+ process.exit(1);
4273
+ }
4274
+ spinner.stop("Identity updated!");
4275
+ spinner.start("Verifying update...");
4276
+ await new Promise((resolve$1) => setTimeout(resolve$1, 1e3));
4277
+ const newDidDoc = await new DidResolver().resolve(did);
4278
+ const newPdsEndpoint = newDidDoc ? getPdsEndpoint(newDidDoc) : null;
4279
+ const keyMismatch = await checkRotationKeys(plcClient, did, choice.rotationKeys).catch(() => void 0);
4280
+ if (newPdsEndpoint?.replace(/\/$/, "") === targetEndpoint && !keyMismatch) spinner.stop("Verified! DID now points to new PDS");
4281
+ else {
4282
+ spinner.stop("Update submitted (verification pending)");
4283
+ p.log.warn("It may take a moment for the update to propagate.");
4284
+ if (keyMismatch) {
4285
+ p.log.warn(`plc.directory lists these rotation keys: ${keyMismatch.join(", ") || "none"}`);
4286
+ p.log.info(`Check them with: ${formatCommand(pm, "pds", "rotation-keys")}`);
4287
+ }
4288
+ }
4289
+ p.log.success("Your identity now points to your new PDS!");
4290
+ if (choice.createdRecoveryKey) p.log.info("Keep your recovery key offline. If your PDS ever makes an identity change you didn't ask for, you have 72 hours to undo it with that key.");
4291
+ p.note(brightNote$2([
4292
+ pc.bold("Final step:"),
4293
+ "",
4294
+ `Run: ${formatCommand(pm, "pds", "activate")}`,
4295
+ "",
4296
+ "This enables writes and notifies the network."
4297
+ ]), "Almost done!");
4298
+ p.outro("Identity updated! 🎉");
4299
+ }
4300
+ });
4301
+
4302
+ //#endregion
4303
+ //#region src/cli/commands/rotation-keys.ts
3703
4304
  /**
3704
- * Check that all blobs are imported
4305
+ * Rotation keys command - review and fix who can update a did:plc identity
4306
+ *
4307
+ * Accounts migrated before `pds identity` set rotation keys still have the
4308
+ * previous PDS's key and not this PDS's. This command shows the current
4309
+ * keys and rewrites them as: keys the user holds, then this PDS's key. The
4310
+ * change is signed by whichever key can: this PDS (if it is already a
4311
+ * rotation key), the previous PDS (with its password and an email code), or
4312
+ * a rotation key the user pastes in.
3705
4313
  */
3706
- function checkBlobsImported(status) {
3707
- const missingBlobs = status.expectedBlobs - status.importedBlobs;
3708
- if (missingBlobs > 0) return {
3709
- ok: false,
3710
- message: `${missingBlobs} blob${missingBlobs === 1 ? "" : "s"} missing`,
3711
- detail: "Run 'pds migrate' to import missing blobs before activating"
3712
- };
3713
- return {
3714
- ok: true,
3715
- message: `${status.importedBlobs}/${status.expectedBlobs} blobs imported`
3716
- };
4314
+ const brightNote$1 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
4315
+ function cancel(message) {
4316
+ p.log.error(message);
4317
+ p.outro("Rotation keys unchanged.");
4318
+ process.exit(1);
3717
4319
  }
3718
- /**
3719
- * Check that repository data exists and is properly initialised
3720
- */
3721
- function checkRepoInitialised(status) {
3722
- if (!status.repoCommit) return {
3723
- ok: false,
3724
- message: "No repo data imported",
3725
- detail: "Run 'pds migrate' to import your repository first"
3726
- };
3727
- if (status.indexedRecords === 0) return {
3728
- ok: false,
3729
- message: "Repository has no indexed records",
3730
- detail: "Run 'pds migrate' to import your repository"
3731
- };
3732
- return {
3733
- ok: true,
3734
- message: `${status.repoBlocks.toLocaleString()} blocks, ${status.indexedRecords.toLocaleString()} records`
3735
- };
4320
+ function displayName(url) {
4321
+ const domain = getDomain(url);
4322
+ return domain.endsWith(".bsky.network") ? "bsky.social" : domain;
3736
4323
  }
3737
- /**
3738
- * Check that repo is complete for activation (combines blob and repo checks)
3739
- */
3740
- function checkRepoComplete(status) {
3741
- const repoCheck = checkRepoInitialised(status);
3742
- if (!repoCheck.ok) return repoCheck;
3743
- if (status.expectedBlobs > 0) {
3744
- const blobCheck = checkBlobsImported(status);
3745
- if (!blobCheck.ok) return blobCheck;
4324
+ const rotationKeysCommand = defineCommand({
4325
+ meta: {
4326
+ name: "rotation-keys",
4327
+ description: "Review your DID's rotation keys and make sure your PDS can update your identity"
4328
+ },
4329
+ args: { dev: {
4330
+ type: "boolean",
4331
+ description: "Target local development server instead of production",
4332
+ default: false
4333
+ } },
4334
+ async run({ args }) {
4335
+ const pm = detectPackageManager();
4336
+ const isDev = args.dev;
4337
+ p.intro("🔑 Rotation Keys");
4338
+ const spinner = p.spinner();
4339
+ const config = {
4340
+ ...readDevVars(),
4341
+ ...getVars()
4342
+ };
4343
+ const did = config.DID;
4344
+ const handle = config.HANDLE;
4345
+ const authToken = config.AUTH_TOKEN;
4346
+ if (!did || !handle || !authToken) cancel("DID, HANDLE and AUTH_TOKEN must be configured. Run 'pds init' first.");
4347
+ if (!did.startsWith("did:plc:")) {
4348
+ p.log.info("did:web identities have no rotation keys. Whoever controls the domain controls the identity.");
4349
+ p.outro("Nothing to do.");
4350
+ return;
4351
+ }
4352
+ let targetUrl;
4353
+ try {
4354
+ targetUrl = getTargetUrl(isDev, config.PDS_HOSTNAME);
4355
+ } catch (err) {
4356
+ cancel(err instanceof Error ? err.message : "Configuration error");
4357
+ }
4358
+ const targetDomain = getDomain(targetUrl);
4359
+ const targetEndpoint = targetUrl.replace(/\/$/, "");
4360
+ const pdsClient = new PDSClient(targetUrl, authToken);
4361
+ spinner.start(`Checking ${targetDomain}...`);
4362
+ let pdsKey;
4363
+ try {
4364
+ pdsKey = await getPdsRotationKey(pdsClient, targetDomain, config.SIGNING_KEY);
4365
+ } catch (err) {
4366
+ spinner.stop("Failed to fetch signing key");
4367
+ cancel(err instanceof Error ? err.message : `Could not reach ${targetDomain}. Is it deployed?`);
4368
+ }
4369
+ spinner.stop(`${targetDomain} signs with ${pdsKey}`);
4370
+ const plcClient = new PlcDirectoryClient();
4371
+ spinner.start("Reading your PLC record...");
4372
+ const log = await plcClient.getAuditLog(did).catch(() => null);
4373
+ const current = log?.filter((entry) => !entry.nullified).pop();
4374
+ if (!log || !current || current.operation.type !== "plc_operation") {
4375
+ spinner.stop("Failed to read PLC record");
4376
+ cancel(`Could not read the current PLC operation for ${did}`);
4377
+ }
4378
+ spinner.stop("PLC record loaded");
4379
+ const operation = current.operation;
4380
+ const currentEndpoint = operation.services.atproto_pds?.endpoint?.replace(/\/$/, "");
4381
+ if (currentEndpoint !== targetEndpoint) cancel(`Your DID points to ${currentEndpoint ?? "no PDS"}, not ${targetDomain}. Run '${formatCommand(pm, "pds", "identity")}' to move your identity here first.`);
4382
+ const labelled = labelRotationKeys(operation.rotationKeys, { pdsKey });
4383
+ const pdsCanSign = operation.rotationKeys.includes(pdsKey);
4384
+ p.note(brightNote$1([
4385
+ pc.bold("Current rotation keys, highest priority first:"),
4386
+ ...labelled.map(({ key, owner }, i) => ` ${i + 1}. ${key}${owner === "this-pds" ? pc.dim(` (${targetDomain})`) : ""}`),
4387
+ "",
4388
+ pdsCanSign ? `${pc.green("✓")} ${targetDomain} can update your identity.` : `${pc.red("✗")} ${targetDomain} can't update your identity, because its key isn't listed.`
4389
+ ]), "Your identity");
4390
+ let signer;
4391
+ if (pdsCanSign) signer = "pds";
4392
+ else signer = await promptSelect({
4393
+ message: "Who should sign the change? It needs one of the keys above.",
4394
+ options: [{
4395
+ value: "previous",
4396
+ label: "My previous PDS",
4397
+ hint: "needs its password and an email code"
4398
+ }, {
4399
+ value: "key",
4400
+ label: "A rotation key I hold",
4401
+ hint: "such as a recovery key"
4402
+ }]
4403
+ });
4404
+ let sourcePdsClient;
4405
+ let sourceName;
4406
+ let sourcePdsKeys;
4407
+ let signingKeypair;
4408
+ if (signer === "previous") {
4409
+ const previous = findPreviousPdsEndpoint(log, targetEndpoint);
4410
+ const sourceUrl = entrywayFor((await promptText({
4411
+ message: "Your previous PDS:",
4412
+ initialValue: previous ? entrywayFor(previous) : "https://bsky.social",
4413
+ validate: (v) => v && /^https?:\/\//.test(v.trim()) && hostnameOf(v.trim()) ? void 0 : "Enter a URL, such as https://bsky.social"
4414
+ })).trim());
4415
+ sourceName = displayName(sourceUrl);
4416
+ sourcePdsClient = new SourcePdsPlcClient(sourceUrl);
4417
+ const password = await p.password({ message: `Your password for ${sourceName}:` });
4418
+ if (p.isCancel(password)) {
4419
+ p.cancel("Rotation keys unchanged.");
4420
+ process.exit(0);
4421
+ }
4422
+ spinner.start(`Logging in to ${sourceName}...`);
4423
+ try {
4424
+ const session = await new PDSClient(sourceUrl).createSession(did, password);
4425
+ sourcePdsClient.setAuthToken(session.accessJwt);
4426
+ spinner.stop("Authenticated");
4427
+ } catch (err) {
4428
+ spinner.stop("Login failed");
4429
+ cancel(err instanceof Error ? err.message : "Authentication failed");
4430
+ }
4431
+ try {
4432
+ sourcePdsKeys = (await sourcePdsClient.getRecommendedDidCredentials()).rotationKeys;
4433
+ } catch {
4434
+ p.log.warn(`Couldn't ask ${sourceName} which rotation keys it holds.`);
4435
+ }
4436
+ if (sourcePdsKeys && !sourcePdsKeys.some((key) => operation.rotationKeys.includes(key))) cancel(`${sourceName}'s key isn't one of your rotation keys, so it can't sign this change. Use a rotation key you hold instead.`);
4437
+ } else if (signer === "key") {
4438
+ const secret = await p.password({ message: "Paste the private key (multibase or hex):" });
4439
+ if (p.isCancel(secret)) {
4440
+ p.cancel("Rotation keys unchanged.");
4441
+ process.exit(0);
4442
+ }
4443
+ try {
4444
+ signingKeypair = await importRotationKey(secret);
4445
+ } catch (err) {
4446
+ cancel(err instanceof Error ? err.message : "Could not read key");
4447
+ }
4448
+ if (!operation.rotationKeys.includes(signingKeypair.did())) cancel(`That key (${signingKeypair.did()}) isn't one of your rotation keys, so it can't sign this change.`);
4449
+ p.log.success(`Signing with ${signingKeypair.did()}`);
4450
+ }
4451
+ let choice;
4452
+ try {
4453
+ choice = await chooseRotationKeys({
4454
+ did,
4455
+ handle,
4456
+ currentKeys: operation.rotationKeys,
4457
+ pdsKey,
4458
+ pdsName: targetDomain,
4459
+ sourcePdsKeys,
4460
+ sourceName,
4461
+ heldKeys: signingKeypair ? [signingKeypair.did()] : []
4462
+ });
4463
+ } catch (err) {
4464
+ cancel(err instanceof Error ? err.message : String(err));
4465
+ }
4466
+ if (choice.rotationKeys.length === operation.rotationKeys.length && choice.rotationKeys.every((key, i) => key === operation.rotationKeys[i])) {
4467
+ p.outro("Your rotation keys are already set up. Nothing to change.");
4468
+ return;
4469
+ }
4470
+ p.note(brightNote$1(describeRotationKeys(choice)), "🔄 New rotation keys");
4471
+ if (!await promptConfirm({
4472
+ message: "Update your rotation keys?",
4473
+ initialValue: true
4474
+ })) {
4475
+ p.outro("Rotation keys unchanged.");
4476
+ process.exit(0);
4477
+ }
4478
+ let signed;
4479
+ if (signer === "pds") {
4480
+ spinner.start(`Asking ${targetDomain} to sign...`);
4481
+ try {
4482
+ const { token, error } = await pdsClient.getMigrationToken();
4483
+ if (!token) throw new Error(error ?? "Could not get a token");
4484
+ signed = await pdsClient.signPlcOperation(token, { rotationKeys: choice.rotationKeys });
4485
+ } catch (err) {
4486
+ spinner.stop("Signing failed");
4487
+ cancel(err instanceof Error ? err.message : "Could not sign");
4488
+ }
4489
+ spinner.stop("Operation signed");
4490
+ } else if (signer === "previous") {
4491
+ spinner.start("Requesting a confirmation code...");
4492
+ const request = await sourcePdsClient.requestPlcOperationSignature();
4493
+ if (!request.success) {
4494
+ spinner.stop("Failed to request code");
4495
+ cancel(request.error ?? "Could not request a confirmation code");
4496
+ }
4497
+ spinner.stop(`${sourceName} has emailed you a confirmation code`);
4498
+ const token = await promptText({
4499
+ message: "Enter the confirmation code from your email:",
4500
+ placeholder: "XXXXX-XXXXX",
4501
+ validate: (v) => !v || v.trim().length < 5 ? "Please enter the confirmation code" : void 0
4502
+ });
4503
+ spinner.start(`Asking ${sourceName} to sign...`);
4504
+ const result = await sourcePdsClient.signPlcOperation(token.trim(), { rotationKeys: choice.rotationKeys });
4505
+ if (!result.success || !result.signedOperation) {
4506
+ spinner.stop("Signing failed");
4507
+ cancel(result.error ?? "Could not sign PLC operation");
4508
+ }
4509
+ signed = result.signedOperation;
4510
+ spinner.stop("Operation signed");
4511
+ } else signed = await signOperation({
4512
+ type: "plc_operation",
4513
+ prev: current.cid,
4514
+ rotationKeys: choice.rotationKeys,
4515
+ verificationMethods: operation.verificationMethods,
4516
+ alsoKnownAs: operation.alsoKnownAs,
4517
+ services: operation.services
4518
+ }, signingKeypair);
4519
+ if (signed.rotationKeys.length !== choice.rotationKeys.length || signed.rotationKeys.some((key, i) => key !== choice.rotationKeys[i]) || signed.services.atproto_pds?.endpoint?.replace(/\/$/, "") !== targetEndpoint) cancel("The signed operation doesn't match what was requested, so it was not submitted.");
4520
+ spinner.start("Submitting to PLC directory...");
4521
+ const submitted = await plcClient.submitOperation(did, signed);
4522
+ if (!submitted.success) {
4523
+ spinner.stop("Failed to submit operation");
4524
+ cancel(submitted.error ?? "PLC directory rejected the operation");
4525
+ }
4526
+ spinner.stop("Submitted");
4527
+ const mismatch = await checkRotationKeys(plcClient, did, choice.rotationKeys).catch(() => void 0);
4528
+ if (mismatch) p.log.warn(`plc.directory lists these rotation keys: ${mismatch.join(", ") || "none"}`);
4529
+ else if (mismatch === null) p.log.success(`${targetDomain} can now update your identity.`);
4530
+ if (choice.createdRecoveryKey) p.log.info("Keep your recovery key offline. If your PDS ever makes an identity change you didn't ask for, you have 72 hours to undo it with that key.");
4531
+ p.outro("Rotation keys updated! 🔑");
3746
4532
  }
3747
- return {
3748
- ok: true,
3749
- message: `${status.repoBlocks} blocks, ${status.importedBlobs} blobs`
3750
- };
3751
- }
3752
- /**
3753
- * Check if profile is indexed by AppView
3754
- */
3755
- async function checkAppViewIndexing(client, did) {
3756
- if (!await client.checkAppViewIndexing(did)) return {
3757
- ok: false,
3758
- message: "Profile not found on AppView",
3759
- detail: "This may be normal for new accounts"
3760
- };
3761
- return {
3762
- ok: true,
3763
- message: "Profile indexed by AppView"
3764
- };
3765
- }
4533
+ });
3766
4534
 
3767
4535
  //#endregion
3768
4536
  //#region src/cli/commands/activate.ts
@@ -3772,7 +4540,7 @@ async function checkAppViewIndexing(client, did) {
3772
4540
  /**
3773
4541
  * Run pre-activation checks
3774
4542
  */
3775
- async function runChecks(handle, did, pdsUrl, status) {
4543
+ async function runChecks(client, handle, did, pdsUrl, status) {
3776
4544
  const checks = [];
3777
4545
  p.log.step("Checking handle resolution...");
3778
4546
  const handleResult = await checkHandleResolution(handle, did);
@@ -3787,7 +4555,7 @@ async function runChecks(handle, did, pdsUrl, status) {
3787
4555
  ...didResult
3788
4556
  });
3789
4557
  p.log.step("Checking repo status...");
3790
- const repoResult = checkRepoComplete(status);
4558
+ const repoResult = await checkRepoComplete(client, status);
3791
4559
  checks.push({
3792
4560
  name: "Repo",
3793
4561
  ...repoResult
@@ -3818,7 +4586,7 @@ async function promptCreateProfile(client, did, handle) {
3818
4586
  process.exit(0);
3819
4587
  }
3820
4588
  if (createProfile) {
3821
- const displayName = await promptText({
4589
+ const displayName$1 = await promptText({
3822
4590
  message: "Display name:",
3823
4591
  placeholder: handle || "Your Name",
3824
4592
  validate: (v) => {
@@ -3835,7 +4603,7 @@ async function promptCreateProfile(client, did, handle) {
3835
4603
  spinner.start("Creating profile...");
3836
4604
  try {
3837
4605
  await client.putProfile(did, {
3838
- displayName: displayName || void 0,
4606
+ displayName: displayName$1 || void 0,
3839
4607
  description: description || void 0
3840
4608
  });
3841
4609
  spinner.stop("Profile created!");
@@ -3935,7 +4703,7 @@ const activateCommand = defineCommand({
3935
4703
  }
3936
4704
  p.log.info("");
3937
4705
  p.log.info(pc.bold("Pre-activation checks:"));
3938
- const checks = await runChecks(handle, did, targetUrl, status);
4706
+ const checks = await runChecks(client, handle, did, targetUrl, status);
3939
4707
  console.log("");
3940
4708
  for (const check of checks) logCheck(check);
3941
4709
  console.log("");
@@ -4267,8 +5035,25 @@ const statusCommand$1 = defineCommand({
4267
5035
  if (handle) console.log(` ${INFO} Handle: ${pc.cyan(`@${handle}`)}`);
4268
5036
  if (did) {
4269
5037
  const didCheck = await checkDidResolution(client, did, pdsHostname);
4270
- if (didCheck.ok) console.log(` ${CHECK} DID resolves to this PDS (via ${didCheck.resolveMethod})`);
4271
- else if (didCheck.pdsEndpoint) {
5038
+ if (didCheck.ok) {
5039
+ console.log(` ${CHECK} DID resolves to this PDS (via ${didCheck.resolveMethod})`);
5040
+ if (did.startsWith("did:plc:")) {
5041
+ const keys = await checkPlcRotationKeys(client, did);
5042
+ if (!keys) {
5043
+ console.log(` ${WARN} Could not check rotation keys`);
5044
+ hasWarnings = true;
5045
+ } else if (!keys.pdsCanSign) {
5046
+ console.log(` ${CROSS} This PDS can't update your identity (its key isn't a rotation key)`);
5047
+ console.log(pc.dim(" Fix with: pds rotation-keys"));
5048
+ hasErrors = true;
5049
+ } else if (keys.otherKeys === 0) {
5050
+ console.log(` ${CHECK} This PDS can update your identity`);
5051
+ console.log(` ${WARN} No recovery key: your PDS is your only rotation key`);
5052
+ console.log(pc.dim(" Add one with: pds rotation-keys"));
5053
+ hasWarnings = true;
5054
+ } else console.log(` ${CHECK} This PDS can update your identity, with ${keys.otherKeys} other rotation ${keys.otherKeys === 1 ? "key" : "keys"}`);
5055
+ }
5056
+ } else if (didCheck.pdsEndpoint) {
4272
5057
  console.log(` ${CROSS} DID resolves to different PDS`);
4273
5058
  console.log(pc.dim(` Resolved via: ${didCheck.resolveMethod}`));
4274
5059
  console.log(pc.dim(` Expected: https://${pdsHostname}`));
@@ -4303,13 +5088,13 @@ const statusCommand$1 = defineCommand({
4303
5088
  console.log();
4304
5089
  if (status.expectedBlobs > 0) {
4305
5090
  console.log(pc.bold("Blobs"));
4306
- const blobCheck = checkBlobsImported(status);
5091
+ const blobCheck = checkBlobsImported(status, await countMissingBlobs(client));
4307
5092
  if (blobCheck.ok) console.log(` ${CHECK} ${blobCheck.message}`);
4308
5093
  else {
4309
- const missing = status.expectedBlobs - status.importedBlobs;
4310
- console.log(` ${WARN} ${status.importedBlobs}/${status.expectedBlobs} blobs imported (${missing} missing)`);
5094
+ console.log(` ${WARN} ${blobCheck.message}`);
4311
5095
  hasWarnings = true;
4312
5096
  }
5097
+ console.log(` ${INFO} ${status.importedBlobs} blobs stored in total`);
4313
5098
  console.log();
4314
5099
  }
4315
5100
  console.log(pc.bold("Federation"));
@@ -5075,15 +5860,16 @@ async function xrpc(ctx, method, nsid, options = {}) {
5075
5860
  ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {}
5076
5861
  });
5077
5862
  if (!res.ok) {
5078
- const text = await res.text();
5079
- let message = text;
5863
+ const text$1 = await res.text();
5864
+ let message = text$1;
5080
5865
  try {
5081
- const parsed = JSON.parse(text);
5082
- message = parsed.error ? `${parsed.error}: ${parsed.message ?? ""}` : text;
5866
+ const parsed = JSON.parse(text$1);
5867
+ message = parsed.error ? `${parsed.error}: ${parsed.message ?? ""}` : text$1;
5083
5868
  } catch {}
5084
5869
  throw new Error(`${nsid} failed (${res.status}): ${message}`);
5085
5870
  }
5086
- return await res.json();
5871
+ const text = await res.text();
5872
+ return text ? JSON.parse(text) : {};
5087
5873
  }
5088
5874
  const devArg = { dev: {
5089
5875
  type: "boolean",
@@ -5105,6 +5891,7 @@ const listCommand = defineCommand({
5105
5891
  for (const space of status.spaces) {
5106
5892
  const flags = [
5107
5893
  space.role,
5894
+ space.policy ? space.policy.replace(/^com\.atproto\.|\.policy$/g, "") : null,
5108
5895
  space.state !== "active" ? pc.yellow(space.state) : null,
5109
5896
  space.outdated ? pc.red("outdated") : null
5110
5897
  ].filter(Boolean).join(", ");
@@ -5120,7 +5907,8 @@ const statusCommand = defineCommand({
5120
5907
  },
5121
5908
  args: { ...devArg },
5122
5909
  async run({ args }) {
5123
- const status = await xrpc(loadContext(args.dev), "GET", "gg.mk.experimental.getSpacesStatus");
5910
+ const ctx = loadContext(args.dev);
5911
+ const status = await xrpc(ctx, "GET", "gg.mk.experimental.getSpacesStatus");
5124
5912
  console.log();
5125
5913
  console.log(pc.bold("Spaces status"));
5126
5914
  console.log(` flag: ${status.enabled ? pc.green("enabled") : pc.yellow("disabled")}`);
@@ -5128,8 +5916,28 @@ const statusCommand = defineCommand({
5128
5916
  console.log(` spaces: ${status.stats.active} active (${status.stats.hosted} hosted), ${status.stats.pending} pending, ${status.stats.deleted} deleted`);
5129
5917
  const outdated = status.spaces.filter((s) => s.outdated);
5130
5918
  if (outdated.length > 0) console.log(pc.red(` ${outdated.length} space(s) hold data from an incompatible alpha build. Run 'pds spaces reset'.`));
5919
+ await reportKem(ctx, status.kem);
5131
5920
  }
5132
5921
  });
5922
+ /**
5923
+ * Check that the deployed `#atproto_kem` key is the one the DID document
5924
+ * publishes: syncers derive MAC secrets against the published key, so a
5925
+ * mismatch fails every credentialed read that returns a commit or record.
5926
+ */
5927
+ async function reportKem(ctx, kem) {
5928
+ if (!kem?.configured) {
5929
+ console.log(pc.yellow(" kem key: not configured — syncers cannot verify space data. Run 'pds spaces kem'."));
5930
+ return;
5931
+ }
5932
+ let published;
5933
+ try {
5934
+ const method = ((await new DidResolver().resolve(ctx.did, { forceRefresh: true }))?.verificationMethod ?? []).find((m) => m.id.endsWith("#atproto_kem"));
5935
+ published = method?.publicKeyMultibase ? `did:key:${method.publicKeyMultibase}` : void 0;
5936
+ } catch {}
5937
+ if (!kem.didKey) console.log(pc.yellow(" kem key: secret set, but SPACES_KEM_KEY_PUBLIC is missing. Re-run 'pds spaces kem'."));
5938
+ else if (published === kem.didKey) console.log(` kem key: ${pc.green("published")} ${pc.dim(kem.didKey)}`);
5939
+ else console.log(pc.yellow(` kem key: ${published ? "DID document publishes a different key" : "not in the DID document"}. ${ctx.did.startsWith("did:plc:") ? "Run 'pds spaces kem --publish'." : "Redeploy so the DID document picks it up."}`));
5940
+ }
5133
5941
  const createCommand = defineCommand({
5134
5942
  meta: {
5135
5943
  name: "create",
@@ -5148,37 +5956,77 @@ const createCommand = defineCommand({
5148
5956
  },
5149
5957
  policy: {
5150
5958
  type: "string",
5151
- description: "User policy: public | member-list | managing-app",
5152
- default: "member-list"
5959
+ description: "Policy: personal | member | managed",
5960
+ default: "member"
5961
+ },
5962
+ "public-read": {
5963
+ type: "boolean",
5964
+ description: "member: anyone may read, with or without a delegation token",
5965
+ default: false
5966
+ },
5967
+ "public-write": {
5968
+ type: "boolean",
5969
+ description: "member: track anyone's writes, not only members'",
5970
+ default: false
5153
5971
  },
5154
5972
  "managing-app": {
5155
5973
  type: "string",
5156
- description: "Managing app service identifier (managing-app policy)"
5974
+ description: "managed: the managing app's did#serviceId reference (e.g. did:web:app.example#forum)"
5157
5975
  },
5158
5976
  allow: {
5159
5977
  type: "string",
5160
- description: "Allowed OAuth client ID (repeatable); sets the allowList app policy"
5978
+ description: "member: allowed OAuth client ID (repeatable); only these apps may read"
5979
+ },
5980
+ "publish-policy": {
5981
+ type: "boolean",
5982
+ description: "Publish the policy to readers as a record in your repo",
5983
+ default: false
5984
+ },
5985
+ "publish-members": {
5986
+ type: "boolean",
5987
+ description: "member: publish the member list to readers",
5988
+ default: false
5161
5989
  }
5162
5990
  },
5163
5991
  async run({ args }) {
5164
5992
  const ctx = loadContext(args.dev);
5165
- const policyType = args.policy;
5166
- const policy = policyType === "public" ? { $type: "com.atproto.simplespace.defs#publicPolicy" } : policyType === "managing-app" ? {
5167
- $type: "com.atproto.simplespace.defs#managingAppPolicy",
5168
- managingApp: args["managing-app"]
5169
- } : { $type: "com.atproto.simplespace.defs#memberListPolicy" };
5170
- const allowed = args.allow ? Array.isArray(args.allow) ? args.allow : [args.allow] : [];
5171
- const appAccess = allowed.length > 0 ? {
5172
- $type: "com.atproto.simplespace.defs#allowList",
5173
- allowed
5174
- } : { $type: "com.atproto.simplespace.defs#open" };
5175
- const result = await xrpc(ctx, "POST", "com.atproto.simplespace.createSpace", { body: {
5176
- type: args.type,
5993
+ const allowed = args.allow ? Array.isArray(args.allow) ? args.allow : [args.allow] : void 0;
5994
+ let policy;
5995
+ switch (args.policy) {
5996
+ case "personal":
5997
+ policy = { $type: "com.atproto.personalspace.policy" };
5998
+ break;
5999
+ case "managed":
6000
+ if (!args["managing-app"]) {
6001
+ console.error(pc.red("Error:"), "--managing-app is required");
6002
+ process.exit(1);
6003
+ }
6004
+ policy = {
6005
+ $type: "com.atproto.managedspace.policy",
6006
+ managingApp: args["managing-app"],
6007
+ publishPolicy: args["publish-policy"]
6008
+ };
6009
+ break;
6010
+ case "member":
6011
+ policy = {
6012
+ $type: "com.atproto.memberspace.policy",
6013
+ publicRead: args["public-read"],
6014
+ publicWrite: args["public-write"],
6015
+ ...allowed ? { allowedApps: allowed } : {},
6016
+ publishPolicy: args["publish-policy"],
6017
+ publishMembers: args["publish-members"]
6018
+ };
6019
+ break;
6020
+ default:
6021
+ console.error(pc.red("Error:"), `Unknown policy '${args.policy}' (personal | member | managed)`);
6022
+ process.exit(1);
6023
+ }
6024
+ const result = await xrpc(ctx, "POST", "com.atproto.space.createSpace", { body: {
6025
+ spaceType: args.type,
5177
6026
  ...args.skey ? { skey: args.skey } : {},
5178
- policy,
5179
- appAccess
6027
+ policy
5180
6028
  } });
5181
- console.log(pc.green("Created:"), result.uri);
6029
+ console.log(pc.green("Created:"), result.space);
5182
6030
  }
5183
6031
  });
5184
6032
  const deleteCommand = defineCommand({
@@ -5212,7 +6060,7 @@ const deleteCommand = defineCommand({
5212
6060
  return;
5213
6061
  }
5214
6062
  }
5215
- await xrpc(ctx, "POST", "com.atproto.simplespace.deleteSpace", { body: { space: args.space } });
6063
+ await xrpc(ctx, "POST", "com.atproto.space.deleteSpace", { body: { space: args.space } });
5216
6064
  console.log(pc.green("Deleted:"), args.space);
5217
6065
  }
5218
6066
  });
@@ -5225,7 +6073,7 @@ const membersCommand = defineCommand({
5225
6073
  add: defineCommand({
5226
6074
  meta: {
5227
6075
  name: "add",
5228
- description: "Add a member"
6076
+ description: "Add a member, or replace their access"
5229
6077
  },
5230
6078
  args: {
5231
6079
  ...devArg,
@@ -5238,14 +6086,28 @@ const membersCommand = defineCommand({
5238
6086
  type: "positional",
5239
6087
  description: "Member DID",
5240
6088
  required: true
6089
+ },
6090
+ read: {
6091
+ type: "boolean",
6092
+ description: "May read (use --no-read to deny)",
6093
+ default: true
6094
+ },
6095
+ write: {
6096
+ type: "boolean",
6097
+ description: "Writes are tracked (use --no-write to deny)",
6098
+ default: true
5241
6099
  }
5242
6100
  },
5243
6101
  async run({ args }) {
5244
- await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.simplespace.addMember", { body: {
6102
+ await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.memberspace.putMembers", { body: {
5245
6103
  space: args.space,
5246
- did: args.did
6104
+ members: [{
6105
+ did: args.did,
6106
+ read: args.read,
6107
+ write: args.write
6108
+ }]
5247
6109
  } });
5248
- console.log(pc.green("Added:"), args.did);
6110
+ console.log(pc.green("Added:"), args.did, pc.dim(`(read: ${args.read}, write: ${args.write})`));
5249
6111
  }
5250
6112
  }),
5251
6113
  remove: defineCommand({
@@ -5267,9 +6129,9 @@ const membersCommand = defineCommand({
5267
6129
  }
5268
6130
  },
5269
6131
  async run({ args }) {
5270
- await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.simplespace.removeMember", { body: {
6132
+ await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.memberspace.removeMembers", { body: {
5271
6133
  space: args.space,
5272
- did: args.did
6134
+ dids: [args.did]
5273
6135
  } });
5274
6136
  console.log(pc.green("Removed:"), args.did);
5275
6137
  }
@@ -5288,7 +6150,7 @@ const membersCommand = defineCommand({
5288
6150
  }
5289
6151
  },
5290
6152
  async run({ args }) {
5291
- const result = await xrpc(loadContext(Boolean(args.dev)), "GET", "com.atproto.simplespace.listMembers", { params: {
6153
+ const result = await xrpc(loadContext(Boolean(args.dev)), "GET", "com.atproto.memberspace.listMembers", { params: {
5292
6154
  space: String(args.space),
5293
6155
  limit: "1000"
5294
6156
  } });
@@ -5296,7 +6158,10 @@ const membersCommand = defineCommand({
5296
6158
  console.log(pc.dim("No members."));
5297
6159
  return;
5298
6160
  }
5299
- for (const member of result.members) console.log(member.did);
6161
+ for (const member of result.members) {
6162
+ const access = [member.read ? "read" : null, member.write ? "write" : null].filter(Boolean).join(", ");
6163
+ console.log(`${member.did} ${pc.dim(`(${access || "no access"})`)}`);
6164
+ }
5300
6165
  }
5301
6166
  })
5302
6167
  }
@@ -5304,7 +6169,7 @@ const membersCommand = defineCommand({
5304
6169
  const exportCommand = defineCommand({
5305
6170
  meta: {
5306
6171
  name: "export",
5307
- description: "Export every space repo as a CAR file"
6172
+ description: "Export every space repo as a STAR archive, plus the host-side state of hosted spaces"
5308
6173
  },
5309
6174
  args: {
5310
6175
  ...devArg,
@@ -5316,26 +6181,126 @@ const exportCommand = defineCommand({
5316
6181
  },
5317
6182
  async run({ args }) {
5318
6183
  const ctx = loadContext(args.dev);
5319
- const exportable = (await xrpc(ctx, "GET", "gg.mk.experimental.getSpacesStatus")).spaces.filter((space) => space.state === "active" && !space.outdated && space.recordCount > 0);
6184
+ const exportable = (await xrpc(ctx, "GET", "gg.mk.experimental.getSpacesStatus")).spaces.filter((space) => space.state === "active" && !space.outdated);
5320
6185
  if (exportable.length === 0) {
5321
6186
  console.log(pc.dim("Nothing to export."));
5322
6187
  return;
5323
6188
  }
5324
6189
  mkdirSync(args.out, { recursive: true });
5325
- for (const space of exportable) {
5326
- const url = new URL(`${ctx.baseUrl}/xrpc/com.atproto.space.getRepo`);
5327
- url.searchParams.set("space", space.uri);
5328
- url.searchParams.set("repo", ctx.did);
6190
+ const download = async (nsid, params, filename, label) => {
6191
+ const url = new URL(`${ctx.baseUrl}/xrpc/${nsid}`);
6192
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
5329
6193
  const res = await fetch(url, { headers: { Authorization: `Bearer ${ctx.authToken}` } });
5330
6194
  if (!res.ok) {
5331
- console.log(pc.red("✗"), `${space.uri}: export failed (${res.status})`);
5332
- continue;
6195
+ console.log(pc.red("✗"), `${label}: export failed (${res.status})`);
6196
+ return;
5333
6197
  }
5334
6198
  const bytes = new Uint8Array(await res.arrayBuffer());
5335
- const filename = `${space.uri.replace("at://", "").replace(/[^a-zA-Z0-9._-]+/g, "_")}.car`;
5336
6199
  writeFileSync(join(args.out, filename), bytes);
5337
- console.log(pc.green("✓"), `${space.uri} → ${filename} (${bytes.length} bytes)`);
6200
+ console.log(pc.green("✓"), `${label} → ${filename} (${bytes.length} bytes)`);
6201
+ };
6202
+ for (const space of exportable) {
6203
+ const base = space.uri.replace(/^at:space\//, "").replace(/[^a-zA-Z0-9._-]+/g, "_");
6204
+ if (space.role === "authority") await download("com.atproto.space.exportSpaceMeta", { space: space.uri }, `${base}.meta.star`, `${space.uri} (space)`);
6205
+ if (space.recordCount > 0) await download("com.atproto.space.getRepo", {
6206
+ space: space.uri,
6207
+ repo: ctx.did
6208
+ }, `${base}.star`, `${space.uri} (repo)`);
6209
+ }
6210
+ }
6211
+ });
6212
+ const kemCommand = defineCommand({
6213
+ meta: {
6214
+ name: "kem",
6215
+ description: "Generate the #atproto_kem key syncers verify space data against, and publish it"
6216
+ },
6217
+ args: {
6218
+ ...devArg,
6219
+ local: {
6220
+ type: "boolean",
6221
+ description: "Write to .dev.vars instead of wrangler secrets/config",
6222
+ default: false
6223
+ },
6224
+ publish: {
6225
+ type: "boolean",
6226
+ description: "did:plc: add the key to your DID document via a PLC operation signed by this PDS",
6227
+ default: false
6228
+ }
6229
+ },
6230
+ async run({ args }) {
6231
+ p.intro("Spaces KEM key");
6232
+ const vars = getVars();
6233
+ const did = vars.DID;
6234
+ if (!did) {
6235
+ p.log.error("No DID configured. Run 'pds init' first.");
6236
+ process.exit(1);
6237
+ }
6238
+ let publicKey = (args.local ? readDevVars() : vars).SPACES_KEM_KEY_PUBLIC;
6239
+ if (publicKey && !args.publish) {
6240
+ const replace = await p.confirm({
6241
+ message: "A KEM key is already configured. Replace it? Syncers holding the old key will fail to verify until the DID document is updated.",
6242
+ initialValue: false
6243
+ });
6244
+ if (p.isCancel(replace) || !replace) {
6245
+ p.cancel("Kept the existing key.");
6246
+ return;
6247
+ }
6248
+ }
6249
+ if (!publicKey || !args.publish) {
6250
+ const keypair = await generateKemKeypair();
6251
+ await setSecretValue("SPACES_KEM_KEY", keypair.privateKey, args.local);
6252
+ setPublicVar("SPACES_KEM_KEY_PUBLIC", keypair.publicKey, args.local);
6253
+ publicKey = keypair.publicKey;
6254
+ p.log.success(`Generated did:key:${publicKey}`);
6255
+ }
6256
+ const didKey = `did:key:${publicKey}`;
6257
+ if (did.startsWith("did:web:")) {
6258
+ p.outro("did:web: the DID document is served by your PDS, so it publishes #atproto_kem once you redeploy.");
6259
+ return;
6260
+ }
6261
+ if (!args.publish) {
6262
+ p.note([
6263
+ "Your DID is a did:plc, so the key must be added to its PLC document",
6264
+ "as the `atproto_kem` verification method. Redeploy, then run:",
6265
+ "",
6266
+ " pds spaces kem --publish",
6267
+ "",
6268
+ "That asks your PDS to sign the PLC operation, which works when its",
6269
+ "signing key is one of your DID's rotation keys. If it isn't, run",
6270
+ "'pds rotation-keys' first, or add it with whoever holds your rotation key."
6271
+ ].join("\n"), "Publish the key");
6272
+ p.outro("Done.");
6273
+ return;
6274
+ }
6275
+ const ctx = loadContext(args.dev);
6276
+ const spinner = p.spinner();
6277
+ spinner.start("Fetching the current PLC operation...");
6278
+ const current = (await new PlcDirectoryClient().getAuditLog(did)).filter((entry) => !entry.nullified).pop();
6279
+ if (!current || current.operation.type !== "plc_operation") {
6280
+ spinner.stop("Could not read a current PLC operation for this DID");
6281
+ process.exit(1);
6282
+ }
6283
+ const verificationMethods = {
6284
+ ...current.operation.verificationMethods,
6285
+ atproto_kem: didKey
6286
+ };
6287
+ spinner.message("Signing the PLC operation...");
6288
+ const { token } = await xrpc(ctx, "GET", "gg.mk.experimental.getMigrationToken");
6289
+ const { operation } = await xrpc(ctx, "POST", "com.atproto.identity.signPlcOperation", { body: {
6290
+ token,
6291
+ verificationMethods
6292
+ } });
6293
+ spinner.message("Submitting to the PLC directory...");
6294
+ try {
6295
+ await xrpc(ctx, "POST", "com.atproto.identity.submitPlcOperation", { body: { operation } });
6296
+ } catch (err) {
6297
+ spinner.stop("The PLC directory refused the operation");
6298
+ p.log.error(err instanceof Error ? err.message : String(err));
6299
+ p.log.info("If this PDS's signing key is not a rotation key for your DID, run 'pds rotation-keys' to give it control, or add the atproto_kem verification method with whoever holds a rotation key.");
6300
+ process.exit(1);
5338
6301
  }
6302
+ spinner.stop("Published #atproto_kem");
6303
+ p.outro(didKey);
5339
6304
  }
5340
6305
  });
5341
6306
  const resetCommand = defineCommand({
@@ -5388,6 +6353,7 @@ const spacesCommand = defineCommand({
5388
6353
  delete: deleteCommand,
5389
6354
  members: membersCommand,
5390
6355
  export: exportCommand,
6356
+ kem: kemCommand,
5391
6357
  reset: resetCommand
5392
6358
  }
5393
6359
  });
@@ -5411,6 +6377,7 @@ runMain(defineCommand({
5411
6377
  migrate: migrateCommand,
5412
6378
  "migrate-token": migrateTokenCommand,
5413
6379
  identity: identityCommand,
6380
+ "rotation-keys": rotationKeysCommand,
5414
6381
  activate: activateCommand,
5415
6382
  deactivate: deactivateCommand,
5416
6383
  status: statusCommand$1,