Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
61 changes: 61 additions & 0 deletions modules/passkey-crypto/src/derivePasskeyPrfKey.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,61 @@
import type { BitGoBase, IWallet } from '@bitgo/sdk-core';
import { buildEvalByCredential, matchDeviceByCredentialId } from './prfHelpers';
import { derivePassword } from './derivePassword';
import type { WebAuthnProvider } from './webAuthnTypes';

interface AssertionChallengeResponse {
challenge: string;
}

/**
* Derives a wallet passphrase from a passkey PRF output.
*
* Fetches the wallet's user keychain, triggers a WebAuthn assertion with PRF
* evaluation, and returns a hex-encoded passphrase suitable for use as
* walletPassphrase in signing calls.
*/
export async function derivePasskeyPrfKey(params: {
bitgo: BitGoBase;
wallet: IWallet;
provider: WebAuthnProvider;
}): Promise<string> {
const { bitgo, wallet, provider } = params;

// Fetch the wallet's user keychain to get webauthnDevices
const keychain = await wallet.getEncryptedUserKeychain();
const devices = keychain.webauthnDevices;

if (!devices || devices.length === 0) {
throw new Error('No passkey devices available');
}

// Build PRF eval map from devices
const { evalByCredential } = buildEvalByCredential(devices as Parameters<typeof buildEvalByCredential>[0]);

if (Object.keys(evalByCredential).length === 0) {
throw new Error('No passkey devices available with a valid PRF salt');
}

// Fetch a server-issued assertion challenge
const { challenge } = (await bitgo
.get(bitgo.url('/user/otp/webauthn/assertion', 2))
.result()) as AssertionChallengeResponse;

// Trigger WebAuthn assertion with PRF evaluation via the provider (navigator layer)
const result = await provider.get({
publicKey: {
challenge: Buffer.from(challenge, 'base64'),
} as PublicKeyCredentialRequestOptions,
evalByCredential,
});
Comment on lines +45 to +50
Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

shouldn't we use the navigator object here?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

To keep things enviroment agnostic I dont think we can

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Updated — bitgo is now used to fetch a server-issued assertion challenge from /user/otp/webauthn/assertion, and the manual allowCredentials construction has been removed. The provider receives { publicKey: { challenge }, evalByCredential } and handles the navigator-level credential selection.

Buffer.from(challenge, 'base64') is consistent with the existing registerPasskey.ts pattern — Buffer extends Uint8Array and satisfies BufferSource, so no DOM compatibility issue there.


// Verify the credential matches a known device
matchDeviceByCredentialId(devices as Parameters<typeof matchDeviceByCredentialId>[0], result.credentialId);

// Derive and return hex-encoded wallet passphrase
if (!result.prfResult) {
throw new Error('PRF output was not returned by the authenticator');
}

return derivePassword(result.prfResult);
}
147 changes: 147 additions & 0 deletions modules/passkey-crypto/test/unit/derivePasskeyPrfKey.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
import * as assert from 'assert';
import * as sinon from 'sinon';
import { derivePasskeyPrfKey } from '../../src/derivePasskeyPrfKey';

