@ledgerhq/vault-common 2.1.1 → 2.1.2
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.
- package/.turbo/turbo-build.log +20 -60
- package/CHANGELOG.md +6 -0
- package/package.json +8 -9
- package/tsup.config.ts +1 -1
- package/lib/chunk-54MXA3ZY.mjs +0 -14
- package/lib/chunk-54MXA3ZY.mjs.map +0 -1
- package/lib/chunk-6TT6A6YA.mjs +0 -1176
- package/lib/chunk-6TT6A6YA.mjs.map +0 -1
- package/lib/chunk-HU7O2ZFW.mjs +0 -249
- package/lib/chunk-HU7O2ZFW.mjs.map +0 -1
- package/lib/chunk-J5LGTIGS.mjs +0 -10
- package/lib/chunk-J5LGTIGS.mjs.map +0 -1
- package/lib/chunk-MNUHUKY3.mjs +0 -503
- package/lib/chunk-MNUHUKY3.mjs.map +0 -1
- package/lib/chunk-QNNV5GBH.mjs +0 -1261
- package/lib/chunk-QNNV5GBH.mjs.map +0 -1
- package/lib/chunk-VOB7PA3G.mjs +0 -97
- package/lib/chunk-VOB7PA3G.mjs.map +0 -1
- package/lib/chunk-ZJCMYPBL.mjs +0 -83
- package/lib/chunk-ZJCMYPBL.mjs.map +0 -1
- package/lib/createHSMBridge.d.mts +0 -27
- package/lib/createHSMBridge.mjs +0 -10
- package/lib/createHSMBridge.mjs.map +0 -1
- package/lib/crypto/utils.d.mts +0 -14
- package/lib/crypto/utils.mjs +0 -12
- package/lib/crypto/utils.mjs.map +0 -1
- package/lib/index-Cm_O9VIx.d.mts +0 -2010
- package/lib/index.d.mts +0 -161
- package/lib/index.mjs +0 -3252
- package/lib/index.mjs.map +0 -1
- package/lib/recipeManifest.d.mts +0 -6
- package/lib/recipeManifest.mjs +0 -11
- package/lib/recipeManifest.mjs.map +0 -1
- package/lib/reviewAPIRequest.d.mts +0 -20
- package/lib/reviewAPIRequest.mjs +0 -11
- package/lib/reviewAPIRequest.mjs.map +0 -1
- package/lib/types/index.d.mts +0 -6
- package/lib/types/index.mjs +0 -10
- package/lib/types/index.mjs.map +0 -1
- package/lib/utils.d.mts +0 -29
- package/lib/utils.mjs +0 -38
- package/lib/utils.mjs.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/reviewAPIRequest.ts","../src/apiUser/index.ts","../src/createDefaultRunner.ts","../src/prepareRequest.ts"],"sourcesContent":["import { SILENT_LOGGER } from \"@ledgerhq/vault-utils\";\n\nimport { authenticate, decodeChallenge, signAndApprove } from \"./apiUser\";\nimport createNetwork from \"./createNetwork\";\nimport { APIRequestResponse, DevicesPool, ManifestAPIV2User, RunnableOptions } from \"./types\";\nimport { getWorkspaceFromGate } from \"./utils\";\n\nexport type ReviewAPIRequestOptions = {\n pool: DevicesPool;\n requestID: number;\n apiUser: ManifestAPIV2User;\n gate: string;\n apiGateway: string;\n reviewType: ReviewType;\n skipDecodeChallenge?: boolean;\n};\n\nexport type ReviewType = \"APPROVE\" | \"REJECT\";\n\nasync function reviewAPIRequest(\n {\n pool,\n requestID,\n apiUser,\n gate,\n apiGateway,\n reviewType,\n skipDecodeChallenge = false,\n }: ReviewAPIRequestOptions,\n { logger = SILENT_LOGGER }: RunnableOptions,\n): Promise<APIRequestResponse> {\n const workspace = getWorkspaceFromGate(gate);\n const apiNetwork = createNetwork({\n baseURL: apiGateway,\n });\n logger.info(`Authenticate for ${apiUser.name}`);\n const bearerToken = await authenticate(pool, apiNetwork, workspace, apiUser, logger);\n\n let apiChallenge = {\n challenge: \"\",\n decodedChallenge: \"\",\n };\n // for example today there is no challenge ro reject a message signing transaction as a simple empty abort is enough like for regular transaction\n if (skipDecodeChallenge === false) {\n logger.info(\"Decode challenge\");\n apiChallenge = await decodeChallenge({\n apiNetwork,\n workspace,\n bearerToken,\n requestID,\n reviewType,\n });\n }\n\n logger.info(apiChallenge.decodedChallenge);\n logger.info(\"Sign and approve\");\n\n return signAndApprove({\n apiNetwork,\n workspace,\n bearerToken,\n requestID,\n apiUser,\n challenge: apiChallenge.challenge,\n reviewType,\n });\n}\n\nexport default reviewAPIRequest;\n","import { Logger } from \"@ledgerhq/vault-utils\";\nimport chalk from \"chalk\";\n\nimport createDefaultRunner from \"../createDefaultRunner\";\nimport { decodeData, genKeys, sign } from \"../crypto/utils\";\nimport { ReviewType } from \"../reviewAPIRequest\";\nimport {\n APIBearerTokenResponse,\n APIGetChallengeResponse,\n APIRequestResponse,\n Connection,\n DevicesPool,\n GateAccount,\n GateWhitelist,\n ManifestAPIV2User,\n Network,\n} from \"../types\";\nimport { TradelinkPledge } from \"../types/tradelink\";\n\nfunction getAPIHeader(bearerToken: string, workspace: string) {\n return {\n headers: {\n \"X-Ledger-Workspace\": workspace,\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${bearerToken}`,\n },\n };\n}\n\nexport async function regenerateCredentials(\n pool: DevicesPool,\n apiNetwork: Network,\n workspace: string,\n apiUser: ManifestAPIV2User,\n logger: Logger,\n): Promise<{ api_key_id: string; api_key_secret: string }> {\n const runner = createDefaultRunner(pool, {});\n const postApiUserAccess = {\n user: apiUser,\n publicKey: genKeys(apiUser.name).hexPubKey,\n role: apiUser.role,\n name: apiUser.name,\n };\n const userAccessRequest = await runner.createAPIV2UserAccess(postApiUserAccess);\n const apiUserAuth = {\n api_key_id: userAccessRequest.api_key_id,\n api_key_secret: userAccessRequest.api_key_secret,\n };\n\n logger.info(\n chalk`{red.bold IMPORTANT:} {red The API user credentials will not be displayed again so note them somewhere}`,\n );\n logger.info(\n JSON.stringify({\n api_key_id: userAccessRequest.api_key_id,\n api_key_secret: userAccessRequest.api_key_secret,\n }),\n );\n return apiUserAuth;\n}\n\nexport async function getAuthTokens(\n apiNetwork: Network,\n workspace: string,\n apiUserAuth: { api_key_id: string; api_key_secret: string },\n) {\n return await apiNetwork<APIBearerTokenResponse>(\"POST\", \"/auth/token\", apiUserAuth, {\n headers: { \"X-Ledger-Workspace\": workspace },\n });\n}\n\nexport async function authenticate(\n pool: DevicesPool,\n apiNetwork: Network,\n workspace: string,\n apiUser: ManifestAPIV2User,\n logger: Logger,\n): Promise<string> {\n const apiUserAuth = await regenerateCredentials(pool, apiNetwork, workspace, apiUser, logger);\n\n const bearerResp = await getAuthTokens(apiNetwork, workspace, apiUserAuth);\n return bearerResp.access_token;\n}\n\nexport type APIChallenge = {\n challenge: string;\n decodedChallenge: any;\n};\n\nexport async function decodeChallenge({\n apiNetwork,\n workspace,\n bearerToken,\n requestID,\n reviewType,\n}: {\n apiNetwork: Network;\n workspace: string;\n bearerToken: string;\n requestID: number;\n reviewType: ReviewType;\n}): Promise<APIChallenge> {\n let challengeUrl = `/requests/${requestID}/challenge`;\n if (reviewType === \"REJECT\") {\n challengeUrl = `${challengeUrl}/reject`;\n }\n const challengeResp = await apiNetwork<APIGetChallengeResponse>(\n \"GET\",\n challengeUrl,\n {},\n getAPIHeader(bearerToken, workspace),\n ).catch((error) => {\n // have to do this sh**t because settlement are transaction today so we have now way to know if this create transaction is part of a tradelink settlement\n if (error.message.includes(\"Get abort challenge is only available for tradelink settlement\")) {\n return { challenge: \"\" };\n }\n /* istanbul ignore next */\n throw error;\n });\n if (challengeResp.challenge === \"\") {\n return {\n challenge: \"\",\n decodedChallenge: \"\",\n };\n }\n return {\n challenge: challengeResp.challenge,\n decodedChallenge: decodeData(challengeResp.challenge),\n };\n}\n\nexport async function signAndApprove({\n apiNetwork,\n workspace,\n bearerToken,\n requestID,\n apiUser,\n challenge,\n reviewType,\n}: {\n apiNetwork: Network;\n workspace: string;\n bearerToken: string;\n requestID: number;\n apiUser: ManifestAPIV2User;\n challenge: string;\n reviewType: ReviewType;\n}): Promise<APIRequestResponse> {\n const keys = genKeys(apiUser.name);\n\n let jws = \"\";\n if (challenge !== \"\") {\n jws = sign(String(keys.privateKey), challenge);\n }\n\n return await apiNetwork<APIRequestResponse>(\n \"POST\",\n `/requests/${requestID}/${reviewType.toLowerCase()}`,\n { jws },\n getAPIHeader(bearerToken, workspace),\n );\n}\n\nexport async function getTradelinkPledge({\n apiNetwork,\n workspace,\n gateAccount,\n bearerToken,\n exchange,\n}: {\n apiNetwork: Network;\n workspace: string;\n gateAccount: GateAccount;\n bearerToken: string;\n exchange: string;\n}): Promise<TradelinkPledge> {\n const pledgesResp = await apiNetwork<Connection<TradelinkPledge>>(\n \"GET\",\n `/pledges?account_id=${gateAccount.id}`,\n {},\n getAPIHeader(bearerToken, workspace),\n );\n // find sub_account\n const pledgeResp = pledgesResp.edges.find((p) => p.node.exchange.name == exchange);\n /* istanbul ignore if */\n if (!pledgeResp) {\n throw new Error(`Exchange '${exchange}' not found`);\n }\n return pledgeResp.node;\n}\n\nexport async function getTradelinkRecipient({\n pool,\n gateAccount,\n pledge,\n}: {\n pool: DevicesPool;\n gateAccount: GateAccount;\n pledge: TradelinkPledge;\n}): Promise<string> {\n const exchangeWLId = pledge.exchange.whitelist_id;\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const wlResp = await admin.network<Connection<GateWhitelist>>(\n \"GET\",\n `/whitelists?id=${exchangeWLId}`,\n );\n /* istanbul ignore next */\n const wlAddress = wlResp.edges[0]?.node.addresses.find(\n (a) => a.currency === gateAccount.currency,\n )?.address;\n return String(wlAddress);\n}\n","import { SILENT_LOGGER } from \"@ledgerhq/vault-utils\";\nimport invariant from \"invariant\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport prepareRequest, {\n GateCreateAccountPayload,\n GateEditWorkspaceRulePayload,\n Input,\n performRequest,\n} from \"./prepareRequest\";\nimport { RecipeManifestResult } from \"./recipeManifest\";\nimport reviewAPIRequest from \"./reviewAPIRequest\";\nimport {\n BakeManifestOptions,\n Connection,\n DevicesPool,\n GateAPIV2UserAccessRequest,\n GateAccount,\n GateAccountRequest,\n GateEditWorkspaceRuleRequest,\n GateExchangeRequest,\n GateGenericRequest,\n GateGroupRequest,\n GatePolicyRequest,\n GateRequestType,\n GateTradelinkAssetManagerRequest,\n GateTradelinkEntity,\n GateTradelinkExchangeRequest,\n GateTradelinkNetwork,\n GateTradelinkRequest,\n GateUserRequest,\n GateVaultEntityRequest,\n GateWhitelistRequest,\n GateWorkspaceRuleStep,\n MRBakeAccountParams,\n MRBakeExchangeParams,\n MRBakeGroupParams,\n MRBakePolicyParams,\n MRBakeTradelinkEntityOnboardingParams,\n MRBakeTradelinkEntityParams,\n MRBakeTradelinkNetworkParams,\n MRBakeTradelinkOnboardingParams,\n MRBakeVaultEntityParams,\n MRBakeWhitelistParams,\n MRCreateAPIUserParams,\n MRCreateAPIV2UserParams,\n MRCreateUserParams,\n MREditQuorumParams,\n MREditWorkspaceRuleParams,\n ManifestRunner,\n} from \"./types\";\nimport { unwrapConnection, wait } from \"./utils\";\n\nconst createDefaultRunner = (pool: DevicesPool, options: BakeManifestOptions): ManifestRunner => {\n const { twoStepsRequest } = options;\n\n const basicHandler = <R>(type: GateRequestType, options?: { withoutHSM: boolean }) => {\n return async (\n params:\n | MRBakeGroupParams\n | MRBakeAccountParams\n | MRBakeVaultEntityParams\n | MRBakeWhitelistParams\n | MRBakeExchangeParams\n | MRBakePolicyParams,\n ) => {\n const { data, existingRequest, noApproval } = params;\n const payload = prepareRequest({ type, data } as Input);\n const extra = { noApproval, existingRequest, twoStepsRequest, ...options };\n return performRequest<R>(payload, pool, extra);\n };\n };\n\n const createAccount = async (params: MRBakeAccountParams) => {\n const { account, data, tradelinkAM } = params;\n if (\"readOnly\" in account && account.readOnly) {\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const payload = prepareRequest({ type: \"CREATE_ACCOUNT\", data }) as GateCreateAccountPayload;\n return admin.post<GateAccountRequest>(\"/dev/accounts\", payload);\n }\n\n let res;\n try {\n res = await basicHandler<GateAccountRequest>(\"CREATE_ACCOUNT\")(params);\n\n if (tradelinkAM) {\n // get the activation request id\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const reqResp = await admin.get<Connection<GateAccountRequest>>(\n `/requests?page=1&type=ACTIVATE&target_id=${res.account.id}`,\n );\n const requests: GateAccountRequest[] = unwrapConnection(reqResp);\n const activationRequest = requests[0];\n\n /* istanbul ignore if */\n if (!activationRequest) {\n throw new Error(`No account activation request found for account ${res.account.name}`);\n }\n /* istanbul ignore if */\n if (!pool.apiGateway) {\n throw new Error(\"apiGateway URL is not set\");\n }\n await reviewAPIRequest(\n {\n pool,\n requestID: activationRequest.id,\n apiUser: tradelinkAM,\n gate: pool.gate,\n apiGateway: pool.apiGateway,\n reviewType: \"APPROVE\",\n },\n { logger: SILENT_LOGGER },\n );\n }\n } catch (err) {\n //\n // VG-18856 mitigate airdropped account when syncing the parent while children accounts\n // are described in manifest\n //\n /* istanbul ignore else */\n if (\n err instanceof Error &&\n err.name === \"ACCOUNT_CHILD_ALREADY_EXISTED_EXCEPTION\" &&\n \"contractAddress\" in account &&\n !!account.parentAccount\n ) {\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const parentAccountsConnection = await admin.network<Connection<GateAccount>>(\n \"GET\",\n `/accounts?name=${account.parentAccount}`,\n );\n const parentAccountEdge = parentAccountsConnection.edges.find(\n (e) => e.node.name === account.parentAccount,\n );\n invariant(parentAccountEdge, `Parent account not found for ${account.name}`);\n const parentAccount = parentAccountEdge.node;\n const rawCurrencyQuery = `${parentAccount.currency}:${account.contractAddress}`;\n const currencyQuery = encodeURIComponent(rawCurrencyQuery);\n const potentialAccounts = await admin.network<Connection<GateAccount>>(\n \"GET\",\n `/accounts?currency=${currencyQuery}&index=${parentAccount.index}`,\n );\n invariant(\n potentialAccounts.edges.length === 1,\n `We should have one matching token account for ${currencyQuery} (index: ${parentAccount.index})`,\n );\n const existingAccount = potentialAccounts.edges[0]!.node;\n const editParams: MRBakeAccountParams = {\n ...params,\n data: { ...params.data, existingAccount },\n };\n res = await basicHandler<GateAccountRequest>(\"EDIT_ACCOUNT\")(editParams);\n } else {\n throw err;\n }\n }\n\n // VG-17223 optionally wait for account to be active\n if (params.waitForActive) {\n const accountId = res.target_id;\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n\n for (let i = 0; i < 60; i++) {\n const account = await admin.get<GateAccount>(`/accounts/${accountId}`);\n if (account.status === \"ACTIVE\") {\n res.account = account;\n break;\n }\n /* istanbul ignore next */\n await wait(3e3);\n }\n }\n return res;\n };\n\n const createUser = async (params: MRCreateUserParams) => {\n const { role, userID, name, device } = params;\n const type = role === \"operator\" ? \"CREATE_OPERATOR\" : \"CREATE_ADMIN\";\n const data = { userID, role, name };\n const payload = prepareRequest({ type, data });\n const extra = { noApproval: true };\n const req = await performRequest<GateUserRequest>(payload, pool, extra);\n const res = await pool.registerDevice(device, req);\n req.user.pub_key = res.u2f_key.pubKey;\n if (!options.noApproval) {\n await pool.runWithQuorum((admin) => admin.approveRequest(req));\n }\n return req;\n };\n\n const createAPIUser = async (\n params: MRCreateAPIUserParams,\n manifestFromGate: RecipeManifestResult,\n ) => {\n const { user, name, userID } = params;\n let request: GateUserRequest | null =\n manifestFromGate.rawData.pendingUserRequests.find((e) => e.user.username === name) || null;\n if (!request) {\n // Tries to invite user -> PENDING_REGISTRATION status if successful (creation/invitation of user from admin front)\n request = await performRequest<GateUserRequest>(\n {\n type: \"CREATE_OPERATOR\",\n username: name,\n user_id: userID,\n is_api: true,\n view_all_override: user.viewAll,\n },\n pool,\n { noApproval: true },\n );\n }\n if (request.status != \"PENDING_APPROVAL\")\n // Tries to register user -> PENDING_APPROVAL status if successful (api user from api)\n await pool.lamAPI.registerUser(name, request.url_id);\n if (!options.noApproval) {\n // Approves registration request (admin in front)\n await pool.runWithQuorum((admin) => admin.approveRequest(request));\n }\n return request;\n };\n\n const createAPIV2User = async (params: MRCreateAPIV2UserParams) => {\n const { name, publicKey, role } = params;\n const type = \"CREATE_API_USER\";\n const data = { publicKey, name, role };\n const payload = prepareRequest({ type, data });\n const extra = { noApproval: true };\n const req = await performRequest<GateUserRequest>(payload, pool, extra);\n if (!options.noApproval) {\n await pool.runWithQuorum((admin) => admin.approveRequest(req));\n }\n return req;\n };\n\n const createAPIV2UserAccess = async (params: MRCreateAPIV2UserParams) => {\n const { name } = params;\n const type = \"CREATE_API_USER_ACCESS\";\n const data = { name };\n const payload = prepareRequest({ type, data });\n const extra = { noApproval: true };\n return await performRequest<GateAPIV2UserAccessRequest>(payload, pool, extra);\n };\n\n const createTradelinkEntity = async <T extends \"ASSET_MANAGER\" | \"EXCHANGE\" | \"CUSTODIAN\">(\n params: MRBakeTradelinkEntityParams,\n ) => {\n const { tradelinkEntity, type } = params;\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const data = {\n id: tradelinkEntity.id,\n name: tradelinkEntity.name,\n code: tradelinkEntity.code,\n logo_url: tradelinkEntity.logoUrl,\n };\n return await admin.post<GateTradelinkEntity<T>>(`/tradelink/${type}`, data);\n };\n\n const createTradelinkNetwork = async (params: MRBakeTradelinkNetworkParams) => {\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const data = {\n id: uuidv4(),\n custodian: params.custodians[0],\n exchanges: params.exchanges,\n asset_managers: params.assetManagers,\n };\n // we keep deleting and create TL network in case manifest got updated\n await admin.network<GateTradelinkNetwork>(\"DELETE\", \"/tradelink/network\").catch(\n /* istanbul ignore next */\n (error) => {\n if (error.message.includes(\"404\")) {\n // Handle 404 error: if there is no network, it will return a 404 as there is nothing to delete\n } else {\n throw error;\n }\n },\n );\n return await admin.post<GateTradelinkNetwork>(`/tradelink/network`, data);\n };\n\n const createTradelink = async (params: MRBakeTradelinkOnboardingParams) => {\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n const request = await admin.post<GateTradelinkRequest>(`/requests`, params);\n await pool.runWithQuorum((admin) => admin.approveRequest(request));\n return request;\n };\n\n const onboardTradelinkEntity = async (params: MRBakeTradelinkEntityOnboardingParams) => {\n const { tradelinkEntity, type, tradelinkEntityApprover } = params;\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n let data = {};\n let request: GateTradelinkAssetManagerRequest | GateTradelinkExchangeRequest;\n if (type === \"exchanges\") {\n data = {\n type: \"CREATE_TRADELINK_EXCHANGE\",\n exchange_name: tradelinkEntity.name,\n operators: tradelinkEntity.operators,\n addresses: tradelinkEntity.addresses,\n };\n request = await admin.post<GateTradelinkExchangeRequest>(`/requests`, data);\n } else {\n data = {\n type: \"CREATE_TRADELINK_ASSET_MANAGER\",\n asset_manager_name: tradelinkEntity.name,\n operators: tradelinkEntity.operators,\n addresses: tradelinkEntity.addresses,\n };\n request = await admin.post<GateTradelinkAssetManagerRequest>(`/requests`, data);\n }\n await pool.runWithQuorum((admin) => admin.approveRequest(request));\n\n /* istanbul ignore next */\n if (!pool.apiGateway) {\n throw new Error(\"apiGateway URL is not set\");\n }\n // for now the API user have to approve the exchange request (soonTM a new operator request to activate)\n await reviewAPIRequest(\n {\n pool,\n requestID: request.id,\n apiUser: tradelinkEntityApprover,\n gate: pool.gate,\n apiGateway: pool.apiGateway,\n reviewType: \"APPROVE\",\n },\n { logger: SILENT_LOGGER },\n );\n return request;\n };\n\n const editQuorum = async (params: MREditQuorumParams) => {\n const { quorum } = params;\n const payload = prepareRequest({\n type: \"UPDATE_QUORUM\",\n data: { quorum },\n });\n await performRequest<GateGenericRequest>(payload, pool);\n };\n\n const editWorkspaceRule = async (params: MREditWorkspaceRuleParams) => {\n const { rule, usersByName } = params;\n const payload: GateEditWorkspaceRulePayload = {\n type: \"EDIT_WORKSPACE_RULE\",\n permission: rule.permission,\n edit_data: {\n steps: rule.steps.map((s): GateWorkspaceRuleStep => {\n return {\n quorum: s.quorum,\n users: s.users.map((username) => {\n const user = usersByName[username];\n invariant(user, `No user with name ${username}`);\n return user.pub_key;\n }),\n };\n }),\n },\n };\n await performRequest<GateEditWorkspaceRuleRequest>(payload, pool);\n };\n\n const runner: ManifestRunner = {\n editQuorum,\n editWorkspaceRule,\n createUser,\n createAPIUser,\n createAPIV2User,\n createAPIV2UserAccess,\n createGroup: basicHandler<GateGroupRequest>(\"CREATE_GROUP\"),\n editGroup: basicHandler<GateGroupRequest>(\"EDIT_GROUP\"),\n createAccount,\n editAccount: basicHandler<GateAccountRequest>(\"EDIT_ACCOUNT\"),\n createWhitelist: basicHandler<GateWhitelistRequest>(\"CREATE_WHITELIST\"),\n editWhitelist: basicHandler<GateWhitelistRequest>(\"EDIT_WHITELIST\"),\n createVaultEntity: basicHandler<GateVaultEntityRequest>(\"CREATE_ENTITY\", {\n withoutHSM: true,\n }),\n editVaultEntity: basicHandler<GateVaultEntityRequest>(\"EDIT_ENTITY\", {\n withoutHSM: true,\n }),\n createExchange: basicHandler<GateExchangeRequest>(\"IMPORT_EXCHANGE\", {\n withoutHSM: true,\n }),\n editExchange: basicHandler<GateExchangeRequest>(\"IMPORT_EXCHANGE\", {\n withoutHSM: true,\n }),\n createPolicy: basicHandler<GatePolicyRequest>(\"CREATE_POLICY\"),\n createTradelink,\n createTradelinkEntity,\n onboardTradelinkEntity,\n createTradelinkNetwork,\n };\n\n return runner;\n};\n\nexport default createDefaultRunner;\n","import invariant from \"invariant\";\n\nimport {\n DevicesPool,\n GateAccount,\n GateExchange,\n GateGenericRequest,\n GateGovernanceRule,\n GateGovernanceRulesSet,\n GateGroup,\n GatePolicy,\n GateRequestType,\n GateRuleMultiAuthStep,\n GateRuleSCI,\n GateRuleTransactionFilter,\n GateTokenCurrency,\n GateUser,\n GateVaultEntity,\n GateWhitelist,\n GateWorkspacePermission,\n GateWorkspaceRuleStep,\n ManifestAccount,\n ManifestAccountRule,\n ManifestAccountRuleMultiAuth,\n ManifestAccountRuleSCI,\n ManifestAccountRuleThreshold,\n ManifestAccountRuleWhitelist,\n ManifestExchange,\n ManifestGroup,\n ManifestPolicy,\n ManifestVaultEntity,\n ManifestWhitelist,\n Unit,\n WeirdGateERC20Token,\n WeirdGateGovernanceRule,\n WeirdGateGovernanceRulesSet,\n WeirdGateRuleMultiAuth,\n WeirdGateRuleMultiAuthStep,\n WeirdGateRuleThreshold,\n WeirdGateRuleWhitelist,\n WeirdGateTokenCurrency,\n} from \"./types\";\nimport {\n getAccountTypeByCurrency,\n getAccountUnit,\n getCurrencyUnit,\n serializeUnitValue,\n} from \"./utils\";\n\ntype PrepareRequestArgs<S, T> = {\n type: S;\n data: T;\n};\n\nexport type GateCreateUserPayload = {\n type: \"CREATE_ADMIN\" | \"CREATE_OPERATOR\";\n username: string;\n user_id: string;\n is_api?: boolean;\n view_all_override?: boolean;\n};\n\nexport type GateCreateAPIUserPayload = {\n type: \"CREATE_API_USER\";\n user_data: {\n username: string;\n public_key: string;\n role: string;\n };\n};\n\ntype GateCreateAPIV2UserAccessPayload = {\n type: \"CREATE_API_USER_ACCESS\";\n user_data: {\n username: string;\n };\n};\n\ntype GateMigrateUserPayload = {\n type: \"MIGRATE_ADMIN\" | \"MIGRATE_OPERATOR\";\n id: number;\n};\n\ntype GateCreateGroupPayload = {\n type: \"CREATE_GROUP\";\n name: string;\n description: string;\n members: number[];\n};\n\ntype GateMigrateGroupPayload = {\n type: \"MIGRATE_GROUP\";\n group_id: number;\n migration_data: {\n members: number[];\n };\n};\n\nexport type GateCreateLamUserPayload = {\n type: \"CREATE_OPERATOR\";\n username: string;\n user_id: number;\n};\n\ntype GateCreateAccountTradelinkPayload = {\n currency: string;\n custodian: number;\n asset_manager: number;\n exchanges: Array<{ id: number; auto_repledge_enabled: boolean; requires_pre_approval: boolean }>;\n};\n\nexport type GateCreateAccountPayload = {\n type: \"CREATE_ACCOUNT\";\n index?: number;\n account_type: string;\n account_data: {\n name: string;\n derivation_mode?: \"standard\" | \"native_segwit\";\n parent_account?: { id: number } | { name: string };\n currency?: { name: string };\n governance_rules?: WeirdGateGovernanceRulesSet[];\n token?: WeirdGateTokenCurrency;\n\n // legacy format for erc20 token (see VFE-951)\n erc20?: WeirdGateERC20Token;\n };\n tradelink_data?: GateCreateAccountTradelinkPayload;\n};\n\ntype GateEditAccountPayload = {\n type: \"EDIT_ACCOUNT\";\n account_id: number;\n edit_data: {\n erc20?: WeirdGateERC20Token;\n token?: WeirdGateTokenCurrency;\n governance_rules?: WeirdGateGovernanceRulesSet[];\n name: string;\n };\n};\n\ntype GateCreateVaultEntityPayload = {\n type: \"CREATE_ENTITY\";\n name: string;\n accounts: number[];\n};\n\ntype GateEditVaultEntityPayload = {\n type: \"EDIT_ENTITY\";\n entity_id: number;\n edit_data: {\n name: string;\n accounts: number[];\n };\n};\n\ntype GateMigrateAccountPayload = {\n type: \"MIGRATE_ACCOUNT\";\n account_id: number;\n migration_data: {\n currency?: string;\n derivation_mode?: \"STANDARD\" | \"NATIVE_SEGWIT\";\n governance_rules: WeirdGateGovernanceRulesSet[];\n name: string;\n };\n};\n\ntype GateEditGroupPayload = {\n type: \"EDIT_GROUP\";\n group_id: number;\n edit_data: {\n name: string;\n members: number[];\n };\n};\n\ntype GateAddressPayload = {\n name: string;\n currency: string;\n address: string;\n};\n\ntype GateCreateWhitelistPayload = {\n type: \"CREATE_WHITELIST\";\n name: string;\n whitelist_type?: \"TRANSACTION\" | \"SMART_CONTRACT\";\n description: string;\n addresses: GateAddressPayload[];\n};\n\ntype GateMigrateWhitelistPayload = {\n type: \"MIGRATE_WHITELIST\";\n whitelist_id: number;\n};\n\ntype GateEditWhitelistPayload = {\n type: \"EDIT_WHITELIST\";\n whitelist_id: number;\n edit_data: {\n name: string;\n addresses: GateAddressPayload[];\n };\n};\n\ntype GateCreateExchangePayload = {\n type: \"IMPORT_EXCHANGE\";\n exchange_data: {\n name: string;\n platform: string;\n governance_rules: WeirdGateGovernanceRulesSet[] | null;\n credentials: {\n apiKey: string;\n secret: string;\n };\n };\n};\n\ntype GateCreatePolicyPayload = {\n type: \"CREATE_POLICY\";\n policy_data: {\n name: string;\n currency?: { name: string };\n governance_rules: WeirdGateGovernanceRulesSet[];\n };\n};\n\nexport type UsersByDevice = Record<number, GateUser>;\nexport type UsersByName = Record<string, GateUser>;\nexport type GroupByName = Record<string, GateGroup>;\nexport type AccountsByName = Record<string, GateAccount>;\n\nexport type IDByName = {\n [_: string]: number;\n};\n\nexport type DataGroup = {\n group: ManifestGroup;\n usersByDevice: UsersByDevice;\n usersByName: UsersByName;\n existingGroup?: GateGroup;\n};\n\nexport type DataWhitelist = {\n whitelist: ManifestWhitelist;\n existingWhitelist?: GateWhitelist;\n};\n\nexport type DataExchange = {\n exchange: ManifestExchange;\n usersByDevice: UsersByDevice;\n usersByName: UsersByName;\n groupsIDsByName: Record<string, number>;\n existingExchange: GateExchange | void;\n};\n\nexport type DataPolicy = {\n policy: ManifestPolicy;\n usersByDevice: UsersByDevice;\n whitelistsIDsByName: IDByName;\n usersByName: UsersByName;\n groupsIDsByName: Record<string, number>;\n existingPolicy: GatePolicy | void;\n};\n\nexport type DataAccount = {\n account: ManifestAccount;\n existingAccount?: GateAccount;\n usersByDevice: UsersByDevice;\n usersByName: UsersByName;\n groupsIDsByName: IDByName;\n whitelistsIDsByName: IDByName;\n hsmAssetManagersIDsByName: IDByName;\n hsmExchangesIDsByName: IDByName;\n hsmCustodiansIDsByName: IDByName;\n accountsByName: { [key: string]: GateAccount };\n tokens: GateTokenCurrency[];\n};\n\nexport type DataVaultEntity = {\n vaultEntity: ManifestVaultEntity;\n existingVaultEntity?: GateVaultEntity;\n accountsByName: { [key: string]: GateAccount };\n};\n\nexport type DataUser = {\n userID: string;\n name: string;\n role: \"operator\" | \"admin\";\n};\n\nexport type DataAPIUser = {\n name: string;\n publicKey: string;\n role: string;\n};\n\nexport type DataAPIUserAccess = {\n name: string;\n};\n\ntype EditGroupInput = PrepareRequestArgs<\"EDIT_GROUP\", DataGroup>;\ntype CreateGroupInput = PrepareRequestArgs<\"CREATE_GROUP\", DataGroup>;\ntype EditWhitelistInput = PrepareRequestArgs<\"EDIT_WHITELIST\", DataWhitelist>;\n\ntype CreateWhitelistInput = PrepareRequestArgs<\"CREATE_WHITELIST\", DataWhitelist>;\n\ntype CreateUserInput = PrepareRequestArgs<\"CREATE_ADMIN\" | \"CREATE_OPERATOR\", DataUser>;\ntype CreateAPIUserInput = PrepareRequestArgs<\"CREATE_API_USER\", DataAPIUser>;\ntype CreateAPIUserAccessInput = PrepareRequestArgs<\"CREATE_API_USER_ACCESS\", DataAPIUserAccess>;\n\ntype CreateAccountInput = PrepareRequestArgs<\"CREATE_ACCOUNT\", DataAccount>;\ntype EditAccountInput = PrepareRequestArgs<\"EDIT_ACCOUNT\", DataAccount>;\n\ntype CreateVaultEntityInput = PrepareRequestArgs<\"CREATE_ENTITY\", DataVaultEntity>;\ntype EditVaultEntityInput = PrepareRequestArgs<\"EDIT_ENTITY\", DataVaultEntity>;\n\ntype CreateExchangeInput = PrepareRequestArgs<\"IMPORT_EXCHANGE\", DataExchange>;\n\ntype CreatePolicyInput = PrepareRequestArgs<\"CREATE_POLICY\", DataPolicy>;\n\ntype PrepareRequest<T, S> = (obj: T) => S;\n\ntype DataQuorum = {\n quorum: number;\n};\n\ntype EditQuorumInput = PrepareRequestArgs<\"UPDATE_QUORUM\", DataQuorum>;\ntype GateEditQuorumPayload = {\n type: \"UPDATE_QUORUM\";\n quorum: number;\n};\n\nexport type GateEditWorkspaceRulePayload = {\n type: \"EDIT_WORKSPACE_RULE\";\n permission: GateWorkspacePermission;\n edit_data: {\n steps: GateWorkspaceRuleStep[];\n };\n};\n\ntype PrepareEditQuorum = PrepareRequest<EditQuorumInput, GateEditQuorumPayload>;\n\ntype PrepareCreateUser = PrepareRequest<CreateUserInput, GateCreateUserPayload>;\ntype PrepareCreateAPIUser = PrepareRequest<CreateAPIUserInput, GateCreateAPIUserPayload>;\ntype PrepareCreateAPIV2UserAccess = PrepareRequest<\n CreateAPIUserAccessInput,\n GateCreateAPIV2UserAccessPayload\n>;\ntype PrepareEditGroup = PrepareRequest<EditGroupInput, GateEditGroupPayload>;\n\ntype PrepareCreateGroup = PrepareRequest<CreateGroupInput, GateCreateGroupPayload>;\n\ntype PrepareCreateAccount = PrepareRequest<CreateAccountInput, GateCreateAccountPayload>;\n\ntype PrepareEditAccount = PrepareRequest<EditAccountInput, GateEditAccountPayload>;\n\ntype PrepareCreateVaultEntity = PrepareRequest<\n CreateVaultEntityInput,\n GateCreateVaultEntityPayload\n>;\n\ntype PrepareEditVaultEntity = PrepareRequest<EditVaultEntityInput, GateEditVaultEntityPayload>;\n\ntype PrepareEditWhitelist = PrepareRequest<EditWhitelistInput, GateEditWhitelistPayload>;\n\ntype PrepareCreateWhitelist = PrepareRequest<CreateWhitelistInput, GateCreateWhitelistPayload>;\n\ntype PrepareCreateExchange = PrepareRequest<CreateExchangeInput, GateCreateExchangePayload>;\n\ntype PrepareCreatePolicy = PrepareRequest<CreatePolicyInput, GateCreatePolicyPayload>;\n\nexport const EMPTY_RULES_SETS: GateGovernanceRulesSet[] = [\n {\n name: \"Rule 1\",\n rules: [\n {\n type: \"MULTI_AUTHORIZATIONS\",\n data: [],\n },\n ],\n },\n];\n\nexport const prepareUserCreation: PrepareCreateUser = ({ data }) => {\n const { role, name, userID } = data;\n return {\n type: role === \"operator\" ? \"CREATE_OPERATOR\" : \"CREATE_ADMIN\",\n username: name,\n user_id: userID,\n };\n};\n\nexport const prepareAPIUserCreation: PrepareCreateAPIUser = ({ data }) => {\n const { publicKey, name, role } = data;\n return {\n type: \"CREATE_API_USER\",\n user_data: {\n username: name,\n public_key: publicKey,\n role,\n },\n };\n};\n\nexport const prepareAPIUserAccessCreation: PrepareCreateAPIV2UserAccess = ({ data }) => {\n const { name } = data;\n return {\n type: \"CREATE_API_USER_ACCESS\",\n user_data: {\n username: name,\n },\n };\n};\n\nexport const prepareAccountCreation: PrepareCreateAccount = ({ type, data }) => {\n const {\n account,\n usersByDevice,\n whitelistsIDsByName,\n groupsIDsByName,\n accountsByName,\n hsmCustodiansIDsByName,\n hsmAssetManagersIDsByName,\n hsmExchangesIDsByName,\n usersByName,\n tokens,\n } = data;\n\n const allAccounts = Object.keys(accountsByName).map((key) => accountsByName[key]);\n\n const token =\n \"contractAddress\" in account\n ? tokens.find((t) => t.contract_address === account.contractAddress)\n : null;\n\n if (\"contractAddress\" in account && !token) {\n throw new Error(`Can't find token with contract address ${account.contractAddress}`);\n }\n\n let account_type = null;\n if (token?.family === \"ethereum\") {\n if (token.parent_currency === \"bsc\") {\n account_type = \"Bep20\";\n } else {\n account_type = \"Erc20\";\n }\n } else if (\"accountType\" in account) {\n account_type = account.accountType;\n } else if (\"currency\" in account) {\n account_type = getAccountTypeByCurrency(account.currency);\n }\n\n if (!account_type) {\n throw new Error(`Can't determine account type`);\n }\n\n const unit = getAccountUnit(account, tokens);\n const governance_rules =\n \"tradelink_data\" in account && !!account.tradelink_data\n ? null\n : transformManifestRules({\n rules: account.rules,\n unit,\n usersByDevice,\n usersByName,\n whitelistsIDsByName,\n groupsIDsByName,\n // VG-18120 accounts *must* enforce having a tx-filter rule of type SEND for rules that are\n // not SCI and not \"any-other-type-of-filter\".\n enforceSendTxFilter: true,\n });\n\n const account_data = {\n name: account.name,\n ...(governance_rules ? { governance_rules } : {}),\n };\n\n if (\"readOnly\" in account && !!account.readOnly) {\n Object.assign(account_data, {\n xpub: account.readOnly.xpub,\n extended_public_key: {\n public_key: account.readOnly.publicKey,\n chain_code: account.readOnly.chainCode,\n },\n address: account.readOnly.address,\n });\n }\n\n if (\"contractAddress\" in account && token) {\n const currencyName = token.parent_currency;\n const parentAccountName = account.parentAccount;\n\n // FIXME there is something weird in this code\n const parent_account = parentAccountName\n ? (() => {\n let parentAccountID = null;\n // FIXME why not using accountsByName\n // search in existing accounts\n const existingParentAccount = allAccounts.find(\n (a) => !!a && a.name === parentAccountName,\n );\n if (existingParentAccount) {\n parentAccountID = existingParentAccount.id;\n } else {\n const createdParentAccount = accountsByName[parentAccountName];\n if (!createdParentAccount) {\n return { name: parentAccountName };\n }\n parentAccountID = createdParentAccount.id;\n }\n return { id: parentAccountID };\n })()\n : null;\n\n // see VFE-951\n if (process.env.LEGACY_TOKENS) {\n const erc20 = {\n ticker: token.ticker,\n address: token.contract_address,\n decimals: token.units[0].magnitude,\n hsm_account_parameters: token.__legacy_hsm_account_parameters,\n hsm_signature: token.__legacy_hsm_signature,\n };\n Object.assign(account_data, { erc20 });\n } else {\n Object.assign(account_data, {\n token: { type: token.token_type, address: token.contract_address },\n });\n }\n\n Object.assign(account_data, {\n currency: { name: currencyName },\n parent_account,\n });\n }\n\n if (\"currency\" in account) {\n Object.assign(account_data, {\n currency: {\n name: account.currency,\n },\n });\n\n if (\"derivationMode\" in account) {\n Object.assign(account_data, {\n derivation_mode: account.derivationMode,\n });\n }\n }\n\n let tradelinkData;\n if (\"tradelink_data\" in account && !!account.tradelink_data) {\n const custodianID = hsmCustodiansIDsByName[account.tradelink_data.custodian.name];\n /* istanbul ignore if */\n if (typeof custodianID === \"undefined\")\n throw new Error(`Invalid custodian name ${account.tradelink_data.custodian.name}`);\n\n const assetManagerID = hsmAssetManagersIDsByName[account.tradelink_data.asset_manager.name];\n /* istanbul ignore if */\n if (typeof assetManagerID === \"undefined\")\n throw new Error(`Invalid asset manager name ${account.tradelink_data.asset_manager.name}`);\n\n tradelinkData = {\n currency: account.tradelink_data.currency,\n custodian: custodianID,\n asset_manager: assetManagerID,\n exchanges: account.tradelink_data.exchanges.map((exchange) => {\n const exchangeID = hsmExchangesIDsByName[exchange.name];\n /* istanbul ignore if */\n if (typeof exchangeID === \"undefined\")\n throw new Error(`Invalid exchange name ${exchange.name}`);\n return {\n auto_repledge_enabled: exchange.auto_repledge_enabled,\n requires_pre_approval: exchange.requires_pre_approval,\n id: exchangeID,\n };\n }),\n };\n }\n\n return {\n type,\n ...(account.index !== undefined ? { index: account.index } : {}),\n ...(tradelinkData ? { tradelink_data: tradelinkData } : {}),\n account_type,\n account_data,\n };\n};\n\nconst prepareAccountEdition: PrepareEditAccount = ({ type, data }) => {\n const {\n account,\n existingAccount,\n usersByDevice,\n usersByName,\n whitelistsIDsByName,\n groupsIDsByName,\n tokens,\n } = data;\n\n /* istanbul ignore if */\n if (!existingAccount) {\n throw new Error(\"No existingAccount given\");\n }\n\n const unit = getAccountUnit(account, tokens);\n const governance_rules = transformManifestRules({\n rules: account.rules,\n unit,\n usersByDevice,\n usersByName,\n whitelistsIDsByName,\n groupsIDsByName,\n enforceSendTxFilter: true,\n });\n\n const edit_data = {\n name: account.name,\n governance_rules,\n };\n\n if (\"contractAddress\" in account) {\n const token = tokens.find((t) => t.contract_address === account.contractAddress);\n\n /* istanbul ignore if */\n if (!token) {\n throw new Error(`Can't find token with contract address ${account.contractAddress}`);\n }\n\n // see VFE-951\n if (process.env.LEGACY_TOKENS) {\n const erc20 = {\n ticker: token.ticker,\n address: token.contract_address,\n decimals: token.units[0].magnitude,\n hsm_account_parameters: token.__legacy_hsm_account_parameters,\n hsm_signature: token.__legacy_hsm_signature,\n };\n Object.assign(edit_data, { erc20 });\n } else {\n Object.assign(edit_data, {\n token: { type: \"erc20\", address: token.contract_address },\n });\n }\n }\n\n return {\n type,\n account_id: existingAccount.id,\n edit_data,\n };\n};\n\nconst serializeGroupMembers = (\n groupUsers: Array<string | number>,\n { usersByDevice, usersByName }: { usersByDevice: UsersByDevice; usersByName: UsersByName },\n): number[] => {\n return groupUsers.map((device) => {\n if (typeof device === \"number\") {\n const u = usersByDevice[device];\n /* istanbul ignore if */\n if (!u) throw new Error(`Invalid device ${device}`);\n return u.id;\n } else {\n const u = usersByName[device];\n /* istanbul ignore if */\n if (!u) throw new Error(`Invalid user name ${device}`);\n return u.id;\n }\n });\n};\n\nconst prepareGroupCreation: PrepareCreateGroup = ({ type, data }) => {\n const { group } = data;\n const members = serializeGroupMembers(group.users, data);\n return {\n type,\n name: group.name,\n description: group.description || \"\",\n members,\n };\n};\n\nconst prepareGroupEdition: PrepareEditGroup = ({ type, data }) => {\n const { group, existingGroup } = data;\n /* istanbul ignore if */\n if (!existingGroup) {\n throw new Error(\"No existingGroup given\");\n }\n const members = serializeGroupMembers(group.users, data);\n return {\n type,\n name: group.name,\n description: group.description || \"\",\n group_id: existingGroup.id,\n edit_data: {\n name: group.name,\n members,\n },\n };\n};\n\nconst serializeVaultEntityAccounts = (\n vaultEntityAccounts: string[],\n { accountsByName }: { accountsByName: AccountsByName },\n): number[] => {\n return vaultEntityAccounts.map((accountName) => {\n const a = accountsByName[accountName];\n /* istanbul ignore if */\n if (!a) throw new Error(`Invalid account ${accountName}`);\n return a.id;\n });\n};\n\nconst prepareVaultEntityCreation: PrepareCreateVaultEntity = ({ type, data }) => {\n const {\n vaultEntity: { name, accounts },\n } = data;\n return {\n type,\n name,\n accounts: accounts ? serializeVaultEntityAccounts(accounts, data) : [],\n };\n};\n\nconst prepareVaultEntityEdition: PrepareEditVaultEntity = ({ type, data }) => {\n const { vaultEntity, existingVaultEntity } = data;\n /* istanbul ignore if */\n if (!existingVaultEntity) {\n throw new Error(\"No existing VaultEntity given\");\n }\n return {\n type,\n entity_id: existingVaultEntity.id,\n edit_data: {\n name: vaultEntity.name,\n accounts: vaultEntity.accounts\n ? serializeVaultEntityAccounts(vaultEntity.accounts, data)\n : [],\n },\n };\n};\n\nconst prepareWhitelistCreation: PrepareCreateWhitelist = ({ type, data }) => {\n const { whitelist } = data;\n const addresses = whitelist.addresses.map((a, i) => ({\n ...a,\n name: a.name || `${a.currency}-${i + 1}`,\n }));\n return {\n type,\n name: whitelist.name,\n description: whitelist.description || \"\",\n addresses,\n ...(whitelist.type && { whitelist_type: whitelist.type }),\n };\n};\n\nconst prepareWhitelistEdition: PrepareEditWhitelist = ({ type, data }) => {\n const { whitelist, existingWhitelist } = data;\n /* istanbul ignore if */\n if (!existingWhitelist) {\n throw new Error(`No existingWhitelist given`);\n }\n const addresses = whitelist.addresses.map((a, i) => ({\n ...a,\n name: a.name || `${a.currency}-${i + 1}`,\n }));\n return {\n type,\n name: whitelist.name,\n description: \"\",\n whitelist_id: existingWhitelist.id,\n edit_data: {\n name: whitelist.name,\n addresses,\n },\n };\n};\n\nconst prepareExchangeCreation: PrepareCreateExchange = ({ type, data }) => {\n const { exchange, usersByDevice, usersByName, groupsIDsByName } = data;\n const governance_rules = exchange.rules\n ? transformManifestRules({ rules: exchange.rules, usersByDevice, usersByName, groupsIDsByName })\n : [];\n return {\n type,\n exchange_data: {\n name: exchange.name,\n governance_rules,\n platform: exchange.platform,\n credentials: {\n apiKey: exchange.configuration.apiKey,\n secret: exchange.configuration.apiSecret,\n },\n },\n };\n};\n\nconst preparePolicyCreation: PrepareCreatePolicy = ({ type, data }) => {\n const { policy, usersByName, usersByDevice, groupsIDsByName, whitelistsIDsByName } = data;\n\n const unit = getCurrencyUnit(data.policy.currency);\n const governance_rules = transformManifestRules({\n rules: policy.rules,\n unit,\n usersByDevice,\n usersByName,\n groupsIDsByName,\n whitelistsIDsByName,\n });\n\n return {\n type,\n policy_data: {\n name: policy.name,\n governance_rules,\n currency: {\n name: policy.currency,\n },\n },\n };\n};\n\nconst prepareQuorumEdition: PrepareEditQuorum = ({ data }) => {\n return {\n type: \"UPDATE_QUORUM\",\n quorum: data.quorum,\n };\n};\n\nexport type Input =\n | EditQuorumInput\n | CreateAPIUserInput\n | CreateUserInput\n | CreateAPIUserAccessInput\n | CreateGroupInput\n | EditGroupInput\n | CreateWhitelistInput\n | EditWhitelistInput\n | CreateExchangeInput\n | CreatePolicyInput\n | CreateAccountInput\n | EditAccountInput\n | CreateVaultEntityInput\n | EditVaultEntityInput;\n\nexport type Output =\n | GateEditQuorumPayload\n | GateEditWorkspaceRulePayload\n | GateCreateAPIUserPayload\n | GateCreateAPIV2UserAccessPayload\n | GateCreateUserPayload\n | GateMigrateUserPayload\n | GateCreateGroupPayload\n | GateMigrateGroupPayload\n | GateEditGroupPayload\n | GateEditWhitelistPayload\n | GateCreateWhitelistPayload\n | GateMigrateWhitelistPayload\n | GateCreateExchangePayload\n | GateCreatePolicyPayload\n | GateCreateAccountPayload\n | GateCreateLamUserPayload\n | GateEditAccountPayload\n | GateMigrateAccountPayload\n | GateCreateVaultEntityPayload\n | GateEditVaultEntityPayload;\n\nconst prepareRequest = (data: Input): Output => {\n if (data.type === \"EDIT_GROUP\") {\n return prepareGroupEdition(data);\n }\n\n if (data.type === \"CREATE_GROUP\") {\n return prepareGroupCreation(data);\n }\n if (data.type === \"EDIT_WHITELIST\") {\n return prepareWhitelistEdition(data);\n }\n if (data.type === \"CREATE_WHITELIST\") {\n return prepareWhitelistCreation(data);\n }\n if (data.type === \"CREATE_ACCOUNT\") {\n return prepareAccountCreation(data);\n }\n if (data.type === \"EDIT_ACCOUNT\") {\n return prepareAccountEdition(data);\n }\n if (data.type === \"CREATE_ENTITY\") {\n return prepareVaultEntityCreation(data);\n }\n if (data.type === \"EDIT_ENTITY\") {\n return prepareVaultEntityEdition(data);\n }\n if (data.type === \"CREATE_ADMIN\" || data.type === \"CREATE_OPERATOR\") {\n return prepareUserCreation(data);\n }\n if (data.type === \"CREATE_API_USER\") {\n return prepareAPIUserCreation(data);\n }\n\n if (data.type === \"CREATE_API_USER_ACCESS\") {\n return prepareAPIUserAccessCreation(data);\n }\n\n if (data.type === \"UPDATE_QUORUM\") {\n return prepareQuorumEdition(data);\n }\n if (data.type === \"IMPORT_EXCHANGE\") {\n return prepareExchangeCreation(data);\n }\n if (data.type === \"CREATE_POLICY\") {\n return preparePolicyCreation(data);\n }\n\n // @ts-ignore\n throw new Error(`Unhandled request type ${data.type}`);\n};\n\nconst getGroupID = (groupsIDsByName: IDByName, groupName: string) => {\n const groupID = groupsIDsByName[groupName];\n /* istanbul ignore if */\n if (typeof groupID === \"undefined\") throw new Error(`Invalid group name ${groupName}`);\n return groupID;\n};\n\nconst transformMultiAuthRuleFromManifest = (\n rule: ManifestAccountRuleMultiAuth,\n groupsIDsByName: IDByName,\n usersByDevice: UsersByDevice,\n usersByName: UsersByName,\n): WeirdGateRuleMultiAuth => {\n return {\n type: rule.type,\n data: rule.steps.map((step) => {\n return {\n quorum: step.quorum,\n ...(\"group\" in step\n ? { group_id: getGroupID(groupsIDsByName, step.group) }\n : {\n users: step.users.map((d) => {\n if (typeof d === \"number\") {\n const user = usersByDevice[d];\n /* istanbul ignore if */\n if (!user) throw new Error(`Invalid device ${d}`);\n return user.id;\n }\n const user = usersByName[d];\n /* istanbul ignore if */\n if (!user) throw new Error(`Invalid name ${d}`);\n return user.id;\n }),\n }),\n };\n }),\n };\n};\n\nconst transformWhitelistRuleFromManifest = (\n rule: ManifestAccountRuleWhitelist,\n whitelistsIDsByName: Record<string, number>,\n): WeirdGateRuleWhitelist => {\n return {\n type: rule.type,\n data: rule.whitelists.map((w) => {\n const whitelistID = whitelistsIDsByName[w];\n /* istanbul ignore if */\n if (typeof whitelistID === \"undefined\") throw new Error(`Invalid whitelist name ${w}`);\n return whitelistID;\n }),\n };\n};\n\nexport const transformSCIRuleFromManifest = (rule: ManifestAccountRuleSCI): GateRuleSCI => {\n return {\n type: rule.type,\n data: [\n {\n enabled: rule.enabled,\n },\n ],\n };\n};\n\nexport const transformTezosDelegationRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"TEZOS_DELEGATION\" } };\n};\n\nexport const transformPolkadotStakingRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"POLKADOT_STAKING\" } };\n};\n\nexport const transformSolanaStakingRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"SOLANA_STAKING\" } };\n};\nexport const transformMessageSigningRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"MESSAGE_SIGNING\" } };\n};\nexport const transformCreateSplTokenAccountRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"CREATE_SPL_TOKEN_ACCOUNT\" } };\n};\n\nexport const transformCardanoStakingRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"CARDANO_STAKING\" } };\n};\n\nexport const transformRawTransactionRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"RAW_SIGNING\" } };\n};\n\nexport const transformSendTransactionRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"SEND\" } };\n};\n\nexport const transformSmartContractDeploymentFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"DEPLOY_CONTRACT\" } };\n};\n\nexport const transformStakeTransactionRuleFromManifest = (): GateRuleTransactionFilter => {\n return { type: \"TRANSACTION_FILTER\", data: { preset: \"STAKE\" } };\n};\n\nexport const transformThresholdRuleFromManifest = (\n rule: ManifestAccountRuleThreshold,\n unit: Unit,\n): WeirdGateRuleThreshold => {\n return {\n type: rule.type,\n data: [\n {\n currency_type: \"CRYPTO\",\n ...(rule.max ? { max: serializeUnitValue(unit, rule.max) } : {}),\n min: serializeUnitValue(unit, rule.min || 0),\n },\n ],\n };\n};\n\nexport const transformManifestRules = ({\n rules,\n unit,\n usersByDevice,\n usersByName,\n whitelistsIDsByName,\n groupsIDsByName,\n enforceSendTxFilter,\n}: {\n rules: Array<ManifestAccountRule[]> | void;\n unit?: Unit;\n usersByDevice: UsersByDevice;\n usersByName: UsersByName;\n whitelistsIDsByName?: IDByName;\n groupsIDsByName: IDByName;\n // VG-18120 ability to enforce `SEND` transaction filter if no transaction filter is present\n enforceSendTxFilter?: boolean;\n}): WeirdGateGovernanceRulesSet[] => {\n const governance_rules =\n rules && rules.length\n ? rules.map((rules, i) => {\n return {\n name: `Rule ${i + 1}`,\n rules: rules.map((rule) => {\n if (rule.type === \"MULTI_AUTHORIZATIONS\") {\n return transformMultiAuthRuleFromManifest(\n rule,\n groupsIDsByName,\n usersByDevice,\n usersByName,\n );\n }\n if (rule.type === \"WHITELIST\") {\n invariant(\n whitelistsIDsByName,\n \"WHITELIST rule configured outside of account context\",\n );\n return transformWhitelistRuleFromManifest(rule, whitelistsIDsByName);\n }\n if (rule.type === \"THRESHOLD\") {\n invariant(unit, \"THRESHOLD: no unit provided\");\n\n return transformThresholdRuleFromManifest(rule, unit);\n }\n if (rule.type === \"SMART_CONTRACT_INTERACTION\") {\n return transformSCIRuleFromManifest(rule);\n }\n\n if (rule.type === \"DEPLOY_CONTRACT\") {\n return transformSmartContractDeploymentFromManifest();\n }\n\n if (rule.type === \"TEZOS_DELEGATION\") {\n return transformTezosDelegationRuleFromManifest();\n }\n if (rule.type === \"POLKADOT_STAKING\") {\n return transformPolkadotStakingRuleFromManifest();\n }\n if (rule.type === \"SOLANA_STAKING\") {\n return transformSolanaStakingRuleFromManifest();\n }\n if (rule.type === \"CARDANO_STAKING\") {\n return transformCardanoStakingRuleFromManifest();\n }\n if (rule.type === \"RAW_SIGNING\") {\n return transformRawTransactionRuleFromManifest();\n }\n if (rule.type === \"SEND\") {\n return transformSendTransactionRuleFromManifest();\n }\n if (rule.type === \"STAKE\") {\n return transformStakeTransactionRuleFromManifest();\n }\n if (rule.type === \"MESSAGE_SIGNING\") {\n return transformMessageSigningRuleFromManifest();\n }\n if (rule.type === \"CREATE_SPL_TOKEN_ACCOUNT\") {\n return transformCreateSplTokenAccountRuleFromManifest();\n }\n // @ts-ignore\n throw new Error(`Unhandled rule type ${rule.type}`);\n }),\n };\n })\n : getDefaultRule(usersByDevice);\n\n // VG-18120 ability to enforce `SEND` transaction filter if no transaction filter is present\n if (enforceSendTxFilter) {\n governance_rules.forEach((rulesSet) => {\n const hasTxFilterRule = !!rulesSet.rules.find((r) => r.type === \"TRANSACTION_FILTER\");\n const hasSCIRule = !!rulesSet.rules.find((r) => r.type === \"SMART_CONTRACT_INTERACTION\");\n if (!hasTxFilterRule && !hasSCIRule) {\n rulesSet.rules.unshift({ type: \"TRANSACTION_FILTER\", data: { preset: \"SEND\" } });\n }\n });\n }\n\n return governance_rules;\n};\n\nconst getDefaultRule = (usersByDevice: Record<string, GateUser>): WeirdGateGovernanceRulesSet[] => {\n const operatorsDevices = Object.keys(usersByDevice).filter((key) => {\n const u = usersByDevice[key];\n /* istanbul ignore if */\n if (!u) throw new Error(`Invalid device ${key}`);\n return u.role === \"OPERATOR\";\n });\n const lastCreatedOperatorDevice = operatorsDevices[0];\n /* istanbul ignore if */\n if (!lastCreatedOperatorDevice) {\n throw new Error(`Can't get the last created operator device`);\n }\n const lastCreatedOperator = usersByDevice[lastCreatedOperatorDevice];\n /* istanbul ignore if */\n if (!lastCreatedOperator) {\n throw new Error(`Can't get the last created operator`);\n }\n\n return [\n {\n name: \"Rule 1\",\n rules: [\n {\n type: \"MULTI_AUTHORIZATIONS\",\n data: [\n {\n quorum: 1,\n users: [lastCreatedOperator.id],\n },\n ],\n },\n ],\n },\n ];\n};\n\nexport const serializeToWeirdGateRulesSets = (\n rulesSets: GateGovernanceRulesSet[],\n): WeirdGateGovernanceRulesSet[] => {\n return rulesSets.map((rulesSet: GateGovernanceRulesSet): WeirdGateGovernanceRulesSet => {\n return {\n name: rulesSet.name,\n rules: rulesSet.rules.map((rule: GateGovernanceRule): WeirdGateGovernanceRule => {\n if (rule.type === \"MULTI_AUTHORIZATIONS\") {\n return {\n type: rule.type,\n data: rule.data.map((step: GateRuleMultiAuthStep): WeirdGateRuleMultiAuthStep => {\n if (step.group.is_internal) {\n return {\n quorum: step.quorum,\n users: step.group.members.map((member) => member.id),\n };\n }\n return {\n quorum: step.quorum,\n group_id: step.group.id,\n };\n }),\n };\n }\n if (rule.type === \"THRESHOLD\") {\n return {\n type: rule.type,\n data: [\n {\n currency_type: \"CRYPTO\",\n min: rule.data[0].min,\n ...(rule.data[0].max ? /* istanbul ignore next */ { max: rule.data[0].max } : {}),\n },\n ],\n };\n }\n if (rule.type === \"WHITELIST\") {\n return {\n type: rule.type,\n data: rule.data.map((whitelist) => whitelist.id),\n };\n }\n /* istanbul ignore next */\n return rule;\n }),\n };\n });\n};\n\nconst TWO_STEPS_CREATION_REQUESTS: GateRequestType[] = [\n \"CREATE_ACCOUNT\",\n \"CREATE_GROUP\",\n \"CREATE_TRANSACTION\",\n \"CREATE_WHITELIST\",\n \"EDIT_ACCOUNT\",\n \"EDIT_GROUP\",\n \"EDIT_WHITELIST\",\n \"REVOKE_USER\",\n \"UPDATE_QUORUM\",\n];\n\nexport const performRequest = async <T>(\n payload: Output,\n pool: DevicesPool,\n options?: {\n existingRequest?: GateGenericRequest | null;\n noApproval?: boolean;\n withoutHSM?: boolean;\n twoStepsRequest?: boolean;\n },\n): Promise<T> => {\n const adminDevices = await pool.getOnboardingAdminDevices();\n const admin = await pool.login(adminDevices[0]![1]);\n\n let request: GateGenericRequest | void | null = options?.existingRequest;\n\n if (!request) {\n const enableTwoStepsCreation =\n options?.twoStepsRequest && TWO_STEPS_CREATION_REQUESTS.includes(payload.type);\n\n if (enableTwoStepsCreation) {\n Object.assign(payload, { enable_two_step_request_creation: true });\n }\n\n const r = await admin.post<GateGenericRequest>(\"/requests\", payload);\n request = r;\n\n if (enableTwoStepsCreation) {\n const pingChallenge = async () => {\n try {\n await admin.post(`/requests/${r.id}/post-create`, {});\n } catch (err) /* istanbul ignore next */ {\n await pingChallenge();\n }\n };\n await pingChallenge();\n }\n }\n\n if (!options || !options.noApproval) {\n await pool.runWithQuorum((admin) =>\n options?.withoutHSM ? admin.approveRequestWithoutHSM(request) : admin.approveRequest(request),\n );\n }\n return request as unknown as T;\n};\n\nexport default prepareRequest;\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAAA,SAAS,iBAAAA,sBAAqB;;;ACC9B,OAAO,WAAW;;;ACDlB,SAAS,qBAAqB;AAC9B,OAAOC,gBAAe;AACtB,SAAS,MAAM,cAAc;;;ACF7B,OAAO,eAAe;AA8Xf,IAAM,sBAAyC,CAAC,EAAE,KAAK,MAAM;AAClE,QAAM,EAAE,MAAM,MAAM,OAAO,IAAI;AAC/B,SAAO;AAAA,IACL,MAAM,SAAS,aAAa,oBAAoB;AAAA,IAChD,UAAU;AAAA,IACV,SAAS;AAAA,EACX;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WAAW,SAAS,MAAM;AAEnF,MAAI,eAAe;AAAA,IACjB,WAAW;AAAA,IACX,kBAAkB;AAAA,EACpB;AAEA,MAAI,wBAAwB,OAAO;AACjC,WAAO,KAAK,kBAAkB;AAC9B,mBAAe,MAAM,gBAAgB;AAAA,MACnC;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF,CAAC;AAAA,EACH;AAEA,SAAO,KAAK,aAAa,gBAAgB;AACzC,SAAO,KAAK,kBAAkB;AAE9B,SAAO,eAAe;AAAA,IACpB;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA,WAAW,aAAa;AAAA,IACxB;AAAA,EACF,CAAC;AACH;AAEA,IAAO,2BAAQ;","names":["SILENT_LOGGER","invariant","user","rules","admin","options","invariant","account","admin","SILENT_LOGGER"]}
|
package/lib/chunk-HU7O2ZFW.mjs
DELETED
|
@@ -1,249 +0,0 @@
|
|
|
1
|
-
// src/crypto/utils.ts
|
|
2
|
-
import crypto from "crypto";
|
|
3
|
-
import * as elliptic from "elliptic";
|
|
4
|
-
import * as jwt from "jsonwebtoken";
|
|
5
|
-
|
|
6
|
-
// src/crypto/keyEncoder.ts
|
|
7
|
-
import * as asn1 from "asn1.js";
|
|
8
|
-
import BN from "bn.js";
|
|
9
|
-
import { ec as EC } from "elliptic";
|
|
10
|
-
var ECPrivateKeyASN = asn1.define("ECPrivateKey", function() {
|
|
11
|
-
const self = this;
|
|
12
|
-
self.seq().obj(
|
|
13
|
-
self.key("version").int(),
|
|
14
|
-
self.key("privateKey").octstr(),
|
|
15
|
-
self.key("parameters").explicit(0).objid().optional(),
|
|
16
|
-
self.key("publicKey").explicit(1).bitstr().optional()
|
|
17
|
-
);
|
|
18
|
-
});
|
|
19
|
-
var ECPrivateKey8ASN = asn1.define(
|
|
20
|
-
"ECPrivateKey",
|
|
21
|
-
/* istanbul ignore next */
|
|
22
|
-
function() {
|
|
23
|
-
const self = this;
|
|
24
|
-
self.seq().obj(
|
|
25
|
-
self.key("version").int(),
|
|
26
|
-
self.key("privateKeyAlgorithm").seq().obj(self.key("ecPublicKey").objid(), self.key("curve").objid()),
|
|
27
|
-
self.key("privateKey").octstr().contains(ECPrivateKeyASN),
|
|
28
|
-
self.key("attributes").explicit(0).bitstr().optional()
|
|
29
|
-
);
|
|
30
|
-
}
|
|
31
|
-
);
|
|
32
|
-
var SubjectPublicKeyInfoASN = asn1.define("SubjectPublicKeyInfo", function() {
|
|
33
|
-
const self = this;
|
|
34
|
-
self.seq().obj(
|
|
35
|
-
self.key("algorithm").seq().obj(self.key("id").objid(), self.key("curve").objid()),
|
|
36
|
-
self.key("pub").bitstr()
|
|
37
|
-
);
|
|
38
|
-
});
|
|
39
|
-
var curves = {
|
|
40
|
-
secp256k1: {
|
|
41
|
-
curveParameters: [1, 3, 132, 0, 10],
|
|
42
|
-
privatePEMOptions: { label: "EC PRIVATE KEY" },
|
|
43
|
-
publicPEMOptions: { label: "PUBLIC KEY" },
|
|
44
|
-
curve: new EC("secp256k1")
|
|
45
|
-
},
|
|
46
|
-
p256: {
|
|
47
|
-
curveParameters: [1, 2, 840, 10045, 3, 1, 7],
|
|
48
|
-
// OID for p256 curve
|
|
49
|
-
privatePEMOptions: { label: "EC PRIVATE KEY" },
|
|
50
|
-
publicPEMOptions: { label: "PUBLIC KEY" },
|
|
51
|
-
curve: new EC("p256")
|
|
52
|
-
}
|
|
53
|
-
};
|
|
54
|
-
var KeyEncoder = class {
|
|
55
|
-
algorithmID;
|
|
56
|
-
options;
|
|
57
|
-
constructor(options) {
|
|
58
|
-
if (typeof options === "string") {
|
|
59
|
-
if (options !== "secp256k1" && options !== "p256") {
|
|
60
|
-
throw new Error("Unknown curve " + options);
|
|
61
|
-
}
|
|
62
|
-
options = curves[options];
|
|
63
|
-
}
|
|
64
|
-
this.options = options;
|
|
65
|
-
this.algorithmID = [1, 2, 840, 10045, 2, 1];
|
|
66
|
-
}
|
|
67
|
-
/* istanbul ignore next */
|
|
68
|
-
PKCS1toPKCS8(privateKey) {
|
|
69
|
-
return {
|
|
70
|
-
version: new BN(0),
|
|
71
|
-
privateKey,
|
|
72
|
-
privateKeyAlgorithm: {
|
|
73
|
-
ecPublicKey: this.algorithmID,
|
|
74
|
-
curve: privateKey.parameters
|
|
75
|
-
}
|
|
76
|
-
};
|
|
77
|
-
}
|
|
78
|
-
privateKeyObject(rawPrivateKey, rawPublicKey) {
|
|
79
|
-
const privateKeyObject = {
|
|
80
|
-
version: new BN(1),
|
|
81
|
-
privateKey: Buffer.from(rawPrivateKey, "hex"),
|
|
82
|
-
parameters: this.options.curveParameters
|
|
83
|
-
};
|
|
84
|
-
if (rawPublicKey) {
|
|
85
|
-
privateKeyObject.publicKey = {
|
|
86
|
-
unused: 0,
|
|
87
|
-
data: Buffer.from(rawPublicKey, "hex")
|
|
88
|
-
};
|
|
89
|
-
}
|
|
90
|
-
return privateKeyObject;
|
|
91
|
-
}
|
|
92
|
-
publicKeyObject(rawPublicKey) {
|
|
93
|
-
return {
|
|
94
|
-
algorithm: {
|
|
95
|
-
id: this.algorithmID,
|
|
96
|
-
curve: this.options.curveParameters
|
|
97
|
-
},
|
|
98
|
-
pub: {
|
|
99
|
-
unused: 0,
|
|
100
|
-
data: Buffer.from(rawPublicKey, "hex")
|
|
101
|
-
}
|
|
102
|
-
};
|
|
103
|
-
}
|
|
104
|
-
/* istanbul ignore next */
|
|
105
|
-
encodePrivate(privateKey, originalFormat, destinationFormat, destinationFormatType = "pkcs1") {
|
|
106
|
-
let privateKeyObject;
|
|
107
|
-
if (originalFormat === "raw") {
|
|
108
|
-
if (typeof privateKey !== "string") {
|
|
109
|
-
throw "private key must be a string";
|
|
110
|
-
}
|
|
111
|
-
const keyPair = this.options.curve.keyFromPrivate(privateKey, "hex");
|
|
112
|
-
const rawPublicKey = keyPair.getPublic("hex");
|
|
113
|
-
privateKeyObject = this.privateKeyObject(privateKey, rawPublicKey);
|
|
114
|
-
} else if (originalFormat === "der") {
|
|
115
|
-
if (typeof privateKey !== "string") {
|
|
116
|
-
} else if (typeof privateKey === "string") {
|
|
117
|
-
privateKey = Buffer.from(privateKey, "hex");
|
|
118
|
-
} else {
|
|
119
|
-
throw "private key must be a buffer or a string";
|
|
120
|
-
}
|
|
121
|
-
privateKeyObject = ECPrivateKeyASN.decode(privateKey, "der");
|
|
122
|
-
} else if (originalFormat === "pem") {
|
|
123
|
-
if (typeof privateKey !== "string") {
|
|
124
|
-
throw "private key must be a string";
|
|
125
|
-
}
|
|
126
|
-
privateKeyObject = ECPrivateKeyASN.decode(privateKey, "pem", this.options.privatePEMOptions);
|
|
127
|
-
} else {
|
|
128
|
-
throw "invalid private key format";
|
|
129
|
-
}
|
|
130
|
-
if (destinationFormat === "raw") {
|
|
131
|
-
return privateKeyObject.privateKey.toString("hex");
|
|
132
|
-
} else if (destinationFormat === "der") {
|
|
133
|
-
return ECPrivateKeyASN.encode(privateKeyObject, "der").toString("hex");
|
|
134
|
-
} else if (destinationFormat === "pem") {
|
|
135
|
-
return destinationFormatType === "pkcs1" ? ECPrivateKeyASN.encode(privateKeyObject, "pem", this.options.privatePEMOptions) : ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), "pem", {
|
|
136
|
-
...this.options.privatePEMOptions,
|
|
137
|
-
label: "PRIVATE KEY"
|
|
138
|
-
});
|
|
139
|
-
} else {
|
|
140
|
-
throw "invalid destination format for private key";
|
|
141
|
-
}
|
|
142
|
-
}
|
|
143
|
-
/* istanbul ignore next */
|
|
144
|
-
encodePublic(publicKey, originalFormat, destinationFormat) {
|
|
145
|
-
let publicKeyObject;
|
|
146
|
-
if (originalFormat === "raw") {
|
|
147
|
-
if (typeof publicKey !== "string") {
|
|
148
|
-
throw "public key must be a string";
|
|
149
|
-
}
|
|
150
|
-
publicKeyObject = this.publicKeyObject(publicKey);
|
|
151
|
-
} else if (originalFormat === "der") {
|
|
152
|
-
if (typeof publicKey !== "string") {
|
|
153
|
-
} else if (typeof publicKey === "string") {
|
|
154
|
-
publicKey = Buffer.from(publicKey, "hex");
|
|
155
|
-
} else {
|
|
156
|
-
throw "public key must be a buffer or a string";
|
|
157
|
-
}
|
|
158
|
-
publicKeyObject = SubjectPublicKeyInfoASN.decode(publicKey, "der");
|
|
159
|
-
} else if (originalFormat === "pem") {
|
|
160
|
-
if (typeof publicKey !== "string") {
|
|
161
|
-
throw "public key must be a string";
|
|
162
|
-
}
|
|
163
|
-
publicKeyObject = SubjectPublicKeyInfoASN.decode(
|
|
164
|
-
publicKey,
|
|
165
|
-
"pem",
|
|
166
|
-
this.options.publicPEMOptions
|
|
167
|
-
);
|
|
168
|
-
} else {
|
|
169
|
-
throw "invalid public key format";
|
|
170
|
-
}
|
|
171
|
-
if (destinationFormat === "raw") {
|
|
172
|
-
return publicKeyObject.pub.data.toString("hex");
|
|
173
|
-
} else if (destinationFormat === "der") {
|
|
174
|
-
return SubjectPublicKeyInfoASN.encode(publicKeyObject, "der").toString("hex");
|
|
175
|
-
} else if (destinationFormat === "pem") {
|
|
176
|
-
return SubjectPublicKeyInfoASN.encode(publicKeyObject, "pem", this.options.publicPEMOptions);
|
|
177
|
-
} else {
|
|
178
|
-
throw "invalid destination format for public key";
|
|
179
|
-
}
|
|
180
|
-
}
|
|
181
|
-
};
|
|
182
|
-
|
|
183
|
-
// src/crypto/utils.ts
|
|
184
|
-
function extractPublicKey(pemKey) {
|
|
185
|
-
const pem = pemKey.split("\n");
|
|
186
|
-
pem.shift();
|
|
187
|
-
pem.pop();
|
|
188
|
-
const keyBuffer = Buffer.from(pem.join(""), "base64");
|
|
189
|
-
const actualKeyBuffer = keyBuffer.slice(26);
|
|
190
|
-
return actualKeyBuffer.toString("hex");
|
|
191
|
-
}
|
|
192
|
-
function decodeData(challenge) {
|
|
193
|
-
const decodedString = atob(challenge);
|
|
194
|
-
return JSON.parse(decodedString);
|
|
195
|
-
}
|
|
196
|
-
function sign2(privateKey, challenge) {
|
|
197
|
-
const pKey = crypto.createPrivateKey({
|
|
198
|
-
key: String(privateKey),
|
|
199
|
-
format: "pem"
|
|
200
|
-
});
|
|
201
|
-
const privateKeyPem = pKey.export({ format: "pem", type: "sec1" });
|
|
202
|
-
const dataToSign = Buffer.from(challenge, "base64").toString("hex");
|
|
203
|
-
return jwt.sign(Buffer.from(dataToSign, "hex"), privateKeyPem, {
|
|
204
|
-
algorithm: "ES256",
|
|
205
|
-
header: {
|
|
206
|
-
alg: "ES256",
|
|
207
|
-
typ: "JWT"
|
|
208
|
-
}
|
|
209
|
-
});
|
|
210
|
-
}
|
|
211
|
-
function genKeys(entropy) {
|
|
212
|
-
if (entropy) {
|
|
213
|
-
const ec2 = new elliptic.ec("p256");
|
|
214
|
-
const hashedEntropy = crypto.createHash("sha256").update(entropy).digest("hex");
|
|
215
|
-
const keyPair = ec2.genKeyPair({
|
|
216
|
-
entropy: Buffer.from(hashedEntropy, "hex")
|
|
217
|
-
});
|
|
218
|
-
return {
|
|
219
|
-
privateKey: String(hexToPem(keyPair.getPrivate("hex"))),
|
|
220
|
-
publicKey: String(hexToPem(keyPair.getPublic("hex"), { isPrivate: false })),
|
|
221
|
-
hexPubKey: extractPublicKey(String(hexToPem(keyPair.getPublic("hex"), { isPrivate: false })))
|
|
222
|
-
};
|
|
223
|
-
}
|
|
224
|
-
const { publicKey, privateKey } = crypto.generateKeyPairSync("ec", {
|
|
225
|
-
namedCurve: "P-256",
|
|
226
|
-
publicKeyEncoding: { type: "spki", format: "pem" },
|
|
227
|
-
privateKeyEncoding: { type: "sec1", format: "pem" }
|
|
228
|
-
});
|
|
229
|
-
const hexPubKey = extractPublicKey(publicKey);
|
|
230
|
-
return {
|
|
231
|
-
privateKey,
|
|
232
|
-
publicKey,
|
|
233
|
-
hexPubKey
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
function hexToPem(hexString, { isPrivate = true } = {}) {
|
|
237
|
-
const keyEncoder = new KeyEncoder("p256");
|
|
238
|
-
if (isPrivate) {
|
|
239
|
-
return keyEncoder.encodePrivate(hexString, "raw", "pem");
|
|
240
|
-
}
|
|
241
|
-
return keyEncoder.encodePublic(hexString, "raw", "pem");
|
|
242
|
-
}
|
|
243
|
-
|
|
244
|
-
export {
|
|
245
|
-
decodeData,
|
|
246
|
-
sign2 as sign,
|
|
247
|
-
genKeys
|
|
248
|
-
};
|
|
249
|
-
//# sourceMappingURL=chunk-HU7O2ZFW.mjs.map
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/crypto/utils.ts","../src/crypto/keyEncoder.ts"],"sourcesContent":["import crypto from \"crypto\";\nimport * as elliptic from \"elliptic\";\nimport * as jwt from \"jsonwebtoken\";\n\nimport KeyEncoder from \"./keyEncoder\";\n\nfunction extractPublicKey(pemKey: string): string {\n // convert the PEM formatted public key to raw public key in X9.62 uncompressed format\n // this is an oversimplified method and may not work with different curves or PEM formats\n const pem = pemKey.split(\"\\n\");\n pem.shift(); // remove the first line (BEGIN PUBLIC KEY)\n pem.pop(); // remove the last line (END PUBLIC KEY)\n // convert base64 to buffer\n const keyBuffer = Buffer.from(pem.join(\"\"), \"base64\");\n // assuming the first 26 bytes are the header for the SPKI formatted key.\n // the actual key should begin after this header.\n const actualKeyBuffer = keyBuffer.slice(26);\n return actualKeyBuffer.toString(\"hex\");\n}\n\ntype GeneratedKeys = {\n privateKey: string;\n publicKey: string;\n hexPubKey: string;\n};\n\nexport function decodeData(challenge: string): void {\n const decodedString = atob(challenge);\n return JSON.parse(decodedString);\n}\n\nexport function sign(privateKey: string, challenge: string) {\n const pKey = crypto.createPrivateKey({\n key: String(privateKey),\n format: \"pem\",\n });\n const privateKeyPem = pKey.export({ format: \"pem\", type: \"sec1\" });\n const dataToSign = Buffer.from(challenge, \"base64\").toString(\"hex\");\n return jwt.sign(Buffer.from(dataToSign, \"hex\"), privateKeyPem, {\n algorithm: \"ES256\",\n header: {\n alg: \"ES256\",\n typ: \"JWT\",\n },\n });\n}\n\n/**\n * If `seed` is passed, will generate keys pair deterministically\n * else, random keys pair generated\n */\nexport function genKeys(entropy?: string): GeneratedKeys {\n if (entropy) {\n const ec = new elliptic.ec(\"p256\");\n const hashedEntropy = crypto.createHash(\"sha256\").update(entropy).digest(\"hex\");\n const keyPair = ec.genKeyPair({\n entropy: Buffer.from(hashedEntropy, \"hex\"),\n });\n return {\n privateKey: String(hexToPem(keyPair.getPrivate(\"hex\"))),\n publicKey: String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false })),\n hexPubKey: extractPublicKey(String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false }))),\n };\n }\n const { publicKey, privateKey } = crypto.generateKeyPairSync(\"ec\", {\n namedCurve: \"P-256\",\n publicKeyEncoding: { type: \"spki\", format: \"pem\" },\n privateKeyEncoding: { type: \"sec1\", format: \"pem\" },\n });\n const hexPubKey = extractPublicKey(publicKey);\n return {\n privateKey,\n publicKey,\n hexPubKey,\n };\n}\n\nfunction hexToPem(hexString: string, { isPrivate = true } = {}) {\n const keyEncoder = new KeyEncoder(\"p256\");\n if (isPrivate) {\n return keyEncoder.encodePrivate(hexString, \"raw\", \"pem\");\n }\n return keyEncoder.encodePublic(hexString, \"raw\", \"pem\");\n}\n","// ========================================================================== //\n// //\n// DISCLAIMER //\n// //\n// This code has been blindly copy-pasted from: //\n// https://github.com/LedgerHQ/pkey-ts //\n// //\n// ========================================================================== //\n//\n// @ts-expect-error\nimport * as asn1 from \"asn1.js\";\nimport BN from \"bn.js\";\nimport { ec as EC } from \"elliptic\";\n\nconst ECPrivateKeyASN = asn1.define(\"ECPrivateKey\", function () {\n // @ts-ignore\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self.key(\"privateKey\").octstr(),\n self.key(\"parameters\").explicit(0).objid().optional(),\n self.key(\"publicKey\").explicit(1).bitstr().optional(),\n );\n});\n\nconst ECPrivateKey8ASN = asn1.define(\n \"ECPrivateKey\",\n /* istanbul ignore next */ function () {\n // @ts-ignore\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self\n .key(\"privateKeyAlgorithm\")\n .seq()\n .obj(self.key(\"ecPublicKey\").objid(), self.key(\"curve\").objid()),\n self.key(\"privateKey\").octstr().contains(ECPrivateKeyASN),\n self.key(\"attributes\").explicit(0).bitstr().optional(),\n );\n },\n);\n\nconst SubjectPublicKeyInfoASN = asn1.define(\"SubjectPublicKeyInfo\", function () {\n // @ts-ignore\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"algorithm\").seq().obj(self.key(\"id\").objid(), self.key(\"curve\").objid()),\n self.key(\"pub\").bitstr(),\n );\n});\n\ninterface CurveOptions {\n curveParameters: number[];\n privatePEMOptions: { label: string };\n publicPEMOptions: { label: string };\n curve: EC;\n}\n\nconst curves: { [index: string]: CurveOptions } = {\n secp256k1: {\n curveParameters: [1, 3, 132, 0, 10],\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new EC(\"secp256k1\"),\n },\n p256: {\n curveParameters: [1, 2, 840, 10045, 3, 1, 7], // OID for p256 curve\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new EC(\"p256\"),\n },\n};\n\ninterface PrivateKeyPKCS1 {\n version: BN;\n privateKey: Buffer;\n parameters: number[];\n publicKey?: {\n unused: number;\n data: Buffer;\n };\n}\n\ninterface PrivateKeyPKCS8 {\n version: BN;\n privateKey: PrivateKeyPKCS1;\n privateKeyAlgorithm: { ecPublicKey: number[]; curve: number[] };\n}\n\ntype KeyFormat = \"raw\" | \"pem\" | \"der\";\n\nexport default class KeyEncoder {\n algorithmID: number[];\n options: CurveOptions;\n\n constructor(options: string | CurveOptions) {\n if (typeof options === \"string\") {\n /* istanbul ignore next */\n if (options !== \"secp256k1\" && options !== \"p256\") {\n throw new Error(\"Unknown curve \" + options);\n }\n options = curves[options] as CurveOptions;\n }\n this.options = options;\n this.algorithmID = [1, 2, 840, 10045, 2, 1];\n }\n\n /* istanbul ignore next */\n private PKCS1toPKCS8(privateKey: PrivateKeyPKCS1): PrivateKeyPKCS8 {\n return {\n version: new BN(0),\n privateKey,\n privateKeyAlgorithm: {\n ecPublicKey: this.algorithmID,\n curve: privateKey.parameters,\n },\n };\n }\n\n privateKeyObject(rawPrivateKey: string, rawPublicKey: string) {\n const privateKeyObject: PrivateKeyPKCS1 = {\n version: new BN(1),\n privateKey: Buffer.from(rawPrivateKey, \"hex\"),\n parameters: this.options.curveParameters,\n };\n\n if (rawPublicKey) {\n privateKeyObject.publicKey = {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n };\n }\n\n return privateKeyObject;\n }\n\n publicKeyObject(rawPublicKey: string) {\n return {\n algorithm: {\n id: this.algorithmID,\n curve: this.options.curveParameters,\n },\n pub: {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n },\n };\n }\n\n /* istanbul ignore next */\n encodePrivate(\n privateKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n destinationFormatType: \"pkcs8\" | \"pkcs1\" = \"pkcs1\",\n ): string {\n let privateKeyObject: PrivateKeyPKCS1;\n\n /* Parse the incoming private key and convert it to a private key object */\n if (originalFormat === \"raw\") {\n if (typeof privateKey !== \"string\") {\n throw \"private key must be a string\";\n }\n const keyPair = this.options.curve.keyFromPrivate(privateKey, \"hex\");\n const rawPublicKey = keyPair.getPublic(\"hex\");\n privateKeyObject = this.privateKeyObject(privateKey, rawPublicKey);\n } else if (originalFormat === \"der\") {\n if (typeof privateKey !== \"string\") {\n // do nothing\n } else if (typeof privateKey === \"string\") {\n privateKey = Buffer.from(privateKey, \"hex\");\n } else {\n throw \"private key must be a buffer or a string\";\n }\n privateKeyObject = ECPrivateKeyASN.decode(privateKey, \"der\");\n } else if (originalFormat === \"pem\") {\n if (typeof privateKey !== \"string\") {\n throw \"private key must be a string\";\n }\n privateKeyObject = ECPrivateKeyASN.decode(privateKey, \"pem\", this.options.privatePEMOptions);\n } else {\n throw \"invalid private key format\";\n }\n\n /* Export the private key object to the desired format */\n if (destinationFormat === \"raw\") {\n return privateKeyObject.privateKey.toString(\"hex\");\n } else if (destinationFormat === \"der\") {\n return ECPrivateKeyASN.encode(privateKeyObject, \"der\").toString(\"hex\");\n } else if (destinationFormat === \"pem\") {\n return destinationFormatType === \"pkcs1\"\n ? ECPrivateKeyASN.encode(privateKeyObject, \"pem\", this.options.privatePEMOptions)\n : ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), \"pem\", {\n ...this.options.privatePEMOptions,\n label: \"PRIVATE KEY\",\n });\n } else {\n throw \"invalid destination format for private key\";\n }\n }\n\n /* istanbul ignore next */\n encodePublic(\n publicKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n ): string {\n let publicKeyObject;\n\n /* Parse the incoming public key and convert it to a public key object */\n if (originalFormat === \"raw\") {\n if (typeof publicKey !== \"string\") {\n throw \"public key must be a string\";\n }\n publicKeyObject = this.publicKeyObject(publicKey);\n } else if (originalFormat === \"der\") {\n if (typeof publicKey !== \"string\") {\n // do nothing\n } else if (typeof publicKey === \"string\") {\n publicKey = Buffer.from(publicKey, \"hex\");\n } else {\n throw \"public key must be a buffer or a string\";\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(publicKey, \"der\");\n } else if (originalFormat === \"pem\") {\n if (typeof publicKey !== \"string\") {\n throw \"public key must be a string\";\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(\n publicKey,\n \"pem\",\n this.options.publicPEMOptions,\n );\n } else {\n throw \"invalid public key format\";\n }\n\n /* Export the private key object to the desired format */\n if (destinationFormat === \"raw\") {\n return publicKeyObject.pub.data.toString(\"hex\");\n } else if (destinationFormat === \"der\") {\n return SubjectPublicKeyInfoASN.encode(publicKeyObject, \"der\").toString(\"hex\");\n } else if (destinationFormat === \"pem\") {\n return SubjectPublicKeyInfoASN.encode(publicKeyObject, \"pem\", this.options.publicPEMOptions);\n } else {\n throw \"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