@ledgerhq/revault-sdk 0.13.1 → 0.16.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.
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/_work/revault/revault/packages/sdk/lib/engine.cjs","../src/engine/index.ts","../src/device/real-device.ts","../src/trpc.ts"],"names":["withApiUser","withWorkspace","withOnboarding","client","engine"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,4FAAsB;ADOtB;AACA;AEpBA,0CAAsD;AAGtD;AACA,4BAAoC;AAkBpC,IAAM,iBAAA,EAAmB,GAAA;AAMzB,IAAM,sBAAA,EACJ,CAAC,MAAA,EAAA,GACD,MAAA,CAAA,EAAA,GAAY;AACV,EAAA,MAAM,IAAI,KAAA,CAAM,CAAA,iBAAA,EAAoB,MAAM,CAAA,CAAA;AAC5C;AAE8D;AACpB,EAAA;AACP,EAAA;AACrC;AAEiE;AAC/C,EAAA;AACyB,EAAA;AACF,IAAA;AACvC,EAAA;AACO,EAAA;AACT;AAE8D;AAK5D;AAG0C,EAAA;AACb,EAAA;AACW,EAAA;AAChB,IAAA;AACE,IAAA;AAGT,IAAA;AAE2B,IAAA;AACxC,MAAA;AACG,MAAA;AACJ,IAAA;AACH,EAAA;AACO,EAAA;AACT;AAMc;AACyB,EAAA;AACC,EAAA;AACA,EAAA;AAEA,EAAA;AACC,EAAA;AACC,EAAA;AAEH,EAAA;AAED,EAAA;AAClC,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACD,EAAA;AAEuC,EAAA;AACC,EAAA;AACV,EAAA;AAEM,EAAA;AACC,EAAA;AACA,EAAA;AAEC,EAAA;AACD,EAAA;AAEX,EAAA;AACzB,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;A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D,cAAA;AAG7B,YAAA;AACF,UAAA;AACF,QAAA;AACF,MAAA;AACF,IAAA;AAI4B,IAAA;AAC8D,MAAA;AAC3DC,QAAAA;AAEoB,QAAA;AACd,UAAA;AACE,UAAA;AACJ,UAAA;AACG,YAAA;AACD,YAAA;AAC9B,UAAA;AACkC,UAAA;AACrC,QAAA;AAEO,QAAA;AAGH,UAAA;AAE4BD,YAAAA;AACR,YAAA;AACC,YAAA;AACR,YAAA;AACU,cAAA;AACC,cAAA;AACC,cAAA;AACxB,YAAA;AAC2B,4BAAA;AACG,YAAA;AACV,cAAA;AACpB,YAAA;AAC8B,YAAA;AACjB,cAAA;AACkB,cAAA;AAC/B,YAAA;AACH,UAAA;AAE0E,UAAA;AAC1C,YAAA;AAChC,UAAA;AACF,QAAA;AACD,MAAA;AACH,IAAA;AAIqC,IAAA;AACsD,MAAA;AACpEC,QAAAA;AACZ,QAAA;AACoF,UAAA;AAC3DD,YAAAA;AACR,YAAA;AACH,YAAA;AACnB,UAAA;AAKoC,UAAA;AACH,YAAA;AACjB,cAAA;AACkB,cAAA;AAC/B,YAAA;AACH,UAAA;AAKoC,UAAA;AACJ,YAAA;AAChB,cAAA;AACkB,cAAA;AAC/B,YAAA;AACH,UAAA;AACF,QAAA;AACD,MAAA;AACH,IAAA;AAEO,IAAA;AACT,EAAA;AAEO,EAAA;AACF,IAAA;AACH,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;ADiJ6C;AACA;AACA;AACA","file":"/home/runner/_work/revault/revault/packages/sdk/lib/engine.cjs","sourcesContent":[null,"import type {\n ApiChallenge,\n ClaimedRole,\n OnboardingSeedChallenge,\n PsdChallenge,\n UserRegistrationChallenge,\n UserRegistrationChallengeResponse,\n UserRegistrationDeviceData,\n UserRegistrationResponse,\n VaultRequestResponse,\n WrappingKeyResponse,\n} from \"@ledgerhq/revault-api\";\nimport invariant from \"invariant\";\n\nimport { type Device, createApiDevice } from \"@/device\";\nimport { createRealDevice } from \"@/device/real-device\";\nimport { type TRPCClientOptions, createClient } from \"@/trpc\";\nimport type { Logger } from \"@/types\";\n\nimport type {\n ApproveRequestParams,\n DecorateWithApiUserAndWorkspaceUnauthenticated,\n DecorateWithDevice,\n DecorateWithDeviceAndOnboarding,\n DecorateWithDeviceAndWorkspaceUnauthenticated,\n DecorateWithWorkspaceApiAuthenticated,\n DecorateWithWorkspacePsdAuthenticated,\n DecorateWithWorkspaceUnauthenticated,\n Engine,\n EngineBase,\n EngineOptions,\n RegisterOnboardingDeviceParams,\n WithApiAuth,\n WithApiUser,\n WithDevice,\n WithOnboarding,\n WithPsdAuth,\n WithWorkspace,\n} from \"./types\";\n\nexport { fetchAll } from \"../utils\";\n\nexport type * from \"./types\";\n\nasync function genericRegister<T>({\n device,\n name,\n role,\n getChallenge,\n submitChallenge,\n}: {\n device: Device;\n name: string;\n role: \"ADMIN\" | \"SHARED_OWNER\" | \"OPERATOR\";\n getChallenge: (p: {\n pubKey: string;\n deviceData: UserRegistrationDeviceData;\n }) => Promise<UserRegistrationChallenge>;\n submitChallenge: (p: {\n pubKey: string;\n challengeResponse: UserRegistrationChallengeResponse;\n }) => Promise<T>;\n}): Promise<T> {\n const [attestation, u2fPubKey, confidentialityKey] = await Promise.all([\n device.getAttestation(),\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n const ephemeralPubKey = await device.initPairingHandshake();\n const deviceData: UserRegistrationDeviceData = {\n name,\n pubKey: u2fPubKey.pubKey,\n psdModel: \"STAX\",\n confidentialityKey: confidentialityKey.pubKey,\n psdEphemeralKey: ephemeralPubKey.pubKey,\n psdEphemeralKeyAttestation: {\n ...attestation.attestation,\n signature: ephemeralPubKey.signature,\n },\n };\n const challenge = await getChallenge({ pubKey: u2fPubKey.pubKey, deviceData });\n const pairingPayload = await device.finalizePairingHandshake({\n handshake: challenge.handshake,\n ciphertext: challenge.ciphertext,\n });\n const register = await device.register({\n challenge: challenge.challenge,\n u2fRegisterData: challenge.u2fRegisterData,\n name,\n role,\n });\n const validationPubKey = await device.getValidationPubKey();\n const registerData = await device.registerData({ challenge: challenge.challenge });\n const attestationOffset = 67 + register.u2fRegister.readInt8(66);\n const u2fRegister = Buffer.concat([\n register.u2fRegister.slice(0, attestationOffset),\n Buffer.from([attestation.buffer.length]),\n attestation.buffer,\n register.u2fRegister.slice(attestationOffset),\n ]).toString(\"hex\");\n const challengeResponse: UserRegistrationChallengeResponse = {\n registerData,\n certificate: {\n ...attestation.attestation,\n signature: validationPubKey.signature,\n },\n u2fRegister,\n u2fKeyHandle: register.keyHandle.toString(\"hex\"),\n validationKey: validationPubKey.pubKey,\n pairingPayload,\n };\n return submitChallenge({ pubKey: u2fPubKey.pubKey, challengeResponse });\n}\n\nexport function createEngine(options: EngineOptions, logger: Logger): Engine {\n const clientOptions: TRPCClientOptions = {\n baseUrl: options.baseUrl,\n };\n const client = createClient(clientOptions);\n const apiDevice = createApiDevice(options, logger);\n\n const base: EngineBase = {\n client,\n createClient: (overrides) => createClient({ ...clientOptions, ...overrides }),\n };\n\n const withDeviceIndex: Engine[\"withDeviceIndex\"] = function <T>(\n this: Engine<T>,\n deviceIndex: number,\n ) {\n const device = apiDevice.with(deviceIndex);\n const withPsd: WithDevice = { device };\n return decorateEngine({ ...this, ...withPsd } as Engine<T & WithDevice>);\n };\n\n const withTransportId: Engine[\"withTransportId\"] = function <T>(\n this: Engine<T>,\n transportId: string,\n ) {\n const device = createRealDevice({ transportId }, logger);\n const withPsd: WithDevice = { device };\n return decorateEngine({ ...this, ...withPsd } as Engine<T & WithDevice>);\n };\n\n const withApiUser: Engine[\"withApiUser\"] = function <T>(this: Engine<T>) {\n const withApiUser: WithApiUser = { __isApiUser: true };\n return decorateEngine({ ...this, ...withApiUser } as Engine<T & WithApiUser>);\n };\n\n const withWorkspace: Engine[\"withWorkspace\"] = function <T>(\n this: Engine<T>,\n workspaceName: string,\n ) {\n const withWorkspace: WithWorkspace = { __workspaceName: workspaceName };\n return decorateEngine({ ...this, ...withWorkspace } as Engine<T & WithWorkspace>);\n };\n\n const withOnboarding: Engine[\"withOnboarding\"] = function <T>(\n this: Engine<T>,\n onboardingId: string,\n ) {\n const withOnboarding: WithOnboarding = { __onboardingId: onboardingId };\n return decorateEngine({ ...this, ...withOnboarding } as Engine<T & WithOnboarding>);\n };\n\n function decorateEngine<T>(\n engine: Engine<\n T &\n Partial<\n WithDevice & WithOnboarding & WithWorkspace & WithPsdAuth & WithApiUser & WithApiAuth\n >\n >,\n ): Engine<T> {\n function decorate<TEnhanced, TDecoration>(\n decorator: (engine: EngineBase & TEnhanced) => TDecoration,\n ): void {\n Object.assign(engine, decorator(engine as EngineBase & TEnhanced));\n }\n\n // DecorateWithDevice\n // -------------------------------------------------------------------------\n if (engine.device) {\n decorate<WithDevice, DecorateWithDevice<T>>(\n (engine) =>\n ({\n getWorkspaces: async (): Promise<string[]> => {\n const { device, client } = engine;\n const { pubKey } = await device.getU2FPubKey();\n const { workspaceNames } = await client.auth.psd.findWorkspaceNames.query({ pubKey });\n return workspaceNames;\n },\n }) satisfies DecorateWithDevice<T>,\n );\n }\n\n // DecorateWithWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && !engine.__psdToken && !engine.__apiAuth) {\n decorate<WithWorkspace, DecorateWithWorkspaceUnauthenticated<T>>((engine) => {\n const { __workspaceName } = engine;\n return {\n withPsdToken: function <T>(this: Engine<T>, token: string): Engine<T & WithPsdAuth> {\n const withPsdAuth: WithPsdAuth = { __psdToken: token };\n const psdAuth = `${__workspaceName}:${token}`;\n const client = engine.createClient({ psdAuth });\n return decorateEngine({ ...this, client, ...withPsdAuth } as Engine<T & WithPsdAuth>);\n },\n } satisfies DecorateWithWorkspaceUnauthenticated<T>;\n });\n }\n\n // DecorateWithDeviceAndOnboarding\n // -------------------------------------------------------------------------\n if (engine.device && engine.__onboardingId) {\n decorate<WithDevice & WithOnboarding, DecorateWithDeviceAndOnboarding>((engine) => {\n const { device, client, __onboardingId } = engine;\n async function enforcePairing(): Promise<void> {\n if (await device.hasPairing()) return;\n const [{ pubKey }, confidentialityKey] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityKey(),\n ]);\n const pairing = await client.onboarding.pairDevicePartition.mutate({\n pubKey,\n onboardingId: __onboardingId,\n data: {\n confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,\n confidentialityKeySignature: confidentialityKey.confidentialityKeySignature,\n },\n });\n await device.setPairing({ pairing });\n }\n return {\n claimDevice: async (params: { role: ClaimedRole; deviceName: string }): Promise<void> => {\n const { role, deviceName } = params;\n const [{ pubKey }, { pubKey: confidentialityKey }] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n await client.onboarding.claimDevice.mutate({\n onboardingId: __onboardingId,\n claim: { role, pubKey, deviceName, confidentialityKey },\n });\n },\n\n collectWrappingKeyFragment: async (wrappingKey: WrappingKeyResponse): Promise<void> => {\n const [{ pubKey }, confidentialityKey] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n await device.openSession({\n secureChannel: {\n pubKey: wrappingKey.ephemeralPubKey,\n certificate: wrappingKey.ephemeralCertificate,\n },\n });\n const { attestation } = await device.getAttestation();\n const blob = await device.generateWrappingKeyFragment();\n await client.onboarding.submitWrappingKeyFragment.mutate({\n pubKey,\n onboardingId: __onboardingId,\n fragment: {\n blob,\n ephemeralPubKey: confidentialityKey.pubKey,\n ephemeralCertificate: {\n ...attestation,\n signature: confidentialityKey.signature,\n },\n },\n });\n },\n\n registerDevice: async (params: RegisterOnboardingDeviceParams): Promise<void> => {\n const { role, name } = params;\n const getChallengeMutation =\n role === \"ADMIN\"\n ? client.onboarding.generateMasterAdminRegistrationChallenge\n : client.onboarding.generateSharedOwnerRegistrationChallenge;\n const submitChallengeMutation =\n role === \"ADMIN\"\n ? client.onboarding.submitMasterAdminRegistration\n : client.onboarding.submitSharedOwnerRegistration;\n await genericRegister({\n device: device,\n name,\n role,\n getChallenge: ({ pubKey, deviceData }) =>\n getChallengeMutation.mutate({\n onboardingId: __onboardingId,\n pubKey,\n deviceData,\n }),\n submitChallenge: ({ pubKey, challengeResponse }) =>\n submitChallengeMutation.mutate({\n onboardingId: engine.__onboardingId,\n pubKey,\n // FIXME this should be renamed to `challengeResponse` on backend side\n response: challengeResponse,\n }),\n });\n },\n\n reviewSharedOwner: async (challenge: PsdChallenge): Promise<void> => {\n await enforcePairing();\n const { pubKey } = await device.getU2FPubKey();\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n const signature = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n await client.onboarding.submitReviewByMasterAdminSignature.mutate({\n onboardingId: __onboardingId,\n pubKey,\n signature,\n });\n },\n\n collectSeedFragment: async (challenge: OnboardingSeedChallenge): Promise<void> => {\n await enforcePairing();\n const [{ pubKey }, { attestation }] = await Promise.all([\n device.getU2FPubKey(),\n device.getAttestation(),\n ]);\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n const challengeResponse = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n const kkPattern = await device.startKKPatternAsResponder({\n partitionId: challenge.partitionId,\n handshake: challenge.kkHandshake,\n handshakeAttestation: challenge.kkHandshakeAttestation,\n });\n const approverBlob = await device.generateSeedFragment();\n await client.onboarding.submitSeedFragment.mutate({\n onboardingId: __onboardingId,\n pubKey,\n seedFragment: {\n challengeResponse,\n approverBlob,\n handshake: kkPattern.handshake,\n handshakeAttestation: {\n ...attestation,\n signature: kkPattern.signature,\n },\n },\n });\n },\n } satisfies DecorateWithDeviceAndOnboarding;\n });\n }\n\n // DecorateWithDeviceAndWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.device && engine.__workspaceName && !engine.__psdToken) {\n decorate<WithDevice & WithWorkspace, DecorateWithDeviceAndWorkspaceUnauthenticated<T>>(\n (engine) => {\n const { device, client, __workspaceName } = engine;\n return {\n login: async function <T>(\n this: Engine<T>,\n opts?: { validityDurationSecs?: number; onScreenDisplayed?: () => void },\n ): Promise<Engine<T & WithPsdAuth>> {\n const { pubKey } = await device.getU2FPubKey();\n const challenge = await client.auth.psd.generateChallenge.mutate({\n pubKey,\n workspaceName: __workspaceName,\n });\n opts?.onScreenDisplayed?.();\n const authentication = await device.authenticate({\n challenge,\n workspaceName: __workspaceName,\n });\n const authPayload = {\n workspaceName: __workspaceName,\n pubKey,\n authentication,\n validityDurationSecs: opts?.validityDurationSecs,\n };\n const { token } = await client.auth.psd.authenticate.mutate({ ...authPayload });\n const withPsdAuth: WithPsdAuth = {\n __psdToken: token,\n };\n const psdAuth = `${engine.__workspaceName}:${token}`;\n const __authClient = engine.createClient({ psdAuth });\n return decorateEngine({ ...this, client: __authClient, ...withPsdAuth } as Engine<\n T & WithPsdAuth\n >);\n },\n\n register: (\n registration: UserRegistrationResponse,\n ): Promise<UserRegistrationResponse> => {\n return genericRegister({\n device,\n name: registration.name,\n role: registration.role,\n getChallenge: async ({ deviceData }) => {\n const challenge = await client.users.generateRegistrationChallenge.mutate({\n id: registration.id,\n workspaceName: __workspaceName,\n deviceData,\n });\n return challenge;\n },\n submitChallenge: ({ challengeResponse }) =>\n client.users.confirmRegistrationChallenge.mutate({\n workspaceName: __workspaceName,\n id: registration.id,\n challengeResponse,\n }),\n });\n },\n } satisfies DecorateWithDeviceAndWorkspaceUnauthenticated<T>;\n },\n );\n }\n\n // DecorateWithApiUserAndWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && engine.__isApiUser && !engine.__apiAuth) {\n decorate<WithWorkspace & WithApiUser, DecorateWithApiUserAndWorkspaceUnauthenticated<T>>(\n (engine) => {\n const { client, __workspaceName } = engine;\n return {\n login: async function <T>(\n this: Engine<T>,\n credentials: {\n apiKeyId: string;\n apiKeySecret: string;\n },\n ): Promise<Engine<T & WithApiAuth>> {\n const res = await client.auth.authenticate.mutate({\n apiKeyId: credentials.apiKeyId,\n apiKeySecret: credentials.apiKeySecret,\n workspace: __workspaceName,\n });\n const withApiAuth: WithApiAuth = {\n __apiAuth: res,\n };\n const __authClient = engine.createClient({ apiAccessToken: res.accessToken });\n return decorateEngine({ ...this, client: __authClient, ...withApiAuth } as Engine<\n T & WithApiAuth\n >);\n },\n } satisfies DecorateWithApiUserAndWorkspaceUnauthenticated<T>;\n },\n );\n }\n\n // DecorateWithWorkspacePsdAuthenticated\n // -------------------------------------------------------------------------\n if (engine.device && engine.__workspaceName && engine.__psdToken) {\n decorate<WithDevice & WithWorkspace, DecorateWithWorkspacePsdAuthenticated>((engine) => {\n const { client, device } = engine;\n\n async function enforcePairing(): Promise<void> {\n if (await device.hasPairing()) return;\n const confidentialityKey = await device.getConfidentialityKey();\n const pairing = await client.debug.pairDevicePartition.mutate({\n confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,\n confidentialityKeySignature: confidentialityKey.confidentialityKeySignature,\n });\n await device.setPairing({ pairing });\n }\n\n return {\n approve: async (\n request: VaultRequestResponse,\n params?: ApproveRequestParams,\n ): Promise<VaultRequestResponse> => {\n const { challenge } = await client.requests.getChallenge.query({ id: request.id });\n invariant(challenge.challengeType === \"PSD\", \"Challenge type must be PSD\");\n await enforcePairing();\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n params?.onScreenDisplayed?.();\n const signature = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n return client.requests.approve.mutate({\n id: request.id,\n data: { challengeType: \"PSD\", signature },\n });\n },\n\n reject: (request: VaultRequestResponse): Promise<VaultRequestResponse> => {\n return client.requests.reject.mutate({ id: request.id, data: null });\n },\n } satisfies DecorateWithWorkspacePsdAuthenticated;\n });\n }\n\n // DecorateWithWorkspaceApiAuthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && engine.__apiAuth) {\n decorate<WithWorkspace & WithApiAuth, DecorateWithWorkspaceApiAuthenticated>((engine) => {\n const { client } = engine;\n return {\n getChallenge: async (request: VaultRequestResponse): Promise<ApiChallenge[\"payload\"]> => {\n const { challenge } = await client.requests.getChallenge.query({ id: request.id });\n invariant(challenge.challengeType === \"API\", \"Challenge type must be API\");\n return challenge.payload;\n },\n\n approve: (\n request: VaultRequestResponse,\n signature: string,\n ): Promise<VaultRequestResponse> => {\n return client.requests.approve.mutate({\n id: request.id,\n data: { challengeType: \"API\", signature },\n });\n },\n\n reject: (\n request: VaultRequestResponse,\n signature: string,\n ): Promise<VaultRequestResponse> => {\n return client.requests.reject.mutate({\n id: request.id,\n data: { challengeType: \"API\", signature },\n });\n },\n } satisfies DecorateWithWorkspaceApiAuthenticated;\n });\n }\n\n return engine;\n }\n\n return {\n ...base,\n withDeviceIndex,\n withTransportId,\n withApiUser,\n withWorkspace,\n withOnboarding,\n };\n}\n","import { DisconnectedDevice, LockedDeviceError } from \"@ledgerhq/errors\";\nimport type Transport from \"@ledgerhq/hw-transport\";\nimport type { HsmCertificate } from \"@ledgerhq/revault-api\";\nimport invariant from \"invariant\";\nimport { from, lastValueFrom } from \"rxjs\";\n\nimport type { Logger } from \"@/types\";\n\nimport {\n APPID_VAULT_ADMINISTRATOR,\n PAGINATED_STATUS,\n PATHS,\n SCRIPT_IDS,\n STATUS_LENGTH,\n STREAMING_NEXT_ACTION,\n STREAMING_RESPONSE,\n STR_ROLES,\n} from \"./constants\";\nimport { withDevicePolling } from \"./device-access\";\nimport type { Device } from \"./types\";\nimport { isTransportStatusError } from \"./utils\";\n\nconst MAX_CHUNK_LENGTH = 250;\n\ntype Options = {\n transportId: string;\n};\n\nconst FIXME_NOT_IMPLEMENTED =\n (fnName: string): (() => Promise<never>) =>\n async () => {\n throw new Error(`Not implemented: ${fnName}`);\n };\n\nconst getPathFromPathString = (pathString: string): number[] => {\n const parts = pathString.split(\"'/\").map((part) => parseInt(part, 10));\n return parts.map((part) => (part | 0x80000000) >>> 0);\n};\n\nconst splitChunks = (chunk: number, buffer: Buffer): Buffer[] => {\n const chunks = [];\n for (let i = 0, size = chunk; i < buffer.length; i += size, size = chunk) {\n chunks.push(buffer.slice(i, i + size));\n }\n return chunks;\n};\n\nconst removeStatus = (result: Buffer): Buffer => result.slice(0, result.length - STATUS_LENGTH);\n\nconst sendByChunk = async (\n transport: Transport,\n command: number[], // eg [0xe0, 0x45, 0x00, 0x00]\n data: Buffer,\n chunkSize: number = MAX_CHUNK_LENGTH,\n): Promise<Buffer> => {\n const chunks = splitChunks(chunkSize, data);\n let response = Buffer.from([]);\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const apdu = [...command];\n // command is 0xe0,0x45,0x00,0x00 for first chunk, then it's 0xe0,0x45,0x80,0x00\n /* v8 ignore start */\n apdu[2] = i && 0x80;\n /* v8 ignore stop */\n response = await transport.send(apdu[0]!, apdu[1]!, apdu[2], apdu[3]!, chunk, [\n 0x9000,\n ...PAGINATED_STATUS,\n ]);\n }\n return response;\n};\n\nconst buildAttestation = (params: {\n handshake: string;\n handshakeAttestation: HsmCertificate;\n partitionId: string;\n}): Buffer => {\n const sigBuffer = Buffer.from(params.handshakeAttestation.signature, \"base64\");\n const sigLengthBuffer = Buffer.alloc(1);\n sigLengthBuffer.writeUIntBE(sigBuffer.length, 0, 1);\n\n const certBuffer = Buffer.from(params.handshakeAttestation.certificate, \"base64\");\n const certLengthBuffer = Buffer.alloc(1);\n certLengthBuffer.writeUIntBE(certBuffer.length, 0, 1);\n\n const pubBuffer = Buffer.from(params.handshakeAttestation.attestationPub, \"base64\");\n\n const certChainData = Buffer.concat([\n sigLengthBuffer,\n sigBuffer,\n pubBuffer,\n certLengthBuffer,\n certBuffer,\n ]);\n\n const cliMsgBuffer = Buffer.from(params.handshake, \"hex\");\n const cliMsgLengthBuffer = Buffer.alloc(1);\n cliMsgLengthBuffer.writeUIntBE(cliMsgBuffer.length, 0, 1);\n\n const pidBuffer = Buffer.from(params.partitionId, \"hex\");\n const pidLengthBuffer = Buffer.alloc(1);\n pidLengthBuffer.writeUIntBE(pidBuffer.length, 0, 1);\n\n const certChainDataLengthBuff = Buffer.alloc(2);\n certChainDataLengthBuff.writeUInt16BE(certChainData.length, 0);\n\n const data = Buffer.concat([\n cliMsgLengthBuffer,\n cliMsgBuffer,\n certChainDataLengthBuff,\n certChainData,\n pidLengthBuffer,\n pidBuffer,\n ]);\n\n const totalLengthBuffer = Buffer.alloc(2);\n totalLengthBuffer.writeUInt16BE(data.length, 0);\n\n const toSend = Buffer.concat([totalLengthBuffer, data]);\n\n return toSend;\n};\n\ntype RetryOnError = (err: Error) => boolean;\n/* v8 ignore start */\nconst genericRetryOnError: RetryOnError = (err) => {\n // device is locked\n if (err instanceof LockedDeviceError) return true;\n // user is on dashboard when receiving a Vault app apdu\n if (isTransportStatusError(err) && err.statusCode === 0x6d09) return true;\n // VG-24797 error that can happen in BLE in some situations (still unclear)\n if (err instanceof DisconnectedDevice) return true;\n\n // for everything else, we don't want to retry\n return false;\n};\n/* v8 ignore stop */\n\nexport function createRealDevice(options: Options, logger: Logger): Device {\n const { transportId } = options;\n\n async function run<T>(\n job: (transport: Transport) => Promise<T>,\n retryOnError: RetryOnError = genericRetryOnError,\n ): Promise<T> {\n return lastValueFrom(\n withDevicePolling(transportId)<T>((transport) => from(job(transport)), retryOnError),\n );\n }\n\n /* v8 ignore start */\n const noRetry = (): boolean => false;\n /* v8 ignore stop */\n const poll = async (): Promise<{ isAppOpened: boolean }> => {\n // waiting for device to be turned on\n await run(\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n async (_transport) => {},\n () => true,\n );\n // checking if app is opened: should return directly on getPubKey\n try {\n await getPublicKey(PATHS.U2F, { secp256k1: true, retryOnError: noRetry });\n return { isAppOpened: true };\n } catch (err) {\n if (isTransportStatusError(err) && genericRetryOnError(err)) {\n return { isAppOpened: false };\n }\n throw err;\n }\n };\n\n const pollApp = async (appName: string): Promise<string> => {\n const res = await run((transport) =>\n transport.send(0xe0, 0xd8, 0x00, 0x00, Buffer.from(appName, \"utf8\")),\n );\n // little delay to give time to the app to be fully opened\n await new Promise((r) => setTimeout(r, 1e3));\n return res.toString(\"hex\");\n };\n\n const getPublicKey = async (\n pathString: string,\n { secp256k1, retryOnError }: { secp256k1: boolean; retryOnError?: RetryOnError },\n ): Promise<{ pubKey: string; signature: string }> => {\n logger.info(`[device] getPublicKey (${pathString})`);\n const path = getPathFromPathString(pathString);\n const data = Buffer.concat([\n Buffer.from([path.length]),\n ...path.map((derivation) => {\n const buf = Buffer.alloc(4);\n buf.writeUInt32BE(derivation, 0);\n return buf;\n }),\n ]);\n const curve = secp256k1 ? 0x01 : 0x02;\n const response = await run(\n (transport) => transport.send(0xe0, 0x40, curve, 0x00, data),\n retryOnError ?? genericRetryOnError,\n );\n const pubKeyLength = response.readInt8(0);\n const pubKey = response\n .slice(1, pubKeyLength + 1)\n .toString(\"hex\")\n .toUpperCase();\n const signature = response\n .slice(pubKeyLength + 1, response.length - STATUS_LENGTH)\n .toString(\"base64\");\n return { pubKey, signature };\n };\n\n const device: Device = {\n authenticate: async ({ challenge: { challenge, name, role, keyHandle }, workspaceName }) => {\n logger.info(`[device] Authenticate`);\n invariant(role !== \"READ_ONLY_API_KEY\", \"Invalid role for authenticate: READ_ONLY_API_KEY\");\n const applicationBuffer = Buffer.from(APPID_VAULT_ADMINISTRATOR, \"hex\");\n const nameBuffer = Buffer.from(name);\n const workspaceBuffer = Buffer.from(workspaceName);\n\n const keyHandleData = Buffer.concat([\n Buffer.from(STR_ROLES[role], \"hex\"),\n Buffer.from([nameBuffer.length]),\n nameBuffer,\n Buffer.from([workspaceBuffer.length]),\n workspaceBuffer,\n ]);\n\n const keyHandleDataLength = Buffer.alloc(2);\n keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);\n\n const data = Buffer.concat([\n Buffer.from(challenge, \"base64\"),\n applicationBuffer,\n Buffer.from([keyHandle.length]),\n Buffer.from(keyHandle, \"hex\"),\n keyHandleDataLength,\n keyHandleData,\n ]);\n\n const authentication = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x02, 0x00, 0x00], data),\n );\n\n return removeStatus(authentication).toString(\"hex\");\n },\n finalizePairingHandshake: FIXME_NOT_IMPLEMENTED(\"finalizePairingHandshake\"),\n generateSeedFragment: FIXME_NOT_IMPLEMENTED(\"generateSeedFragment\"),\n generateWrappingKeyFragment: FIXME_NOT_IMPLEMENTED(\"generateWrappingKeyFragment\"),\n getAttestation: FIXME_NOT_IMPLEMENTED(\"getAttestation\"),\n getConfidentialityKey: async () => {\n logger.info(`[device] getConfidentialityKey`);\n const bufWithStatus = await run((transport) => transport.send(0xe0, 0x4d, 0x00, 0x00));\n const buf = removeStatus(bufWithStatus);\n const keyLength = buf[0]!;\n const key = buf.slice(1, 1 + keyLength);\n const sig = buf.slice(1 + keyLength + 1);\n return {\n confidentialityKeyCurve25519: key.toString(\"hex\"),\n confidentialityKeySignature: sig.toString(\"hex\"),\n };\n },\n getConfidentialityPubKey: () => getPublicKey(PATHS.CONFIDENTIALITY, { secp256k1: true }),\n getDeviceUserId: FIXME_NOT_IMPLEMENTED(\"getDeviceUserId\"),\n getU2FPubKey: () => getPublicKey(PATHS.U2F, { secp256k1: false }),\n getValidationPubKey: () => getPublicKey(PATHS.VALIDATION, { secp256k1: true }),\n hasPairing: async () => {\n logger.info(`[device] hasPairing`);\n const apdu = [0xe0, 0x51, 0x00, 0x00, 0xb5];\n const res = await run((transport) => transport.exchange(Buffer.from(apdu)));\n const hex = Buffer.from(res).toString(\"hex\");\n\n // 6f45 => this error means that there is no partition ID on the device\n // if no error, it means there is (at least) one\n //\n // 6a87 => TEMPORARY hack because Stax apparently does not implement\n // the \"get partition id\" APDU, so it returns \"incorrect length\"\n // easier to just assume that in this case there is no partition,\n // and try to insert one anyway (done on revault onboarding)\n //\n return hex !== \"6f45\" && hex !== \"6a87\";\n },\n initPairingHandshake: FIXME_NOT_IMPLEMENTED(\"initPairingHandshake\"),\n openSession: FIXME_NOT_IMPLEMENTED(\"openSession\"),\n register: FIXME_NOT_IMPLEMENTED(\"register\"),\n registerData: FIXME_NOT_IMPLEMENTED(\"registerData\"),\n setPairing: async ({ pairing }) => {\n logger.info(`[device] setPairing`);\n const psdPayload = Buffer.from(pairing.blob, \"base64\");\n const length = Buffer.alloc(2);\n length.writeUInt16BE(psdPayload.length, 0);\n const final = Buffer.concat([length, psdPayload]);\n await run((transport) => sendByChunk(transport, [0xe0, 0x4e, 0x00, 0x00], final));\n },\n startKKPatternAsResponder: FIXME_NOT_IMPLEMENTED(\"startKKPatternAsResponder\"),\n startKPatternAsResponder: async (params) => {\n logger.info(`[device] startKPatternAsResponder`);\n const data = buildAttestation(params);\n await run((transport) =>\n sendByChunk(transport, [0xe0, 0x49, 0x00, SCRIPT_IDS.ACCOUNT_MANAGER_SESSION], data),\n );\n },\n validateVaultOperation: async (params) => {\n logger.info(`[device] validateVaultOperation`);\n const path = getPathFromPathString(PATHS.VALIDATION);\n const paths = Buffer.concat([\n Buffer.from([path.length]),\n ...path.map((derivation) => {\n const buf = Buffer.alloc(4);\n buf.writeUInt32BE(derivation, 0);\n return buf;\n }),\n ]);\n\n let nextActionId = 1;\n let finalResponse;\n\n while (!finalResponse) {\n const screen = Buffer.from(params.actions[nextActionId - 1]!, \"base64\");\n const length = Buffer.alloc(2);\n length.writeUInt16BE(screen.length, 0);\n const data = Buffer.concat([paths, length, screen]);\n const response = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x45, 0x00, 0x00], data),\n );\n const responseType = response.readInt8(0);\n let responseStatus = response.readUInt16BE(response.length - 2);\n if (responseType === STREAMING_NEXT_ACTION) {\n nextActionId = response.readUIntBE(1, 2);\n } else if (responseType === STREAMING_RESPONSE) {\n finalResponse = response.slice(3, response.length - 2);\n /* v8 ignore start */\n while (responseStatus !== 0x9000) {\n const resp = await run((transport) => transport.send(0x00, 0xc0, 0x00, 0x00));\n responseStatus = resp.readUInt16BE(resp.length - 2);\n finalResponse = Buffer.concat([finalResponse, removeStatus(resp)]);\n }\n } else {\n throw Error(`${responseType}`);\n }\n /* v8 ignore stop */\n }\n return finalResponse.toString(\"base64\");\n },\n\n sendAPDU: async (apduCommand: string) => {\n const res = await run((transport) => transport.exchange(Buffer.from(apduCommand, \"hex\")));\n return Buffer.from(res).toString(\"hex\");\n },\n poll,\n pollApp,\n };\n return device;\n}\n","import type { AppRouter } from \"@ledgerhq/revault-api\";\nimport { type TRPCClient, createTRPCClient, httpBatchLink } from \"@trpc/client\";\nimport type { inferRouterInputs, inferRouterOutputs } from \"@trpc/server\";\nimport superjson from \"superjson\";\n\nexport type TRPCClientOptions = {\n baseUrl: string;\n debugAuthToken?: string;\n rootAuthToken?: string;\n apiAccessToken?: string;\n psdAuth?: string;\n};\n\nexport type RevaultApiTRPCClient = TRPCClient<AppRouter>;\n\nexport type RouterInputs = inferRouterInputs<AppRouter>;\nexport type RouterOutputs = inferRouterOutputs<AppRouter>;\n\nexport const createClient = (options: TRPCClientOptions): RevaultApiTRPCClient => {\n const trpc = createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url: `${options.baseUrl}/trpc`,\n transformer: superjson,\n headers() {\n return {\n ...(options.debugAuthToken\n ? { \"x-revault-debug-auth-token\": options.debugAuthToken }\n : {}),\n ...(options.rootAuthToken\n ? { \"x-revault-root-auth-token\": options.rootAuthToken }\n : {}),\n ...(options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {}),\n };\n },\n }),\n ],\n });\n return trpc;\n};\n"]}
1
+ {"version":3,"sources":["/home/runner/_work/revault/revault/packages/sdk/lib/engine.cjs","../src/engine/index.ts","../src/device/real-device.ts","../src/trpc.ts"],"names":["withApiUser","withWorkspace","withOnboarding","client","engine"],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACF,wDAA6B;AAC7B;AACA;ACLA,4FAA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AACT,EAAA;AAEO,EAAA;AACF,IAAA;AACH,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACA,IAAA;AACF,EAAA;AACF;ADqN6C;AACA;AACA;AACA","file":"/home/runner/_work/revault/revault/packages/sdk/lib/engine.cjs","sourcesContent":[null,"import type {\n ApiChallenge,\n ClaimedRole,\n OnboardingSeedChallenge,\n PsdChallenge,\n UserRegistrationChallenge,\n UserRegistrationChallengeResponse,\n UserRegistrationDeviceData,\n UserRegistrationResponse,\n VaultRequestResponse,\n WrappingKeyResponse,\n} from \"@ledgerhq/revault-api\";\nimport invariant from \"invariant\";\n\nimport { type Device, createApiDevice } from \"@/device\";\nimport { createRealDevice } from \"@/device/real-device\";\nimport { type TRPCClientOptions, createClient } from \"@/trpc\";\nimport type { Logger } from \"@/types\";\n\nimport type {\n ApproveRequestParams,\n DecorateWithApiUserAndWorkspaceUnauthenticated,\n DecorateWithDevice,\n DecorateWithDeviceAndOnboarding,\n DecorateWithDeviceAndWorkspaceUnauthenticated,\n DecorateWithWorkspaceApiAuthenticated,\n DecorateWithWorkspacePsdAuthenticated,\n DecorateWithWorkspaceUnauthenticated,\n Engine,\n EngineBase,\n EngineOptions,\n RegisterOnboardingDeviceParams,\n WithApiAuth,\n WithApiUser,\n WithDevice,\n WithOnboarding,\n WithPsdAuth,\n WithWorkspace,\n} from \"./types\";\n\nexport { fetchAll } from \"../utils\";\n\nexport type * from \"./types\";\n\nasync function genericRegister<T>({\n device,\n name,\n role,\n getChallenge,\n submitChallenge,\n}: {\n device: Device;\n name: string;\n role: \"ADMIN\" | \"SHARED_OWNER\" | \"OPERATOR\";\n getChallenge: (p: {\n pubKey: string;\n deviceData: UserRegistrationDeviceData;\n }) => Promise<UserRegistrationChallenge>;\n submitChallenge: (p: {\n pubKey: string;\n challengeResponse: UserRegistrationChallengeResponse;\n }) => Promise<T>;\n}): Promise<T> {\n const [attestation, u2fPubKey, confidentialityKey] = await Promise.all([\n device.getAttestation(),\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n const ephemeralPubKey = await device.initPairingHandshake();\n const deviceData: UserRegistrationDeviceData = {\n name,\n pubKey: u2fPubKey.pubKey,\n psdModel: \"STAX\",\n confidentialityKey: confidentialityKey.pubKey,\n psdEphemeralKey: ephemeralPubKey.pubKey,\n psdEphemeralKeyAttestation: {\n ...attestation.attestation,\n signature: ephemeralPubKey.signature,\n },\n };\n const challenge = await getChallenge({ pubKey: u2fPubKey.pubKey, deviceData });\n const pairingPayload = await device.finalizePairingHandshake({\n handshake: challenge.handshake,\n partitionId: challenge.ciphertext,\n handshakeAttestation: challenge.handshakeAttestation,\n });\n const register = await device.register({\n challenge: challenge.challenge,\n u2fRegisterData: challenge.u2fRegisterData,\n name,\n role,\n });\n const validationPubKey = await device.getValidationPubKey();\n const registerData = await device.registerData({ challenge: challenge.challenge });\n const attestationOffset = 67 + register.u2fRegister.readInt8(66);\n const u2fRegister = Buffer.concat([\n register.u2fRegister.slice(0, attestationOffset),\n Buffer.from([attestation.buffer.length]),\n attestation.buffer,\n register.u2fRegister.slice(attestationOffset),\n ]).toString(\"hex\");\n const challengeResponse: UserRegistrationChallengeResponse = {\n registerData,\n certificate: {\n ...attestation.attestation,\n signature: validationPubKey.signature,\n },\n u2fRegister,\n u2fKeyHandle: register.keyHandle.toString(\"hex\"),\n validationKey: validationPubKey.pubKey,\n pairingPayload,\n };\n return submitChallenge({ pubKey: u2fPubKey.pubKey, challengeResponse });\n}\n\nexport function createEngine(options: EngineOptions, logger: Logger): Engine {\n const clientOptions: TRPCClientOptions = {\n baseUrl: options.baseUrl,\n };\n const client = createClient(clientOptions);\n const apiDevice = createApiDevice(options, logger);\n\n const base: EngineBase = {\n client,\n createClient: (overrides) => createClient({ ...clientOptions, ...overrides }),\n };\n\n const withDeviceIndex: Engine[\"withDeviceIndex\"] = function <T>(\n this: Engine<T>,\n deviceIndex: number,\n ) {\n const device = apiDevice.with(deviceIndex);\n const withPsd: WithDevice = { device };\n return decorateEngine({ ...this, ...withPsd } as Engine<T & WithDevice>);\n };\n\n const withTransportId: Engine[\"withTransportId\"] = function <T>(\n this: Engine<T>,\n transportId: string,\n ) {\n const device = createRealDevice({ transportId }, logger);\n const withPsd: WithDevice = { device };\n return decorateEngine({ ...this, ...withPsd } as Engine<T & WithDevice>);\n };\n\n const withApiUser: Engine[\"withApiUser\"] = function <T>(this: Engine<T>) {\n const withApiUser: WithApiUser = { __isApiUser: true };\n return decorateEngine({ ...this, ...withApiUser } as Engine<T & WithApiUser>);\n };\n\n const withWorkspace: Engine[\"withWorkspace\"] = function <T>(\n this: Engine<T>,\n workspaceName: string,\n ) {\n const withWorkspace: WithWorkspace = { __workspaceName: workspaceName };\n return decorateEngine({ ...this, ...withWorkspace } as Engine<T & WithWorkspace>);\n };\n\n const withOnboarding: Engine[\"withOnboarding\"] = function <T>(\n this: Engine<T>,\n onboardingId: string,\n ) {\n const withOnboarding: WithOnboarding = { __onboardingId: onboardingId };\n return decorateEngine({ ...this, ...withOnboarding } as Engine<T & WithOnboarding>);\n };\n\n function decorateEngine<T>(\n engine: Engine<\n T &\n Partial<\n WithDevice & WithOnboarding & WithWorkspace & WithPsdAuth & WithApiUser & WithApiAuth\n >\n >,\n ): Engine<T> {\n function decorate<TEnhanced, TDecoration>(\n decorator: (engine: EngineBase & TEnhanced) => TDecoration,\n ): void {\n Object.assign(engine, decorator(engine as EngineBase & TEnhanced));\n }\n\n // DecorateWithDevice\n // -------------------------------------------------------------------------\n if (engine.device) {\n decorate<WithDevice, DecorateWithDevice<T>>(\n (engine) =>\n ({\n getWorkspaces: async (): Promise<string[]> => {\n const { device, client } = engine;\n const { pubKey } = await device.getU2FPubKey();\n const { workspaceNames } = await client.auth.psd.findWorkspaceNames.query({ pubKey });\n return workspaceNames;\n },\n }) satisfies DecorateWithDevice<T>,\n );\n }\n\n // DecorateWithWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && !engine.__psdToken && !engine.__apiAuth) {\n decorate<WithWorkspace, DecorateWithWorkspaceUnauthenticated<T>>((engine) => {\n const { __workspaceName } = engine;\n return {\n withPsdToken: function <T>(this: Engine<T>, token: string): Engine<T & WithPsdAuth> {\n const withPsdAuth: WithPsdAuth = { __psdToken: token };\n const psdAuth = `${__workspaceName}:${token}`;\n const client = engine.createClient({ psdAuth });\n return decorateEngine({ ...this, client, ...withPsdAuth } as Engine<T & WithPsdAuth>);\n },\n } satisfies DecorateWithWorkspaceUnauthenticated<T>;\n });\n }\n\n // DecorateWithDeviceAndOnboarding\n // -------------------------------------------------------------------------\n if (engine.device && engine.__onboardingId) {\n decorate<WithDevice & WithOnboarding, DecorateWithDeviceAndOnboarding>((engine) => {\n const { device, client, __onboardingId } = engine;\n async function enforcePairing(): Promise<void> {\n if (await device.hasPairing()) return;\n const [{ pubKey }, confidentialityKey] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityKey(),\n ]);\n const pairing = await client.onboarding.pairDevicePartition.mutate({\n pubKey,\n onboardingId: __onboardingId,\n data: {\n confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,\n confidentialityKeySignature: confidentialityKey.confidentialityKeySignature,\n },\n });\n await device.setPairing({ pairing });\n }\n return {\n claimDevice: async (params: { role: ClaimedRole; deviceName: string }): Promise<void> => {\n const { role, deviceName } = params;\n const [{ pubKey }, { pubKey: confidentialityKey }] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n await client.onboarding.claimDevice.mutate({\n onboardingId: __onboardingId,\n claim: { role, pubKey, deviceName, confidentialityKey },\n });\n },\n\n collectWrappingKeyFragment: async (wrappingKey: WrappingKeyResponse): Promise<void> => {\n const [{ pubKey }, confidentialityKey] = await Promise.all([\n device.getU2FPubKey(),\n device.getConfidentialityPubKey(),\n ]);\n await device.openSession({\n secureChannel: {\n pubKey: wrappingKey.ephemeralPubKey,\n certificate: wrappingKey.ephemeralCertificate,\n },\n });\n const { attestation } = await device.getAttestation();\n const blob = await device.generateWrappingKeyFragment();\n await client.onboarding.submitWrappingKeyFragment.mutate({\n pubKey,\n onboardingId: __onboardingId,\n fragment: {\n blob,\n ephemeralPubKey: confidentialityKey.pubKey,\n ephemeralCertificate: {\n ...attestation,\n signature: confidentialityKey.signature,\n },\n },\n });\n },\n\n registerDevice: async (params: RegisterOnboardingDeviceParams): Promise<void> => {\n const { role, name } = params;\n const getChallengeMutation =\n role === \"ADMIN\"\n ? client.onboarding.generateMasterAdminRegistrationChallenge\n : client.onboarding.generateSharedOwnerRegistrationChallenge;\n const submitChallengeMutation =\n role === \"ADMIN\"\n ? client.onboarding.submitMasterAdminRegistration\n : client.onboarding.submitSharedOwnerRegistration;\n await genericRegister({\n device: device,\n name,\n role,\n getChallenge: ({ pubKey, deviceData }) =>\n getChallengeMutation.mutate({\n onboardingId: __onboardingId,\n pubKey,\n deviceData,\n }),\n submitChallenge: ({ pubKey, challengeResponse }) =>\n submitChallengeMutation.mutate({\n onboardingId: engine.__onboardingId,\n pubKey,\n // FIXME this should be renamed to `challengeResponse` on backend side\n response: challengeResponse,\n }),\n });\n },\n\n reviewSharedOwner: async (challenge: PsdChallenge): Promise<void> => {\n await enforcePairing();\n const { pubKey } = await device.getU2FPubKey();\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n const signature = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n await client.onboarding.submitReviewByMasterAdminSignature.mutate({\n onboardingId: __onboardingId,\n pubKey,\n signature,\n });\n },\n\n collectSeedFragment: async (challenge: OnboardingSeedChallenge): Promise<void> => {\n await enforcePairing();\n const [{ pubKey }, { attestation }] = await Promise.all([\n device.getU2FPubKey(),\n device.getAttestation(),\n ]);\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n const challengeResponse = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n const kkPattern = await device.startKKPatternAsResponder({\n partitionId: challenge.partitionId,\n handshake: challenge.kkHandshake,\n handshakeAttestation: challenge.kkHandshakeAttestation,\n });\n const approverBlob = await device.generateSeedFragment();\n await client.onboarding.submitSeedFragment.mutate({\n onboardingId: __onboardingId,\n pubKey,\n seedFragment: {\n challengeResponse,\n approverBlob,\n handshake: kkPattern.handshake,\n handshakeAttestation: {\n ...attestation,\n signature: kkPattern.signature,\n },\n },\n });\n },\n } satisfies DecorateWithDeviceAndOnboarding;\n });\n }\n\n // DecorateWithDeviceAndWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.device && engine.__workspaceName && !engine.__psdToken) {\n decorate<WithDevice & WithWorkspace, DecorateWithDeviceAndWorkspaceUnauthenticated<T>>(\n (engine) => {\n const { device, client, __workspaceName } = engine;\n return {\n login: async function <T>(\n this: Engine<T>,\n opts?: { validityDurationSecs?: number; onScreenDisplayed?: () => void },\n ): Promise<Engine<T & WithPsdAuth>> {\n const { pubKey } = await device.getU2FPubKey();\n const challenge = await client.auth.psd.generateChallenge.mutate({\n pubKey,\n workspaceName: __workspaceName,\n });\n opts?.onScreenDisplayed?.();\n const authentication = await device.authenticate({\n challenge,\n workspaceName: __workspaceName,\n });\n const authPayload = {\n workspaceName: __workspaceName,\n pubKey,\n authentication,\n validityDurationSecs: opts?.validityDurationSecs,\n };\n const { token } = await client.auth.psd.authenticate.mutate({ ...authPayload });\n const withPsdAuth: WithPsdAuth = {\n __psdToken: token,\n };\n const psdAuth = `${engine.__workspaceName}:${token}`;\n const __authClient = engine.createClient({ psdAuth });\n return decorateEngine({ ...this, client: __authClient, ...withPsdAuth } as Engine<\n T & WithPsdAuth\n >);\n },\n\n register: (\n registration: UserRegistrationResponse,\n ): Promise<UserRegistrationResponse> => {\n return genericRegister({\n device,\n name: registration.name,\n role: registration.role,\n getChallenge: async ({ deviceData }) => {\n const challenge = await client.userRegistrations.generateChallenge.mutate({\n id: registration.id,\n workspaceName: __workspaceName,\n deviceData,\n });\n return challenge;\n },\n submitChallenge: ({ challengeResponse }) =>\n client.userRegistrations.submitChallenge.mutate({\n workspaceName: __workspaceName,\n id: registration.id,\n challengeResponse,\n }),\n });\n },\n } satisfies DecorateWithDeviceAndWorkspaceUnauthenticated<T>;\n },\n );\n }\n\n // DecorateWithApiUserAndWorkspaceUnauthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && engine.__isApiUser && !engine.__apiAuth) {\n decorate<WithWorkspace & WithApiUser, DecorateWithApiUserAndWorkspaceUnauthenticated<T>>(\n (engine) => {\n const { client, __workspaceName } = engine;\n return {\n login: async function <T>(\n this: Engine<T>,\n credentials: {\n apiKeyId: string;\n apiKeySecret: string;\n },\n ): Promise<Engine<T & WithApiAuth>> {\n const res = await client.auth.authenticate.mutate({\n apiKeyId: credentials.apiKeyId,\n apiKeySecret: credentials.apiKeySecret,\n workspace: __workspaceName,\n });\n const withApiAuth: WithApiAuth = {\n __apiAuth: res,\n };\n const __authClient = engine.createClient({ apiAccessToken: res.accessToken });\n return decorateEngine({ ...this, client: __authClient, ...withApiAuth } as Engine<\n T & WithApiAuth\n >);\n },\n } satisfies DecorateWithApiUserAndWorkspaceUnauthenticated<T>;\n },\n );\n }\n\n // DecorateWithWorkspacePsdAuthenticated\n // -------------------------------------------------------------------------\n if (engine.device && engine.__workspaceName && engine.__psdToken) {\n decorate<WithDevice & WithWorkspace, DecorateWithWorkspacePsdAuthenticated>((engine) => {\n const { client, device } = engine;\n\n async function enforcePairing(): Promise<void> {\n if (await device.hasPairing()) return;\n const confidentialityKey = await device.getConfidentialityKey();\n const pairing = await client.debug.pairDevicePartition.mutate({\n confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,\n confidentialityKeySignature: confidentialityKey.confidentialityKeySignature,\n });\n await device.setPairing({ pairing });\n }\n\n return {\n approve: async (\n request: VaultRequestResponse,\n params?: ApproveRequestParams,\n ): Promise<VaultRequestResponse> => {\n const { challenge } = await client.requests.getChallenge.query({ id: request.id });\n invariant(challenge.challengeType === \"PSD\", \"Challenge type must be PSD\");\n await enforcePairing();\n await device.startKPatternAsResponder({\n handshake: challenge.handshake,\n handshakeAttestation: challenge.handshakeAttestation,\n partitionId: challenge.partitionId,\n });\n params?.onScreenDisplayed?.();\n const signature = await device.validateVaultOperation({\n actions: challenge.wActions,\n });\n return client.requests.approve.mutate({\n id: request.id,\n data: { challengeType: \"PSD\", signature },\n });\n },\n\n reject: (request: VaultRequestResponse): Promise<VaultRequestResponse> => {\n return client.requests.reject.mutate({ id: request.id, data: null });\n },\n } satisfies DecorateWithWorkspacePsdAuthenticated;\n });\n }\n\n // DecorateWithWorkspaceApiAuthenticated\n // -------------------------------------------------------------------------\n if (engine.__workspaceName && engine.__apiAuth) {\n decorate<WithWorkspace & WithApiAuth, DecorateWithWorkspaceApiAuthenticated>((engine) => {\n const { client } = engine;\n return {\n getChallenge: async (request: VaultRequestResponse): Promise<ApiChallenge[\"payload\"]> => {\n const { challenge } = await client.requests.getChallenge.query({ id: request.id });\n invariant(challenge.challengeType === \"API\", \"Challenge type must be API\");\n return challenge.payload;\n },\n\n approve: (\n request: VaultRequestResponse,\n signature: string,\n ): Promise<VaultRequestResponse> => {\n return client.requests.approve.mutate({\n id: request.id,\n data: { challengeType: \"API\", signature },\n });\n },\n\n reject: (\n request: VaultRequestResponse,\n signature: string,\n ): Promise<VaultRequestResponse> => {\n return client.requests.reject.mutate({\n id: request.id,\n data: { challengeType: \"API\", signature },\n });\n },\n } satisfies DecorateWithWorkspaceApiAuthenticated;\n });\n }\n\n return engine;\n }\n\n return {\n ...base,\n withDeviceIndex,\n withTransportId,\n withApiUser,\n withWorkspace,\n withOnboarding,\n };\n}\n","import { DisconnectedDevice, LockedDeviceError } from \"@ledgerhq/errors\";\nimport type Transport from \"@ledgerhq/hw-transport\";\nimport type { HsmCertificate } from \"@ledgerhq/revault-api\";\nimport invariant from \"invariant\";\nimport { from, lastValueFrom } from \"rxjs\";\n\nimport type { Logger } from \"@/types\";\n\nimport {\n APPID_VAULT_ADMINISTRATOR,\n PAGINATED_STATUS,\n PATHS,\n SCRIPT_IDS,\n STATUS_LENGTH,\n STREAMING_NEXT_ACTION,\n STREAMING_RESPONSE,\n STR_ROLES,\n} from \"./constants\";\nimport { withDevicePolling } from \"./device-access\";\nimport type { Device } from \"./types\";\nimport { isTransportStatusError } from \"./utils\";\n\nconst MAX_CHUNK_LENGTH = 250;\n\ntype Options = {\n transportId: string;\n};\n\nconst FIXME_NOT_IMPLEMENTED =\n (fnName: string): (() => Promise<never>) =>\n async () => {\n throw new Error(`Not implemented: ${fnName}`);\n };\n\nconst getPathFromPathString = (pathString: string): number[] => {\n const parts = pathString.split(\"'/\").map((part) => parseInt(part, 10));\n return parts.map((part) => (part | 0x80000000) >>> 0);\n};\n\nconst splitChunks = (chunk: number, buffer: Buffer): Buffer[] => {\n const chunks = [];\n for (let i = 0, size = chunk; i < buffer.length; i += size, size = chunk) {\n chunks.push(buffer.slice(i, i + size));\n }\n return chunks;\n};\n\nconst removeStatus = (result: Buffer): Buffer => result.slice(0, result.length - STATUS_LENGTH);\n\nconst sendByChunk = async (\n transport: Transport,\n command: number[], // eg [0xe0, 0x45, 0x00, 0x00]\n data: Buffer,\n chunkSize: number = MAX_CHUNK_LENGTH,\n): Promise<Buffer> => {\n const chunks = splitChunks(chunkSize, data);\n let response = Buffer.from([]);\n for (let i = 0; i < chunks.length; i++) {\n const chunk = chunks[i];\n const apdu = [...command];\n // command is 0xe0,0x45,0x00,0x00 for first chunk, then it's 0xe0,0x45,0x80,0x00\n /* v8 ignore start */\n apdu[2] = i && 0x80;\n /* v8 ignore stop */\n response = await transport.send(apdu[0]!, apdu[1]!, apdu[2], apdu[3]!, chunk, [\n 0x9000,\n ...PAGINATED_STATUS,\n ]);\n }\n return response;\n};\n\nconst buildAttestation = (params: {\n handshake: string;\n handshakeAttestation: HsmCertificate;\n partitionId: string;\n}): Buffer => {\n const sigBuffer = Buffer.from(params.handshakeAttestation.signature, \"base64\");\n const sigLengthBuffer = Buffer.alloc(1);\n sigLengthBuffer.writeUIntBE(sigBuffer.length, 0, 1);\n\n const certBuffer = Buffer.from(params.handshakeAttestation.certificate, \"base64\");\n const certLengthBuffer = Buffer.alloc(1);\n certLengthBuffer.writeUIntBE(certBuffer.length, 0, 1);\n\n const pubBuffer = Buffer.from(params.handshakeAttestation.attestationPub, \"base64\");\n\n const certChainData = Buffer.concat([\n sigLengthBuffer,\n sigBuffer,\n pubBuffer,\n certLengthBuffer,\n certBuffer,\n ]);\n\n const cliMsgBuffer = Buffer.from(params.handshake, \"hex\");\n const cliMsgLengthBuffer = Buffer.alloc(1);\n cliMsgLengthBuffer.writeUIntBE(cliMsgBuffer.length, 0, 1);\n\n const pidBuffer = Buffer.from(params.partitionId, \"hex\");\n const pidLengthBuffer = Buffer.alloc(1);\n pidLengthBuffer.writeUIntBE(pidBuffer.length, 0, 1);\n\n const certChainDataLengthBuff = Buffer.alloc(2);\n certChainDataLengthBuff.writeUInt16BE(certChainData.length, 0);\n\n const data = Buffer.concat([\n cliMsgLengthBuffer,\n cliMsgBuffer,\n certChainDataLengthBuff,\n certChainData,\n pidLengthBuffer,\n pidBuffer,\n ]);\n\n const totalLengthBuffer = Buffer.alloc(2);\n totalLengthBuffer.writeUInt16BE(data.length, 0);\n\n const toSend = Buffer.concat([totalLengthBuffer, data]);\n\n return toSend;\n};\n\ntype RetryOnError = (err: Error) => boolean;\n/* v8 ignore start */\nconst genericRetryOnError: RetryOnError = (err) => {\n // device is locked\n if (err instanceof LockedDeviceError) return true;\n // user is on dashboard when receiving a Vault app apdu\n if (isTransportStatusError(err) && err.statusCode === 0x6d09) return true;\n // VG-24797 error that can happen in BLE in some situations (still unclear)\n if (err instanceof DisconnectedDevice) return true;\n\n // for everything else, we don't want to retry\n return false;\n};\n/* v8 ignore stop */\n\nexport function createRealDevice(options: Options, logger: Logger): Device {\n const { transportId } = options;\n\n async function run<T>(\n job: (transport: Transport) => Promise<T>,\n retryOnError: RetryOnError = genericRetryOnError,\n ): Promise<T> {\n return lastValueFrom(\n withDevicePolling(transportId)<T>((transport) => from(job(transport)), retryOnError),\n );\n }\n\n /* v8 ignore start */\n const noRetry = (): boolean => false;\n const alwaysRetry = (): boolean => true;\n /* v8 ignore stop */\n const poll = async (\n opts: { retryOnError?: RetryOnError } = {},\n ): Promise<{ isAppOpened: boolean }> => {\n // waiting for device to be turned on\n await run(\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n async (_transport) => {},\n opts.retryOnError ?? alwaysRetry,\n );\n // checking if app is opened: should return directly on getPubKey\n try {\n await getPublicKey(PATHS.U2F, { secp256k1: true, retryOnError: noRetry });\n return { isAppOpened: true };\n } catch (err) {\n if (isTransportStatusError(err) && genericRetryOnError(err)) {\n return { isAppOpened: false };\n }\n throw err;\n }\n };\n\n const pollApp = async (appName: string): Promise<string> => {\n const res = await run((transport) =>\n transport.send(0xe0, 0xd8, 0x00, 0x00, Buffer.from(appName, \"utf8\")),\n );\n // little delay to give time to the app to be fully opened\n await new Promise((r) => setTimeout(r, 1e3));\n return res.toString(\"hex\");\n };\n\n const getPublicKey = async (\n pathString: string,\n { secp256k1, retryOnError }: { secp256k1: boolean; retryOnError?: RetryOnError },\n ): Promise<{ pubKey: string; signature: string }> => {\n logger.info(`[device] getPublicKey (${pathString})`);\n const path = getPathFromPathString(pathString);\n const data = Buffer.concat([\n Buffer.from([path.length]),\n ...path.map((derivation) => {\n const buf = Buffer.alloc(4);\n buf.writeUInt32BE(derivation, 0);\n return buf;\n }),\n ]);\n const curve = secp256k1 ? 0x01 : 0x02;\n const response = await run(\n (transport) => transport.send(0xe0, 0x40, curve, 0x00, data),\n retryOnError ?? genericRetryOnError,\n );\n const pubKeyLength = response.readInt8(0);\n const pubKey = response\n .slice(1, pubKeyLength + 1)\n .toString(\"hex\")\n .toUpperCase();\n const signature = response\n .slice(pubKeyLength + 1, response.length - STATUS_LENGTH)\n .toString(\"base64\");\n return { pubKey, signature };\n };\n\n const device: Device = {\n authenticate: async ({ challenge: { challenge, name, role, keyHandle }, workspaceName }) => {\n logger.info(`[device] Authenticate`);\n invariant(role !== \"READ_ONLY_API_KEY\", \"Invalid role for authenticate: READ_ONLY_API_KEY\");\n const applicationBuffer = Buffer.from(APPID_VAULT_ADMINISTRATOR, \"hex\");\n const nameBuffer = Buffer.from(name);\n const workspaceBuffer = Buffer.from(workspaceName);\n\n const keyHandleData = Buffer.concat([\n Buffer.from(STR_ROLES[role], \"hex\"),\n Buffer.from([nameBuffer.length]),\n nameBuffer,\n Buffer.from([workspaceBuffer.length]),\n workspaceBuffer,\n ]);\n\n const keyHandleDataLength = Buffer.alloc(2);\n keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);\n\n const data = Buffer.concat([\n Buffer.from(challenge, \"base64\"),\n applicationBuffer,\n Buffer.from([keyHandle.length]),\n Buffer.from(keyHandle, \"hex\"),\n keyHandleDataLength,\n keyHandleData,\n ]);\n\n const authentication = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x02, 0x00, 0x00], data),\n );\n\n return removeStatus(authentication).toString(\"hex\");\n },\n\n finalizePairingHandshake: async (params: {\n handshake: string;\n partitionId: string;\n handshakeAttestation: HsmCertificate;\n }): Promise<string> => {\n const bufWithStatus = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x47, 0x00, 0x02], buildAttestation(params)),\n );\n return removeStatus(bufWithStatus).toString(\"hex\");\n },\n\n generateSeedFragment: FIXME_NOT_IMPLEMENTED(\"generateSeedFragment\"),\n generateWrappingKeyFragment: FIXME_NOT_IMPLEMENTED(\"generateWrappingKeyFragment\"),\n getAttestation: async (): Promise<{\n attestation: {\n codeHash: string;\n attestationPub: string;\n certificate: string;\n };\n buffer: Buffer;\n }> => {\n const bufWithStatus = await run((transport) => transport.send(0xe0, 0x41, 0x00, 0x00));\n const buffer = removeStatus(bufWithStatus);\n const certLen = buffer.readInt8(32 + 65 + 1);\n return {\n attestation: {\n codeHash: buffer.slice(0, 32).toString(\"base64\"),\n attestationPub: buffer.slice(32, 32 + 65).toString(\"base64\"),\n certificate: buffer.slice(32 + 65, 32 + 65 + 2 + certLen).toString(\"base64\"),\n },\n buffer,\n };\n },\n getConfidentialityKey: async () => {\n logger.info(`[device] getConfidentialityKey`);\n const bufWithStatus = await run((transport) => transport.send(0xe0, 0x4d, 0x00, 0x00));\n const buf = removeStatus(bufWithStatus);\n const keyLength = buf[0]!;\n const key = buf.slice(1, 1 + keyLength);\n const sig = buf.slice(1 + keyLength + 1);\n return {\n confidentialityKeyCurve25519: key.toString(\"hex\"),\n confidentialityKeySignature: sig.toString(\"hex\"),\n };\n },\n getConfidentialityPubKey: () => getPublicKey(PATHS.CONFIDENTIALITY, { secp256k1: true }),\n getDeviceUserId: FIXME_NOT_IMPLEMENTED(\"getDeviceUserId\"),\n getU2FPubKey: () => getPublicKey(PATHS.U2F, { secp256k1: false }),\n getValidationPubKey: () => getPublicKey(PATHS.VALIDATION, { secp256k1: true }),\n hasPairing: async () => {\n logger.info(`[device] hasPairing`);\n const apdu = [0xe0, 0x51, 0x00, 0x00, 0xb5];\n const res = await run((transport) => transport.exchange(Buffer.from(apdu)));\n const hex = Buffer.from(res).toString(\"hex\");\n\n // 6f45 => this error means that there is no partition ID on the device\n // if no error, it means there is (at least) one\n //\n // 6a87 => TEMPORARY hack because Stax apparently does not implement\n // the \"get partition id\" APDU, so it returns \"incorrect length\"\n // easier to just assume that in this case there is no partition,\n // and try to insert one anyway (done on revault onboarding)\n //\n return hex !== \"6f45\" && hex !== \"6a87\";\n },\n\n initPairingHandshake: async (): Promise<{ pubKey: string; signature: string }> => {\n const res = await run((transport) => transport.send(0xe0, 0x46, 0x00, 0x00));\n const pubKeyLength = res.readInt8(0);\n const pubKey = res\n .slice(1, pubKeyLength + 1)\n .toString(\"hex\")\n .toUpperCase();\n const signature = res.slice(pubKeyLength + 1, res.length - STATUS_LENGTH).toString(\"base64\");\n return { pubKey, signature };\n },\n\n openSession: FIXME_NOT_IMPLEMENTED(\"openSession\"),\n\n register: async (params: {\n challenge: string;\n u2fRegisterData: string;\n name: string;\n role: \"ADMIN\" | \"SHARED_OWNER\" | \"OPERATOR\";\n }): Promise<{\n u2fRegister: Buffer;\n keyHandle: Buffer;\n rfu: number;\n pubKey: string;\n }> => {\n const { challenge: strChallenge, u2fRegisterData: _, name, role } = params;\n const challenge = Buffer.from(strChallenge, \"hex\");\n\n invariant(challenge.length === 32, \"challenge hex is expected to have 32 bytes\");\n const applicationBuf = Buffer.from(APPID_VAULT_ADMINISTRATOR, \"hex\");\n invariant(applicationBuf.length === 32, \"application hex is expected to have 32 bytes\");\n\n const userNameBuff = Buffer.from(name);\n\n const keyHandleData = Buffer.concat([\n Buffer.from(STR_ROLES[role], \"hex\"),\n Buffer.from([userNameBuff.length]),\n userNameBuff,\n ]);\n\n const keyHandleDataLength = Buffer.alloc(2);\n keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);\n\n const data = Buffer.concat([challenge, applicationBuf, keyHandleDataLength, keyHandleData]);\n\n const response = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x01, 0x00, 0x00], data),\n );\n\n let i = 0;\n const rfu = response.slice(i, (i += 1))[0]!;\n const pubKey = response.slice(i, (i += 65)).toString(\"hex\");\n const keyHandleLength = response.slice(i, ++i)[0]!;\n const keyHandle = response.slice(i, (i += keyHandleLength));\n return {\n u2fRegister: removeStatus(response),\n keyHandle,\n rfu,\n pubKey,\n };\n },\n registerData: async (params: { challenge: string }): Promise<string> => {\n const { challenge: strChallenge } = params;\n const challenge = Buffer.from(strChallenge, \"hex\");\n invariant(challenge.length === 32, \"challenge hex is expected to have 32 bytes\");\n const response = await run((transport) => transport.send(0xe0, 0x03, 0x00, 0x00, challenge));\n return removeStatus(response).toString(\"hex\");\n },\n\n setPairing: async ({ pairing }) => {\n logger.info(`[device] setPairing`);\n const psdPayload = Buffer.from(pairing.blob, \"base64\");\n const length = Buffer.alloc(2);\n length.writeUInt16BE(psdPayload.length, 0);\n const final = Buffer.concat([length, psdPayload]);\n await run((transport) => sendByChunk(transport, [0xe0, 0x4e, 0x00, 0x00], final));\n },\n startKKPatternAsResponder: FIXME_NOT_IMPLEMENTED(\"startKKPatternAsResponder\"),\n startKPatternAsResponder: async (params) => {\n logger.info(`[device] startKPatternAsResponder`);\n const data = buildAttestation(params);\n await run((transport) =>\n sendByChunk(transport, [0xe0, 0x49, 0x00, SCRIPT_IDS.ACCOUNT_MANAGER_SESSION], data),\n );\n },\n validateVaultOperation: async (params) => {\n logger.info(`[device] validateVaultOperation`);\n const path = getPathFromPathString(PATHS.VALIDATION);\n const paths = Buffer.concat([\n Buffer.from([path.length]),\n ...path.map((derivation) => {\n const buf = Buffer.alloc(4);\n buf.writeUInt32BE(derivation, 0);\n return buf;\n }),\n ]);\n\n let nextActionId = 1;\n let finalResponse;\n\n while (!finalResponse) {\n const screen = Buffer.from(params.actions[nextActionId - 1]!, \"base64\");\n const length = Buffer.alloc(2);\n length.writeUInt16BE(screen.length, 0);\n const data = Buffer.concat([paths, length, screen]);\n const response = await run((transport) =>\n sendByChunk(transport, [0xe0, 0x45, 0x00, 0x00], data),\n );\n const responseType = response.readInt8(0);\n let responseStatus = response.readUInt16BE(response.length - 2);\n if (responseType === STREAMING_NEXT_ACTION) {\n nextActionId = response.readUIntBE(1, 2);\n } else if (responseType === STREAMING_RESPONSE) {\n finalResponse = response.slice(3, response.length - 2);\n /* v8 ignore start */\n while (responseStatus !== 0x9000) {\n const resp = await run((transport) => transport.send(0x00, 0xc0, 0x00, 0x00));\n responseStatus = resp.readUInt16BE(resp.length - 2);\n finalResponse = Buffer.concat([finalResponse, removeStatus(resp)]);\n }\n } else {\n throw Error(`${responseType}`);\n }\n /* v8 ignore stop */\n }\n return finalResponse.toString(\"base64\");\n },\n\n sendAPDU: async (apduCommand: string) => {\n const res = await run((transport) => transport.exchange(Buffer.from(apduCommand, \"hex\")));\n return Buffer.from(res).toString(\"hex\");\n },\n getVersion: async () => {\n const res = await run((transport) => transport.send(0xb0, 0x01, 0x00, 0x00));\n const appNameLen = res.readInt8(1);\n const appVersionLen = res.readInt8(2 + appNameLen);\n const appVersionHex = res.slice(2 + 1 + appNameLen, 2 + appNameLen + appVersionLen + 1);\n\n const appVersion = Buffer.from(appVersionHex).toString();\n\n return appVersion;\n },\n poll,\n pollApp,\n };\n return device;\n}\n","import type { AppRouter } from \"@ledgerhq/revault-api\";\nimport { type TRPCClient, createTRPCClient, httpBatchLink } from \"@trpc/client\";\nimport type { inferRouterInputs, inferRouterOutputs } from \"@trpc/server\";\nimport superjson from \"superjson\";\n\nexport type TRPCClientOptions = {\n baseUrl: string;\n debugAuthToken?: string;\n rootAuthToken?: string;\n apiAccessToken?: string;\n psdAuth?: string;\n};\n\nexport type RevaultApiTRPCClient = TRPCClient<AppRouter>;\n\nexport type RouterInputs = inferRouterInputs<AppRouter>;\nexport type RouterOutputs = inferRouterOutputs<AppRouter>;\n\nexport const createClient = (options: TRPCClientOptions): RevaultApiTRPCClient => {\n const trpc = createTRPCClient<AppRouter>({\n links: [\n httpBatchLink({\n url: `${options.baseUrl}/trpc`,\n transformer: superjson,\n headers() {\n return {\n ...(options.debugAuthToken\n ? { \"x-revault-debug-auth-token\": options.debugAuthToken }\n : {}),\n ...(options.rootAuthToken\n ? { \"x-revault-root-auth-token\": options.rootAuthToken }\n : {}),\n ...(options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {}),\n ...(options.apiAccessToken\n ? { Authorization: `Bearer ${options.apiAccessToken}` }\n : {}),\n };\n },\n }),\n ],\n });\n return trpc;\n};\n"]}
package/lib/engine.d.cts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Logger } from './index.cjs';
2
- import { a as EngineOptions, E as Engine } from './types-DVIS-vF0.cjs';
3
- export { A as ApproveRequestParams, m as DecorateWithApiUserAndWorkspaceUnauthenticated, D as DecorateWithDevice, e as DecorateWithDeviceAndOnboarding, k as DecorateWithDeviceAndWorkspaceUnauthenticated, g as DecorateWithWorkspace, j as DecorateWithWorkspaceApiAuthenticated, i as DecorateWithWorkspacePsdAuthenticated, h as DecorateWithWorkspaceUnauthenticated, b as EngineBase, R as RegisterOnboardingDeviceParams, n as WithApiAuth, d as WithApiUser, c as WithDevice, W as WithOnboarding, l as WithPsdAuth, f as WithWorkspace } from './types-DVIS-vF0.cjs';
2
+ import { a as EngineOptions, E as Engine } from './types-BxfmwEOw.cjs';
3
+ export { A as ApproveRequestParams, m as DecorateWithApiUserAndWorkspaceUnauthenticated, D as DecorateWithDevice, e as DecorateWithDeviceAndOnboarding, k as DecorateWithDeviceAndWorkspaceUnauthenticated, g as DecorateWithWorkspace, j as DecorateWithWorkspaceApiAuthenticated, i as DecorateWithWorkspacePsdAuthenticated, h as DecorateWithWorkspaceUnauthenticated, b as EngineBase, R as RegisterOnboardingDeviceParams, n as WithApiAuth, d as WithApiUser, c as WithDevice, W as WithOnboarding, l as WithPsdAuth, f as WithWorkspace } from './types-BxfmwEOw.cjs';
4
4
  import { Paginated } from '@ledgerhq/revault-api';
