Skip to content

Commit e5bcfaa

Browse files
committed
feat: safe keycard regeneration SDK support
sdk-lib-mpc: pure CBOR reduce helpers (reduceDklsKeyShare, reduceMpsKeyShare) extracted from the DKG classes, with byte-equality goldens against Dkg.getReducedKeyShare. sdk-lib-safes: parseSafeKeycardBox accepts any non-empty declared subset of root slots (aligned with the unmerged WCN-2734 branch, adapted for the ed25519 chain-code entry). key-card: safe keycard generation accepts a slot subset and gains a blob-returning variant (generateSafeKeycardBlob) for mobile. sdk-core: Safe.requestKeycardAccess / claimKeycardMaterial (WCN-3921 route contract), buildSafeKeycardRoots (Box A re-encrypt under the creation password, MPC reduce + re-envelope in one encryption session, backup envelopes byte-identical), Box D decrypt helper, generateSafe takes passcodeEncryptionCode (stored as originalPasscodeEncryptionCode on the multisig and MPC user/backup roots) and returns the root triplets incl. reducedEncryptedPrv, decrypt/derive tolerate slot subsets. Express handlers keep their documented wire contracts (root key ids only; no key material over the wire). Experimental/beta surface; no runtime flag — the routes are gated server-side by wp_safe_keycard_access. Ticket: WCN-3922
1 parent 55d7118 commit e5bcfaa

29 files changed

Lines changed: 1337 additions & 163 deletions

File tree

