@getcirrus/pds 0.19.0 → 0.20.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/cli.js CHANGED
@@ -2,7 +2,7 @@
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
8
  import { experimental_patchConfig, experimental_readRawConfig } from "wrangler";
@@ -14,8 +14,10 @@ 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
18
  import { getPdsEndpoint } from "@atcute/identity";
19
+ import { encode } from "@atcute/cbor";
20
+ import { base64url } from "jose";
19
21
  import { decodeAll } from "@atproto/lex-cbor";
20
22
 
21
23
  //#region src/cli/utils/wrangler.ts
@@ -397,12 +399,47 @@ async function is1PasswordAvailable() {
397
399
  child.on("close", (code) => resolve$1(code === 0));
398
400
  });
399
401
  }
402
+ const KEY_BACKUP_TEXT = {
403
+ signing: {
404
+ name: "signing key",
405
+ label: "Signing Key",
406
+ title: "Cirrus PDS Signing Key",
407
+ heading: "CIRRUS PDS SIGNING KEY",
408
+ filePrefix: "signing-key-backup",
409
+ tag: "signing-key",
410
+ warning: "WARNING: This key controls your identity!",
411
+ encoding: "hex-encoded secp256k1 private key"
412
+ },
413
+ recovery: {
414
+ name: "recovery key",
415
+ label: "Recovery Key",
416
+ title: "atproto Recovery Key",
417
+ heading: "ATPROTO RECOVERY KEY",
418
+ filePrefix: "recovery-key-backup",
419
+ tag: "recovery-key",
420
+ warning: "WARNING: This key can take control of your identity!",
421
+ encoding: "multibase private key, usable with goat"
422
+ }
423
+ };
400
424
  /**
401
425
  * Save a key to 1Password using the CLI
402
- * Creates a secure note with the signing key
426
+ * Creates a secure note with the key and any extra details
403
427
  */
