Skip to content

feat: safes BYOK backup root support in SDK - #10098

Draft
s84krish wants to merge 1 commit into
masterfrom
WCN-3880
Draft

s84krish wants to merge 1 commit into
masterfrom
WCN-3880

Conversation

@s84krish

@s84krish s84krish commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

Ticket: WCN-3880

Lets a caller create a safe whose multisig backup root is a public key they supply — the same way backupXpub works for Wallets.generateWallet. The SDK never generates, encrypts,
or sees the caller's backup private key. Covers the secp256k1Multisig (①) and ed25519Multisig (④) slots; MPC slots are rejected.

  • Create (sdk-core): new CreateSafeOptions.multisigRoots keyed by slot ({ backupXpub }); generateSafe/initializeSafe derive and send externalBackupSlots; createSafeKeys validates the supplied slots against the server declaration and archives the safe on mismatch; createMultisigRoot registers the caller's pub via keychains.add({ source: 'backup' }) instead of generating one. ① validates with coin.isValidPub; ④ accepts an ed25519 StrKey and converts it to the derivable composite format.
  • Keycard: sdk-lib-safes gains an additive box-B entry { kind: 'external', pub } (older cards still decode); key-card renders external slots as public-key-only in Box B, reading the declared slots from safe data.
  • Recovery: decryptSafeKeycard returns external roots without decrypting; backup children derive from the public root (relative soft paths, so non-master HSM xpubs work); signed
    ① recovery accepts the caller's externalBackupRootPrv; ④ holders sign through the existing ExternalEd25519Signer.
  • Express: multisigRoots forwarded through the generateSafe/generateSafeKeys typed routes, with generateSafeKeys checking declared external slots against the supplied keys.

Testing: unit coverage for create/keycard/recovery/express paths (multisig-root registration, StrKey conversion, malformed-key rejection, old-card decode round-trip, depth-3 xpub
child derivation, signed recovery with external prv). Existing safes and keycards are unaffected. Note: a backup xpub can back exactly one safe — wallet platform rejects a pub already
used as a safe root.

@linear-code

linear-code Bot commented Oct 29, 2026

Copy link
Copy Markdown
Contributor

WCN-3880

@github-actions

github-actions Bot commented Oct 29, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility checks are failing on Node.js 27-nightly (experimental, non-blocking). This does not block merge, but it signals an incompatibility to fix before this release becomes supported.

View run

@s84krish

Copy link
Copy Markdown
Contributor Author

@claude review this PR for correctness, code quality, and implementation. Flag any regressions and give an approval score

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @s84krish's task in 41s —— View job


Review of PR #10098: safes BYOK backup root support

Approval score: 8/10. I'd approve once the points below are addressed or acknowledged.

I read the full source diff: sdk-core, sdk-lib-safes, key-card and express. I skimmed the tests and did not run them, so the unit suites and CI status are unverified on my side.

What looks good

  • Fail-safe handling of declared vs. supplied slots. createSafeKeys compares supplied, declared and enabled slots before any key is created, and archives the safe on mismatch (safes.ts). If an older WP ignores externalBackupSlots at initialize, the call fails loudly instead of silently generating a local backup key.
  • Validation order. generateSafe runs externalBackupSlotsOf before initializeSafe, so a bad option leaves no half-created safe. MPC slots are rejected both in the SDK and in initializeSafe.
  • Keycard codec is additive. ExternalBackupEntryCodec is added to the union, so old cards still decode. External entries in boxes A and C still throw through requireBareString.
  • Key-card guards. selectBackupRootEntry asserts the external keychain has a pub and no encryptedPrv. A mismatch between declared slots and keychain contents fails loudly instead of printing a wrong card.
  • Relative soft derivation. deriveSoftPathRelative removes the "Expected master, got child" failure for non-master HSM xpubs. The externalBackupRootPrv check, which compares the derived child xpub against the root pub, catches wrong-key mistakes. The local-root path keeps its strict master-key derivation.
  • Overloads keep existing callers unchanged. deriveSafeWalletKeys and deriveSafeChildTriplet keep their original signatures, so there is no type regression for current callers.