‎modules/express/src/clientRoutes.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -722,7 +722,7 @@ export async function handleV2GenerateSafe(
722722
req: ExpressApiRouteRequest<'express.v2.safes.generate', 'post'>
723723
): Promise<any> {
724724
const safes = new Safes(req.bitgo, req.decoded.enterpriseId);
725-
const safe = await safes.generateSafe({
725+
const { safe } = await safes.generateSafe({
726726
label: req.decoded.label,
727727
passphrase: req.decoded.passphrase,
728728
});
@@ -751,12 +751,15 @@ export async function handleV2GenerateSafeWallet(
751751
*/
752752
export async function handleV2GenerateSafeKeys(req: ExpressApiRouteRequest<'express.v2.safes.keys.generate', 'post'>) {
753753
const safes = new Safes(req.bitgo, req.decoded.enterpriseId);
754-
return safes.createSafeKeys({
754+
const created = await safes.createSafeKeys({
755755
label: '',
756756
passphrase: req.decoded.passphrase,
757757
safeId: req.decoded.safeId,
758758
enabledRootSlots: req.decoded.enabledRootSlots,
759759
});
760+
// The root triplets are client-side keycard material (encrypted private keys); the express
761+
// wire contract stays the documented one — only the root key ids.
762+
return { rootKeys: created.rootKeys };
760763
}
761764

762765
/**

‎modules/express/test/unit/typedRoutes/generateSafe.ts‎

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -48,11 +48,12 @@ describe('Generate Safe Typed Routes Tests', function () {
4848
const label = 'Test Safe';
4949
const passphrase = 'mySecurePassphrase123';
5050
const safeJson = mockSafeJson(label);
51-
const generateSafeStub = sinon.stub(Safes.prototype, 'generateSafe').resolves(
52-
stubSafe({
51+
const generateSafeStub = sinon.stub(Safes.prototype, 'generateSafe').resolves({
52+
safe: stubSafe({
5353
toJSON: () => safeJson,
54-
})
55-
);
54+
}),
55+
rootKeychains: {},
56+
});
5657

5758
const res = await agent.post(`/api/v2/enterprise/${ENTERPRISE_ID}/safes/generate`).send({
5859
label,
@@ -222,6 +223,7 @@ describe('Generate Safe Typed Routes Tests', function () {
222223
secp256k1Multisig: ['user-1', 'backup-1', 'bitgo-1'] as [string, string, string],
223224
},
224225
},
226+
rootKeychains: {},
225227
};
226228

227229
it('should run phase-2 ceremonies and return root key ids', async function () {
@@ -235,6 +237,8 @@ describe('Generate Safe Typed Routes Tests', function () {
235237

236238
res.status.should.equal(200);
237239
res.body.should.have.property('rootKeys');
240+
// The express contract returns only the ids; the root triplets stay client-side.
241+
res.body.should.not.have.property('rootKeychains');
238242
res.body.rootKeys.hot.secp256k1Multisig.should.deepEqual(['user-1', 'backup-1', 'bitgo-1']);
239243
createSafeKeysStub.should.have.been.calledOnce();
240244
createSafeKeysStub.firstCall.args[0].should.have.property('passphrase', passphrase);

‎modules/key-card/src/generateQrData.ts‎

Lines changed: 17 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -247,19 +247,24 @@ function selectRootPublicKey(keychain: Keychain, slot: SafeRootKeyType): string
247247
}
248248

249249
/**
250-
* Serializes one box's four roots into a single JSON object keyed by rootKeyType, e.g.
251-
* `{"secp256k1Multisig":"<encPrv>","ecdsaMpc":"<reducedEncPrv>",...}`. This keeps the safe
252-
* keycard on the existing 4-box layout — one box (= one QR/data block) per role — with the
253-
* four roots packed into each box's data. `splitKeys` fragments the box if it exceeds the QR
254-
* threshold, exactly as for a normal wallet keycard. Reversed by {@link parseSafeKeycardBox}.
250+
* Serializes one box's roots into a single JSON object keyed by rootKeyType, e.g.
251+
* `{"secp256k1Multisig":"<encPrv>","ecdsaMpc":"<reducedEncPrv>",...}`. Only the root slots the
252+
* safe actually carries are packed, in canonical order, so partial-slot safes render a
253+
* keycard too. This keeps the safe keycard on the existing 4-box layout — one box (= one
254+
* QR/data block) per role — with the roots packed into each box's data. `splitKeys` fragments
255+
* the box if it exceeds the QR threshold, exactly as for a normal wallet keycard. Reversed
256+
* by {@link parseSafeKeycardBox}.
255257
*/
256258
function buildSafeBoxData(
257-
roots: Record<SafeRootKeyType, KeychainsTriplet>,
259+
roots: Partial<Record<SafeRootKeyType, KeychainsTriplet>>,
258260
select: (root: KeychainsTriplet, slot: SafeRootKeyType) => SafeKeycardRootEntry
259261
): string {
260262
const box: SafeKeycardRoots = {} as SafeKeycardRoots;
261263
for (const slot of SAFE_ROOT_ORDER) {
262264
const root = roots[slot];
265+
if (root === undefined) {
266+
continue;
267+
}
263268
assert.ok(root, `Safe is missing the ${slot} root`);
264269
box[slot] = select(root, slot);
265270
}
@@ -268,11 +273,15 @@ function buildSafeBoxData(
268273

269274
/**
270275
* Builds safe keycard QR data in the existing wallet {@link QrData} shape: boxes A (user),
271-
* B (backup), C (BitGo), D (passcode). Each of A/B/C carries a JSON object of the four roots,
272-
* so the safe renders and parses through the same {@link drawKeycard} path as a wallet.
276+
* B (backup), C (BitGo), D (passcode). Each of A/B/C carries a JSON object of the safe's
277+
* root slots, so the safe renders and parses through the same {@link drawKeycard} path as
278+
* a wallet. Requires at least one root triplet.
273279
*/
274280
export async function generateSafeQrData(params: GenerateSafeQrDataParams): Promise<QrData> {
275281
const { roots } = params;
282+
if (Object.keys(roots).length === 0) {
283+
throw new Error('safe keycard requires at least one root triplet');
284+
}
276285
const qrData: QrData = {
277286
user: {
278287
title: 'A: User Key',

‎modules/key-card/src/index.ts‎

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -53,8 +53,8 @@ export async function generateLightningKeycard(
5353

5454
/**
5555
* Generates a safe keycard using the existing 4-box layout: boxes A/B/C each carry a JSON
56-
* object of the four roots (see {@link generateSafeQrData}), rendered through the same
57-
* {@link drawKeycard} path as a wallet. Generated as part of safe creation, once all four
56+
* object of the safe's root slots (see {@link generateSafeQrData}), rendered through the same
57+
* {@link drawKeycard} path as a wallet. Generated as part of safe creation, once the safe's
5858
* root triplets exist.
5959
*/
6060
export async function generateSafeKeycard(params: GenerateQrDataBaseParams & GenerateSafeQrDataParams): Promise<void> {
@@ -70,3 +70,22 @@ export async function generateSafeKeycard(params: GenerateQrDataBaseParams & Gen
7070
const label = params.walletLabel || params.coin.fullName;
7171
keycard.save(`BitGo Keycard for ${label}.pdf`);
7272
}
73+
74+
/**
75+
* Same as {@link generateSafeKeycard} but returns the PDF as a {@link Blob} instead of saving
76+
* it to disk, for callers (e.g. mobile) that stream the bytes themselves.
77+
*/
78+
export async function generateSafeKeycardBlob(
79+
params: GenerateQrDataBaseParams & GenerateSafeQrDataParams
80+
): Promise<Blob> {
81+
const questions = generateFaq(params.coin.fullName);
82+
const qrData = await generateSafeQrData(params);
83+
const keycard = await drawKeycard({
84+
...params,
85+
questions,
86+
qrData,
87+
pageBreakBeforeIndices: [1, 2],
88+
useQrPartHeaders: true,
89+
});
90+
return keycard.output('blob');
91+
}

‎modules/key-card/src/types.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -78,8 +78,9 @@ export const SAFE_ROOT_ORDER = Object.keys(slotsInRenderOrder) as SafeRootKeyTyp
7878
export type KeycardEntity = 'wallet' | 'safe';
7979

8080
export interface GenerateSafeQrDataParams extends GenerateQrDataCoinParams {
81-
// The four root triplets (user/backup/bitgo keychains), keyed by rootKeyType.
82-
roots: Record<SafeRootKeyType, KeychainsTriplet>;
81+
// The safe's root triplets (user/backup/bitgo keychains), keyed by rootKeyType. Any non-empty
82+
// subset of the four slots is valid; the keycard carries exactly the slots present here.
83+
roots: Partial<Record<SafeRootKeyType, KeychainsTriplet>>;
8384
}
8485

8586
export type GenerateKeycardParams = GenerateQrDataBaseParams &

‎modules/key-card/test/unit/safeQrData.ts‎

Lines changed: 42 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ import {
1212
parseMpcV2KeyShareEnvelope,
1313
} from '@bitgo/sdk-core';
1414
import { generateSafeQrData } from '../../src/generateQrData';
15+
import { generateSafeKeycardBlob } from '../../src';
1516
import { splitKeys } from '../../src/utils';
1617
import { QRBinaryMaxLength } from '../../src/drawKeycard';
1718
import { parseKeycardFromLines, parseSafeKeycardBox } from '../../src/parseKeycard';
@@ -223,10 +224,44 @@ describe('generateSafeQrData', function () {
223224
await assert.rejects(() => generateSafeQrData({ coin: coins.get('btc'), roots }), /missing encrypted private key/);
224225
});
225226

226-
it('throws a clear error when an entire root triplet is missing', async function () {
227+
it('round-trips a 2-slot subset: only the declared slots appear in every box', async function () {
228+
const { roots, plaintexts, bitgoPubs } = await buildRoots();
229+
const subset: Partial<Record<SafeRootKeyType, KeychainsTriplet>> = {
230+
secp256k1Multisig: roots.secp256k1Multisig,
231+
ecdsaMpc: roots.ecdsaMpc,
232+
};
233+
const qrData = await generateSafeQrData({ coin: coins.get('btc'), roots: subset });
234+
assert.ok(qrData.backup && qrData.bitgo);
235+
236+
const expectedKeys = ['secp256k1Multisig', 'ecdsaMpc'];
237+
for (const box of [qrData.user, qrData.backup, qrData.bitgo]) {
238+
assert.ok(box);
239+
Object.keys(parseSafeKeycardBox(box.data)).should.deepEqual(expectedKeys);
240+
}
241+
242+
const userBox = parseSafeKeycardBox(qrData.user.data);
243+
const backupBox = parseSafeKeycardBox(qrData.backup.data);
244+
const bitgoBox = parseSafeKeycardBox(qrData.bitgo.data);
245+
for (const slot of expectedKeys) {
246+
(await decrypt(passphrase, userBox[slot] as string)).should.equal(plaintexts[slot].user);
247+
(await decrypt(passphrase, backupBox[slot] as string)).should.equal(plaintexts[slot].backup);
248+
bitgoBox[slot].should.equal(bitgoPubs[slot]);
249+
}
250+
});
251+
252+
it('throws when roots is empty', async function () {
253+
await assert.rejects(() => generateSafeQrData({ coin: coins.get('btc'), roots: {} }), /at least one root triplet/);
254+
});
255+
256+
it('generateSafeKeycardBlob returns a non-empty PDF blob without saving to disk', async function () {
227257
const { roots } = await buildRoots();
228-
delete (roots as Partial<Record<SafeRootKeyType, KeychainsTriplet>>).ecdsaMpc;
229-
await assert.rejects(() => generateSafeQrData({ coin: coins.get('btc'), roots }), /missing the ecdsaMpc root/);
258+
const subset: Partial<Record<SafeRootKeyType, KeychainsTriplet>> = {
259+
secp256k1Multisig: roots.secp256k1Multisig,
260+
ed25519Multisig: roots.ed25519Multisig,
261+
};
262+
const blob = await generateSafeKeycardBlob({ coin: coins.get('btc'), roots: subset });
263+
assert.ok(blob instanceof Blob, 'expected a Blob');
264+
assert.ok(blob.size > 0, 'expected a non-empty PDF blob');
230265
});
231266

232267
it('recovers all 4 roots through the existing PDF-line parser + JSON.parse', async function () {
@@ -262,9 +297,11 @@ describe('generateSafeQrData', function () {
262297
it('parseSafeKeycardBox rejects malformed / incomplete box data', function () {
263298
assert.throws(() => parseSafeKeycardBox('not json'), /parseSafeKeycardBox/); // invalid JSON
264299
assert.throws(() => parseSafeKeycardBox('"a string"'), /parseSafeKeycardBox/); // not an object
265-
assert.throws(() => parseSafeKeycardBox('{"secp256k1Multisig":"x"}'), /parseSafeKeycardBox/); // missing roots
300+
assert.throws(() => parseSafeKeycardBox('{}'), /empty slot set/); // declares no roots
301+
assert.throws(() => parseSafeKeycardBox('{"secp256k1Multisig":"a","unknownRoot":"b"}'), /unknownRoot/);
302+
parseSafeKeycardBox('{"secp256k1Multisig":"x"}').should.deepEqual({ secp256k1Multisig: 'x' }); // a subset now parses
266303
// A well-formed box with all four roots decodes successfully.
267304
const ok = parseSafeKeycardBox('{"secp256k1Multisig":"a","ecdsaMpc":"b","eddsaMpc":"c","ed25519Multisig":"d"}');
268-
ok.ecdsaMpc.should.equal('b');
305+
ok.ecdsaMpc!.should.equal('b');
269306
});
270307
});

‎modules/sdk-core/src/bitgo/keychain/iKeychains.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -298,6 +298,9 @@ export interface CreateBackupOptions {
298298
encryptedPrv?: string;
299299
passphrase?: string;
300300
encryptionVersion?: EncryptionVersion;
301+
/** Code the backup root's encryptedPrv is additionally wrapped under server-side, so a
302+
* regenerated keycard can re-derive it (WCN-3922). Forwarded by `add` on the wire. @experimental */
303+
originalPasscodeEncryptionCode?: string;
301304
/** Public id of the safe this backup key is a root of (Wallet Safes v1). @experimental */
302305
safeId?: string;
303306
}

‎modules/sdk-core/src/bitgo/safe/iSafe.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import type {
1919
import type { EncryptionVersion } from '../../api/types';
2020
import type { Wallet, WalletShare } from '../wallet';
2121
import type { WebAuthnProvider } from '../webauthn';
22+
import type { SafeKeycardAccess, SafeKeycardMaterial, SafeKeycardPendingApproval } from './keycard';
2223

2324
/** @experimental */
2425
export interface InitializeSafeOptions {
@@ -139,6 +140,22 @@ export interface ISafe {
139140
acceptShare(params: AcceptSafeShareOptions): Promise<SafeShareData>;
140141
registerPasskey(params: RegisterSafePasskeyOptions): Promise<RegisterSafePasskeyResponse>;
141142
removePasskey(params: RemoveSafePasskeyOptions): Promise<void>;
143+
/**
144+
* Request keycard regeneration access for this safe (WCN-3921 route contract). Returns the
145+
* granted access window, or the pending approval the request created when policy requires
146+
* one. Gated server-side by the `wp_safe_keycard_access` flag.
147+
* @experimental
148+
*/
149+
requestKeycardAccess(): Promise<
150+
{ keycardAccess: SafeKeycardAccess } | { pendingApproval: SafeKeycardPendingApproval }
151+
>;
152+
/**
153+
* Claim the safe's keycard material (root triplets + optional passcode encryption code)
154+
* once keycard access has been granted. Wire shapes are decoded minimally; the exact PA
155+
* serialization is owned by the WP routes.
156+
* @experimental
157+
*/
158+
claimKeycardMaterial(): Promise<SafeKeycardMaterial>;
142159
freeze(params?: FreezeSafeBody): Promise<SafeData>;
143160
archive(): Promise<SafeData>;
144161
toJSON(): SafeData;

‎modules/sdk-core/src/bitgo/safe/iSafes.ts‎

Lines changed: 14 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
*/
77
import type { InitializeSafeResponse } from '@bitgo/public-types';
88
import { FinalizeSafeOptions, InitializeSafeOptions } from './iSafe';
9+
import type { SafeKeychainRoots } from './keycard';
910
import { Safe } from './safe';
1011

1112
/**
@@ -20,6 +21,8 @@ import { Safe } from './safe';
2021
export interface CreateSafeOptions {
2122
label: string;
2223
passphrase: string; // encrypts the locally-generated multisig user/backup prvs; shared with the MPC ceremonies
24+
/** Generated by the caller and stored on the roots as `originalPasscodeEncryptionCode`; absent ⇒ no Box D. @experimental */
25+
passcodeEncryptionCode?: string;
2326
}
2427

2528
/**
@@ -35,11 +38,18 @@ export interface SafeCreationHandle {
3538
}
3639

3740
/**
38-
* The minted root key ids produced by `createSafeKeys`, as ordered [user, backup, bitgo]
39-
* triplets for the enabled slots — exactly the payload `finalizeSafe` consumes.
41+
* The minted root keys produced by `createSafeKeys`: the ordered [user, backup, bitgo] id
42+
* triplets `finalizeSafe` consumes, plus the full keychain triplets (including each root's
43+
* `encryptedPrv` / `reducedEncryptedPrv`) the caller needs to generate the safe keycard.
4044
* @experimental
4145
*/
42-
export type SafeKeys = FinalizeSafeOptions;
46+
export type SafeKeys = FinalizeSafeOptions & { rootKeychains: SafeKeychainRoots };
47+
48+
/** Result of the one-call `generateSafe`: the finalized safe plus its root keychain triplets. */
49+
export interface SafeCreationResult {
50+
safe: Safe;
51+
rootKeychains: SafeKeychainRoots;
52+
}
4353

4454
/**
4555
* @experimental
@@ -66,7 +76,7 @@ export interface ISafes {
6676
* HOT custody only in v1.
6777
* @experimental
6878
*/
69-
generateSafe(params: CreateSafeOptions): Promise<Safe>;
79+
generateSafe(params: CreateSafeOptions): Promise<SafeCreationResult>;
7080
/**
7181
* Phase 1 — initialize a safe (metadata only, no key material). The server response is
7282
* `{ id, status }` plus optional `enabledRootSlots` (no `label`/`enterpriseId`/`creator`/`users`/

‎modules/sdk-core/src/bitgo/safe/index.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
export * from './derivableEd25519Pub';
22
export * from './iSafe';
33
export * from './iSafes';
4+
export * from './keycard';
45
export * from './recovery';
56
export * from './safe';
67
export * from './safes';

0 commit comments

Comments
 (0)