404
- async function saveTo1Password(key, handle) {
405
- const itemName = `Cirrus PDS Signing Key - ${handle}`;
428
+ async function saveTo1Password(key, handle, kind = "signing", details = []) {
429
+ const text = KEY_BACKUP_TEXT[kind];
430
+ const itemName = `${text.title} - ${handle}`;
431
+ const notes = [
432
+ text.heading,
433
+ "",
434
+ `Handle: ${handle}`,
435
+ `Created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
436
+ ...details,
437
+ "",
438
+ text.warning,
439
+ "",
440
+ `${text.name.toUpperCase()}:`,
441
+ key
442
+ ].join("\n");
406
443
  return new Promise((resolve$1) => {
407
444
  const child = spawn("op", [
408
445
  "item",
@@ -411,9 +448,9 @@ async function saveTo1Password(key, handle) {
411
448
  "Secure Note",
412
449
  "--title",
413
450
  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}`,
451
+ `notesPlain=${notes}`,
415
452
  "--tags",
416
- "cirrus,pds,signing-key"
453
+ `cirrus,pds,${text.tag}`
417
454
  ], { stdio: [
418
455
  "ignore",
419
456
  "pipe",
@@ -516,25 +553,27 @@ function runCommand(cmd, args, options = {}) {
516
553
  /**
517
554
  * Save a key backup file with appropriate warnings
518
555
  */
519
- async function saveKeyBackup(key, handle) {
520
- const filename = `signing-key-backup-${handle.replace(/[^a-z0-9]/gi, "-")}.txt`;
556
+ async function saveKeyBackup(key, handle, kind = "signing", details = []) {
557
+ const text = KEY_BACKUP_TEXT[kind];
558
+ const filename = `${text.filePrefix}-${handle.replace(/[^a-z0-9]/gi, "-")}.txt`;
521
559
  const filepath = join(process.cwd(), filename);
522
560
  await writeFile(filepath, [
523
561
  "=".repeat(60),
524
- "CIRRUS PDS SIGNING KEY BACKUP",
562
+ `${text.heading} BACKUP`,
525
563
  "=".repeat(60),
526
564
  "",
527
565
  `Handle: ${handle}`,
528
566
  `Created: ${(/* @__PURE__ */ new Date()).toISOString()}`,
567
+ ...details,
529
568
  "",
530
- "WARNING: This key controls your identity!",
569
+ text.warning,
531
570
  "- Store this file in a secure location (password manager, encrypted drive)",
532
571
  "- Delete this file from your local disk after backing up",
533
572
  "- Never share this key with anyone",
534
573
  "- If compromised, your identity can be stolen",
535
574
  "",
536
575
  "=".repeat(60),
537
- "SIGNING KEY (hex-encoded secp256k1 private key)",
576
+ `${text.name.toUpperCase()} (${text.encoding})`,
538
577
  "=".repeat(60),
539
578
  "",
540
579
  key,
@@ -543,6 +582,83 @@ async function saveKeyBackup(key, handle) {
543
582
  ].join("\n"), { mode: 384 });
544
583
  return filepath;
545
584
  }
585
+ /**
586
+ * Ask how to back up a key (1Password, clipboard, file or on screen), do
587
+ * it, and ask the user to confirm it is saved. Returns whether they
588
+ * confirmed. With allowSkip, the user may decline to back it up.
589
+ */
590
+ async function promptKeyBackup(opts) {
591
+ const text = KEY_BACKUP_TEXT[opts.kind];
592
+ const details = opts.details ?? [];
593
+ const capitalised = text.name[0].toUpperCase() + text.name.slice(1);
594
+ const showKey = () => p.note([
595
+ `${text.name.toUpperCase()} (keep this secret!):`,
596
+ "",
597
+ opts.key,
598
+ "",
599
+ "Copy this to your password manager now."
600
+ ].join("\n"), `🔑 Your ${text.label}`);
601
+ const options = [];
602
+ if (await is1PasswordAvailable()) options.push({
603
+ value: "1password",
604
+ label: "Save to 1Password",
605
+ hint: "recommended - uses op CLI"
606
+ });
607
+ options.push({
608
+ value: "copy",
609
+ label: "Copy to clipboard",
610
+ hint: "paste into password manager"
611
+ }, {
612
+ value: "file",
613
+ label: "Save to file",
614
+ hint: `${text.filePrefix}.txt`
615
+ }, {
616
+ value: "show",
617
+ label: "Display it (I'll copy manually)",
618
+ hint: "shown in terminal"
619
+ });
620
+ if (opts.allowSkip) options.push({
621
+ value: "skip",
622
+ label: "Skip (I understand the risk)",
623
+ hint: "not recommended"
624
+ });
625
+ const choice = await promptSelect({
626
+ message: `How would you like to back up your ${text.name}?`,
627
+ options
628
+ });
629
+ if (choice === "1password") {
630
+ const spinner = p.spinner();
631
+ spinner.start("Saving to 1Password...");
632
+ const result = await saveTo1Password(opts.key, opts.handle, opts.kind, details);
633
+ if (result.success) {
634
+ spinner.stop("Saved to 1Password");
635
+ p.log.success(`Created: "${result.itemName}"`);
636
+ } else {
637
+ spinner.stop("Failed to save to 1Password");
638
+ p.log.error(result.error || "Unknown error");
639
+ p.log.info("Falling back to displaying the key...");
640
+ showKey();
641
+ }
642
+ } else if (choice === "copy") {
643
+ await copyToClipboard(opts.key);
644
+ p.log.success(`${capitalised} copied to clipboard`);
645
+ p.log.info("Paste it into your password manager now!");
646
+ } else if (choice === "file") {
647
+ const backupPath = await saveKeyBackup(opts.key, opts.handle, opts.kind, details);
648
+ p.log.success(`${capitalised} saved to: ${backupPath}`);
649
+ p.log.warn("Move this file to a secure location and delete the local copy!");
650
+ } else if (choice === "show") showKey();
651
+ if (choice === "skip") return false;
652
+ const confirmed = await promptConfirm({
653
+ message: `Have you saved your ${text.name} securely?`,
654
+ initialValue: true
655
+ });
656
+ if (!confirmed) {
657
+ p.log.warn("Please back up your key before continuing!");
658
+ p.note(opts.key, `🔑 ${text.label}`);
659
+ }
660
+ return confirmed;
661
+ }
546
662
 
547
663
  //#endregion
548
664
  //#region src/cli/utils/secrets.ts
@@ -560,6 +676,17 @@ async function generateSigningKeypair() {
560
676
  };
561
677
  }
562
678
  /**
679
+ * Generate a P-256 keypair for the spaces `#atproto_kem` verification
680
+ * method, which MACs space data for syncers.
681
+ */
682
+ async function generateKemKeypair() {
683
+ const keypair = await P256Keypair.create({ exportable: true });
684
+ return {
685
+ privateKey: Buffer.from(await keypair.export()).toString("hex"),
686
+ publicKey: keypair.did().replace("did:key:", "")
687
+ };
688
+ }
689
+ /**
563
690
  * Derive public key from an existing private key
564
691
  */
565
692
  async function derivePublicKey(privateKeyHex) {
@@ -1406,6 +1533,28 @@ var PDSClient = class PDSClient {
1406
1533
  };
1407
1534
  }
1408
1535
  /**
1536
+ * Get this PDS's recommended PLC credentials. The rotation key and
1537
+ * atproto verification method are both the deployed signing key.
1538
+ */
1539
+ async getRecommendedDidCredentials() {
1540
+ const result = await ok(this.client.get("com.atproto.identity.getRecommendedDidCredentials", {}));
1541
+ return {
1542
+ rotationKeys: result.rotationKeys ?? [],
1543
+ verificationMethods: result.verificationMethods ?? {}
1544
+ };
1545
+ }
1546
+ /**
1547
+ * Get this PDS to sign a PLC operation applying the given changes to the
1548
+ * DID's current state. Needs a token from getMigrationToken, and fails
1549
+ * unless the PDS's signing key is a rotation key.
1550
+ */
1551
+ async signPlcOperation(token, changes) {
1552
+ return (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
1553
+ token,
1554
+ ...changes
1555
+ } }))).operation;
1556
+ }
1557
+ /**
1409
1558
  * List notifications (proxied through PDS to AppView)
1410
1559
  */
1411
1560
  async listNotifications(limit = 25) {
@@ -2163,10 +2312,21 @@ const appPasswordCommand = defineCommand({
2163
2312
  /**
2164
2313
  * Utilities for resolving AT Protocol handles to DIDs
2165
2314
  */
2166
- const resolver = new DohJsonHandleResolver({ dohUrl: "https://cloudflare-dns.com/dns-query" });
2315
+ const currentFetch = (input, init) => globalThis.fetch(input, init);
2316
+ const resolver = new CompositeHandleResolver({
2317
+ strategy: "dns-first",
2318
+ methods: {
2319
+ dns: new DohJsonHandleResolver({
2320
+ dohUrl: "https://cloudflare-dns.com/dns-query",
2321
+ fetch: currentFetch
2322
+ }),
2323
+ http: new WellKnownHandleResolver({ fetch: currentFetch })
2324
+ }
2325
+ });
2167
2326
  /**
2168
- * Resolve a handle to a DID using the AT Protocol handle resolution methods.
2169
- * Uses DNS-over-HTTPS via Cloudflare for DNS resolution.
2327
+ * Resolve a handle to a DID using the AT Protocol handle resolution methods:
2328
+ * a DNS TXT record (via Cloudflare DNS-over-HTTPS), then
2329
+ * /.well-known/atproto-did on the handle's domain.
2170
2330
  */
2171
2331
  async function resolveHandleToDid(handle) {
2172
2332
  try {
@@ -2241,6 +2401,39 @@ var DidResolver = class {
2241
2401
  * Interactive PDS setup wizard
2242
2402
  */
2243
2403
  /**
2404
+ * Explain how the handle will be verified: automatically when it matches the
2405
+ * PDS hostname, otherwise with a DNS TXT record or a file on the handle's
2406
+ * domain. For a migration (didWeb false) the handle switches when
2407
+ * `pds identity` runs, so the record must exist by then.
2408
+ */
2409
+ function showHandleSetup(opts) {
2410
+ const { handle, hostname, did, didWeb } = opts;
2411
+ const didWebLines = (verb) => didWeb ? [
2412
+ `For did:web, your PDS ${verb} the DID document at:`,
2413
+ ` https://${hostname}/.well-known/did.json`,
2414
+ ""
2415
+ ] : [];
2416
+ if (handle === hostname) p.note([
2417
+ "Your handle matches your PDS hostname, so your PDS will",
2418
+ "automatically handle domain verification for you!",
2419
+ "",
2420
+ ...didWebLines("serves"),
2421
+ "For handle verification, it serves:",
2422
+ ` https://${hostname}/.well-known/atproto-did`,
2423
+ "",
2424
+ didWeb ? "No additional DNS or hosting setup needed. Easy! 🎉" : "No additional DNS setup needed. Your handle switches when you run 'pds identity'."
2425
+ ].join("\n"), "Identity Setup 🪪");
2426
+ else p.note([
2427
+ ...didWebLines("will serve"),
2428
+ didWeb ? "To verify your handle, create a DNS TXT record:" : "Before you run 'pds identity', verify your handle with a DNS TXT record:",
2429
+ ` _atproto.${handle} TXT "did=${did}"`,
2430
+ "",
2431
+ "Or serve a file at:",
2432
+ ` https://${handle}/.well-known/atproto-did`,
2433
+ ` containing: ${did}`
2434
+ ].join("\n"), "Identity Setup 🪪");
2435
+ }
2436
+ /**
2244
2437
  * Slugify a handle to create a worker name
2245
2438
  * e.g., "example.com" -> "example-com-pds"
2246
2439
  */
@@ -2407,7 +2600,7 @@ const initCommand = defineCommand({
2407
2600
  if (isHostedHandle(existingHandle)) {
2408
2601
  const theirDomain = hostedDomains.find((d) => existingHandle?.endsWith(d));
2409
2602
  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.`);
2603
+ 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
2604
  }
2412
2605
  if (attempts >= MAX_ATTEMPTS) {
2413
2606
  p.log.error("Unable to resolve handle after 3 attempts.");
@@ -2437,6 +2630,12 @@ const initCommand = defineCommand({
2437
2630
  initialValue: currentVars.PDS_HOSTNAME || handle,
2438
2631
  validate: (v) => !v ? "Hostname is required" : void 0
2439
2632
  });
2633
+ if (handle !== existingHandle) showHandleSetup({
2634
+ handle,
2635
+ hostname,
2636
+ did,
2637
+ didWeb: false
2638
+ });
2440
2639
  workerName = await promptWorkerName(handle, currentWorkerName);
2441
2640
  initialActive = "false";
2442
2641
  await ensureAccountConfigured();
@@ -2467,29 +2666,12 @@ const initCommand = defineCommand({
2467
2666
  workerName = await promptWorkerName(handle, currentWorkerName);
2468
2667
  initialActive = "true";
2469
2668
  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 🪪");
2669
+ showHandleSetup({
2670
+ handle,
2671
+ hostname,
2672
+ did,
2673
+ didWeb: true
2674
+ });
2493
2675
  }
2494
2676
  let dataLocation;
2495
2677
  if (currentVars.DATA_LOCATION) dataLocation = currentVars.DATA_LOCATION;
@@ -2571,76 +2753,12 @@ const initCommand = defineCommand({
2571
2753
  "",
2572
2754
  "We strongly recommend backing it up now."
2573
2755
  ].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"
2756
+ await promptKeyBackup({
2757
+ key: signingKey,
2758
+ kind: "signing",
2759
+ handle,
2760
+ allowSkip: true
2597
2761
  });
2598
- const backupChoice = await promptSelect({
2599
- message: "How would you like to back up your signing key?",
2600
- options: backupOptions
2601
- });
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
2762
  }
2645
2763
  const jwtSecret = await getOrGenerateSecret("JWT_SECRET", devVars, async () => {
2646
2764
  spinner.start("Generating JWT secret...");
@@ -2794,7 +2912,7 @@ async function getOrGenerateSecret(name, devVars, generate) {
2794
2912
 
2795
2913
  //#endregion
2796
2914
  //#region src/cli/commands/migrate.ts
2797
- const brightNote$2 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
2915
+ const brightNote$3 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
2798
2916
  /**
2799
2917
  * Format number with commas
2800
2918
  */
@@ -2916,7 +3034,7 @@ const migrateCommand = defineCommand({
2916
3034
  p.outro("Migration cancelled.");
2917
3035
  process.exit(1);
2918
3036
  }
2919
- p.note(brightNote$2([
3037
+ p.note(brightNote$3([
2920
3038
  pc.bold("This will permanently delete from your new PDS:"),
2921
3039
  "",
2922
3040
  ` • ${num(status.repoBlocks)} repository blocks`,
@@ -2992,7 +3110,7 @@ const migrateCommand = defineCommand({
2992
3110
  ` 👥 ${num(profileStats.followsCount)} follows`,
2993
3111
  ` ...plus all your images, likes and preferences`
2994
3112
  ] : [` 📝 Posts, follows, images, likes and preferences`];
2995
- p.note(brightNote$2([
3113
+ p.note(brightNote$3([
2996
3114
  pc.bold(`@${handle}`) + ` (${did.slice(0, 20)}...)`,
2997
3115
  "",
2998
3116
  `Currently at: ${sourceDomain}`,
@@ -3119,7 +3237,7 @@ const migrateCommand = defineCommand({
3119
3237
  }
3120
3238
  });
3121
3239
  function showNextSteps(pm, sourceDomain) {
3122
- p.note(brightNote$2([
3240
+ p.note(brightNote$3([
3123
3241
  pc.bold("Your data is safe in your new PDS."),
3124
3242
  "Two more steps to go live:",
3125
3243
  "",
@@ -3225,6 +3343,48 @@ const migrateTokenCommand = defineCommand({
3225
3343
  }
3226
3344
  });
3227
3345
 
3346
+ //#endregion
3347
+ //#region src/plc.ts
3348
+ const PLC_DIRECTORY = "https://plc.directory";
3349
+ /**
3350
+ * Headers for submitting a PLC operation (POST /{did}). An update (any
3351
+ * operation with a `prev`) carries `If-Match: *`, which tells the directory
3352
+ * the DID already exists, so it is rate-limited per identifier rather than
3353
+ * per IP. That matters on Workers, whose egress IPs are shared. A genesis
3354
+ * operation (`prev: null`) must not carry it. Directories that predate the
3355
+ * header ignore it.
3356
+ * https://discourse.atmosphere.community/t/plc-directory-and-rate-limits/1506
3357
+ */
3358
+ function plcSubmitHeaders(operation) {
3359
+ return {
3360
+ "Content-Type": "application/json",
3361
+ ...typeof operation.prev === "string" ? { "If-Match": "*" } : {}
3362
+ };
3363
+ }
3364
+ /**
3365
+ * Set the account's handle in an alsoKnownAs list. Handles are verified
3366
+ * against the first at:// entry, so the handle replaces it, or is added
3367
+ * first if there is none. Any later copy of the handle is dropped, and
3368
+ * other entries are kept.
3369
+ */
3370
+ function withHandle(alsoKnownAs, handle) {
3371
+ const aka = `at://${handle}`;
3372
+ const first = alsoKnownAs.findIndex((uri) => uri.startsWith("at://"));
3373
+ if (first < 0) return [aka, ...alsoKnownAs];
3374
+ return alsoKnownAs.map((uri, i) => i === first ? aka : uri).filter((uri, i) => uri !== aka || i === first);
3375
+ }
3376
+ /**
3377
+ * Sign a PLC operation: DAG-CBOR encode the unsigned operation, sign the
3378
+ * bytes, and attach the signature as base64url.
3379
+ */
3380
+ async function signOperation(op, keypair) {
3381
+ const sig = await keypair.sign(encode(op));
3382
+ return {
3383
+ ...op,
3384
+ sig: base64url.encode(sig)
3385
+ };
3386
+ }
3387
+
3228
3388
  //#endregion
3229
3389
  //#region src/cli/utils/plc-client.ts
3230
3390
  /**
@@ -3235,7 +3395,6 @@ const migrateTokenCommand = defineCommand({
3235
3395
  *
3236
3396
  * Uses @atcute/client for type-safe XRPC calls.
3237
3397
  */
3238
- const PLC_DIRECTORY = "https://plc.directory";
3239
3398
  /**
3240
3399
  * Create a fetch handler that adds optional auth token
3241
3400
  */
@@ -3291,28 +3450,30 @@ var SourcePdsPlcClient = class {
3291
3450
  }
3292
3451
  }
3293
3452
  /**
3294
- * Get a signed PLC operation from the source PDS.
3295
- * This builds and signs the operation to migrate to the new PDS.
3453
+ * Get the source PDS's recommended credentials for this account. Its
3454
+ * rotationKeys are the keys the source PDS holds.
3455
+ *
3456
+ * Uses: com.atproto.identity.getRecommendedDidCredentials
3457
+ */
3458
+ async getRecommendedDidCredentials() {
3459
+ return { rotationKeys: (await ok(this.client.get("com.atproto.identity.getRecommendedDidCredentials", {}))).rotationKeys ?? [] };
3460
+ }
3461
+ /**
3462
+ * Get the source PDS to sign a PLC operation applying the given changes
3463
+ * to the DID's current state.
3296
3464
  *
3297
3465
  * Uses: com.atproto.identity.signPlcOperation
3298
3466
  *
3299
3467
  * @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:...)
3468
+ * @param changes - Fields to change; omitted fields keep their values
3302
3469
  */
3303
- async signPlcOperation(token, newPdsEndpoint, newSigningKey) {
3470
+ async signPlcOperation(token, changes) {
3304
3471
  try {
3305
3472
  return {
3306
3473
  success: true,
3307
3474
  signedOperation: (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
3308
3475
  token,
3309
- rotationKeys: void 0,
3310
- alsoKnownAs: void 0,
3311
- verificationMethods: { atproto: newSigningKey },
3312
- services: { atproto_pds: {
3313
- type: "AtprotoPersonalDataServer",
3314
- endpoint: newPdsEndpoint
3315
- } }
3476
+ ...changes
3316
3477
  } }))).operation
3317
3478
  };
3318
3479
  } catch (err) {
@@ -3351,6 +3512,12 @@ var PlcDirectoryClient = class {
3351
3512
  return res.json();
3352
3513
  }
3353
3514
  /**
3515
+ * Get the most recent non-nullified operation for a DID
3516
+ */
3517
+ async getLatestOperation(did) {
3518
+ return (await this.getAuditLog(did)).filter((entry) => !entry.nullified).pop() ?? null;
3519
+ }
3520
+ /**
3354
3521
  * Get the current DID document
3355
3522
  */
3356
3523
  async getDocument(did) {
@@ -3368,7 +3535,7 @@ var PlcDirectoryClient = class {
3368
3535
  try {
3369
3536
  const res = await fetch(`${this.plcUrl}/${did}`, {
3370
3537
  method: "POST",
3371
- headers: { "Content-Type": "application/json" },
3538
+ headers: plcSubmitHeaders(operation),
3372
3539
  body: JSON.stringify(operation)
3373
3540
  });
3374
3541
  if (!res.ok) return {
@@ -3386,231 +3553,220 @@ var PlcDirectoryClient = class {
3386
3553
  };
3387
3554
 
3388
3555
  //#endregion
3389
- //#region src/cli/commands/identity.ts
3556
+ //#region src/cli/utils/rotation-keys.ts
3390
3557
  /**
3391
- * Identity command - update DID document to point to new PDS
3558
+ * PLC rotation key helpers: ordering, labelling, and recovery keys.
3392
3559
  *
3393
- * This command handles the PLC operation flow for migrating identity
3394
- * 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
3560
+ * Rotation keys are listed in priority order. A higher-priority key can
3561
+ * override an operation signed by a lower one for 72 hours, so keys the
3562
+ * user holds offline come before the PDS key.
3398
3563
  */
3399
- const brightNote$1 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
3400
- const identityCommand = defineCommand({
3401
- meta: {
3402
- name: "identity",
3403
- description: "Update your DID to point to your new PDS"
3404
- },
3405
- args: {
3406
- dev: {
3407
- type: "boolean",
3408
- description: "Target local development server instead of production",
3409
- default: false
3410
- },
3411
- token: {
3412
- type: "string",
3413
- description: "Email token (if you already have one)"
3414
- }
3415
- },
3416
- async run({ args }) {
3417
- const pm = detectPackageManager();
3418
- const isDev = args.dev;
3419
- p.intro("🆔 Update Identity");
3420
- const spinner = p.spinner();
3421
- const wranglerVars = getVars();
3422
- const config = {
3423
- ...readDevVars(),
3424
- ...wranglerVars
3425
- };
3426
- const did = config.DID;
3427
- const handle = config.HANDLE;
3428
- const authToken = config.AUTH_TOKEN;
3429
- const pdsHostname = config.PDS_HOSTNAME;
3430
- const signingKey = config.SIGNING_KEY;
3431
- if (!did) {
3432
- p.log.error("No DID configured. Run 'pds init' first.");
3433
- p.outro("Identity update cancelled.");
3434
- process.exit(1);
3435
- }
3436
- if (!handle) {
3437
- p.log.error("No HANDLE configured. Run 'pds init' first.");
3438
- p.outro("Identity update cancelled.");
3439
- process.exit(1);
3440
- }
3441
- if (!authToken) {
3442
- p.log.error("No AUTH_TOKEN found. Run 'pds init' first.");
3443
- p.outro("Identity update cancelled.");
3444
- process.exit(1);
3445
- }
3446
- if (!pdsHostname && !isDev) {
3447
- p.log.error("No PDS_HOSTNAME configured in wrangler.jsonc");
3448
- p.outro("Identity update cancelled.");
3449
- process.exit(1);
3450
- }
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
- if (!did.startsWith("did:plc:")) {
3457
- p.log.error("Only did:plc identities are supported for now.");
3458
- p.log.info("did:web identities don't use PLC operations.");
3459
- p.outro("Identity update cancelled.");
3460
- process.exit(1);
3461
- }
3462
- let targetUrl;
3564
+ /** plc.directory accepts at most this many rotation keys */
3565
+ const MAX_ROTATION_KEYS = 5;
3566
+ const SECP256K1_PRIV_PREFIX = [129, 38];
3567
+ const P256_PRIV_PREFIX = [134, 38];
3568
+ /**
3569
+ * Build the rotation key list: keys the user holds, in the order given,
3570
+ * followed by the PDS key.
3571
+ */
3572
+ function buildRotationKeys(opts) {
3573
+ const keys = [...new Set([...opts.userKeys.filter((k) => k !== opts.pdsKey), opts.pdsKey])];
3574
+ const invalid = keys.find((k) => !k.startsWith("did:key:"));
3575
+ if (invalid) throw new Error(`Not a did:key: ${invalid}`);
3576
+ if (keys.length > MAX_ROTATION_KEYS) throw new Error(`A DID can have at most ${MAX_ROTATION_KEYS} rotation keys (got ${keys.length})`);
3577
+ return keys;
3578
+ }
3579
+ /**
3580
+ * Tag each current rotation key with who holds it, where known.
3581
+ */
3582
+ function labelRotationKeys(current, known) {
3583
+ return current.map((key) => ({
3584
+ key,
3585
+ owner: key === known.pdsKey ? "this-pds" : known.sourcePdsKeys?.includes(key) ? "source-pds" : "unknown"
3586
+ }));
3587
+ }
3588
+ /**
3589
+ * Find the PDS a DID pointed at before the current one, from its PLC audit
3590
+ * log. Returns null if it has never pointed anywhere else.
3591
+ */
3592
+ function findPreviousPdsEndpoint(log, currentEndpoint) {
3593
+ const current = currentEndpoint.replace(/\/$/, "");
3594
+ for (const entry of [...log].reverse()) {
3595
+ if (entry.nullified || entry.operation.type !== "plc_operation") continue;
3596
+ const endpoint = entry.operation.services.atproto_pds?.endpoint?.replace(/\/$/, "");
3597
+ if (endpoint && endpoint !== current) return endpoint;
3598
+ }
3599
+ return null;
3600
+ }
3601
+ /**
3602
+ * Generate a secp256k1 recovery key.
3603
+ */
3604
+ async function generateRecoveryKey() {
3605
+ const keypair = await Secp256k1Keypair.create({ exportable: true });
3606
+ const bytes = await keypair.export();
3607
+ return {
3608
+ privateKey: bytesToMultibase(new Uint8Array([...SECP256K1_PRIV_PREFIX, ...bytes]), "base58btc"),
3609
+ did: keypair.did()
3610
+ };
3611
+ }
3612
+ /**
3613
+ * Parse a private rotation key pasted by the user: multibase (from goat or
3614
+ * generateRecoveryKey, secp256k1 or P-256), or a hex secp256k1 key like
3615
+ * the PDS signing key.
3616
+ */
3617
+ async function importRotationKey(input) {
3618
+ const value = input.trim();
3619
+ if (/^[0-9a-f]{64}$/i.test(value)) return Secp256k1Keypair.import(value.toLowerCase());
3620
+ if (value.startsWith("z")) {
3621
+ let bytes;
3463
3622
  try {
3464
- targetUrl = getTargetUrl(isDev, pdsHostname);
3465
- } catch (err) {
3466
- p.log.error(err instanceof Error ? err.message : "Configuration error");
3467
- p.outro("Identity update cancelled.");
3468
- process.exit(1);
3623
+ bytes = multibaseToBytes(value);
3624
+ } catch {
3625
+ throw new Error("Not a valid multibase key");
3469
3626
  }
3470
- const targetDomain = getDomain(targetUrl);
3471
- spinner.start("Resolving your DID...");
3472
- const didDoc = await new DidResolver().resolve(did);
3473
- if (!didDoc) {
3474
- spinner.stop("Failed to resolve DID");
3475
- p.log.error(`Could not resolve DID: ${did}`);
3476
- p.outro("Identity update cancelled.");
3477
- process.exit(1);
3627
+ const prefix = [bytes[0], bytes[1]];
3628
+ const key = bytes.slice(2);
3629
+ if (key.length === 32) {
3630
+ if (samePrefix(prefix, SECP256K1_PRIV_PREFIX)) return Secp256k1Keypair.import(key);
3631
+ if (samePrefix(prefix, P256_PRIV_PREFIX)) return P256Keypair.import(key);
3478
3632
  }
3479
- const sourcePdsUrl = getPdsEndpoint(didDoc);
3480
- if (!sourcePdsUrl) {
3481
- spinner.stop("No PDS found in DID document");
3482
- p.log.error("Could not find PDS endpoint in DID document");
3483
- p.outro("Identity update cancelled.");
3484
- process.exit(1);
3633
+ }
3634
+ throw new Error("Unrecognised key format. Expected a multibase private key (starting with z) or a 64-character hex key.");
3635
+ }
3636
+ function samePrefix(a, b) {
3637
+ return a[0] === b[0] && a[1] === b[1];
3638
+ }
3639
+
3640
+ //#endregion
3641
+ //#region src/cli/utils/rotation-key-prompts.ts
3642
+ /**
3643
+ * Interactive steps for choosing a DID's rotation keys, shared by
3644
+ * `pds identity` and `pds rotation-keys`.
3645
+ */
3646
+ /**
3647
+ * Get the key the deployed PDS signs with, from its recommended
3648
+ * credentials. The DID must name this key, which may not be the one in
3649
+ * .dev.vars, so a different local key is an error.
3650
+ */
3651
+ async function getPdsRotationKey(client, pdsName, localSigningKey) {
3652
+ const credentials = await client.getRecommendedDidCredentials();
3653
+ const pdsKey = credentials.rotationKeys[0];
3654
+ if (!pdsKey || credentials.verificationMethods.atproto !== pdsKey) throw new Error(`${pdsName} returned unexpected credentials`);
3655
+ if (localSigningKey) {
3656
+ const localKey = (await Secp256k1Keypair.import(localSigningKey)).did();
3657
+ 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.`);
3658
+ }
3659
+ return pdsKey;
3660
+ }
3661
+ /**
3662
+ * Decide the new rotation keys: keep the current keys the user holds, offer
3663
+ * to generate a recovery key if there are none, and put this PDS's key last.
3664
+ *
3665
+ * @param sourcePdsKeys - Keys held by the previous PDS, if known. Without
3666
+ * them, the user is asked about every key that isn't this PDS's.
3667
+ * @param sourceName - Display name for the previous PDS
3668
+ * @param heldKeys - Keys known to be the user's, kept without asking
3669
+ */
3670
+ async function chooseRotationKeys(opts) {
3671
+ const descriptions = new Map([[opts.pdsKey, `${opts.pdsName} (this PDS)`]]);
3672
+ const labelled = labelRotationKeys(opts.currentKeys, {
3673
+ pdsKey: opts.pdsKey,
3674
+ sourcePdsKeys: opts.sourcePdsKeys
3675
+ });
3676
+ const sourceKnown = opts.sourcePdsKeys !== void 0;
3677
+ const userKeys = [];
3678
+ for (const { key, owner } of labelled) {
3679
+ if (owner === "source-pds") {
3680
+ descriptions.set(key, opts.sourceName ?? "previous PDS");
3681
+ continue;
3485
3682
  }
3486
- const sourceDomain = getDomain(sourcePdsUrl);
3487
- spinner.stop(`Current PDS: ${sourceDomain}`);
3488
- 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;
3683
+ if (owner === "this-pds") continue;
3684
+ if (opts.heldKeys?.includes(key)) {
3685
+ userKeys.push(key);
3686
+ descriptions.set(key, "your key");
3687
+ continue;
3494
3688
  }
3495
- spinner.start(`Checking ${targetDomain}...`);
3496
- if (!await new PDSClient(targetUrl, authToken).healthCheck()) {
3497
- spinner.stop(`PDS not responding`);
3498
- p.log.error(`Your new PDS isn't responding at ${targetUrl}`);
3499
- if (isDev) p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
3500
- else p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
3501
- p.outro("Identity update cancelled.");
3502
- process.exit(1);
3689
+ if (await promptConfirm({
3690
+ 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.`,
3691
+ initialValue: true
3692
+ })) {
3693
+ userKeys.push(key);
3694
+ descriptions.set(key, "your key");
3695
+ } else descriptions.set(key, "not held by you");
3696
+ }
3697
+ let createdRecoveryKey = false;
3698
+ if (userKeys.length === 0) {
3699
+ p.note([
3700
+ "A recovery key is a rotation key you keep offline.",
3701
+ "It ranks above your PDS's key, so for 72 hours after any",
3702
+ "identity change it can override it. If your PDS is lost or",
3703
+ "compromised, it is how you take your identity back."
3704
+ ].join("\n"), "Recovery key");
3705
+ if (await promptConfirm({
3706
+ message: "Create a recovery key? (recommended)",
3707
+ initialValue: true
3708
+ })) {
3709
+ const recoveryKey = await generateRecoveryKey();
3710
+ const backup = () => promptKeyBackup({
3711
+ key: recoveryKey.privateKey,
3712
+ kind: "recovery",
3713
+ handle: opts.handle,
3714
+ details: [`DID: ${opts.did}`, `Public key: ${recoveryKey.did}`],
3715
+ allowSkip: false
3716
+ });
3717
+ let saved = await backup();
3718
+ while (!saved) {
3719
+ if (!await promptConfirm({
3720
+ message: "Try saving it again? Choosing no continues without a recovery key.",
3721
+ initialValue: true
3722
+ })) break;
3723
+ saved = await backup();
3724
+ }
3725
+ if (saved) {
3726
+ userKeys.push(recoveryKey.did);
3727
+ descriptions.set(recoveryKey.did, "your new recovery key");
3728
+ createdRecoveryKey = true;
3729
+ }
3503
3730
  }
3504
- 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");
3510
- p.outro("Identity update cancelled.");
3511
- process.exit(1);
3731
+ }
3732
+ 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.`);
3733
+ const rotationKeys = buildRotationKeys({
3734
+ userKeys,
3735
+ pdsKey: opts.pdsKey
3736
+ });
3737
+ return {
3738
+ rotationKeys,
3739
+ descriptions,
3740
+ removed: opts.currentKeys.filter((k) => !rotationKeys.includes(k)),
3741
+ createdRecoveryKey
3742
+ };
3743
+ }
3744
+ /**
3745
+ * Lines describing a rotation key change, for a note.
3746
+ */
3747
+ function describeRotationKeys(choice) {
3748
+ const lines = [pc.bold("Rotation keys, highest priority first:")];
3749
+ choice.rotationKeys.forEach((key, i) => {
3750
+ lines.push(` ${i + 1}. ${key}`);
3751
+ lines.push(` ${pc.dim(choice.descriptions.get(key) ?? "")}`);
3752
+ });
3753
+ if (choice.removed.length > 0) {
3754
+ lines.push("", pc.bold("Removed:"));
3755
+ for (const key of choice.removed) {
3756
+ lines.push(` ${key}`);
3757
+ lines.push(` ${pc.dim(choice.descriptions.get(key) ?? "")}`);
3512
3758
  }
3513
- spinner.stop("Signing key ready");
3514
- const sourceDisplayName = sourceDomain.endsWith(".bsky.network") ? "bsky.social" : sourceDomain;
3515
- p.note(brightNote$1([
3516
- pc.bold("Updating your identity:"),
3517
- "",
3518
- `${pc.dim("From:")} ${sourceDisplayName}`,
3519
- `${pc.dim("To:")} ${targetDomain}`,
3520
- "",
3521
- pc.dim("This tells the network where to find you.")
3522
- ]), "🔄 DID Update");
3523
- const sourcePdsClient = new SourcePdsPlcClient(sourcePdsUrl);
3524
- let token = args.token;
3525
- 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
- spinner.start("Requesting identity update token...");
3544
- const signatureRequest = await sourcePdsClient.requestPlcOperationSignature();
3545
- if (!signatureRequest.success) {
3546
- spinner.stop("Failed to request token");
3547
- p.log.error(signatureRequest.error ?? "Could not request PLC operation signature");
3548
- p.outro("Identity update cancelled.");
3549
- process.exit(1);
3550
- }
3551
- spinner.stop("Token requested");
3552
- p.log.info("");
3553
- 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
3759
  }
3602
- });
3760
+ return lines;
3761
+ }
3603
3762
  /**
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.
3763
+ * Read the DID's latest operation back and check its rotation keys.
3764
+ * Returns the keys plc.directory has, or null if they match.
3607
3765
  */
3608
- async function getSigningKeyDid(hexPrivateKey) {
3609
- try {
3610
- return (await Secp256k1Keypair.import(hexPrivateKey)).did();
3611
- } catch {
3612
- return null;
3613
- }
3766
+ async function checkRotationKeys(plcClient, did, expected) {
3767
+ const latest = await plcClient.getLatestOperation(did);
3768
+ const actual = latest?.operation.type === "plc_operation" ? latest.operation.rotationKeys : [];
3769
+ return actual.length === expected.length && actual.every((key, i) => key === expected[i]) ? null : actual;
3614
3770
  }
3615
3771
 
3616
3772
  //#endregion
@@ -3683,6 +3839,26 @@ async function checkDidDocument(did, expectedPdsUrl) {
3683
3839
  };
3684
3840
  }
3685
3841
  /**
3842
+ * Check whether this PDS can update a did:plc identity: its signing key
3843
+ * must be one of the DID's rotation keys. Also reports whether any other
3844
+ * key is listed, such as a recovery key. Returns null if either side
3845
+ * can't be read.
3846
+ */
3847
+ async function checkPlcRotationKeys(client, did, plcClient = new PlcDirectoryClient()) {
3848
+ try {
3849
+ const [credentials, latest] = await Promise.all([client.getRecommendedDidCredentials(), plcClient.getLatestOperation(did)]);
3850
+ const pdsKey = credentials.rotationKeys[0];
3851
+ if (!pdsKey || latest?.operation.type !== "plc_operation") return null;
3852
+ const keys = latest.operation.rotationKeys;
3853
+ return {
3854
+ pdsCanSign: keys.includes(pdsKey),
3855
+ otherKeys: keys.filter((key) => key !== pdsKey).length
3856
+ };
3857
+ } catch {
3858
+ return null;
3859
+ }
3860
+ }
3861
+ /**
3686
3862
  * Check that DID resolves and returns the PDS endpoint (simpler version using PDSClient)
3687
3863
  */
3688
3864
  async function checkDidResolution(client, did, expectedPdsHostname) {
@@ -3764,6 +3940,560 @@ async function checkAppViewIndexing(client, did) {
3764
3940
  };
3765
3941
  }
3766
3942
 
3943
+ //#endregion
3944
+ //#region src/cli/commands/identity.ts
3945
+ /**
3946
+ * Identity command - update DID document to point to new PDS
3947
+ *
3948
+ * This command handles the PLC operation flow for migrating identity
3949
+ * from source PDS to Cirrus. It:
3950
+ * 1. Chooses the rotation keys: keys the user holds, an optional new
3951
+ * recovery key, then this PDS's key. The source PDS's key is removed.
3952
+ * 2. Requests an email token from the source PDS
3953
+ * 3. Gets the source PDS to sign a PLC operation with the new endpoint,
3954
+ * signing key, rotation keys and handle
3955
+ * 4. Submits the signed operation to the PLC directory
3956
+ */
3957
+ const brightNote$2 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
3958
+ const identityCommand = defineCommand({
3959
+ meta: {
3960
+ name: "identity",
3961
+ description: "Update your DID to point to your new PDS"
3962
+ },
3963
+ args: {
3964
+ dev: {
3965
+ type: "boolean",
3966
+ description: "Target local development server instead of production",
3967
+ default: false
3968
+ },
3969
+ token: {
3970
+ type: "string",
3971
+ description: "Confirmation code from your previous PDS's email, if you already have one"
3972
+ }
3973
+ },
3974
+ async run({ args }) {
3975
+ const pm = detectPackageManager();
3976
+ const isDev = args.dev;
3977
+ p.intro("🆔 Update Identity");
3978
+ const spinner = p.spinner();
3979
+ const wranglerVars = getVars();
3980
+ const config = {
3981
+ ...readDevVars(),
3982
+ ...wranglerVars
3983
+ };
3984
+ const did = config.DID;
3985
+ const handle = config.HANDLE;
3986
+ const authToken = config.AUTH_TOKEN;
3987
+ const pdsHostname = config.PDS_HOSTNAME;
3988
+ const signingKey = config.SIGNING_KEY;
3989
+ if (!did) {
3990
+ p.log.error("No DID configured. Run 'pds init' first.");
3991
+ p.outro("Identity update cancelled.");
3992
+ process.exit(1);
3993
+ }
3994
+ if (!handle) {
3995
+ p.log.error("No HANDLE configured. Run 'pds init' first.");
3996
+ p.outro("Identity update cancelled.");
3997
+ process.exit(1);
3998
+ }
3999
+ if (!authToken) {
4000
+ p.log.error("No AUTH_TOKEN found. Run 'pds init' first.");
4001
+ p.outro("Identity update cancelled.");
4002
+ process.exit(1);
4003
+ }
4004
+ if (!pdsHostname && !isDev) {
4005
+ p.log.error("No PDS_HOSTNAME configured in wrangler.jsonc");
4006
+ p.outro("Identity update cancelled.");
4007
+ process.exit(1);
4008
+ }
4009
+ if (!did.startsWith("did:plc:")) {
4010
+ p.log.error("Only did:plc identities are supported for now.");
4011
+ p.log.info("did:web identities don't use PLC operations.");
4012
+ p.outro("Identity update cancelled.");
4013
+ process.exit(1);
4014
+ }
4015
+ let targetUrl;
4016
+ try {
4017
+ targetUrl = getTargetUrl(isDev, pdsHostname);
4018
+ } catch (err) {
4019
+ p.log.error(err instanceof Error ? err.message : "Configuration error");
4020
+ p.outro("Identity update cancelled.");
4021
+ process.exit(1);
4022
+ }
4023
+ const targetDomain = getDomain(targetUrl);
4024
+ spinner.start("Resolving your DID...");
4025
+ const didDoc = await new DidResolver().resolve(did);
4026
+ if (!didDoc) {
4027
+ spinner.stop("Failed to resolve DID");
4028
+ p.log.error(`Could not resolve DID: ${did}`);
4029
+ p.outro("Identity update cancelled.");
4030
+ process.exit(1);
4031
+ }
4032
+ const sourcePdsUrl = getPdsEndpoint(didDoc);
4033
+ if (!sourcePdsUrl) {
4034
+ spinner.stop("No PDS found in DID document");
4035
+ p.log.error("Could not find PDS endpoint in DID document");
4036
+ p.outro("Identity update cancelled.");
4037
+ process.exit(1);
4038
+ }
4039
+ const sourceDomain = getDomain(sourcePdsUrl);
4040
+ spinner.stop(`Current PDS: ${sourceDomain}`);
4041
+ const targetEndpoint = targetUrl.replace(/\/$/, "");
4042
+ const currentEndpoint = sourcePdsUrl.replace(/\/$/, "");
4043
+ spinner.start(`Checking ${targetDomain}...`);
4044
+ const targetClient = new PDSClient(targetUrl, authToken);
4045
+ if (!await targetClient.healthCheck()) {
4046
+ spinner.stop(`PDS not responding`);
4047
+ p.log.error(`Your new PDS isn't responding at ${targetUrl}`);
4048
+ if (isDev) p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
4049
+ else p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
4050
+ p.outro("Identity update cancelled.");
4051
+ process.exit(1);
4052
+ }
4053
+ spinner.stop(`New PDS is ready`);
4054
+ spinner.start("Fetching your PDS's signing key...");
4055
+ let pdsKey;
4056
+ try {
4057
+ pdsKey = await getPdsRotationKey(targetClient, targetDomain, signingKey);
4058
+ } catch (err) {
4059
+ spinner.stop("Failed to fetch signing key");
4060
+ p.log.error(err instanceof Error ? err.message : "Could not fetch credentials");
4061
+ p.outro("Identity update cancelled.");
4062
+ process.exit(1);
4063
+ }
4064
+ spinner.stop(`Signing key: ${pdsKey}`);
4065
+ const plcClient = new PlcDirectoryClient();
4066
+ spinner.start("Reading your PLC record...");
4067
+ const current = await plcClient.getLatestOperation(did).catch(() => null);
4068
+ if (!current || current.operation.type !== "plc_operation") {
4069
+ spinner.stop("Failed to read PLC record");
4070
+ p.log.error(`Could not read the current PLC operation for ${did}`);
4071
+ p.outro("Identity update cancelled.");
4072
+ process.exit(1);
4073
+ }
4074
+ const currentKeys = current.operation.rotationKeys;
4075
+ const currentHandle = current.operation.alsoKnownAs.find((uri) => uri.startsWith("at://"))?.slice(5);
4076
+ const alsoKnownAs = withHandle(current.operation.alsoKnownAs, handle);
4077
+ spinner.stop("PLC record loaded");
4078
+ if (currentEndpoint === targetEndpoint) {
4079
+ p.log.success("Your DID already points to your new PDS!");
4080
+ if (!currentKeys.includes(pdsKey)) {
4081
+ p.log.warn("Your PDS can't update your identity, because its key isn't one of your rotation keys.");
4082
+ p.log.info(`Fix this with: ${formatCommand(pm, "pds", "rotation-keys")}`);
4083
+ }
4084
+ p.log.info(`Next step: ${formatCommand(pm, "pds", "activate")}`);
4085
+ p.outro("All set!");
4086
+ return;
4087
+ }
4088
+ if (currentHandle !== handle) {
4089
+ spinner.start(`Checking ${handle} resolves to your DID...`);
4090
+ const handleCheck = await checkHandleResolutionDetailed(targetClient, handle, did);
4091
+ if (handleCheck.ok) spinner.stop(`${handle} resolves to your DID (via ${handleCheck.methods.join(", ")})`);
4092
+ else {
4093
+ spinner.stop(`${handle} doesn't resolve to your DID yet`);
4094
+ p.note(brightNote$2(handle === pdsHostname ? [
4095
+ "Your handle is your PDS hostname, so your PDS verifies it at:",
4096
+ ` https://${handle}/.well-known/atproto-did`,
4097
+ "",
4098
+ "Check the PDS is deployed on that domain."
4099
+ ] : [
4100
+ "Add a DNS TXT record:",
4101
+ ` _atproto.${handle} TXT "did=${did}"`,
4102
+ "",
4103
+ "Or serve a file at:",
4104
+ ` https://${handle}/.well-known/atproto-did`,
4105
+ ` containing: ${did}`
4106
+ ]), "Handle not verified");
4107
+ if (!await promptConfirm({
4108
+ message: "Continue anyway? Apps will show your handle as invalid until it resolves.",
4109
+ initialValue: false
4110
+ })) {
4111
+ p.outro("Identity update cancelled. Set up your handle, then run this again.");
4112
+ process.exit(0);
4113
+ }
4114
+ }
4115
+ }
4116
+ const sourceDisplayName = sourceDomain.endsWith(".bsky.network") ? "bsky.social" : sourceDomain;
4117
+ const sourcePdsClient = new SourcePdsPlcClient(sourcePdsUrl);
4118
+ let token = args.token;
4119
+ let sourcePdsKeys;
4120
+ const password = await p.password({ message: `Your password for ${sourceDisplayName}:` });
4121
+ if (p.isCancel(password)) {
4122
+ p.cancel("Identity update cancelled.");
4123
+ process.exit(0);
4124
+ }
4125
+ spinner.start(`Logging in to ${sourceDisplayName}...`);
4126
+ const sourceClient = new PDSClient(sourcePdsUrl);
4127
+ try {
4128
+ const session = await sourceClient.createSession(did, password);
4129
+ sourcePdsClient.setAuthToken(session.accessJwt);
4130
+ spinner.stop("Authenticated");
4131
+ } catch (err) {
4132
+ spinner.stop("Login failed");
4133
+ p.log.error(err instanceof Error ? err.message : "Authentication failed");
4134
+ p.outro("Identity update cancelled.");
4135
+ process.exit(1);
4136
+ }
4137
+ try {
4138
+ sourcePdsKeys = (await sourcePdsClient.getRecommendedDidCredentials()).rotationKeys;
4139
+ } catch {
4140
+ p.log.warn(`Couldn't ask ${sourceDisplayName} which rotation keys it holds.`);
4141
+ }
4142
+ let choice;
4143
+ try {
4144
+ choice = await chooseRotationKeys({
4145
+ did,
4146
+ handle,
4147
+ currentKeys,
4148
+ pdsKey,
4149
+ pdsName: targetDomain,
4150
+ sourcePdsKeys,
4151
+ sourceName: sourceDisplayName
4152
+ });
4153
+ } catch (err) {
4154
+ p.log.error(err instanceof Error ? err.message : String(err));
4155
+ p.outro("Identity update cancelled.");
4156
+ process.exit(1);
4157
+ }
4158
+ p.note(brightNote$2([
4159
+ pc.bold("Updating your identity:"),
4160
+ "",
4161
+ `${pc.dim("From:")} ${sourceDisplayName}`,
4162
+ `${pc.dim("To:")} ${targetDomain}`,
4163
+ currentHandle && currentHandle !== handle ? `${pc.dim("Handle:")} ${currentHandle} → ${handle}` : `${pc.dim("Handle:")} ${handle}`,
4164
+ "",
4165
+ ...describeRotationKeys(choice),
4166
+ "",
4167
+ pc.dim("This tells the network where to find you, and gives"),
4168
+ pc.dim("your new PDS control of your identity.")
4169
+ ]), "🔄 DID Update");
4170
+ if (!await promptConfirm({
4171
+ message: "Update your identity?",
4172
+ initialValue: true
4173
+ })) {
4174
+ p.outro("Identity update cancelled.");
4175
+ process.exit(0);
4176
+ }
4177
+ if (!token) {
4178
+ spinner.start("Requesting identity update token...");
4179
+ const signatureRequest = await sourcePdsClient.requestPlcOperationSignature();
4180
+ if (!signatureRequest.success) {
4181
+ spinner.stop("Failed to request token");
4182
+ p.log.error(signatureRequest.error ?? "Could not request PLC operation signature");
4183
+ p.outro("Identity update cancelled.");
4184
+ process.exit(1);
4185
+ }
4186
+ spinner.stop("Token requested");
4187
+ p.log.info("");
4188
+ p.log.info(pc.bold("📧 Check your email!"));
4189
+ p.log.info(`${sourceDisplayName} has sent you a confirmation code.`);
4190
+ p.log.info("");
4191
+ token = await promptText({
4192
+ message: "Enter the confirmation code from your email:",
4193
+ placeholder: "XXXXX-XXXXX",
4194
+ validate: (v) => {
4195
+ if (!v || v.trim().length < 5) return "Please enter the confirmation code";
4196
+ }
4197
+ });
4198
+ }
4199
+ spinner.start("Signing identity update...");
4200
+ const signResult = await sourcePdsClient.signPlcOperation(token.trim(), {
4201
+ rotationKeys: choice.rotationKeys,
4202
+ alsoKnownAs,
4203
+ verificationMethods: { atproto: pdsKey },
4204
+ services: { atproto_pds: {
4205
+ type: "AtprotoPersonalDataServer",
4206
+ endpoint: targetUrl
4207
+ } }
4208
+ });
4209
+ if (!signResult.success || !signResult.signedOperation) {
4210
+ spinner.stop("Failed to sign operation");
4211
+ p.log.error(signResult.error ?? "Could not sign PLC operation");
4212
+ if (signResult.error?.includes("expired")) p.log.info("Run the command again to request a new token.");
4213
+ p.outro("Identity update cancelled.");
4214
+ process.exit(1);
4215
+ }
4216
+ spinner.stop("Operation signed");
4217
+ const signed = signResult.signedOperation;
4218
+ const sameList = (a, b) => a.length === b.length && a.every((item, i) => item === b[i]);
4219
+ if (!sameList(signed.rotationKeys, choice.rotationKeys)) {
4220
+ p.log.error(`${sourceDisplayName} signed different rotation keys than requested: ${signed.rotationKeys.join(", ")}`);
4221
+ p.outro("Identity update cancelled. Nothing was submitted.");
4222
+ process.exit(1);
4223
+ }
4224
+ if (!sameList(signed.alsoKnownAs, alsoKnownAs)) {
4225
+ p.log.error(`${sourceDisplayName} signed a different handle than requested: ${signed.alsoKnownAs.join(", ")}`);
4226
+ p.outro("Identity update cancelled. Nothing was submitted.");
4227
+ process.exit(1);
4228
+ }
4229
+ spinner.start("Submitting to PLC directory...");
4230
+ const submitResult = await plcClient.submitOperation(did, signed);
4231
+ if (!submitResult.success) {
4232
+ spinner.stop("Failed to submit operation");
4233
+ p.log.error(submitResult.error ?? "PLC directory rejected the operation");
4234
+ p.outro("Identity update cancelled.");
4235
+ process.exit(1);
4236
+ }
4237
+ spinner.stop("Identity updated!");
4238
+ spinner.start("Verifying update...");
4239
+ await new Promise((resolve$1) => setTimeout(resolve$1, 1e3));
4240
+ const newDidDoc = await new DidResolver().resolve(did);
4241
+ const newPdsEndpoint = newDidDoc ? getPdsEndpoint(newDidDoc) : null;
4242
+ const keyMismatch = await checkRotationKeys(plcClient, did, choice.rotationKeys).catch(() => void 0);
4243
+ if (newPdsEndpoint?.replace(/\/$/, "") === targetEndpoint && !keyMismatch) spinner.stop("Verified! DID now points to new PDS");
4244
+ else {
4245
+ spinner.stop("Update submitted (verification pending)");
4246
+ p.log.warn("It may take a moment for the update to propagate.");
4247
+ if (keyMismatch) {
4248
+ p.log.warn(`plc.directory lists these rotation keys: ${keyMismatch.join(", ") || "none"}`);
4249
+ p.log.info(`Check them with: ${formatCommand(pm, "pds", "rotation-keys")}`);
4250
+ }
4251
+ }
4252
+ p.log.success("Your identity now points to your new PDS!");
4253
+ 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.");
4254
+ p.note(brightNote$2([
4255
+ pc.bold("Final step:"),
4256
+ "",
4257
+ `Run: ${formatCommand(pm, "pds", "activate")}`,
4258
+ "",
4259
+ "This enables writes and notifies the network."
4260
+ ]), "Almost done!");
4261
+ p.outro("Identity updated! 🎉");
4262
+ }
4263
+ });
4264
+
4265
+ //#endregion
4266
+ //#region src/cli/commands/rotation-keys.ts
4267
+ /**
4268
+ * Rotation keys command - review and fix who can update a did:plc identity
4269
+ *
4270
+ * Accounts migrated before `pds identity` set rotation keys still have the
4271
+ * previous PDS's key and not this PDS's. This command shows the current
4272
+ * keys and rewrites them as: keys the user holds, then this PDS's key. The
4273
+ * change is signed by whichever key can: this PDS (if it is already a
4274
+ * rotation key), the previous PDS (with its password and an email code), or
4275
+ * a rotation key the user pastes in.
4276
+ */
4277
+ const brightNote$1 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
4278
+ function cancel(message) {
4279
+ p.log.error(message);
4280
+ p.outro("Rotation keys unchanged.");
4281
+ process.exit(1);
4282
+ }
4283
+ function displayName(url) {
4284
+ const domain = getDomain(url);
4285
+ return domain.endsWith(".bsky.network") ? "bsky.social" : domain;
4286
+ }
4287
+ const rotationKeysCommand = defineCommand({
4288
+ meta: {
4289
+ name: "rotation-keys",
4290
+ description: "Review your DID's rotation keys and make sure your PDS can update your identity"
4291
+ },
4292
+ args: { dev: {
4293
+ type: "boolean",
4294
+ description: "Target local development server instead of production",
4295
+ default: false
4296
+ } },
4297
+ async run({ args }) {
4298
+ const pm = detectPackageManager();
4299
+ const isDev = args.dev;
4300
+ p.intro("🔑 Rotation Keys");
4301
+ const spinner = p.spinner();
4302
+ const config = {
4303
+ ...readDevVars(),
4304
+ ...getVars()
4305
+ };
4306
+ const did = config.DID;
4307
+ const handle = config.HANDLE;
4308
+ const authToken = config.AUTH_TOKEN;
4309
+ if (!did || !handle || !authToken) cancel("DID, HANDLE and AUTH_TOKEN must be configured. Run 'pds init' first.");
4310
+ if (!did.startsWith("did:plc:")) {
4311
+ p.log.info("did:web identities have no rotation keys. Whoever controls the domain controls the identity.");
4312
+ p.outro("Nothing to do.");
4313
+ return;
4314
+ }
4315
+ let targetUrl;
4316
+ try {
4317
+ targetUrl = getTargetUrl(isDev, config.PDS_HOSTNAME);
4318
+ } catch (err) {
4319
+ cancel(err instanceof Error ? err.message : "Configuration error");
4320
+ }
4321
+ const targetDomain = getDomain(targetUrl);
4322
+ const targetEndpoint = targetUrl.replace(/\/$/, "");
4323
+ const pdsClient = new PDSClient(targetUrl, authToken);
4324
+ spinner.start(`Checking ${targetDomain}...`);
4325
+ let pdsKey;
4326
+ try {
4327
+ pdsKey = await getPdsRotationKey(pdsClient, targetDomain, config.SIGNING_KEY);
4328
+ } catch (err) {
4329
+ spinner.stop("Failed to fetch signing key");
4330
+ cancel(err instanceof Error ? err.message : `Could not reach ${targetDomain}. Is it deployed?`);
4331
+ }
4332
+ spinner.stop(`${targetDomain} signs with ${pdsKey}`);
4333
+ const plcClient = new PlcDirectoryClient();
4334
+ spinner.start("Reading your PLC record...");
4335
+ const log = await plcClient.getAuditLog(did).catch(() => null);
4336
+ const current = log?.filter((entry) => !entry.nullified).pop();
4337
+ if (!log || !current || current.operation.type !== "plc_operation") {
4338
+ spinner.stop("Failed to read PLC record");
4339
+ cancel(`Could not read the current PLC operation for ${did}`);
4340
+ }
4341
+ spinner.stop("PLC record loaded");
4342
+ const operation = current.operation;
4343
+ const currentEndpoint = operation.services.atproto_pds?.endpoint?.replace(/\/$/, "");
4344
+ if (currentEndpoint !== targetEndpoint) cancel(`Your DID points to ${currentEndpoint ?? "no PDS"}, not ${targetDomain}. Run '${formatCommand(pm, "pds", "identity")}' to move your identity here first.`);
4345
+ const labelled = labelRotationKeys(operation.rotationKeys, { pdsKey });
4346
+ const pdsCanSign = operation.rotationKeys.includes(pdsKey);
4347
+ p.note(brightNote$1([
4348
+ pc.bold("Current rotation keys, highest priority first:"),
4349
+ ...labelled.map(({ key, owner }, i) => ` ${i + 1}. ${key}${owner === "this-pds" ? pc.dim(` (${targetDomain})`) : ""}`),
4350
+ "",
4351
+ pdsCanSign ? `${pc.green("✓")} ${targetDomain} can update your identity.` : `${pc.red("✗")} ${targetDomain} can't update your identity, because its key isn't listed.`
4352
+ ]), "Your identity");
4353
+ let signer;
4354
+ if (pdsCanSign) signer = "pds";
4355
+ else signer = await promptSelect({
4356
+ message: "Who should sign the change? It needs one of the keys above.",
4357
+ options: [{
4358
+ value: "previous",
4359
+ label: "My previous PDS",
4360
+ hint: "needs its password and an email code"
4361
+ }, {
4362
+ value: "key",
4363
+ label: "A rotation key I hold",
4364
+ hint: "such as a recovery key"
4365
+ }]
4366
+ });
4367
+ let sourcePdsClient;
4368
+ let sourceName;
4369
+ let sourcePdsKeys;
4370
+ let signingKeypair;
4371
+ if (signer === "previous") {
4372
+ const sourceUrl = await promptText({
4373
+ message: "Your previous PDS:",
4374
+ initialValue: findPreviousPdsEndpoint(log, targetEndpoint) ?? "https://bsky.social",
4375
+ validate: (v) => v && /^https?:\/\//.test(v.trim()) ? void 0 : "Enter a URL, such as https://bsky.social"
4376
+ });
4377
+ sourceName = displayName(sourceUrl.trim());
4378
+ sourcePdsClient = new SourcePdsPlcClient(sourceUrl.trim());
4379
+ const password = await p.password({ message: `Your password for ${sourceName}:` });
4380
+ if (p.isCancel(password)) {
4381
+ p.cancel("Rotation keys unchanged.");
4382
+ process.exit(0);
4383
+ }
4384
+ spinner.start(`Logging in to ${sourceName}...`);
4385
+ try {
4386
+ const session = await new PDSClient(sourceUrl.trim()).createSession(did, password);
4387
+ sourcePdsClient.setAuthToken(session.accessJwt);
4388
+ spinner.stop("Authenticated");
4389
+ } catch (err) {
4390
+ spinner.stop("Login failed");
4391
+ cancel(err instanceof Error ? err.message : "Authentication failed");
4392
+ }
4393
+ try {
4394
+ sourcePdsKeys = (await sourcePdsClient.getRecommendedDidCredentials()).rotationKeys;
4395
+ } catch {
4396
+ p.log.warn(`Couldn't ask ${sourceName} which rotation keys it holds.`);
4397
+ }
4398
+ 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.`);
4399
+ } else if (signer === "key") {
4400
+ const secret = await p.password({ message: "Paste the private key (multibase or hex):" });
4401
+ if (p.isCancel(secret)) {
4402
+ p.cancel("Rotation keys unchanged.");
4403
+ process.exit(0);
4404
+ }
4405
+ try {
4406
+ signingKeypair = await importRotationKey(secret);
4407
+ } catch (err) {
4408
+ cancel(err instanceof Error ? err.message : "Could not read key");
4409
+ }
4410
+ 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.`);
4411
+ p.log.success(`Signing with ${signingKeypair.did()}`);
4412
+ }
4413
+ let choice;
4414
+ try {
4415
+ choice = await chooseRotationKeys({
4416
+ did,
4417
+ handle,
4418
+ currentKeys: operation.rotationKeys,
4419
+ pdsKey,
4420
+ pdsName: targetDomain,
4421
+ sourcePdsKeys,
4422
+ sourceName,
4423
+ heldKeys: signingKeypair ? [signingKeypair.did()] : []
4424
+ });
4425
+ } catch (err) {
4426
+ cancel(err instanceof Error ? err.message : String(err));
4427
+ }
4428
+ if (choice.rotationKeys.length === operation.rotationKeys.length && choice.rotationKeys.every((key, i) => key === operation.rotationKeys[i])) {
4429
+ p.outro("Your rotation keys are already set up. Nothing to change.");
4430
+ return;
4431
+ }
4432
+ p.note(brightNote$1(describeRotationKeys(choice)), "🔄 New rotation keys");
4433
+ if (!await promptConfirm({
4434
+ message: "Update your rotation keys?",
4435
+ initialValue: true
4436
+ })) {
4437
+ p.outro("Rotation keys unchanged.");
4438
+ process.exit(0);
4439
+ }
4440
+ let signed;
4441
+ if (signer === "pds") {
4442
+ spinner.start(`Asking ${targetDomain} to sign...`);
4443
+ try {
4444
+ const { token, error } = await pdsClient.getMigrationToken();
4445
+ if (!token) throw new Error(error ?? "Could not get a token");
4446
+ signed = await pdsClient.signPlcOperation(token, { rotationKeys: choice.rotationKeys });
4447
+ } catch (err) {
4448
+ spinner.stop("Signing failed");
4449
+ cancel(err instanceof Error ? err.message : "Could not sign");
4450
+ }
4451
+ spinner.stop("Operation signed");
4452
+ } else if (signer === "previous") {
4453
+ spinner.start("Requesting a confirmation code...");
4454
+ const request = await sourcePdsClient.requestPlcOperationSignature();
4455
+ if (!request.success) {
4456
+ spinner.stop("Failed to request code");
4457
+ cancel(request.error ?? "Could not request a confirmation code");
4458
+ }
4459
+ spinner.stop(`${sourceName} has emailed you a confirmation code`);
4460
+ const token = await promptText({
4461
+ message: "Enter the confirmation code from your email:",
4462
+ placeholder: "XXXXX-XXXXX",
4463
+ validate: (v) => !v || v.trim().length < 5 ? "Please enter the confirmation code" : void 0
4464
+ });
4465
+ spinner.start(`Asking ${sourceName} to sign...`);
4466
+ const result = await sourcePdsClient.signPlcOperation(token.trim(), { rotationKeys: choice.rotationKeys });
4467
+ if (!result.success || !result.signedOperation) {
4468
+ spinner.stop("Signing failed");
4469
+ cancel(result.error ?? "Could not sign PLC operation");
4470
+ }
4471
+ signed = result.signedOperation;
4472
+ spinner.stop("Operation signed");
4473
+ } else signed = await signOperation({
4474
+ type: "plc_operation",
4475
+ prev: current.cid,
4476
+ rotationKeys: choice.rotationKeys,
4477
+ verificationMethods: operation.verificationMethods,
4478
+ alsoKnownAs: operation.alsoKnownAs,
4479
+ services: operation.services
4480
+ }, signingKeypair);
4481
+ 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.");
4482
+ spinner.start("Submitting to PLC directory...");
4483
+ const submitted = await plcClient.submitOperation(did, signed);
4484
+ if (!submitted.success) {
4485
+ spinner.stop("Failed to submit operation");
4486
+ cancel(submitted.error ?? "PLC directory rejected the operation");
4487
+ }
4488
+ spinner.stop("Submitted");
4489
+ const mismatch = await checkRotationKeys(plcClient, did, choice.rotationKeys).catch(() => void 0);
4490
+ if (mismatch) p.log.warn(`plc.directory lists these rotation keys: ${mismatch.join(", ") || "none"}`);
4491
+ else if (mismatch === null) p.log.success(`${targetDomain} can now update your identity.`);
4492
+ 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.");
4493
+ p.outro("Rotation keys updated! 🔑");
4494
+ }
4495
+ });
4496
+
3767
4497
  //#endregion
3768
4498
  //#region src/cli/commands/activate.ts
3769
4499
  /**
@@ -3818,7 +4548,7 @@ async function promptCreateProfile(client, did, handle) {
3818
4548
  process.exit(0);
3819
4549
  }
3820
4550
  if (createProfile) {
3821
- const displayName = await promptText({
4551
+ const displayName$1 = await promptText({
3822
4552
  message: "Display name:",
3823
4553
  placeholder: handle || "Your Name",
3824
4554
  validate: (v) => {
@@ -3835,7 +4565,7 @@ async function promptCreateProfile(client, did, handle) {
3835
4565
  spinner.start("Creating profile...");
3836
4566
  try {
3837
4567
  await client.putProfile(did, {
3838
- displayName: displayName || void 0,
4568
+ displayName: displayName$1 || void 0,
3839
4569
  description: description || void 0
3840
4570
  });
3841
4571
  spinner.stop("Profile created!");
@@ -4267,8 +4997,25 @@ const statusCommand$1 = defineCommand({
4267
4997
  if (handle) console.log(` ${INFO} Handle: ${pc.cyan(`@${handle}`)}`);
4268
4998
  if (did) {
4269
4999
  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) {
5000
+ if (didCheck.ok) {
5001
+ console.log(` ${CHECK} DID resolves to this PDS (via ${didCheck.resolveMethod})`);
5002
+ if (did.startsWith("did:plc:")) {
5003
+ const keys = await checkPlcRotationKeys(client, did);
5004
+ if (!keys) {
5005
+ console.log(` ${WARN} Could not check rotation keys`);
5006
+ hasWarnings = true;
5007
+ } else if (!keys.pdsCanSign) {
5008
+ console.log(` ${CROSS} This PDS can't update your identity (its key isn't a rotation key)`);
5009
+ console.log(pc.dim(" Fix with: pds rotation-keys"));
5010
+ hasErrors = true;
5011
+ } else if (keys.otherKeys === 0) {
5012
+ console.log(` ${CHECK} This PDS can update your identity`);
5013
+ console.log(` ${WARN} No recovery key: your PDS is your only rotation key`);
5014
+ console.log(pc.dim(" Add one with: pds rotation-keys"));
5015
+ hasWarnings = true;
5016
+ } else console.log(` ${CHECK} This PDS can update your identity, with ${keys.otherKeys} other rotation ${keys.otherKeys === 1 ? "key" : "keys"}`);
5017
+ }
5018
+ } else if (didCheck.pdsEndpoint) {
4272
5019
  console.log(` ${CROSS} DID resolves to different PDS`);
4273
5020
  console.log(pc.dim(` Resolved via: ${didCheck.resolveMethod}`));
4274
5021
  console.log(pc.dim(` Expected: https://${pdsHostname}`));
@@ -5075,15 +5822,16 @@ async function xrpc(ctx, method, nsid, options = {}) {
5075
5822
  ...options.body !== void 0 ? { body: JSON.stringify(options.body) } : {}
5076
5823
  });
5077
5824
  if (!res.ok) {
5078
- const text = await res.text();
5079
- let message = text;
5825
+ const text$1 = await res.text();
5826
+ let message = text$1;
5080
5827
  try {
5081
- const parsed = JSON.parse(text);
5082
- message = parsed.error ? `${parsed.error}: ${parsed.message ?? ""}` : text;
5828
+ const parsed = JSON.parse(text$1);
5829
+ message = parsed.error ? `${parsed.error}: ${parsed.message ?? ""}` : text$1;
5083
5830
  } catch {}
5084
5831
  throw new Error(`${nsid} failed (${res.status}): ${message}`);
5085
5832
  }
5086
- return await res.json();
5833
+ const text = await res.text();
5834
+ return text ? JSON.parse(text) : {};
5087
5835
  }
5088
5836
  const devArg = { dev: {
5089
5837
  type: "boolean",
@@ -5105,6 +5853,7 @@ const listCommand = defineCommand({
5105
5853
  for (const space of status.spaces) {
5106
5854
  const flags = [
5107
5855
  space.role,
5856
+ space.policy ? space.policy.replace(/^com\.atproto\.|\.policy$/g, "") : null,
5108
5857
  space.state !== "active" ? pc.yellow(space.state) : null,
5109
5858
  space.outdated ? pc.red("outdated") : null
5110
5859
  ].filter(Boolean).join(", ");
@@ -5120,7 +5869,8 @@ const statusCommand = defineCommand({
5120
5869
  },
5121
5870
  args: { ...devArg },
5122
5871
  async run({ args }) {
5123
- const status = await xrpc(loadContext(args.dev), "GET", "gg.mk.experimental.getSpacesStatus");
5872
+ const ctx = loadContext(args.dev);
5873
+ const status = await xrpc(ctx, "GET", "gg.mk.experimental.getSpacesStatus");
5124
5874
  console.log();
5125
5875
  console.log(pc.bold("Spaces status"));
5126
5876
  console.log(` flag: ${status.enabled ? pc.green("enabled") : pc.yellow("disabled")}`);
@@ -5128,8 +5878,28 @@ const statusCommand = defineCommand({
5128
5878
  console.log(` spaces: ${status.stats.active} active (${status.stats.hosted} hosted), ${status.stats.pending} pending, ${status.stats.deleted} deleted`);
5129
5879
  const outdated = status.spaces.filter((s) => s.outdated);
5130
5880
  if (outdated.length > 0) console.log(pc.red(` ${outdated.length} space(s) hold data from an incompatible alpha build. Run 'pds spaces reset'.`));
5881
+ await reportKem(ctx, status.kem);
5131
5882
  }
5132
5883
  });
5884
+ /**
5885
+ * Check that the deployed `#atproto_kem` key is the one the DID document
5886
+ * publishes: syncers derive MAC secrets against the published key, so a
5887
+ * mismatch fails every credentialed read that returns a commit or record.
5888
+ */
5889
+ async function reportKem(ctx, kem) {
5890
+ if (!kem?.configured) {
5891
+ console.log(pc.yellow(" kem key: not configured — syncers cannot verify space data. Run 'pds spaces kem'."));
5892
+ return;
5893
+ }
5894
+ let published;
5895
+ try {
5896
+ const method = ((await new DidResolver().resolve(ctx.did, { forceRefresh: true }))?.verificationMethod ?? []).find((m) => m.id.endsWith("#atproto_kem"));
5897
+ published = method?.publicKeyMultibase ? `did:key:${method.publicKeyMultibase}` : void 0;
5898
+ } catch {}
5899
+ if (!kem.didKey) console.log(pc.yellow(" kem key: secret set, but SPACES_KEM_KEY_PUBLIC is missing. Re-run 'pds spaces kem'."));
5900
+ else if (published === kem.didKey) console.log(` kem key: ${pc.green("published")} ${pc.dim(kem.didKey)}`);
5901
+ 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."}`));
5902
+ }
5133
5903
  const createCommand = defineCommand({
5134
5904
  meta: {
5135
5905
  name: "create",
@@ -5148,37 +5918,77 @@ const createCommand = defineCommand({
5148
5918
  },
5149
5919
  policy: {
5150
5920
  type: "string",
5151
- description: "User policy: public | member-list | managing-app",
5152
- default: "member-list"
5921
+ description: "Policy: personal | member | managed",
5922
+ default: "member"
5923
+ },
5924
+ "public-read": {
5925
+ type: "boolean",
5926
+ description: "member: anyone may read, with or without a delegation token",
5927
+ default: false
5928
+ },
5929
+ "public-write": {
5930
+ type: "boolean",
5931
+ description: "member: track anyone's writes, not only members'",
5932
+ default: false
5153
5933
  },
5154
5934
  "managing-app": {
5155
5935
  type: "string",
5156
- description: "Managing app service identifier (managing-app policy)"
5936
+ description: "managed: the managing app's did#serviceId reference (e.g. did:web:app.example#forum)"
5157
5937
  },
5158
5938
  allow: {
5159
5939
  type: "string",
5160
- description: "Allowed OAuth client ID (repeatable); sets the allowList app policy"
5940
+ description: "member: allowed OAuth client ID (repeatable); only these apps may read"
5941
+ },
5942
+ "publish-policy": {
5943
+ type: "boolean",
5944
+ description: "Publish the policy to readers as a record in your repo",
5945
+ default: false
5946
+ },
5947
+ "publish-members": {
5948
+ type: "boolean",
5949
+ description: "member: publish the member list to readers",
5950
+ default: false
5161
5951
  }
5162
5952
  },
5163
5953
  async run({ args }) {
5164
5954
  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,
5955
+ const allowed = args.allow ? Array.isArray(args.allow) ? args.allow : [args.allow] : void 0;
5956
+ let policy;
5957
+ switch (args.policy) {
5958
+ case "personal":
5959
+ policy = { $type: "com.atproto.personalspace.policy" };
5960
+ break;
5961
+ case "managed":
5962
+ if (!args["managing-app"]) {
5963
+ console.error(pc.red("Error:"), "--managing-app is required");
5964
+ process.exit(1);
5965
+ }
5966
+ policy = {
5967
+ $type: "com.atproto.managedspace.policy",
5968
+ managingApp: args["managing-app"],
5969
+ publishPolicy: args["publish-policy"]
5970
+ };
5971
+ break;
5972
+ case "member":
5973
+ policy = {
5974
+ $type: "com.atproto.memberspace.policy",
5975
+ publicRead: args["public-read"],
5976
+ publicWrite: args["public-write"],
5977
+ ...allowed ? { allowedApps: allowed } : {},
5978
+ publishPolicy: args["publish-policy"],
5979
+ publishMembers: args["publish-members"]
5980
+ };
5981
+ break;
5982
+ default:
5983
+ console.error(pc.red("Error:"), `Unknown policy '${args.policy}' (personal | member | managed)`);
5984
+ process.exit(1);
5985
+ }
5986
+ const result = await xrpc(ctx, "POST", "com.atproto.space.createSpace", { body: {
5987
+ spaceType: args.type,
5177
5988
  ...args.skey ? { skey: args.skey } : {},
5178
- policy,
5179
- appAccess
5989
+ policy
5180
5990
  } });
5181
- console.log(pc.green("Created:"), result.uri);
5991
+ console.log(pc.green("Created:"), result.space);
5182
5992
  }
5183
5993
  });
5184
5994
  const deleteCommand = defineCommand({
@@ -5212,7 +6022,7 @@ const deleteCommand = defineCommand({
5212
6022
  return;
5213
6023
  }
5214
6024
  }
5215
- await xrpc(ctx, "POST", "com.atproto.simplespace.deleteSpace", { body: { space: args.space } });
6025
+ await xrpc(ctx, "POST", "com.atproto.space.deleteSpace", { body: { space: args.space } });
5216
6026
  console.log(pc.green("Deleted:"), args.space);
5217
6027
  }
5218
6028
  });
@@ -5225,7 +6035,7 @@ const membersCommand = defineCommand({
5225
6035
  add: defineCommand({
5226
6036
  meta: {
5227
6037
  name: "add",
5228
- description: "Add a member"
6038
+ description: "Add a member, or replace their access"
5229
6039
  },
5230
6040
  args: {
5231
6041
  ...devArg,
@@ -5238,14 +6048,28 @@ const membersCommand = defineCommand({
5238
6048
  type: "positional",
5239
6049
  description: "Member DID",
5240
6050
  required: true
6051
+ },
6052
+ read: {
6053
+ type: "boolean",
6054
+ description: "May read (use --no-read to deny)",
6055
+ default: true
6056
+ },
6057
+ write: {
6058
+ type: "boolean",
6059
+ description: "Writes are tracked (use --no-write to deny)",
6060
+ default: true
5241
6061
  }
5242
6062
  },
5243
6063
  async run({ args }) {
5244
- await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.simplespace.addMember", { body: {
6064
+ await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.memberspace.putMembers", { body: {
5245
6065
  space: args.space,
5246
- did: args.did
6066
+ members: [{
6067
+ did: args.did,
6068
+ read: args.read,
6069
+ write: args.write
6070
+ }]
5247
6071
  } });
5248
- console.log(pc.green("Added:"), args.did);
6072
+ console.log(pc.green("Added:"), args.did, pc.dim(`(read: ${args.read}, write: ${args.write})`));
5249
6073
  }
5250
6074
  }),
5251
6075
  remove: defineCommand({
@@ -5267,9 +6091,9 @@ const membersCommand = defineCommand({
5267
6091
  }
5268
6092
  },
5269
6093
  async run({ args }) {
5270
- await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.simplespace.removeMember", { body: {
6094
+ await xrpc(loadContext(Boolean(args.dev)), "POST", "com.atproto.memberspace.removeMembers", { body: {
5271
6095
  space: args.space,
5272
- did: args.did
6096
+ dids: [args.did]
5273
6097
  } });
5274
6098
  console.log(pc.green("Removed:"), args.did);
5275
6099
  }
@@ -5288,7 +6112,7 @@ const membersCommand = defineCommand({
5288
6112
  }
5289
6113
  },
5290
6114
  async run({ args }) {
5291
- const result = await xrpc(loadContext(Boolean(args.dev)), "GET", "com.atproto.simplespace.listMembers", { params: {
6115
+ const result = await xrpc(loadContext(Boolean(args.dev)), "GET", "com.atproto.memberspace.listMembers", { params: {
5292
6116
  space: String(args.space),
5293
6117
  limit: "1000"
5294
6118
  } });
@@ -5296,7 +6120,10 @@ const membersCommand = defineCommand({
5296
6120
  console.log(pc.dim("No members."));
5297
6121
  return;
5298
6122
  }
5299
- for (const member of result.members) console.log(member.did);
6123
+ for (const member of result.members) {
6124
+ const access = [member.read ? "read" : null, member.write ? "write" : null].filter(Boolean).join(", ");
6125
+ console.log(`${member.did} ${pc.dim(`(${access || "no access"})`)}`);
6126
+ }
5300
6127
  }
5301
6128
  })
5302
6129
  }
@@ -5304,7 +6131,7 @@ const membersCommand = defineCommand({
5304
6131
  const exportCommand = defineCommand({
5305
6132
  meta: {
5306
6133
  name: "export",
5307
- description: "Export every space repo as a CAR file"
6134
+ description: "Export every space repo as a STAR archive, plus the host-side state of hosted spaces"
5308
6135
  },
5309
6136
  args: {
5310
6137
  ...devArg,
@@ -5316,26 +6143,129 @@ const exportCommand = defineCommand({
5316
6143
  },
5317
6144
  async run({ args }) {
5318
6145
  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);
6146
+ const exportable = (await xrpc(ctx, "GET", "gg.mk.experimental.getSpacesStatus")).spaces.filter((space) => space.state === "active" && !space.outdated);
5320
6147
  if (exportable.length === 0) {
5321
6148
  console.log(pc.dim("Nothing to export."));
5322
6149
  return;
5323
6150
  }
5324
6151
  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);
6152
+ const download = async (nsid, params, filename, label) => {
6153
+ const url = new URL(`${ctx.baseUrl}/xrpc/${nsid}`);
6154
+ for (const [key, value] of Object.entries(params)) url.searchParams.set(key, value);
5329
6155
  const res = await fetch(url, { headers: { Authorization: `Bearer ${ctx.authToken}` } });
5330
6156
  if (!res.ok) {
5331
- console.log(pc.red("✗"), `${space.uri}: export failed (${res.status})`);
5332
- continue;
6157
+ console.log(pc.red("✗"), `${label}: export failed (${res.status})`);
6158
+ return;
5333
6159
  }
5334
6160
  const bytes = new Uint8Array(await res.arrayBuffer());
5335
- const filename = `${space.uri.replace("at://", "").replace(/[^a-zA-Z0-9._-]+/g, "_")}.car`;
5336
6161
  writeFileSync(join(args.out, filename), bytes);
5337
- console.log(pc.green("✓"), `${space.uri} → ${filename} (${bytes.length} bytes)`);
6162
+ console.log(pc.green("✓"), `${label} → ${filename} (${bytes.length} bytes)`);
6163
+ };
6164
+ for (const space of exportable) {
6165
+ const base = space.uri.replace(/^at:space\//, "").replace(/[^a-zA-Z0-9._-]+/g, "_");
6166
+ if (space.role === "authority") await download("com.atproto.space.exportSpaceMeta", { space: space.uri }, `${base}.meta.star`, `${space.uri} (space)`);
6167
+ if (space.recordCount > 0) await download("com.atproto.space.getRepo", {
6168
+ space: space.uri,
6169
+ repo: ctx.did
6170
+ }, `${base}.star`, `${space.uri} (repo)`);
6171
+ }
6172
+ }
6173
+ });
6174
+ const kemCommand = defineCommand({
6175
+ meta: {
6176
+ name: "kem",
6177
+ description: "Generate the #atproto_kem key syncers verify space data against, and publish it"
6178
+ },
6179
+ args: {
6180
+ ...devArg,
6181
+ local: {
6182
+ type: "boolean",
6183
+ description: "Write to .dev.vars instead of wrangler secrets/config",
6184
+ default: false
6185
+ },
6186
+ publish: {
6187
+ type: "boolean",
6188
+ description: "did:plc: add the key to your DID document via a PLC operation signed by this PDS",
6189
+ default: false
6190
+ }
6191
+ },
6192
+ async run({ args }) {
6193
+ p.intro("Spaces KEM key");
6194
+ const config = {
6195
+ ...readDevVars(),
6196
+ ...getVars()
6197
+ };
6198
+ const did = config.DID;
6199
+ if (!did) {
6200
+ p.log.error("No DID configured. Run 'pds init' first.");
6201
+ process.exit(1);
6202
+ }
6203
+ let publicKey = config.SPACES_KEM_KEY_PUBLIC;
6204
+ if (publicKey && !args.publish) {
6205
+ const replace = await p.confirm({
6206
+ message: "A KEM key is already configured. Replace it? Syncers holding the old key will fail to verify until the DID document is updated.",
6207
+ initialValue: false
6208
+ });
6209
+ if (p.isCancel(replace) || !replace) {
6210
+ p.cancel("Kept the existing key.");
6211
+ return;
6212
+ }
6213
+ }
6214
+ if (!publicKey || !args.publish) {
6215
+ const keypair = await generateKemKeypair();
6216
+ await setSecretValue("SPACES_KEM_KEY", keypair.privateKey, args.local);
6217
+ setPublicVar("SPACES_KEM_KEY_PUBLIC", keypair.publicKey, args.local);
6218
+ publicKey = keypair.publicKey;
6219
+ p.log.success(`Generated did:key:${publicKey}`);
6220
+ }
6221
+ const didKey = `did:key:${publicKey}`;
6222
+ if (did.startsWith("did:web:")) {
6223
+ p.outro("did:web: the DID document is served by your PDS, so it publishes #atproto_kem once you redeploy.");
6224
+ return;
6225
+ }
6226
+ if (!args.publish) {
6227
+ p.note([
6228
+ "Your DID is a did:plc, so the key must be added to its PLC document",
6229
+ "as the `atproto_kem` verification method. Redeploy, then run:",
6230
+ "",
6231
+ " pds spaces kem --publish",
6232
+ "",
6233
+ "That asks your PDS to sign the PLC operation, which works when its",
6234
+ "signing key is one of your DID's rotation keys. If it isn't, run",
6235
+ "'pds rotation-keys' first, or add it with whoever holds your rotation key."
6236
+ ].join("\n"), "Publish the key");
6237
+ p.outro("Done.");
6238
+ return;
6239
+ }
6240
+ const ctx = loadContext(args.dev);
6241
+ const spinner = p.spinner();
6242
+ spinner.start("Fetching the current PLC operation...");
6243
+ const current = (await new PlcDirectoryClient().getAuditLog(did)).filter((entry) => !entry.nullified).pop();
6244
+ if (!current || current.operation.type !== "plc_operation") {
6245
+ spinner.stop("Could not read a current PLC operation for this DID");
6246
+ process.exit(1);
6247
+ }
6248
+ const verificationMethods = {
6249
+ ...current.operation.verificationMethods,
6250
+ atproto_kem: didKey
6251
+ };
6252
+ spinner.message("Signing the PLC operation...");
6253
+ const { token } = await xrpc(ctx, "GET", "gg.mk.experimental.getMigrationToken");
6254
+ const { operation } = await xrpc(ctx, "POST", "com.atproto.identity.signPlcOperation", { body: {
6255
+ token,
6256
+ verificationMethods
6257
+ } });
6258
+ spinner.message("Submitting to the PLC directory...");
6259
+ try {
6260
+ await xrpc(ctx, "POST", "com.atproto.identity.submitPlcOperation", { body: { operation } });
6261
+ } catch (err) {
6262
+ spinner.stop("The PLC directory refused the operation");
6263
+ p.log.error(err instanceof Error ? err.message : String(err));
6264
+ 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.");
6265
+ process.exit(1);
5338
6266
  }
6267
+ spinner.stop("Published #atproto_kem");
6268
+ p.outro(didKey);
5339
6269
  }
5340
6270
  });
5341
6271
  const resetCommand = defineCommand({
@@ -5388,6 +6318,7 @@ const spacesCommand = defineCommand({
5388
6318
  delete: deleteCommand,
5389
6319
  members: membersCommand,
5390
6320
  export: exportCommand,
6321
+ kem: kemCommand,
5391
6322
  reset: resetCommand
5392
6323
  }
5393
6324
  });
@@ -5411,6 +6342,7 @@ runMain(defineCommand({
5411
6342
  migrate: migrateCommand,
5412
6343
  "migrate-token": migrateTokenCommand,
5413
6344
  identity: identityCommand,
6345
+ "rotation-keys": rotationKeysCommand,
5414
6346
  activate: activateCommand,
5415
6347
  deactivate: deactivateCommand,
5416
6348
  status: statusCommand$1,