5
- import './types-CsvE9Mlb.cjs';
5
+ import './types-DJfbanPz.cjs';
6
6
  import '@trpc/client';
7
7
  import '@trpc/server';
8
8
 
package/lib/engine.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import { Logger } from './index.js';
2
- import { a as EngineOptions, E as Engine } from './types-CisIFJCB.js';
3
- export { A as ApproveRequestParams, m as DecorateWithApiUserAndWorkspaceUnauthenticated, D as DecorateWithDevice, e as DecorateWithDeviceAndOnboarding, k as DecorateWithDeviceAndWorkspaceUnauthenticated, g as DecorateWithWorkspace, j as DecorateWithWorkspaceApiAuthenticated, i as DecorateWithWorkspacePsdAuthenticated, h as DecorateWithWorkspaceUnauthenticated, b as EngineBase, R as RegisterOnboardingDeviceParams, n as WithApiAuth, d as WithApiUser, c as WithDevice, W as WithOnboarding, l as WithPsdAuth, f as WithWorkspace } from './types-CisIFJCB.js';
2
+ import { a as EngineOptions, E as Engine } from './types-ZEEgdlx2.js';
3
+ export { A as ApproveRequestParams, m as DecorateWithApiUserAndWorkspaceUnauthenticated, D as DecorateWithDevice, e as DecorateWithDeviceAndOnboarding, k as DecorateWithDeviceAndWorkspaceUnauthenticated, g as DecorateWithWorkspace, j as DecorateWithWorkspaceApiAuthenticated, i as DecorateWithWorkspacePsdAuthenticated, h as DecorateWithWorkspaceUnauthenticated, b as EngineBase, R as RegisterOnboardingDeviceParams, n as WithApiAuth, d as WithApiUser, c as WithDevice, W as WithOnboarding, l as WithPsdAuth, f as WithWorkspace } from './types-ZEEgdlx2.js';
4
4
  import { Paginated } from '@ledgerhq/revault-api';
