/ ACCOUNT_MIGRATION.md
ACCOUNT_MIGRATION.md
  1  # Account Migration 
  2  
  3  ### ⚠️ Warning ⚠️ ️
  4  Account migration is a potentially destructive operation. Part of the operation involves signing away your old PDS's ability to make updates to your DID. If something goes wrong, you could be permanently locked out of your account, and Bluesky will not be able to help you recover it. 
  5  
  6  Therefore, we do not recommend migrating your primary account yet. And we specifically recommend _against_ migrating your main account if you do not understand how PLC operations work.
  7  
  8  Also, the Bluesky PDS is not currently accepting incoming migrations (it will in the future). Therefore this is currently a one-way street. If you migrate off of `bsky.social`, _you will not be able to return_. However, you will be able to migrate between other PDSs.
  9  
 10  ![Diagram of account migration flow](https://raw.githubusercontent.com/bluesky-social/pds/main/assets/account-migration.png)
 11  
 12  Account Migration occurs in 4 main steps:
 13  - Creating an account on the new PDS
 14  - Migrating data from the old PDS to the new PDS
 15  - Updating identity to point to the new PDS
 16  - Finalizing the migration
 17  
 18  
 19  ### Creating an Account
 20  
 21  In order to create an account, you first need to prove to the new PDS that you're in control of the DID that you're attempting to register as.
 22  
 23  To do so, you need a JWT signed with the signing key associated with your DID. You can obtain this through calling `com.atproto.server.getServiceAuth` from your old PDS. If your old PDS is not willing to provide the authentication token, you will need to update your DID document to point to a signing key that you possess in order to mint an authentication token yourself.
 24  
 25  With this JWT set as a Bearer token, you can then create an account on the new PDS by calling `com.atproto.server.createAccount`. You'll need to fulfill any challenges that the new PDS requires - such as an invite code. 
 26  
 27  After creating an account, you'll have a signing key on the new PDS and an empty repository. Your account will be in a "deactivated" state such that it is not usable yet.
 28  
 29  ### Migrating data
 30  
 31  Now that you have an account on the new PDS, you can start migrating data into it. After creating your account, you will have received an access token for the new PDS and it will be required for all incoming data.
 32  
 33  First, you can grab your entire repository in the form of a [CAR file](https://ipld.io/specs/transport/car/carv1/) by calling `com.atproto.sync.getRepo`. You can then upload those exact bytes to your new PDS through `com.atproto.repo.importRepo`. The new PDS will parse the CAR file, index all blocks and records, and sign a new commit for the repository.
 34  
 35  Next, you'll need to upload all relevant blobs. These can be discovered by calling `com.atproto.sync.listBlobs` on your old PDS. For each blob, you'll need to download the contents through `com.atproto.sync.getBlob` and upload them to your new PDS through `com.atproto.repo.uploadBlob`. 
 36  
 37  Finally, you'll need to migrate private state. Currently the only private state held on your PDS is your preferences. You can migrate this by calling `app.bsky.actor.getPreferences` on your old PDS, and submitting the results to `app.bsky.actor.putPreferences` on your new PDS.
 38  
 39  At any point during this process, you can check the status of your new account by calling `com.atproto.server.checkAccountStatus` which will inform you of your repo state, how many records are indexed, how many private state values are stored, how many blobs it is expecting (based on parsing records), and how many blobs have been uploaded. If you find you are missing blobs and are not sure which, you may use `com.atproto.repo.listMissingBlobs` on your new PDS to find them.
 40  
 41  ### Updating identity
 42  
 43  After your data has been migrated to your new PDS, you'll need to update your DID to point to the correct credentials - handle, pds endpoint, signing key, and (if using a did:plc) the new PDS's rotation key.
 44  
 45  You can fetch your new PDS's recommendations for these by calling `com.atproto.identity.getRecommendedDidCredentials`. If using a did:plc, we recommend taking this chance to generate a new rotation key and adding it to the list of recommended rotation keys that comes from your new PDS.
 46  
 47  If using a did:plc (as most accounts are), you can then request a signed PLC operation from your old PDS by passing the credentials through to `com.atproto.identity.signPlcOperation`. However, since this is a sensitive and possibly destructive operation, you'll need to fulfill an email challenge. To do so, simply call `com.atproto.identity.requestPlcOperationSignature` and send the provided token along with your request for a signed operation.
 48  
 49  The operation you receive has the capability to update your PLC identity. Of course, you may submit it yourself to `https://plc.directory`. However, we strongly encourage you to submit it through your new PDS at `com.atproto.identity.submitPlcOperation`. Your new PDS will check the operation to ensure that it does not get your account into a bad state. We also encourage you to check the operation yourself.
 50  
 51  If you are using a did:web or if your old PDS is not cooperating, you will need to take care of updating your DID yourself, either by updating the `.well-known` endpoint for your did:web or by signing a PLC operation with a rotation key that you possess.
 52  
 53  ### Finalizing the migration
 54  
 55  After your identity is updated, you're nearly ready to go!
 56  
 57  We recommend doing a final check of `com.atproto.server.checkAccountStatus` to ensure that everything looks in order.
 58  
 59  After doing so, call `com.atproto.server.activateAccount` on your new PDS. It will ensure that your DID is set up correctly, activate your account, and send out events on its firehose noting that you updated your identity and published a new commit.
 60  
 61  As a clean up step, you can deactivate or delete your account on your old PDS by calling `com.atproto.server.deleteAccount` or `com.atproto.server.deactivateAccount`. If doing the latter, you may provide an optional `deleteAfter` param that suggests to the server that it should hold onto your deactivated account until at least that date.
 62  
 63  ### After migration
 64  
 65  After migrating, you should be good to start using the app as normal! You'll need to log out and log back in through your new PDS so that the client is talking to the correct service. It's possible that some services (such as feed generators) will have a stale DID cache and may not be able to accurately verify your auth tokens immediately. However, we've found that most services handle this gracefully, and those that don't should sort themselves out pretty quickly.
 66  
 67  
 68  ## Example Code
 69  
 70  The below Typescript code gives an example of how this account migration flow may function. Please note that it is for documentation purposes only and can not be run exactly as is as there is an out-of-band step where you need to get a confirmation token from your email.
 71  
 72  It also does not handle some of the more advanced steps such as verifying a full import, looking for missing blobs, adding your own recovery key, or validating the PLC operation itself.
 73  
 74  ```ts
 75  import AtpAgent from '@atproto/api'
 76  import { Secp256k1Keypair } from '@atproto/crypto'
 77  import * as ui8 from 'uint8arrays'
 78  
 79  const OLD_PDS_URL = 'https://bsky.social'
 80  const NEW_PDS_URL = 'https://example.com'
 81  const CURRENT_HANDLE = 'to-migrate.bsky.social'
 82  const CURRENT_PASSWORD = 'password'
 83  const NEW_HANDLE = 'migrated.example.com'
 84  const NEW_ACCOUNT_EMAIL = 'migrated@example.com'
 85  const NEW_ACCOUNT_PASSWORD = 'password'
 86  const NEW_PDS_INVITE_CODE = 'example-com-12345-abcde'
 87  
 88  const migrateAccount = async () => {
 89    const oldAgent = new AtpAgent({ service: OLD_PDS_URL })
 90    const newAgent = new AtpAgent({ service: NEW_PDS_URL })
 91  
 92    await oldAgent.login({
 93      identifier: CURRENT_HANDLE,
 94      password: CURRENT_PASSWORD,
 95    })
 96  
 97    const accountDid = oldAgent.session?.did
 98    if (!accountDid) {
 99      throw new Error('Could not get DID for old account')
100    }
101  
102    // Create account
103    // ------------------
104  
105    const describeRes = await newAgent.api.com.atproto.server.describeServer()
106    const newServerDid = describeRes.data.did
107  
108    const serviceJwtRes = await oldAgent.com.atproto.server.getServiceAuth({
109      aud: newServerDid,
110      lxm: 'com.atproto.server.createAccount',
111    })
112    const serviceJwt = serviceJwtRes.data.token
113  
114    await newAgent.api.com.atproto.server.createAccount(
115      {
116        handle: NEW_HANDLE,
117        email: NEW_ACCOUNT_EMAIL,
118        password: NEW_ACCOUNT_PASSWORD,
119        did: accountDid,
120        inviteCode: NEW_PDS_INVITE_CODE,
121      },
122      {
123        headers: { authorization: `Bearer ${serviceJwt}` },
124        encoding: 'application/json',
125      },
126    )
127    await newAgent.login({
128      identifier: NEW_HANDLE,
129      password: NEW_ACCOUNT_PASSWORD,
130    })
131  
132    // Migrate Data
133    // ------------------
134  
135    const repoRes = await oldAgent.com.atproto.sync.getRepo({ did: accountDid })
136    await newAgent.com.atproto.repo.importRepo(repoRes.data, {
137      encoding: 'application/vnd.ipld.car',
138    })
139  
140    let blobCursor: string | undefined = undefined
141    do {
142      const listedBlobs = await oldAgent.com.atproto.sync.listBlobs({
143        did: accountDid,
144        cursor: blobCursor,
145      })
146      for (const cid of listedBlobs.data.cids) {
147        const blobRes = await oldAgent.com.atproto.sync.getBlob({
148          did: accountDid,
149          cid,
150        })
151        await newAgent.com.atproto.repo.uploadBlob(blobRes.data, {
152          encoding: blobRes.headers['content-type'],
153        })
154      }
155      blobCursor = listedBlobs.data.cursor
156    } while (blobCursor)
157  
158    const prefs = await oldAgent.api.app.bsky.actor.getPreferences()
159    await newAgent.api.app.bsky.actor.putPreferences(prefs.data)
160  
161    // Migrate Identity
162    // ------------------
163  
164    const recoveryKey = await Secp256k1Keypair.create({ exportable: true })
165    const privateKeyBytes = await recoveryKey.export()
166    const privateKey = ui8.toString(privateKeyBytes, 'hex')
167  
168    await oldAgent.com.atproto.identity.requestPlcOperationSignature()
169  
170    const getDidCredentials =
171      await newAgent.com.atproto.identity.getRecommendedDidCredentials()
172    const rotationKeys = getDidCredentials.data.rotationKeys ?? []
173    if (!rotationKeys) {
174      throw new Error('No rotation key provided')
175    }
176    const credentials = {
177      ...getDidCredentials.data,
178      rotationKeys: [recoveryKey.did(), ...rotationKeys],
179    }
180  
181    // @NOTE, this token will need to come from the email from the previous step
182    const TOKEN = ''
183  
184    const plcOp = await oldAgent.com.atproto.identity.signPlcOperation({
185      token: TOKEN,
186      ...credentials,
187    })
188  
189    console.log(
190      `❗ Your private recovery key is: ${privateKey}. Please store this in a secure location! ❗`,
191    )
192  
193    await newAgent.com.atproto.identity.submitPlcOperation({
194      operation: plcOp.data.operation,
195    })
196  
197    // Finalize Migration
198    // ------------------
199  
200    await newAgent.com.atproto.server.activateAccount()
201    await oldAgent.com.atproto.server.deactivateAccount({})
202  }
203  
204  ```