@getcirrus/pds 0.20.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.
Files changed (3) hide show
  1. package/dist/cli.js +631 -596
  2. package/dist/index.js +1 -1
  3. package/package.json +2 -2
package/dist/cli.js CHANGED
@@ -5,8 +5,8 @@ import { randomBytes } from "node:crypto";
5
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";
@@ -15,9 +15,9 @@ import { Client, ClientResponseError, ok } from "@atcute/client";
15
15
  import "@atcute/bluesky";
16
16
  import "@atcute/atproto";
17
17
  import { CompositeDidDocumentResolver, CompositeHandleResolver, DohJsonHandleResolver, PlcDidDocumentResolver, WebDidDocumentResolver, WellKnownHandleResolver } from "@atcute/identity-resolver";
18
- import { getPdsEndpoint } from "@atcute/identity";
19
18
  import { encode } from "@atcute/cbor";
20
19
  import { base64url } from "jose";
20
+ import { getPdsEndpoint } from "@atcute/identity";
21
21
  import { decodeAll } from "@atproto/lex-cbor";
22
22
 
23
23
  //#region src/cli/utils/wrangler.ts
@@ -81,20 +81,27 @@ function runWrangler(args, options = {}) {
81
81
  });
82
82
  }
83
83
  /**
84
- * Set a var in wrangler.jsonc using experimental_patchConfig
84
+ * Patch the wrangler config, keeping the file's trailing newline as it was.
85
85
  */
86
- function setVar(name, value) {
86
+ function patchConfig(patch) {
87
87
  const { configPath } = experimental_readRawConfig({});
88
88
  if (!configPath) throw new Error("No wrangler config found");
89
- 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 } });
90
99
  }
91
100
  /**
92
101
  * Set multiple vars in wrangler.jsonc
93
102
  */
94
103
  function setVars(vars) {
95
- const { configPath } = experimental_readRawConfig({});
96
- if (!configPath) throw new Error("No wrangler config found");
97
- experimental_patchConfig(configPath, { vars });
104
+ patchConfig({ vars });
98
105
  }
99
106
  /**
100
107
  * Get current vars from wrangler config
@@ -114,9 +121,7 @@ function getWorkerName() {
114
121
  * Set worker name in wrangler config
115
122
  */
116
123
  function setWorkerName(name) {
117
- const { configPath } = experimental_readRawConfig({});
118
- if (!configPath) throw new Error("No wrangler config found");
119
- experimental_patchConfig(configPath, { name });
124
+ patchConfig({ name });
120
125
  }
121
126
  /**
122
127
  * Set a secret using wrangler secret put
@@ -142,17 +147,13 @@ function getAccountId() {
142
147
  * Set account_id in wrangler config
143
148
  */
144
149
  function setAccountId(accountId) {
145
- const { configPath } = experimental_readRawConfig({});
146
- if (!configPath) throw new Error("No wrangler config found");
147
- experimental_patchConfig(configPath, { account_id: accountId });
150
+ patchConfig({ account_id: accountId });
148
151
  }
149
152
  /**
150
153
  * Set custom domain routes in wrangler config
151
154
  */