5
- import './types-CsvE9Mlb.js';
5
+ import './types-DJfbanPz.js';
6
6
  import '@trpc/client';
7
7
  import '@trpc/server';
8
8
 
package/lib/engine.js CHANGED
@@ -13,7 +13,7 @@ import {
13
13
  createApiDevice,
14
14
  isTransportStatusError,
15
15
  withDevicePolling
16
- } from "./chunk-DPHEFR6E.js";
16
+ } from "./chunk-BGVGHXMO.js";
17
17
 
18
18
  // src/engine/index.ts
19
19
  import invariant2 from "invariant";
@@ -102,12 +102,13 @@ function createRealDevice(options, logger) {
102
102
  );
103
103
  }
104
104
  const noRetry = () => false;
105
- const poll = async () => {
105
+ const alwaysRetry = () => true;
106
+ const poll = async (opts = {}) => {
106
107
  await run(
107
108
  // eslint-disable-next-line @typescript-eslint/no-empty-function
108
109
  async (_transport) => {
109
110
  },
110
- () => true
111
+ opts.retryOnError ?? alwaysRetry
111
112
  );
112
113
  try {
113
114
  await getPublicKey(PATHS.U2F, { secp256k1: true, retryOnError: noRetry });
@@ -176,10 +177,27 @@ function createRealDevice(options, logger) {
176
177
  );
177
178
  return removeStatus(authentication).toString("hex");
178
179
  },
179
- finalizePairingHandshake: FIXME_NOT_IMPLEMENTED("finalizePairingHandshake"),
180
+ finalizePairingHandshake: async (params) => {
181
+ const bufWithStatus = await run(
182
+ (transport) => sendByChunk(transport, [224, 71, 0, 2], buildAttestation(params))
183
+ );
184
+ return removeStatus(bufWithStatus).toString("hex");
185
+ },
180
186
  generateSeedFragment: FIXME_NOT_IMPLEMENTED("generateSeedFragment"),
181
187
  generateWrappingKeyFragment: FIXME_NOT_IMPLEMENTED("generateWrappingKeyFragment"),
182
- getAttestation: FIXME_NOT_IMPLEMENTED("getAttestation"),
188
+ getAttestation: async () => {
189
+ const bufWithStatus = await run((transport) => transport.send(224, 65, 0, 0));
190
+ const buffer = removeStatus(bufWithStatus);
191
+ const certLen = buffer.readInt8(32 + 65 + 1);
192
+ return {
193
+ attestation: {
194
+ codeHash: buffer.slice(0, 32).toString("base64"),
195
+ attestationPub: buffer.slice(32, 32 + 65).toString("base64"),
196
+ certificate: buffer.slice(32 + 65, 32 + 65 + 2 + certLen).toString("base64")
197
+ },
198
+ buffer
199
+ };
200
+ },
183
201
  getConfidentialityKey: async () => {
184
202
  logger.info(`[device] getConfidentialityKey`);
185
203
  const bufWithStatus = await run((transport) => transport.send(224, 77, 0, 0));
@@ -203,10 +221,51 @@ function createRealDevice(options, logger) {
203
221
  const hex = Buffer.from(res).toString("hex");
204
222
  return hex !== "6f45" && hex !== "6a87";
205
223
  },
206
- initPairingHandshake: FIXME_NOT_IMPLEMENTED("initPairingHandshake"),
224
+ initPairingHandshake: async () => {
225
+ const res = await run((transport) => transport.send(224, 70, 0, 0));
226
+ const pubKeyLength = res.readInt8(0);
227
+ const pubKey = res.slice(1, pubKeyLength + 1).toString("hex").toUpperCase();
228
+ const signature = res.slice(pubKeyLength + 1, res.length - STATUS_LENGTH).toString("base64");
229
+ return { pubKey, signature };
230
+ },
207
231
  openSession: FIXME_NOT_IMPLEMENTED("openSession"),
208
- register: FIXME_NOT_IMPLEMENTED("register"),
209
- registerData: FIXME_NOT_IMPLEMENTED("registerData"),
232
+ register: async (params) => {
233
+ const { challenge: strChallenge, u2fRegisterData: _, name, role } = params;
234
+ const challenge = Buffer.from(strChallenge, "hex");
235
+ invariant(challenge.length === 32, "challenge hex is expected to have 32 bytes");
236
+ const applicationBuf = Buffer.from(APPID_VAULT_ADMINISTRATOR, "hex");
237
+ invariant(applicationBuf.length === 32, "application hex is expected to have 32 bytes");
238
+ const userNameBuff = Buffer.from(name);
239
+ const keyHandleData = Buffer.concat([
240
+ Buffer.from(STR_ROLES[role], "hex"),
241
+ Buffer.from([userNameBuff.length]),
242
+ userNameBuff
243
+ ]);
244
+ const keyHandleDataLength = Buffer.alloc(2);
245
+ keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);
246
+ const data = Buffer.concat([challenge, applicationBuf, keyHandleDataLength, keyHandleData]);
247
+ const response = await run(
248
+ (transport) => sendByChunk(transport, [224, 1, 0, 0], data)
249
+ );
250
+ let i = 0;
251
+ const rfu = response.slice(i, i += 1)[0];
252
+ const pubKey = response.slice(i, i += 65).toString("hex");
253
+ const keyHandleLength = response.slice(i, ++i)[0];
254
+ const keyHandle = response.slice(i, i += keyHandleLength);
255
+ return {
256
+ u2fRegister: removeStatus(response),
257
+ keyHandle,
258
+ rfu,
259
+ pubKey
260
+ };
261
+ },
262
+ registerData: async (params) => {
263
+ const { challenge: strChallenge } = params;
264
+ const challenge = Buffer.from(strChallenge, "hex");
265
+ invariant(challenge.length === 32, "challenge hex is expected to have 32 bytes");
266
+ const response = await run((transport) => transport.send(224, 3, 0, 0, challenge));
267
+ return removeStatus(response).toString("hex");
268
+ },
210
269
  setPairing: async ({ pairing }) => {
211
270
  logger.info(`[device] setPairing`);
212
271
  const psdPayload = Buffer.from(pairing.blob, "base64");
@@ -265,6 +324,14 @@ function createRealDevice(options, logger) {
265
324
  const res = await run((transport) => transport.exchange(Buffer.from(apduCommand, "hex")));
266
325
  return Buffer.from(res).toString("hex");
267
326
  },
327
+ getVersion: async () => {
328
+ const res = await run((transport) => transport.send(176, 1, 0, 0));
329
+ const appNameLen = res.readInt8(1);
330
+ const appVersionLen = res.readInt8(2 + appNameLen);
331
+ const appVersionHex = res.slice(2 + 1 + appNameLen, 2 + appNameLen + appVersionLen + 1);
332
+ const appVersion = Buffer.from(appVersionHex).toString();
333
+ return appVersion;
334
+ },
268
335
  poll,
269
336
  pollApp
270
337
  };
@@ -284,7 +351,8 @@ var createClient = (options) => {
284
351
  return {
285
352
  ...options.debugAuthToken ? { "x-revault-debug-auth-token": options.debugAuthToken } : {},
286
353
  ...options.rootAuthToken ? { "x-revault-root-auth-token": options.rootAuthToken } : {},
287
- ...options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {}
354
+ ...options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {},
355
+ ...options.apiAccessToken ? { Authorization: `Bearer ${options.apiAccessToken}` } : {}
288
356
  };
289
357
  }
290
358
  })