describe('derivePasskeyPrfKey', function () {
const mockDevices = [
{
otpDeviceId: 'device-1',
authenticatorInfo: { credID: 'cred-aaa', fmt: 'none' as const, publicKey: 'pk-1' },
prfSalt: 'salt-aaa',
encryptedPrv: 'enc-prv-1',
},
{
otpDeviceId: 'device-2',
authenticatorInfo: { credID: 'cred-bbb', fmt: 'none' as const, publicKey: 'pk-2' },
prfSalt: 'salt-bbb',
encryptedPrv: 'enc-prv-2',
},
];

function makeWallet(devices: typeof mockDevices | undefined) {
return {
getEncryptedUserKeychain: sinon.stub().resolves({
id: 'keychain-id',
pub: 'xpub123',
encryptedPrv: 'encrypted-prv',
type: 'independent',
webauthnDevices: devices,
}),
};
}

function makeBitGo(challenge = 'dGVzdC1jaGFsbGVuZ2U=') {
return {
url: sinon.stub().callsFake((path: string) => `https://app.bitgo.com/api/v2${path}`),
get: sinon.stub().returns({
result: sinon.stub().resolves({ challenge }),
}),
};
}

afterEach(function () {
sinon.restore();
});

it('should return a hex string on happy path', async function () {
const prfResult = new Uint8Array([0xde, 0xad, 0xbe, 0xef]).buffer;

const mockProvider = {
create: sinon.stub(),
get: sinon.stub().resolves({
prfResult,
credentialId: 'cred-aaa',
otpCode: 'otp-123',
}),
};

const wallet = makeWallet(mockDevices);
const mockBitGo = makeBitGo();

const result = await derivePasskeyPrfKey({
bitgo: mockBitGo as any,
wallet: wallet as any,
provider: mockProvider,
});

// derivePassword converts ArrayBuffer to hex
assert.strictEqual(result, 'deadbeef');
assert.ok(mockProvider.get.calledOnce);
// Verify evalByCredential was passed
const getCallArgs = mockProvider.get.firstCall.args[0];
assert.strictEqual(getCallArgs.evalByCredential['cred-aaa'], 'salt-aaa');
assert.strictEqual(getCallArgs.evalByCredential['cred-bbb'], 'salt-bbb');
// Verify bitgo was used to fetch the assertion challenge
assert.ok(mockBitGo.get.calledOnce);
assert.ok(mockBitGo.url.calledWith('/user/otp/webauthn/assertion', 2));
});

it("should throw 'No passkey devices available' when no devices", async function () {
const wallet = makeWallet(undefined);
const mockProvider = { create: sinon.stub(), get: sinon.stub() };

await assert.rejects(
() => derivePasskeyPrfKey({ bitgo: makeBitGo() as any, wallet: wallet as any, provider: mockProvider }),
(err: Error) => {
assert.strictEqual(err.message, 'No passkey devices available');
return true;
}
);
});

it("should throw 'No passkey devices available' when devices array is empty", async function () {
const wallet = makeWallet([] as any);
const mockProvider = { create: sinon.stub(), get: sinon.stub() };

await assert.rejects(
() => derivePasskeyPrfKey({ bitgo: makeBitGo() as any, wallet: wallet as any, provider: mockProvider }),
(err: Error) => {
assert.strictEqual(err.message, 'No passkey devices available');
return true;
}
);
});

it("should throw 'No passkey devices available with a valid PRF salt' when no device has prfSalt", async function () {
const devicesWithoutSalt = [
{
otpDeviceId: 'device-1',
authenticatorInfo: { credID: 'cred-aaa', fmt: 'none' as const, publicKey: 'pk-1' },
prfSalt: '', // empty — buildEvalByCredential skips falsy prfSalt
encryptedPrv: 'enc-prv-1',
},
];

const wallet = makeWallet(devicesWithoutSalt as any);
const mockProvider = { create: sinon.stub(), get: sinon.stub() };

await assert.rejects(
() => derivePasskeyPrfKey({ bitgo: makeBitGo() as any, wallet: wallet as any, provider: mockProvider }),
(err: Error) => {
assert.strictEqual(err.message, 'No passkey devices available with a valid PRF salt');
return true;
}
);
});

it("should throw 'Could not identify which passkey device was used' when credentialId not found", async function () {
const mockProvider = {
create: sinon.stub(),
get: sinon.stub().resolves({
prfResult: new ArrayBuffer(32),
credentialId: 'unknown-cred-id',
otpCode: 'otp-123',
}),
};

const wallet = makeWallet(mockDevices);

await assert.rejects(
() => derivePasskeyPrfKey({ bitgo: makeBitGo() as any, wallet: wallet as any, provider: mockProvider }),
(err: Error) => {
assert.strictEqual(err.message, 'Could not identify which passkey device was used');
return true;
}
);
});
});
Loading