152
155
  function setCustomDomains(domains) {
153
- const { configPath } = experimental_readRawConfig({});
154
- if (!configPath) throw new Error("No wrangler config found");
155
- experimental_patchConfig(configPath, { routes: domains.map((pattern) => ({
156
+ patchConfig({ routes: domains.map((pattern) => ({
156
157
  pattern,
157
158
  custom_domain: true
158
159
  })) });
@@ -2911,120 +2912,518 @@ async function getOrGenerateSecret(name, devVars, generate) {
2911
2912
  }
2912
2913
 
2913
2914
  //#endregion
2914
- //#region src/cli/commands/migrate.ts
2915
- const brightNote$3 = (lines) => lines.map((l) => `\x1b[0m${l}`).join("\n");
2915
+ //#region src/plc.ts
2916
+ const PLC_DIRECTORY = "https://plc.directory";
2916
2917
  /**
2917
- * 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
2918
2925
  */
2919
- function num(n) {
2920
- return n.toLocaleString();
2926
+ function plcSubmitHeaders(operation) {
2927
+ return {
2928
+ "Content-Type": "application/json",
2929
+ ...typeof operation.prev === "string" ? { "If-Match": "*" } : {}
2930
+ };
2921
2931
  }
2922
2932
  /**
2923
- * 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.
2924
2937
  */
2925
- function formatBytes(bytes) {
2926
- if (bytes < 1024) return `${bytes} B`;
2927
- if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
2928
- 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);
2929
2943
  }
2930
- const migrateCommand = defineCommand({
2931
- meta: {
2932
- name: "migrate",
2933
- description: "Migrate account from source PDS to your new PDS"
2934
- },
2935
- args: {
2936
- clean: {
2937
- type: "boolean",
2938
- description: "Reset migration and start fresh",
2939
- default: false
2940
- },
2941
- dev: {
2942
- type: "boolean",
2943
- description: "Target local development server instead of production",
2944
- default: false
2945
- }
2946
- },
2947
- async run({ args }) {
2948
- const pm = detectPackageManager();
2949
- const isDev = args.dev;
2950
- const vars = getVars();
2951
- 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() {
2952
3007
  try {
2953
- 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
+ };
2954
3013
  } catch (err) {
2955
- p.log.error(err instanceof Error ? err.message : "Configuration error");
2956
- p.log.info("Run 'pds init' first to configure your PDS.");
2957
- process.exit(1);
2958
- }
2959
- const targetDomain = getDomain(targetUrl);
2960
- p.intro("🦋 PDS Migration");
2961
- const spinner = p.spinner();
2962
- spinner.start(`Checking PDS at ${targetDomain}...`);
2963
- const targetClient = new PDSClient(targetUrl);
2964
- if (!await targetClient.healthCheck()) {
2965
- spinner.stop(`PDS not responding at ${targetDomain}`);
2966
- if (isDev) {
2967
- p.log.error(`Your local PDS isn't running at ${targetUrl}`);
2968
- p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
2969
- } else {
2970
- p.log.error(`Your PDS isn't responding at ${targetUrl}`);
2971
- p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
2972
- p.log.info(`Or test locally first: ${formatCommand(pm, "pds", "migrate", "--dev")}`);
2973
- }
2974
- p.outro("Migration cancelled.");
2975
- process.exit(1);
2976
- }
2977
- spinner.stop(`Connected to ${targetDomain}`);
2978
- const wranglerVars = getVars();
2979
- const config = {
2980
- ...readDevVars(),
2981
- ...wranglerVars
2982
- };
2983
- const did = config.DID;
2984
- const handle = config.HANDLE;
2985
- const authToken = config.AUTH_TOKEN;
2986
- if (!did) {
2987
- p.log.error("No DID configured. Run 'pds init' first.");
2988
- p.outro("Migration cancelled.");
2989
- process.exit(1);
2990
- }
2991
- if (!authToken) {
2992
- p.log.error("No AUTH_TOKEN found. Run 'pds init' first.");
2993
- p.outro("Migration cancelled.");
2994
- process.exit(1);
2995
- }
2996
- targetClient.setAuthToken(authToken);
2997
- spinner.start(`Looking up @${handle}...`);
2998
- const didDoc = await new DidResolver().resolve(did);
2999
- if (!didDoc) {
3000
- spinner.stop("Failed to resolve DID");
3001
- p.log.error(`Could not resolve DID: ${did}`);
3002
- p.outro("Migration cancelled.");
3003
- process.exit(1);
3004
- }
3005
- const sourcePdsUrl = getPdsEndpoint(didDoc);
3006
- if (!sourcePdsUrl) {
3007
- spinner.stop("No PDS found in DID document");
3008
- p.log.error("Could not find PDS endpoint in DID document");
3009
- p.outro("Migration cancelled.");
3010
- process.exit(1);
3014
+ return {
3015
+ success: false,
3016
+ error: err instanceof Error ? err.message : "Network error"
3017
+ };
3011
3018
  }
3012
- const sourceDomain = getDomain(sourcePdsUrl);
3013
- spinner.stop(`Found your account at ${sourceDomain}`);
3014
- spinner.start("Checking account status...");
3015
- const pdsDisplayName = sourceDomain.endsWith(".bsky.network") ? "bsky.social" : sourceDomain;
3016
- let status;
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) {
3017
3039
  try {
3018
- status = await targetClient.getAccountStatus();
3040
+ return {
3041
+ success: true,
3042
+ signedOperation: (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
3043
+ token,
3044
+ ...changes
3045
+ } }))).operation
3046
+ };
3019
3047
  } catch (err) {
3020
- spinner.stop("Failed to get account status");
3021
- p.log.error(err instanceof Error ? err.message : "Could not get account status");
3022
- p.outro("Migration cancelled.");
3023
- process.exit(1);
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
+ };
3024
3061
  }
3025
- spinner.stop("Account status retrieved");
3026
- if (args.clean) {
3027
- if (status.active) {
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.");
3393
+ process.exit(1);
3394
+ }
3395
+ targetClient.setAuthToken(authToken);
3396
+ spinner.start(`Looking up @${handle}...`);
3397
+ const didDoc = await new DidResolver().resolve(did);
3398
+ if (!didDoc) {
3399
+ spinner.stop("Failed to resolve DID");
3400
+ p.log.error(`Could not resolve DID: ${did}`);
3401
+ p.outro("Migration cancelled.");
3402
+ process.exit(1);
3403
+ }
3404
+ const sourcePdsUrl = getPdsEndpoint(didDoc);
3405
+ if (!sourcePdsUrl) {
3406
+ spinner.stop("No PDS found in DID document");
3407
+ p.log.error("Could not find PDS endpoint in DID document");
3408
+ p.outro("Migration cancelled.");
3409
+ process.exit(1);
3410
+ }
3411
+ const sourceDomain = getDomain(sourcePdsUrl);
3412
+ spinner.stop(`Found your account at ${sourceDomain}`);
3413
+ spinner.start("Checking account status...");
3414
+ const pdsDisplayName = sourceDomain.endsWith(".bsky.network") ? "bsky.social" : sourceDomain;
3415
+ let status;
3416
+ try {
3417
+ status = await targetClient.getAccountStatus();
3418
+ } catch (err) {
3419
+ spinner.stop("Failed to get account status");
3420
+ p.log.error(err instanceof Error ? err.message : "Could not get account status");
3421
+ p.outro("Migration cancelled.");
3422
+ process.exit(1);
3423
+ }
3424
+ spinner.stop("Account status retrieved");
3425
+ if (args.clean) {
3426
+ if (status.active) {
3028
3427
  p.log.error("Cannot reset: account is active");
3029
3428
  p.log.info("The --clean flag only works on deactivated accounts.");
3030
3429
  p.log.info("Your account is already live");
@@ -3084,15 +3483,15 @@ const migrateCommand = defineCommand({
3084
3483
  const profileStats = await sourceClient.getProfileStats(did);
3085
3484
  spinner.stop("Account details fetched");
3086
3485
  const needsRepoImport = status.repoBlocks === 0 || status.indexedRecords === 0 && status.expectedBlobs === 0;
3087
- const needsBlobSync = status.expectedBlobs - status.importedBlobs > 0 || needsRepoImport;
3088
- if (!needsRepoImport && needsBlobSync) {
3486
+ const missingBlobs = needsRepoImport ? 0 : await countMissingBlobs(targetClient);
3487
+ if (!needsRepoImport && (missingBlobs > 0 || needsRepoImport)) {
3089
3488
  p.log.info("Welcome back!");
3090
3489
  p.log.info("Looks like you started packing earlier. Let's pick up where we left off.");
3091
3490
  p.note([
3092
3491
  `@${handle} (${did.slice(0, 20)}...)`,
3093
3492
  "",
3094
3493
  "✓ Repository imported",
3095
- `◐ Media: ${num(status.importedBlobs)}/${num(status.expectedBlobs)} images and videos transferred`
3494
+ `◐ Media: ${num(status.expectedBlobs - missingBlobs)}/${num(status.expectedBlobs)} images and videos transferred`
3096
3495
  ].join("\n"), "Migration Progress");
3097
3496
  const continueTransfer = await p.confirm({
3098
3497
  message: "Continue transferring images and video?",
@@ -3173,7 +3572,6 @@ const migrateCommand = defineCommand({
3173
3572
  p.outro("Migration cancelled.");
3174
3573
  process.exit(1);
3175
3574
  }
3176
- status = await targetClient.getAccountStatus();
3177
3575
  }
3178
3576
  spinner.start("Migrating your preferences...");
3179
3577
  try {
@@ -3185,9 +3583,11 @@ const migrateCommand = defineCommand({
3185
3583
  } catch (err) {
3186
3584
  spinner.stop("Skipped preferences (not available)");
3187
3585
  }
3188
- 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 {
3189
3590
  let synced = 0;
3190
- let totalBlobs = 0;
3191
3591
  let cursor;
3192
3592
  let failedBlobs = [];
3193
3593
  const progressBar = (current, total) => {
@@ -3197,26 +3597,24 @@ const migrateCommand = defineCommand({
3197
3597
  const empty = width - filled;
3198
3598
  return `${"█".repeat(filled)}${"░".repeat(empty)} ${current}/${total}`;
3199
3599
  };
3200
- spinner.start("Counting images to transfer...");
3201
- let countCursor;
3202
- do {
3203
- const page = await targetClient.listMissingBlobs(500, countCursor);
3204
- totalBlobs += page.blobs.length;
3205
- countCursor = page.cursor;
3206
- } while (countCursor);
3207
3600
  spinner.message(`Transferring media ${progressBar(0, totalBlobs)}`);
3601
+ const attempted = /* @__PURE__ */ new Set();
3208
3602
  do {
3209
3603
  const page = await targetClient.listMissingBlobs(100, cursor);
3210
3604
  cursor = page.cursor;
3211
- for (const blob of page.blobs) try {
3212
- const { bytes, mimeType } = await sourceClient.getBlob(did, blob.cid);
3213
- await targetClient.uploadBlob(bytes, mimeType);
3214
- synced++;
3215
- spinner.message(`Transferring media ${progressBar(synced, totalBlobs)}`);
3216
- } catch (err) {
3217
- synced++;
3218
- failedBlobs.push(blob.cid);
3219
- 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
+ }
3220
3618
  }
3221
3619
  } while (cursor);
3222
3620
  if (failedBlobs.length > 0) {
@@ -3225,11 +3623,11 @@ const migrateCommand = defineCommand({
3225
3623
  } else spinner.stop(`Transferred ${num(synced)} images and videos`);
3226
3624
  }
3227
3625
  spinner.start("Verifying migration...");
3228
- const finalStatus = await targetClient.getAccountStatus();
3626
+ const remainingBlobs = await countMissingBlobs(targetClient);
3229
3627
  spinner.stop("Verification complete");
3230
- if (finalStatus.importedBlobs >= finalStatus.expectedBlobs) p.log.success("All packed and moved!");
3628
+ if (remainingBlobs === 0) p.log.success("All packed and moved!");
3231
3629
  else {
3232
- p.log.warn(`Migration partially complete. ${finalStatus.expectedBlobs - finalStatus.importedBlobs} images remaining.`);
3630
+ p.log.warn(`Migration partially complete. ${remainingBlobs} images remaining.`);
3233
3631
  p.log.info("Run 'pds migrate' again to continue.");
3234
3632
  }
3235
3633
  showNextSteps(pm, pdsDisplayName);
@@ -3284,273 +3682,64 @@ const migrateTokenCommand = defineCommand({
3284
3682
  const pdsHostname = config.PDS_HOSTNAME;
3285
3683
  const authToken = config.AUTH_TOKEN;
3286
3684
  if (!pdsHostname && !isDev) {
3287
- spinner.stop("No PDS_HOSTNAME configured");
3288
- p.log.error("Run 'pds init' first to set up your PDS.");
3289
- p.outro("Token generation cancelled.");
3290
- process.exit(1);
3291
- }
3292
- if (!authToken) {
3293
- spinner.stop("No AUTH_TOKEN found");
3294
- p.log.error("AUTH_TOKEN is required to authenticate with your PDS.");
3295
- p.outro("Token generation cancelled.");
3296
- process.exit(1);
3297
- }
3298
- let targetUrl;
3299
- try {
3300
- targetUrl = getTargetUrl(isDev, pdsHostname);
3301
- } catch (err) {
3302
- spinner.stop("Configuration error");
3303
- p.log.error(err instanceof Error ? err.message : "Configuration error");
3304
- p.outro("Token generation cancelled.");
3305
- process.exit(1);
3306
- }
3307
- spinner.stop("Configuration loaded");
3308
- spinner.start("Connecting to PDS...");
3309
- const pdsClient = new PDSClient(targetUrl, authToken);
3310
- if (!await pdsClient.healthCheck()) {
3311
- spinner.stop("PDS not responding");
3312
- p.log.error(`Your PDS isn't responding at ${targetUrl}`);
3313
- if (isDev) p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
3314
- else p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
3315
- p.outro("Token generation cancelled.");
3316
- process.exit(1);
3317
- }
3318
- spinner.stop("Connected to PDS");
3319
- spinner.start("Generating migration token...");
3320
- const result = await pdsClient.getMigrationToken();
3321
- if (!result.success || !result.token) {
3322
- spinner.stop("Failed to generate token");
3323
- p.log.error(result.error ?? "Could not generate migration token");
3324
- p.outro("Token generation cancelled.");
3325
- process.exit(1);
3326
- }
3327
- spinner.stop("Token generated");
3328
- if (await copyToClipboard(result.token)) p.log.success("Migration token copied to clipboard!");
3329
- else p.log.info("Could not copy to clipboard. Token:");
3330
- console.log("");
3331
- console.log(pc.bold(result.token));
3332
- console.log("");
3333
- p.note([
3334
- "This token is valid for 15 minutes.",
3335
- "",
3336
- "Paste it into the new PDS when prompted for",
3337
- "a migration/confirmation code.",
3338
- "",
3339
- "Once migration is complete, you can deactivate",
3340
- "this PDS with: pnpm pds deactivate"
3341
- ].join("\n"), "Next Steps");
3342
- p.outro("Good luck with the migration!");
3343
- }
3344
- });
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
-
3388
- //#endregion
3389
- //#region src/cli/utils/plc-client.ts
3390
- /**
3391
- * PLC Directory client for identity operations
3392
- *
3393
- * Handles communication with the PLC directory and source PDS
3394
- * for DID document updates during migration.
3395
- *
3396
- * Uses @atcute/client for type-safe XRPC calls.
3397
- */
3398
- /**
3399
- * Create a fetch handler that adds optional auth token
3400
- */
3401
- function createAuthHandler(baseUrl, token) {
3402
- return async (pathname, init) => {
3403
- const url = new URL(pathname, baseUrl);
3404
- const headers = new Headers(init.headers);
3405
- if (token) headers.set("Authorization", `Bearer ${token}`);
3406
- return fetch(url, {
3407
- ...init,
3408
- headers
3409
- });
3410
- };
3411
- }
3412
- /**
3413
- * Client for interacting with source PDS for PLC operations
3414
- *
3415
- * Uses @atcute/client for type-safe XRPC calls to:
3416
- * - com.atproto.identity.requestPlcOperationSignature
3417
- * - com.atproto.identity.signPlcOperation
3418
- */
3419
- var SourcePdsPlcClient = class {
3420
- client;
3421
- authToken;
3422
- baseUrl;
3423
- constructor(baseUrl, authToken) {
3424
- this.baseUrl = baseUrl;
3425
- this.authToken = authToken;
3426
- this.client = new Client({ handler: createAuthHandler(baseUrl, authToken) });
3427
- }
3428
- setAuthToken(token) {
3429
- this.authToken = token;
3430
- this.client = new Client({ handler: createAuthHandler(this.baseUrl, token) });
3431
- }
3432
- /**
3433
- * Request a PLC operation signature from the source PDS.
3434
- * This triggers the source PDS to send an email token to the user.
3435
- *
3436
- * Uses: com.atproto.identity.requestPlcOperationSignature
3437
- */
3438
- async requestPlcOperationSignature() {
3439
- try {
3440
- await ok(this.client.post("com.atproto.identity.requestPlcOperationSignature", { as: null }));
3441
- return {
3442
- success: true,
3443
- credentialInfo: { type: "email" }
3444
- };
3445
- } catch (err) {
3446
- return {
3447
- success: false,
3448
- error: err instanceof Error ? err.message : "Network error"
3449
- };
3450
- }
3451
- }
3452
- /**
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.
3464
- *
3465
- * Uses: com.atproto.identity.signPlcOperation
3466
- *
3467
- * @param token - The email token received from the source PDS
3468
- * @param changes - Fields to change; omitted fields keep their values
3469
- */
3470
- async signPlcOperation(token, changes) {
3471
- try {
3472
- return {
3473
- success: true,
3474
- signedOperation: (await ok(this.client.post("com.atproto.identity.signPlcOperation", { input: {
3475
- token,
3476
- ...changes
3477
- } }))).operation
3478
- };
3479
- } catch (err) {
3480
- const errorMessage = err instanceof Error ? err.message : "Network error";
3481
- if (errorMessage.includes("expired") || errorMessage.includes("ExpiredToken")) return {
3482
- success: false,
3483
- error: "Token expired. Request a new one and try again."
3484
- };
3485
- if (errorMessage.includes("invalid") || errorMessage.includes("InvalidToken")) return {
3486
- success: false,
3487
- error: "Invalid token. Check you entered it correctly."
3488
- };
3489
- return {
3490
- success: false,
3491
- error: errorMessage
3492
- };
3493
- }
3494
- }
3495
- };
3496
- /**
3497
- * Client for interacting with the PLC directory
3498
- *
3499
- * The PLC directory has its own REST API (not XRPC), so we use raw fetch here.
3500
- * See: https://web.plc.directory/
3501
- */
3502
- var PlcDirectoryClient = class {
3503
- constructor(plcUrl = PLC_DIRECTORY) {
3504
- this.plcUrl = plcUrl;
3505
- }
3506
- /**
3507
- * Get the audit log for a DID (list of all operations)
3508
- */
3509
- async getAuditLog(did) {
3510
- const res = await fetch(`${this.plcUrl}/${did}/log/audit`);
3511
- if (!res.ok) throw new Error(`Failed to fetch audit log: ${res.status}`);
3512
- return res.json();
3513
- }
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
- /**
3521
- * Get the current DID document
3522
- */
3523
- async getDocument(did) {
3524
- const res = await fetch(`${this.plcUrl}/${did}`);
3525
- if (!res.ok) {
3526
- if (res.status === 404) return null;
3527
- throw new Error(`Failed to fetch DID document: ${res.status}`);
3685
+ spinner.stop("No PDS_HOSTNAME configured");
3686
+ p.log.error("Run 'pds init' first to set up your PDS.");
3687
+ p.outro("Token generation cancelled.");
3688
+ process.exit(1);
3528
3689
  }
3529
- return res.json();
3530
- }
3531
- /**
3532
- * Submit a signed PLC operation to the directory
3533
- */
3534
- async submitOperation(did, operation) {
3690
+ if (!authToken) {
3691
+ spinner.stop("No AUTH_TOKEN found");
3692
+ p.log.error("AUTH_TOKEN is required to authenticate with your PDS.");
3693
+ p.outro("Token generation cancelled.");
3694
+ process.exit(1);
3695
+ }
3696
+ let targetUrl;
3535
3697
  try {
3536
- const res = await fetch(`${this.plcUrl}/${did}`, {
3537
- method: "POST",
3538
- headers: plcSubmitHeaders(operation),
3539
- body: JSON.stringify(operation)
3540
- });
3541
- if (!res.ok) return {
3542
- success: false,
3543
- error: `PLC directory rejected operation: ${await res.text()}`
3544
- };
3545
- return { success: true };
3698
+ targetUrl = getTargetUrl(isDev, pdsHostname);
3546
3699
  } catch (err) {
3547
- return {
3548
- success: false,
3549
- error: err instanceof Error ? err.message : "Network error"
3550
- };
3700
+ spinner.stop("Configuration error");
3701
+ p.log.error(err instanceof Error ? err.message : "Configuration error");
3702
+ p.outro("Token generation cancelled.");
3703
+ process.exit(1);
3704
+ }
3705
+ spinner.stop("Configuration loaded");
3706
+ spinner.start("Connecting to PDS...");
3707
+ const pdsClient = new PDSClient(targetUrl, authToken);
3708
+ if (!await pdsClient.healthCheck()) {
3709
+ spinner.stop("PDS not responding");
3710
+ p.log.error(`Your PDS isn't responding at ${targetUrl}`);
3711
+ if (isDev) p.log.info(`Start it with: ${formatCommand(pm, "dev")}`);
3712
+ else p.log.info(`Make sure your worker is deployed: ${formatCommand(pm, "deploy")}`);
3713
+ p.outro("Token generation cancelled.");
3714
+ process.exit(1);
3715
+ }
3716
+ spinner.stop("Connected to PDS");
3717
+ spinner.start("Generating migration token...");
3718
+ const result = await pdsClient.getMigrationToken();
3719
+ if (!result.success || !result.token) {
3720
+ spinner.stop("Failed to generate token");
3721
+ p.log.error(result.error ?? "Could not generate migration token");
3722
+ p.outro("Token generation cancelled.");
3723
+ process.exit(1);
3551
3724
  }
3725
+ spinner.stop("Token generated");
3726
+ if (await copyToClipboard(result.token)) p.log.success("Migration token copied to clipboard!");
3727
+ else p.log.info("Could not copy to clipboard. Token:");
3728
+ console.log("");
3729
+ console.log(pc.bold(result.token));
3730
+ console.log("");
3731
+ p.note([
3732
+ "This token is valid for 15 minutes.",
3733
+ "",
3734
+ "Paste it into the new PDS when prompted for",
3735
+ "a migration/confirmation code.",
3736
+ "",
3737
+ "Once migration is complete, you can deactivate",
3738
+ "this PDS with: pnpm pds deactivate"
3739
+ ].join("\n"), "Next Steps");
3740
+ p.outro("Good luck with the migration!");
3552
3741
  }
3553
- };
3742
+ });
3554
3743
 
3555
3744
  //#endregion
3556
3745
  //#region src/cli/utils/rotation-keys.ts
@@ -3599,6 +3788,25 @@ function findPreviousPdsEndpoint(log, currentEndpoint) {
3599
3788
  return null;
3600
3789
  }
3601
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;
3807
+ }
3808
+ }
3809
+ /**
3602
3810
  * Generate a secp256k1 recovery key.
3603
3811
  */
3604
3812
  async function generateRecoveryKey() {
@@ -3769,177 +3977,6 @@ async function checkRotationKeys(plcClient, did, expected) {
3769
3977
  return actual.length === expected.length && actual.every((key, i) => key === expected[i]) ? null : actual;
3770
3978
  }
3771
3979
 
3772
- //#endregion
3773
- //#region src/cli/utils/checks.ts
3774
- /**
3775
- * Check that handle resolves to the expected DID
3776
- */
3777
- async function checkHandleResolution(handle, expectedDid) {
3778
- const resolvedDid = await resolveHandleToDid(handle);
3779
- if (!resolvedDid) return {
3780
- ok: false,
3781
- message: `@${handle} does not resolve to any DID`,
3782
- detail: "Update your DNS TXT record or .well-known/atproto-did file"
3783
- };
3784
- if (resolvedDid !== expectedDid) return {
3785
- ok: false,
3786
- message: `@${handle} resolves to wrong DID`,
3787
- detail: `Expected: ${expectedDid}\n Got: ${resolvedDid}`
3788
- };
3789
- return {
3790
- ok: true,
3791
- message: `@${handle} → ${expectedDid.slice(0, 24)}...`
3792
- };
3793
- }
3794
- /**
3795
- * Check that handle resolves via DNS and/or HTTP, returning both methods
3796
- */
3797
- async function checkHandleResolutionDetailed(client, handle, expectedDid) {
3798
- const [httpDid, dnsDid] = await Promise.all([client.checkHandleViaHttp(handle), client.checkHandleViaDns(handle)]);
3799
- const httpValid = httpDid === expectedDid;
3800
- const dnsValid = dnsDid === expectedDid;
3801
- const methods = [];
3802
- if (dnsValid) methods.push("DNS");
3803
- if (httpValid) methods.push("HTTP");
3804
- return {
3805
- ok: httpValid || dnsValid,
3806
- httpDid,
3807
- dnsDid,
3808
- methods
3809
- };
3810
- }
3811
- /**
3812
- * Check that DID document points to the expected PDS endpoint
3813
- */
3814
- async function checkDidDocument(did, expectedPdsUrl) {
3815
- const didDoc = await new DidResolver().resolve(did);
3816
- const expectedEndpoint = expectedPdsUrl.replace(/\/$/, "");
3817
- if (!didDoc) return {
3818
- ok: false,
3819
- message: `Could not resolve DID document for ${did}`,
3820
- detail: "Make sure your DID is published to the PLC directory or did:web endpoint"
3821
- };
3822
- const pdsService = didDoc.service?.find((s) => {
3823
- return (Array.isArray(s.type) ? s.type : [s.type]).includes("AtprotoPersonalDataServer") || s.id === "#atproto_pds";
3824
- });
3825
- if (!pdsService?.serviceEndpoint) return {
3826
- ok: false,
3827
- message: "DID document has no PDS service endpoint",
3828
- detail: "Update your DID document to include an AtprotoPersonalDataServer service"
3829
- };
3830
- const actualEndpoint = pdsService.serviceEndpoint.replace(/\/$/, "");
3831
- if (actualEndpoint !== expectedEndpoint) return {
3832
- ok: false,
3833
- message: "DID document points to different PDS",
3834
- detail: `Expected: ${expectedEndpoint}\n Got: ${actualEndpoint}`
3835
- };
3836
- return {
3837
- ok: true,
3838
- message: `PDS endpoint → ${expectedEndpoint}`
3839
- };
3840
- }
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
- /**
3862
- * Check that DID resolves and returns the PDS endpoint (simpler version using PDSClient)
3863
- */
3864
- async function checkDidResolution(client, did, expectedPdsHostname) {
3865
- const resolved = await client.resolveDid(did);
3866
- const resolveMethod = did.startsWith("did:plc:") ? "plc.directory" : did.startsWith("did:web:") ? "/.well-known/did.json" : "unknown";
3867
- if (!resolved.pdsEndpoint) return {
3868
- ok: false,
3869
- pdsEndpoint: null,
3870
- resolveMethod
3871
- };
3872
- const expectedEndpoint = `https://${expectedPdsHostname}`;
3873
- return {
3874
- ok: resolved.pdsEndpoint === expectedEndpoint || resolved.pdsEndpoint === expectedPdsHostname,
3875
- pdsEndpoint: resolved.pdsEndpoint,
3876
- resolveMethod
3877
- };
3878
- }
3879
- /**
3880
- * Check that all blobs are imported
3881
- */
3882
- function checkBlobsImported(status) {
3883
- const missingBlobs = status.expectedBlobs - status.importedBlobs;
3884
- if (missingBlobs > 0) return {
3885
- ok: false,
3886
- message: `${missingBlobs} blob${missingBlobs === 1 ? "" : "s"} missing`,
3887
- detail: "Run 'pds migrate' to import missing blobs before activating"
3888
- };
3889
- return {
3890
- ok: true,
3891
- message: `${status.importedBlobs}/${status.expectedBlobs} blobs imported`
3892
- };
3893
- }
3894
- /**
3895
- * Check that repository data exists and is properly initialised
3896
- */
3897
- function checkRepoInitialised(status) {
3898
- if (!status.repoCommit) return {
3899
- ok: false,
3900
- message: "No repo data imported",
3901
- detail: "Run 'pds migrate' to import your repository first"
3902
- };
3903
- if (status.indexedRecords === 0) return {
3904
- ok: false,
3905
- message: "Repository has no indexed records",
3906
- detail: "Run 'pds migrate' to import your repository"
3907
- };
3908
- return {
3909
- ok: true,
3910
- message: `${status.repoBlocks.toLocaleString()} blocks, ${status.indexedRecords.toLocaleString()} records`
3911
- };
3912
- }
3913
- /**
3914
- * Check that repo is complete for activation (combines blob and repo checks)
3915
- */
3916
- function checkRepoComplete(status) {
3917
- const repoCheck = checkRepoInitialised(status);
3918
- if (!repoCheck.ok) return repoCheck;
3919
- if (status.expectedBlobs > 0) {
3920
- const blobCheck = checkBlobsImported(status);
3921
- if (!blobCheck.ok) return blobCheck;
3922
- }
3923
- return {
3924
- ok: true,
3925
- message: `${status.repoBlocks} blocks, ${status.importedBlobs} blobs`
3926
- };
3927
- }
3928
- /**
3929
- * Check if profile is indexed by AppView
3930
- */
3931
- async function checkAppViewIndexing(client, did) {
3932
- if (!await client.checkAppViewIndexing(did)) return {
3933
- ok: false,
3934
- message: "Profile not found on AppView",
3935
- detail: "This may be normal for new accounts"
3936
- };
3937
- return {
3938
- ok: true,
3939
- message: "Profile indexed by AppView"
3940
- };
3941
- }
3942
-
3943
3980
  //#endregion
3944
3981
  //#region src/cli/commands/identity.ts
3945
3982
  /**
@@ -4369,13 +4406,14 @@ const rotationKeysCommand = defineCommand({
4369
4406
  let sourcePdsKeys;
4370
4407
  let signingKeypair;
4371
4408
  if (signer === "previous") {
4372
- const sourceUrl = await promptText({
4409
+ const previous = findPreviousPdsEndpoint(log, targetEndpoint);
4410
+ const sourceUrl = entrywayFor((await promptText({
4373
4411
  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());
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);
4379
4417
  const password = await p.password({ message: `Your password for ${sourceName}:` });
4380
4418
  if (p.isCancel(password)) {
4381
4419
  p.cancel("Rotation keys unchanged.");
@@ -4383,7 +4421,7 @@ const rotationKeysCommand = defineCommand({
4383
4421
  }
4384
4422
  spinner.start(`Logging in to ${sourceName}...`);
4385
4423
  try {
4386
- const session = await new PDSClient(sourceUrl.trim()).createSession(did, password);
4424
+ const session = await new PDSClient(sourceUrl).createSession(did, password);
4387
4425
  sourcePdsClient.setAuthToken(session.accessJwt);
4388
4426
  spinner.stop("Authenticated");
4389
4427
  } catch (err) {
@@ -4502,7 +4540,7 @@ const rotationKeysCommand = defineCommand({
4502
4540
  /**
4503
4541
  * Run pre-activation checks
4504
4542
  */
4505
- async function runChecks(handle, did, pdsUrl, status) {
4543
+ async function runChecks(client, handle, did, pdsUrl, status) {
4506
4544
  const checks = [];
4507
4545
  p.log.step("Checking handle resolution...");
4508
4546
  const handleResult = await checkHandleResolution(handle, did);
@@ -4517,7 +4555,7 @@ async function runChecks(handle, did, pdsUrl, status) {
4517
4555
  ...didResult
4518
4556
  });
4519
4557
  p.log.step("Checking repo status...");
4520
- const repoResult = checkRepoComplete(status);
4558
+ const repoResult = await checkRepoComplete(client, status);
4521
4559
  checks.push({
4522
4560
  name: "Repo",
4523
4561
  ...repoResult
@@ -4665,7 +4703,7 @@ const activateCommand = defineCommand({
4665
4703
  }
4666
4704
  p.log.info("");
4667
4705
  p.log.info(pc.bold("Pre-activation checks:"));
4668
- const checks = await runChecks(handle, did, targetUrl, status);
4706
+ const checks = await runChecks(client, handle, did, targetUrl, status);
4669
4707
  console.log("");
4670
4708
  for (const check of checks) logCheck(check);
4671
4709
  console.log("");
@@ -5050,13 +5088,13 @@ const statusCommand$1 = defineCommand({
5050
5088
  console.log();
5051
5089
  if (status.expectedBlobs > 0) {
5052
5090
  console.log(pc.bold("Blobs"));
5053
- const blobCheck = checkBlobsImported(status);
5091
+ const blobCheck = checkBlobsImported(status, await countMissingBlobs(client));
5054
5092
  if (blobCheck.ok) console.log(` ${CHECK} ${blobCheck.message}`);
5055
5093
  else {
5056
- const missing = status.expectedBlobs - status.importedBlobs;
5057
- console.log(` ${WARN} ${status.importedBlobs}/${status.expectedBlobs} blobs imported (${missing} missing)`);
5094
+ console.log(` ${WARN} ${blobCheck.message}`);
5058
5095
  hasWarnings = true;
5059
5096
  }
5097
+ console.log(` ${INFO} ${status.importedBlobs} blobs stored in total`);
5060
5098
  console.log();
5061
5099
  }
5062
5100
  console.log(pc.bold("Federation"));
@@ -6191,16 +6229,13 @@ const kemCommand = defineCommand({
6191
6229
  },
6192
6230
  async run({ args }) {
6193
6231
  p.intro("Spaces KEM key");
6194
- const config = {
6195
- ...readDevVars(),
6196
- ...getVars()
6197
- };
6198
- const did = config.DID;
6232
+ const vars = getVars();
6233
+ const did = vars.DID;
6199
6234
  if (!did) {
6200
6235
  p.log.error("No DID configured. Run 'pds init' first.");
6201
6236
  process.exit(1);
6202
6237
  }
6203
- let publicKey = config.SPACES_KEM_KEY_PUBLIC;
6238
+ let publicKey = (args.local ? readDevVars() : vars).SPACES_KEM_KEY_PUBLIC;
6204
6239
  if (publicKey && !args.publish) {
6205
6240
  const replace = await p.confirm({
6206
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.",