@@ -321,7 +389,8 @@ async function genericRegister({
321
389
  const challenge = await getChallenge({ pubKey: u2fPubKey.pubKey, deviceData });
322
390
  const pairingPayload = await device.finalizePairingHandshake({
323
391
  handshake: challenge.handshake,
324
- ciphertext: challenge.ciphertext
392
+ partitionId: challenge.ciphertext,
393
+ handshakeAttestation: challenge.handshakeAttestation
325
394
  });
326
395
  const register = await device.register({
327
396
  challenge: challenge.challenge,
@@ -580,14 +649,14 @@ function createEngine(options, logger) {
580
649
  name: registration.name,
581
650
  role: registration.role,
582
651
  getChallenge: async ({ deviceData }) => {
583
- const challenge = await client2.users.generateRegistrationChallenge.mutate({
652
+ const challenge = await client2.userRegistrations.generateChallenge.mutate({
584
653
  id: registration.id,
585
654
  workspaceName: __workspaceName,
586
655
  deviceData
587
656
  });
588
657
  return challenge;
589
658
  },
590
- submitChallenge: ({ challengeResponse }) => client2.users.confirmRegistrationChallenge.mutate({
659
+ submitChallenge: ({ challengeResponse }) => client2.userRegistrations.submitChallenge.mutate({
591
660
  workspaceName: __workspaceName,
592
661
  id: registration.id,
593
662
  challengeResponse