Issues and risks

  1. @bitgo/public-types major bump (6.90.0 → 7.1.0) in only 3 packages. express, sdk-core and sdk-lib-safes move to 7.1.0. bitgo, abstract-lightning, passkey-crypto, sdk-coin-flrp and sdk-coin-sol stay on 6.90.0 (grep of modules/*/package.json). That leaves two copies of the package in the tree.

    • bitgo depends on sdk-core and express and re-exports types. A mismatch between 6.x and 7.x io-ts codecs or branded types can surface as type errors or .is() failures across the boundary.
    • I could not confirm whether 7.0 contains breaking changes beyond the new externalBackupSlots/MultisigRootKeyType additions.
    • The yarn.lock hunk replaces the 6.91.0 entry with 7.1.0, which doesn't match the 6.90.0 pins above. Please check that the lockfile still resolves the 6.90.0 consumers.
    • Either bump all consumers in this PR, or state in the PR description why the split is safe.
  2. Ed25519 BYOK chain code is generated by the SDK, and the holder needs it later (prepareExternalBackupPub, safes.ts). When a StrKey is supplied, the SDK appends a fresh random chain code, so the caller's seed alone can't derive the backup child. The chain code lives only in the registered composite pub, which is on the keycard Box B entry and on the server.

    • Recovery needs the composite pub from the card to build the ExternalEd25519Signer for the soft-derived child. That is workable, but the keycard description and the docs should say that the composite pub must be kept.
    • Registering a different chain code than the one the caller expects will also break signing for a caller who derives their own children from the StrKey. Consider documenting this, or accepting a caller-supplied composite pub as the preferred path.
  3. Archiving on mismatch is aggressive in generateSafeKeys (express). In the Phase-2-only route, a caller typo in multisigRoots or externalBackupSlots archives the safe permanently. That is defensible because the slot declaration is fixed at initialize. However, the error message always says "create a new safe and retry". Because the failure can also come from an older WP not echoing externalBackupSlots, the message should name that cause too.

  4. deriveSafeChildTriplet silently ignores opts.externalBackupRootPrv when the backup root is a local string (safeDerivation.ts). deriveSafeWalletKeys guards against this, but direct callers of the lib function don't get the same check. A throw would be consistent.

  5. The ① external-pub check relies on coin.isValidPub. The code comment says a private key is never accepted. Please make sure there is a test that passes an xprv for slot ① and expects rejection. The PR description mentions malformed-key rejection, but I only skimmed the tests.

  6. Operational constraint: one xpub per safe. The PR notes that the wallet platform rejects a pub already used as a safe root. A retry after a partial failure still works because the safe is archived, but the user-facing error from keychains.add on a duplicate pub is not translated. A clearer message would help.

Minor

  • Ed25519ExternalBackupChildKeys and the ...WithExternal type family duplicate a lot of surface. A single generic or union would be easier to maintain, but this is non-blocking.
  • toLowerCase() on the signer pub comparison in buildEd25519MultisigRecoverKeyParams is fine for hex. Consider also validating that both strings are hex.
  • Express SafeMultisigRoots is a t.partial, so unknown keys such as MPC slots decode successfully and are only rejected in the SDK. That's fine, but the doc comment ("rejected before a ceremony runs") should say the rejection happens in sdk-core.

Regression assessment

No regression found for existing safes or keycards:

  • The new multisigRoots and externalBackupSlots options are optional everywhere.
  • The new codec branch is additive.
  • Local-root derivation paths are unchanged.

The main regression risk is the public-types major bump (item 1). I'd resolve that before merge.
· branch WCN-3880

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 A typo in one slot's BYOK key can burn a valid backup xpub supplied for the other slot. The safe is archived after that xpub is already registered. prepareExternalBackupPub runs inside each slot's ceremony, after initializeSafe. createSafeKeys starts all ceremonies in parallel (Promise.allSettled, safes.ts:267). Fix: validate and prepare every supplied multisigRoots entry (isValidPub, ed25519 StrKey/derivable format) in externalBackupSlotsOf/generateSafe before initialize and before any ceremony starts, using coinForRoot per slot. [also at: modules/sdk-core/src/bitgo/safe/safes.ts:160 - A malformed backupXpub is only caught after the safe is initialized and the other root ceremonies have run. Callers are left with an archived safe and orphaned keys.]

Why this was flagged

A caller passes a valid multisigRoots.secp256k1Multisig.backupXpub and a malformed multisigRoots.ed25519Multisig.backupXpub to generateSafe. externalBackupSlotsOf (safes.ts:65) only checks that each value is a non-empty string, so initializeSafe creates the safe. createSafeKeys (safes.ts:267) runs both multisig ceremonies at once. The ed25519 ceremony rejects in prepareExternalBackupPub (safes.ts:747). Meanwhile the secp256k1 ceremony calls keychains.add({ pub, source: 'backup', safeId }) (safes.ts:912) with the caller's xpub. The safe is then archived. The PR states that wallet platform rejects a pub already used as a safe root. If archived safes still hold that claim, the caller cannot retry with their own backup key and must make a new one. The comment at safes.ts:157, 'Validate before initialize so a bad option never leaves a half-created safe behind', does not hold for key-format errors. The base branch had no caller-supplied keys, so nothing like this could happen.

Verification: Trigger: a caller passes a valid slot-① backupXpub together with a malformed slot-④ backupXpub to generateSafe. externalBackupSlotsOf (safes.ts:65-85) only checks that each backupXpub is a non-empty string. It never checks the key format. createSafeKeys starts every ceremony at once (safes.ts:267). Because there is a failure, safes.ts:287-302 then archives the safe and throws.

@claude claude Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Additional findings (outside the current diff — GitHub can't attach inline comments there):

  • 🔴 modules/sdk-core/src/bitgo/safe/keycard.ts — Callers can no longer rebuild a keycard for a BYOK safe: every buildSafeKeycardRoots call throws user/backup root is missing encryptedPrv. buildMultisigSlot still requires backupKeychain.encryptedPrv, but this PR registers external backups as pub-only keys. Fix: in buildMultisigSlot, treat a backup keychain that has pub and no encryptedPrv as external and pass it through untouched. Check the keycard passphrase against another envelope, or skip the check when no backup envelope exists. Keep throwing when a local backup is missing its envelope. [also at: modules/sdk-core/src/bitgo/safe/safes.ts:373 - Callers who build a keycard for a BYOK safe get a hard error, so a safe with a caller-supplied backup root can never get a keycard.]

    Why this was flagged

    After this PR, createMultisigRoot (modules/sdk-core/src/bitgo/safe/safes.ts:373) registers the external backup with keychains.add({ pub, source: 'backup', safeId, enterprise }). That keychain has no encryptedPrv. The keycard flow is Safe.claimKeycardMaterial (safe.ts:510), then buildSafeKeycardRoots (keycard.ts:288), then buildMultisigSlot. That function throws at keycard.ts:137-139 whenever backupKeychain.encryptedPrv is falsy, so any safe with a multisigRoots slot cannot produce keycard roots. The new {kind:'external'} path in key-card's selectBackupRootEntry is never reached from this documented flow. The same error happens if the triplets returned by generateSafe are passed through buildSafeKeycardRoots. Safes created on the base branch are not affected, because every multisig backup there came from createBackup with an encrypted prv.

    Verification: After this PR, createMultisigRoot in modules/sdk-core/src/bitgo/safe/safes.ts no longer calls createBackup, so the backup keychain has no encryptedPrv. buildMultisigSlot, unchanged by this PR, throws safe ${slot} user/backup root is missing encryptedPrv (keycard.ts:137-139). The regeneration flow is therefore always unavailable for BYOK safes.

Comment on lines +370 to +373
const backupKeychainPromise: Promise<Keychain> =
externalBackupPub === undefined
? keychains.createBackup({ passphrase, safeId, originalPasscodeEncryptionCode: passcodeEncryptionCode })
: keychains.add({ pub: externalBackupPub, source: 'backup', safeId, enterprise });

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔴 BYOK callers can lose their backup xpub when any unrelated ceremony fails, and the error then tells them to retry with a new safe, which fails. The external backup is registered alongside the other ceremonies (Promise.allSettled, line 267). Any rejection, such as a transient DKLS/EdDSA MPC error or the slot's own user or BitGo key add, archives the safe with the xpub already bound to it. Fix: register the caller's backup pub only after every other ceremony and the slot's own user/BitGo keys succeed. For BYOK safes, also change the "create a new safe and retry" text (lines 298, 153).

Why this was flagged

Trigger: a caller runs generateSafe or Express handleV2GenerateSafe with multisigRoots.secp256k1Multisig.backupXpub while all four slots are enabled. createSafeKeys starts all ceremonies at once (safes.ts:267). createMultisigRoot posts keychains.add({ pub: externalBackupPub, source: 'backup', safeId, enterprise }) (safes.ts:373) in parallel with the MPC ceremonies (createMpcRoot) and with the slot's own keychains.add user key and createBitGo calls. If any of those rejects, the failure branch at safes.ts:287-302 archives the safe. The caller is then told the safe "has been archived; create a new safe and retry." The PR says wallet platform rejects a pub already used as a safe root, so retrying with the same slot-① xpub fails. On the base branch a failed run only throws away locally generated keys, so retrying always works. Checking multisigRoots before initialize, as the filed candidates propose, does not help here: the failing ceremony is unrelated to the BYOK input.

Verification: safes.ts:267 starts every enabled ceremony at once. The caller's pub is posted at line 373 alongside the user key add (363) and createBitGo (374). Lines 287-302 then archive the safe and throw "The safe (...) has been archived; create a new safe and retry." The base code only generated a fresh backup key each run (createBackup), so a retry always worked there.

@s84krish

Copy link
Copy Markdown
Contributor Author

@claude re-review checking if all feedback has been addressed

@github-actions

github-actions Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @s84krish's task in 29s —— View job


Re-review: feedback status

I read the current code in safes.ts, keycard.ts and safeDerivation.ts, and checked the lockfile and package.json files. I did not run the test suites or CI, so none of this is verified by tests.

Addressed in the code (HEAD b3da5c4)

Feedback Status
🔴 A malformed key in one slot can burn a valid xpub for another slot ✅ Fixed. generateSafe calls prepareExternalBackupPub for every supplied slot before initializeSafe. createSafeKeys repeats this before any ceremony starts.
🔴 An unrelated ceremony failure archives the safe with the xpub already bound ✅ Fixed. The ceremonies no longer register the pub. Phase 2 binds the BYOK pubs one at a time, only after every ceremony succeeds. The error text says "No backup xpub was registered, so the same keys work on the new safe."
🔴 buildMultisigSlot throws for pub-only backups ✅ Fixed. A pub-only backup keychain passes through without a passphrase check. A local backup still has its envelope verified.
deriveSafeChildTriplet ignores externalBackupRootPrv when the backup root is local ✅ Fixed. It now throws.
An xprv passed for slot ① must be rejected ✅ There is a test at safes.ts:471, and the mock isValidPub rejects non-neutered keys.
Archive-on-mismatch message ✅ Mostly fixed. The message names the older-WP case ("does not echo externalBackupSlots") and tells the caller whether any xpub was consumed.

Still open

  1. @bitgo/public-types split (6.90.0 vs 7.1.0). This is unchanged. express, sdk-core and sdk-lib-safes use 7.1.0. bitgo, abstract-lightning, passkey-crypto, sdk-coin-flrp and sdk-coin-sol stay on 6.90.0.
    • The lockfile is fine. It holds separate 6.90.0 and 7.1.0 entries, so my earlier lockfile concern is withdrawn.
    • The question is still open. bitgo consumes sdk-core and express types, so two copies of the package will sit in the tree. Please either bump the other consumers or add a line to the PR description saying why the split is safe, for example that no 7.x codecs or branded types cross the package boundary.
  2. Ed25519 BYOK chain code. I did not find any doc or keycard text saying that the registered composite pub, which includes the SDK-generated chain code, must be kept for recovery. Please add a short note to the docs or JSDoc for multisigRoots.
  3. Duplicate-pub error from keychains.add. It is wrapped with context, but I did not see a message specific to "pub already used as a safe root". This is non-blocking and optional.
  4. Minor, non-blocking. Ed25519ExternalBackupChildKeys and the ...WithExternal types still repeat a lot of surface. The express SafeMultisigRoots doc comment should say the MPC-slot rejection happens in sdk-core.

Summary: all three 🔴 blockers and the main smaller items are fixed. Only the public-types split needs a decision before merge, plus the small docs note in item 2. If item 1 is resolved or explained, I'd rate this 9/10. I can't approve PRs, so that approval is yours to give.
· branch WCN-3880

This branch is waiting to be deployed

1 waiting deployment
breaking-changes-override — b3da5c4d Waiting Nov 17, 2026 by s84krish via Linter Override #6348
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant