@circle-fin/daa-react-native-sdk 0.4.0 → 0.5.0

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.
Files changed (157) hide show
  1. package/DaaReactNativeSdk.podspec +14 -8
  2. package/README.md +498 -24
  3. package/android/build.gradle +12 -7
  4. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +1 -18
  5. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +38 -4
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +139 -6
  7. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +50 -1
  8. package/build/DaaClient.d.ts +183 -3
  9. package/build/DaaClient.js +296 -12
  10. package/build/api/AccountsClient.d.ts +3 -0
  11. package/build/api/AccountsClient.js +3 -0
  12. package/build/api/AuthClient.d.ts +17 -42
  13. package/build/api/AuthClient.js +26 -62
  14. package/build/api/ContractExecutionsClient.d.ts +114 -0
  15. package/build/api/ContractExecutionsClient.js +462 -0
  16. package/build/api/DaaUserClient.d.ts +74 -11
  17. package/build/api/DaaUserClient.js +84 -17
  18. package/build/api/TransactionsClient.d.ts +1 -1
  19. package/build/api/TransactionsClient.js +1 -0
  20. package/build/api/TransfersClient.d.ts +3 -0
  21. package/build/api/TransfersClient.js +3 -0
  22. package/build/api/WithdrawalsClient.d.ts +3 -0
  23. package/build/api/WithdrawalsClient.js +3 -0
  24. package/build/api/deviceApproval.d.ts +48 -0
  25. package/build/api/deviceApproval.js +247 -0
  26. package/build/api/deviceStatus.d.ts +61 -0
  27. package/build/api/deviceStatus.js +216 -0
  28. package/build/api/loginFailure.d.ts +10 -2
  29. package/build/api/loginFailure.js +33 -2
  30. package/build/api/signedResource.d.ts +49 -2
  31. package/build/api/signedResource.js +135 -36
  32. package/build/auth/RegistrationFlowKey.js +1 -1
  33. package/build/auth/daaRegistrationNative.d.ts +0 -22
  34. package/build/auth/daaRegistrationNative.js +3 -29
  35. package/build/auth/deviceAuthorization.d.ts +17 -3
  36. package/build/auth/deviceAuthorization.js +60 -8
  37. package/build/auth/registrationAuthorization.d.ts +2 -2
  38. package/build/auth/registrationAuthorization.js +13 -10
  39. package/build/config.d.ts +27 -0
  40. package/build/config.js +15 -0
  41. package/build/crypto/matchingCode.d.ts +47 -0
  42. package/build/crypto/matchingCode.js +93 -0
  43. package/build/errors.d.ts +150 -33
  44. package/build/errors.js +208 -47
  45. package/build/index.d.ts +11 -3
  46. package/build/models/ContractExecution.d.ts +197 -0
  47. package/build/models/ContractExecution.js +130 -0
  48. package/build/models/CreateContractExecutionRequest.d.ts +81 -0
  49. package/build/models/CreateContractExecutionRequest.js +19 -0
  50. package/build/models/DaaUserContext.d.ts +53 -3
  51. package/build/models/DaaUserContext.js +33 -2
  52. package/build/models/DeviceStatus.d.ts +69 -0
  53. package/build/models/DeviceStatus.js +19 -0
  54. package/build/models/PendingDeviceApproval.d.ts +121 -0
  55. package/build/models/PendingDeviceApproval.js +208 -0
  56. package/build/models/PendingDeviceRegistration.d.ts +162 -23
  57. package/build/models/PendingDeviceRegistration.js +525 -69
  58. package/build/models/PreparedContractExecution.d.ts +70 -0
  59. package/build/models/PreparedContractExecution.js +77 -0
  60. package/build/models/PreparedSocialLogin.d.ts +19 -26
  61. package/build/models/PreparedSocialLogin.js +32 -15
  62. package/build/models/Transaction.d.ts +48 -2
  63. package/build/models/Transaction.js +52 -4
  64. package/build/models/codeSecrets.d.ts +100 -0
  65. package/build/models/codeSecrets.js +321 -0
  66. package/build/securekey/InMemorySecureKey.d.ts +3 -1
  67. package/build/securekey/InMemorySecureKey.js +47 -6
  68. package/build/securekey/NativeSecureKey.d.ts +3 -1
  69. package/build/securekey/NativeSecureKey.js +204 -27
  70. package/build/securekey/NativeSecureKeyBridge.d.ts +72 -4
  71. package/build/securekey/SecureKey.d.ts +128 -8
  72. package/build/securekey/alias.d.ts +9 -0
  73. package/build/securekey/alias.js +11 -2
  74. package/build/securekey/ownerAuthKeyResolver.d.ts +26 -9
  75. package/build/securekey/ownerAuthKeyResolver.js +35 -20
  76. package/build/securekey/registration.d.ts +19 -0
  77. package/build/securekey/registration.js +38 -0
  78. package/build/securekey/resolveNativeBridge.d.ts +3 -0
  79. package/build/securekey/resolveNativeBridge.js +88 -7
  80. package/build/transport/headers.d.ts +11 -0
  81. package/build/transport/headers.js +36 -0
  82. package/build/wire/contractExecutionPayload.d.ts +24 -0
  83. package/build/wire/contractExecutionPayload.js +130 -0
  84. package/build/wire/daaStatusCodes.d.ts +20 -3
  85. package/build/wire/daaStatusCodes.js +20 -3
  86. package/build/wire/deviceContextPayload.d.ts +9 -7
  87. package/build/wire/deviceContextPayload.js +9 -7
  88. package/build/wire/deviceRegistrationResultPayload.d.ts +55 -10
  89. package/build/wire/deviceRegistrationResultPayload.js +116 -82
  90. package/build/wire/deviceStatusPayload.d.ts +20 -0
  91. package/build/wire/deviceStatusPayload.js +66 -0
  92. package/build/wire/instant.js +4 -1
  93. package/build/wire/pendingRegistrationPayload.d.ts +16 -0
  94. package/build/wire/pendingRegistrationPayload.js +18 -0
  95. package/build/wire/socialLoginRequestPayload.d.ts +0 -5
  96. package/build/wire/socialLoginRequestPayload.js +2 -19
  97. package/build/wire/transactionPayload.d.ts +2 -2
  98. package/build/wire/transactionPayload.js +27 -4
  99. package/ios/DaaRegistrationModule.swift +1 -19
  100. package/ios/DaaSecureKeyExceptions.swift +53 -5
  101. package/ios/DaaSecureKeyModule.swift +149 -5
  102. package/ios/InstallationIdentityStore.swift +43 -7
  103. package/package.json +1 -1
  104. package/src/DaaClient.ts +353 -15
  105. package/src/api/AccountsClient.ts +3 -0
  106. package/src/api/AuthClient.ts +33 -98
  107. package/src/api/ContractExecutionsClient.ts +527 -0
  108. package/src/api/DaaUserClient.ts +92 -17
  109. package/src/api/TransactionsClient.ts +1 -0
  110. package/src/api/TransfersClient.ts +3 -0
  111. package/src/api/WithdrawalsClient.ts +3 -0
  112. package/src/api/deviceApproval.ts +306 -0
  113. package/src/api/deviceStatus.ts +238 -0
  114. package/src/api/loginFailure.ts +39 -2
  115. package/src/api/signedResource.ts +206 -46
  116. package/src/auth/RegistrationFlowKey.ts +1 -1
  117. package/src/auth/daaRegistrationNative.ts +4 -49
  118. package/src/auth/deviceAuthorization.ts +74 -11
  119. package/src/auth/registrationAuthorization.ts +12 -9
  120. package/src/config.ts +36 -0
  121. package/src/crypto/matchingCode.ts +100 -0
  122. package/src/errors.ts +309 -52
  123. package/src/index.ts +36 -1
  124. package/src/models/ContractExecution.ts +250 -0
  125. package/src/models/CreateContractExecutionRequest.ts +100 -0
  126. package/src/models/DaaUserContext.ts +59 -3
  127. package/src/models/DeviceStatus.ts +50 -0
  128. package/src/models/PendingDeviceApproval.ts +229 -0
  129. package/src/models/PendingDeviceRegistration.ts +673 -79
  130. package/src/models/PreparedContractExecution.ts +128 -0
  131. package/src/models/PreparedSocialLogin.ts +41 -31
  132. package/src/models/Transaction.ts +77 -2
  133. package/src/models/codeSecrets.ts +360 -0
  134. package/src/securekey/InMemorySecureKey.ts +61 -7
  135. package/src/securekey/NativeSecureKey.ts +234 -25
  136. package/src/securekey/NativeSecureKeyBridge.ts +84 -4
  137. package/src/securekey/SecureKey.ts +138 -8
  138. package/src/securekey/alias.ts +11 -3
  139. package/src/securekey/ownerAuthKeyResolver.ts +63 -24
  140. package/src/securekey/registration.ts +40 -0
  141. package/src/securekey/resolveNativeBridge.ts +167 -9
  142. package/src/transport/headers.ts +47 -0
  143. package/src/wire/contractExecutionPayload.ts +152 -0
  144. package/src/wire/daaStatusCodes.ts +20 -3
  145. package/src/wire/deviceContextPayload.ts +9 -7
  146. package/src/wire/deviceRegistrationResultPayload.ts +156 -98
  147. package/src/wire/deviceStatusPayload.ts +68 -0
  148. package/src/wire/instant.ts +4 -1
  149. package/src/wire/pendingRegistrationPayload.ts +44 -1
  150. package/src/wire/socialLoginRequestPayload.ts +2 -25
  151. package/src/wire/transactionPayload.ts +40 -4
  152. package/build/auth/prepareReceipt.d.ts +0 -150
  153. package/build/auth/prepareReceipt.js +0 -357
  154. package/build/crypto/es256Jws.d.ts +0 -56
  155. package/build/crypto/es256Jws.js +0 -196
  156. package/src/auth/prepareReceipt.ts +0 -522
  157. package/src/crypto/es256Jws.ts +0 -240
@@ -21,13 +21,20 @@ import type { DaaEnvironment } from '../config'
21
21
  import { idempotencyKeyFromExactBody } from '../auth/deviceAuthorization'
22
22
  import { contractViolation, DaaError, transportFailure } from '../errors'
23
23
  import type { DeviceContext } from '../models/DaaUserContext'
24
- import type { OwnerAuthKey } from '../securekey/SecureKey'
24
+ import type { DeviceStatus } from '../models/DeviceStatus'
25
+ import type {
26
+ AuthKeyRegistration,
27
+ DeviceApprovalSigning,
28
+ OwnerAuthKey,
29
+ } from '../securekey/SecureKey'
25
30
  import type { DaaHttpRequest, DaaTransport } from '../transport/DaaTransport'
26
31
  import { toDeviceContext } from '../wire/deviceContextPayload'
27
32
  import { AccountLimitsClient } from './AccountLimitsClient'
28
33
  import { AccountsClient } from './AccountsClient'
34
+ import { ContractExecutionsClient } from './ContractExecutionsClient'
29
35
  import { DepositAddressesClient } from './DepositAddressesClient'
30
36
  import { DepositsClient } from './DepositsClient'
37
+ import { approveDevice, type ApproveDeviceArgs, type KeptApprovals } from './deviceApproval'
31
38
  import { FiatAccountsClient } from './FiatAccountsClient'
32
39
  import { getSignedResource, type DaaUserSigning } from './signedResource'
33
40
  import { TransactionsClient } from './TransactionsClient'
@@ -67,11 +74,15 @@ export class DaaUserClient {
67
74
  readonly transfers: TransfersClient
68
75
  /** Reads over DAA withdrawals, and the signed withdrawal create. */
69
76
  readonly withdrawals: WithdrawalsClient
77
+ /** Reads over self-custody contract executions, and the signed create. */
78
+ readonly contractExecutions: ContractExecutionsClient
70
79
  /** Reads over wire and ACH fiat accounts, and their receiving instructions. */
71
80
  readonly fiatAccounts: FiatAccountsClient
72
81
 
73
82
  readonly #transport: DaaTransport
74
83
  readonly #signing: DaaUserSigning
84
+ readonly #approvals: KeptApprovals = new Map()
85
+ readonly #assertOpen: () => void
75
86
  readonly #markClosed: () => void
76
87
 
77
88
  /** @internal Constructed only through {@link createDaaUserClient}. */
@@ -85,10 +96,11 @@ export class DaaUserClient {
85
96
 
86
97
  // `close()` has to reach every signed operation this surface
87
98
  // exposes, not just `refreshContext` — an accounts/transfers/withdrawals
88
- // `create` reached through a "closed" client is exactly the further use
89
- // `close()` exists to refuse. Every signed client below is handed this one
90
- // wrapper rather than the caller's `signing` directly, so flipping `closed`
91
- // here closes all of them at once without editing any resource client.
99
+ // `create`, or a contract-execution `prepare`, reached through a "closed"
100
+ // client is exactly the further use `close()` exists to refuse. Every
101
+ // signed client below is handed this one wrapper rather than the caller's
102
+ // `signing` directly, so flipping `closed` here closes all of them at once
103
+ // without editing any resource client.
92
104
  let closed = false
93
105
  const assertOpen = (): void => {
94
106
  if (closed) {
@@ -99,6 +111,7 @@ export class DaaUserClient {
99
111
  }
100
112
  const guardedSigning: DaaUserSigning = Object.freeze({
101
113
  authKeyId: signing.authKeyId,
114
+ clientEntityId: signing.clientEntityId,
102
115
  resolveAuthKey: async () => {
103
116
  assertOpen()
104
117
  return guardAuthKey(await signing.resolveAuthKey(), assertOpen)
@@ -133,10 +146,12 @@ export class DaaUserClient {
133
146
  this.transactions = new TransactionsClient(guardedTransport, publicApiOrigin)
134
147
  this.transfers = new TransfersClient(guardedTransport, publicApiOrigin, guardedSigning)
135
148
  this.withdrawals = new WithdrawalsClient(guardedTransport, publicApiOrigin, guardedSigning)
149
+ this.contractExecutions = new ContractExecutionsClient(guardedTransport, guardedSigning)
136
150
  this.fiatAccounts = new FiatAccountsClient(guardedTransport)
137
151
 
138
152
  this.#transport = guardedTransport
139
153
  this.#signing = guardedSigning
154
+ this.#assertOpen = assertOpen
140
155
  this.#markClosed = () => {
141
156
  closed = true
142
157
  }
@@ -160,7 +175,10 @@ export class DaaUserClient {
160
175
  * that is not yet registered, for a rejected or replayed authorization
161
176
  * (including a key that is no longer active: DAA has no revoked-credential
162
177
  * code, so this never throws `device_revoked`), for a response the SDK
163
- * cannot read, and once this client is {@link close}d;
178
+ * cannot read, and once this client is {@link close}d; `clock_skew` when
179
+ * DAA refused the authorization because the device clock was more than 60
180
+ * seconds off: correct the device time, then refresh again;
181
+ * `user_cancelled` when the user dismisses the authentication prompt;
164
182
  * `detail.kind === 'api'` for a status other than the documented `200`; and
165
183
  * `detail.kind === 'transport'` if the consumer's transport throws, with
166
184
  * the thrown value as `err.cause`.
@@ -176,6 +194,49 @@ export class DaaUserClient {
176
194
  })
177
195
  }
178
196
 
197
+ /**
198
+ * Approve a new device on this account from this one (add-a-device).
199
+ *
200
+ * The new device shows a six-digit matching code; the user types it here.
201
+ * The SDK reads the request from the device list, checks the typed code
202
+ * against the code the new device's secret produces, and only then signs
203
+ * `approve_device` with this device's key, so a wrong code is refused before
204
+ * any biometric prompt. The prompt shows the code. On success the new device
205
+ * is in its cool-down: the result is normally `pending_activation` with its
206
+ * `readyAt`.
207
+ *
208
+ * `requestId` comes from the partner (the `account.device.pending` webhook
209
+ * pushed to this device) or from the device list's `pendingRequests`.
210
+ *
211
+ * After a `transport` failure, a retryable `api` error, a `401` (once
212
+ * credentials are refreshed) or a `contract_violation`, call it again on this
213
+ * client with the same `requestId`: it signs the same approval body again (the
214
+ * user sees the prompt again), and DAA returns its saved result if the first
215
+ * one went through. Another `4xx` is DAA refusing the approval, and calling
216
+ * again gets the same answer. The body is kept in memory until a valid
217
+ * result, `device_approval_invalid` or `close()`.
218
+ * After `device_approval_busy` the same applies: nothing was saved, so DAA
219
+ * runs the re-signed approval again.
220
+ *
221
+ * Don't call it again for a `requestId` while a call for it is still
222
+ * running: each call reads and signs on its own, so the user sees two
223
+ * prompts.
224
+ *
225
+ * @throws DaaError with `detail.kind`:
226
+ * `matching_code_mismatch` when the typed code is wrong (let the user type
227
+ * it again); `device_approval_not_ready` when the new device has not sent
228
+ * its code secret yet (try again in a few seconds);
229
+ * `device_approval_invalid` when the request is no longer waiting (it
230
+ * expired, or was decided or cancelled); `device_approval_busy` when the
231
+ * account changed meanwhile (call again; the user sees the prompt again);
232
+ * `user_cancelled` when the user dismisses the prompt (the request stays
233
+ * waiting); `clock_skew`, `contract_violation`, `api` and `transport` as
234
+ * for any signed write.
235
+ */
236
+ async approveDevice(args: ApproveDeviceArgs): Promise<DeviceStatus> {
237
+ return approveDevice(this.#transport, this.#signing, this.#approvals, this.#assertOpen, args)
238
+ }
239
+
179
240
  /**
180
241
  * `DaaUserClient.close()` clears active context from memory and cancels
181
242
  * unsent work. It preserves an active profile-scoped AuthKey and credential;
@@ -187,18 +248,22 @@ export class DaaUserClient {
187
248
  * closure, and every call this SDK makes is a single `transport.send` awaited
188
249
  * to completion with no cancellation token in the transport contract to
189
250
  * cancel. Concretely, close() revokes this instance's own capability to
190
- * produce a fresh `X-Device-Authorization` at all, so `refreshContext` and
191
- * every signed `create` on `accounts` / `transfers` / `withdrawals` fail
192
- * closed with `contract_violation` from this point on instead of silently
193
- * continuing to sign. The guarded transport also refuses unsigned reads, writes, and
194
- * retained Page navigation closures after close, so unsent work cannot
195
- * outlive the user surface that created it. The registered AuthKey and
196
- * Circle's registration acknowledgement are untouched — nothing here calls
197
- * the native store, so there is nothing here that could revoke either.
198
- * Idempotent: closing an already-closed client is a no-op.
251
+ * produce a fresh `X-Device-Authorization` at all, so `refreshContext`,
252
+ * every signed `create` on `accounts` / `transfers` / `withdrawals`, and
253
+ * `contractExecutions.prepare` fail closed with `contract_violation` from
254
+ * this point on instead of silently continuing to sign. The guarded
255
+ * transport also refuses unsigned reads, writes, retained Page navigation
256
+ * closures, and a `contractExecutions.submit` of an execution prepared
257
+ * earlier, so unsent work cannot outlive the user surface that created it.
258
+ * That prepared execution stays valid: a later `forUser` client for the same
259
+ * AuthKey can submit it. The registered AuthKey and Circle's registration
260
+ * acknowledgement are untouched — nothing here calls the native store, so
261
+ * there is nothing here that could revoke either. Idempotent: closing an
262
+ * already-closed client is a no-op.
199
263
  */
200
264
  close(): void {
201
265
  this.#markClosed()
266
+ this.#approvals.clear()
202
267
  }
203
268
  }
204
269
 
@@ -209,11 +274,13 @@ export class DaaUserClient {
209
274
  * otherwise sign with the already-resolved AuthKey.
210
275
  */
211
276
  function guardAuthKey(authKey: OwnerAuthKey, assertOpen: () => void): OwnerAuthKey {
277
+ const signDeviceApproval = authKey.signDeviceApproval?.bind(authKey)
212
278
  return Object.freeze({
213
279
  publicKeySpkiBase64Url: () => authKey.publicKeySpkiBase64Url(),
214
280
  thumbprint: () => authKey.thumbprint(),
215
281
  resolution: () => authKey.resolution(),
216
- acknowledgeRegistration: () => authKey.acknowledgeRegistration(),
282
+ acknowledgeRegistration: (registration: AuthKeyRegistration) =>
283
+ authKey.acknowledgeRegistration(registration),
217
284
  signExactBytes: async (message: Uint8Array) => {
218
285
  assertOpen()
219
286
  return authKey.signExactBytes(message)
@@ -222,6 +289,14 @@ function guardAuthKey(authKey: OwnerAuthKey, assertOpen: () => void): OwnerAuthK
222
289
  assertOpen()
223
290
  return authKey.signRegistrationDeviceAuthorization(message)
224
291
  },
292
+ ...(signDeviceApproval === undefined
293
+ ? {}
294
+ : {
295
+ signDeviceApproval: async (message: Uint8Array, approval: DeviceApprovalSigning) => {
296
+ assertOpen()
297
+ return signDeviceApproval(message, approval)
298
+ },
299
+ }),
225
300
  })
226
301
  }
227
302
 
@@ -254,7 +329,7 @@ export function createDaaUserClient(
254
329
  * reader cannot parse leaves the key off rather than replacing the transport
255
330
  * failure with a different error.
256
331
  */
257
- function asTransportFailure(err: unknown, request: DaaHttpRequest): DaaError {
332
+ export function asTransportFailure(err: unknown, request: DaaHttpRequest): DaaError {
258
333
  if (err instanceof DaaError) {
259
334
  return err
260
335
  }
@@ -37,6 +37,7 @@ const TRANSACTION_TYPES = Object.freeze([
37
37
  'fx',
38
38
  'fee',
39
39
  'credit',
40
+ 'contract_execution',
40
41
  'other',
41
42
  ] as const)
42
43
 
@@ -186,6 +186,9 @@ export class TransfersClient {
186
186
  * sent — for a rejected or replayed authorization (including a key that is
187
187
  * no longer active: DAA has no revoked-credential code, so this never
188
188
  * throws `device_revoked`), and for a response the SDK cannot read;
189
+ * `clock_skew` when DAA refused the authorization because the device clock
190
+ * was more than 60 seconds off: correct the device time, then send the same
191
+ * request again;
189
192
  * `idempotency_conflict`, with the request's key, for a `409` with
190
193
  * `IDEMPOTENCY_KEY_REUSED` (`420034`): reconcile the original transfer with
191
194
  * the same key; do not mint a new key for it;
@@ -159,6 +159,9 @@ export class WithdrawalsClient {
159
159
  * sent — for a rejected or replayed authorization (including a key that is
160
160
  * no longer active: DAA has no revoked-credential code, so this never
161
161
  * throws `device_revoked`), and for a response the SDK cannot read;
162
+ * `clock_skew` when DAA refused the authorization because the device clock
163
+ * was more than 60 seconds off: correct the device time, then send the same
164
+ * request again;
162
165
  * `idempotency_conflict`, with the request's key, for a `409` with
163
166
  * `IDEMPOTENCY_KEY_REUSED` (`420034`): reconcile the original withdrawal with
164
167
  * the same key; do not mint a new key for it;
@@ -0,0 +1,306 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // The approving device's side of add-a-device: an existing device approves a
20
+ // new one after the user types the code the new device shows.
21
+ //
22
+ // 1. Read the device list and find the request. Its entry carries everything
23
+ // the approval signs (the new key's id and thumbprint, `codeSeal`,
24
+ // `codeNonce`) and the new device's code secret.
25
+ // 2. Check that the secret opens `codeSeal`, and that the typed code is the
26
+ // code they produce. A wrong code stops here: nothing is signed or sent and
27
+ // no biometric prompt is shown.
28
+ // 3. Serialize the approval body once, sign `approve_device` over it with the
29
+ // native approval seam (which checks the same things again and shows the
30
+ // code in its prompt), and send those bytes.
31
+ //
32
+ // The secret and the body both come from the server, so step 2's seal check
33
+ // only catches inconsistent data; the typed code is what ties the approval to
34
+ // the screen the user is looking at.
35
+ //
36
+ // A retry signs the same body again. DAA answers an approval it already
37
+ // committed when the body hash and the approving key match, whatever the
38
+ // `jti`, but drops the request from the device list once it is decided. So
39
+ // the client keeps each request's body until it has a valid result or
40
+ // `device_approval_invalid`, and a second call
41
+ // for that request skips step 1 and signs those bytes again: after a lost
42
+ // response the user gets DAA's saved result, not `device_approval_invalid`.
43
+
44
+ import { randomUuidV4 } from '../crypto/random'
45
+ import { serializeBody } from '../crypto/serialization'
46
+ import { canonicalBytes32, codeSeal, matchingCode } from '../crypto/matchingCode'
47
+ import { toBase64Url } from '../crypto/base64url'
48
+ import { contractViolation, DaaError, deviceApprovalFailure } from '../errors'
49
+ import type { DeviceStatus } from '../models/DeviceStatus'
50
+ import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
51
+ import { headerValueIgnoringCase } from '../transport/headers'
52
+ import { isUuid } from '../validation/uuid'
53
+ import { isDaaStatus } from '../wire/daaStatusCodes'
54
+ import { toDeviceStatus } from '../wire/deviceStatusPayload'
55
+ import { readDaaStatusCode } from '../wire/errorEnvelope'
56
+ import { asObject, MalformedPayloadError, optionalString, requiredString } from '../wire/payload'
57
+ import { authorizeSignedPost, postAuthorizedResource, type DaaUserSigning } from './signedResource'
58
+ import { readResource } from './resourceRequest'
59
+
60
+ /** The device list: the user's devices and the new devices waiting for approval. */
61
+ export const DEVICE_LIST_PATH = '/v1/accounts/auth/devices'
62
+
63
+ /** One `pendingRequests` entry, as far as an approval reads it. */
64
+ type PendingRequest = Readonly<{
65
+ requestId: string
66
+ authKeyId: string
67
+ publicKeyThumbprint: string
68
+ codeSeal: string
69
+ codeNonce: string
70
+ codeSecret: string | null
71
+ }>
72
+
73
+ /**
74
+ * What a retry of one request's approval needs: the exact body (its
75
+ * `idempotencyKey` included), the code secret native checks against it, and
76
+ * the code a typed code must match.
77
+ */
78
+ type KeptApproval = Readonly<{
79
+ targetAuthKeyId: string
80
+ codeSecret: Uint8Array
81
+ code: string
82
+ bodyBytes: Uint8Array
83
+ }>
84
+
85
+ /** Approval bodies DAA has not answered yet, by lowercase request id. One per `DaaUserClient`. */
86
+ export type KeptApprovals = Map<string, KeptApproval>
87
+
88
+ export type ApproveDeviceArgs = Readonly<{
89
+ /** The add-a-device request to approve, from the device list or the partner's push. */
90
+ requestId: string
91
+ /** The six digits the user typed from the new device's screen. Spaces and dashes are ignored. */
92
+ typedCode: string
93
+ }>
94
+
95
+ /**
96
+ * Approve the waiting device `requestId` with the code the user typed. Resolves
97
+ * with the new device's status, normally `pending_activation` with its
98
+ * `readyAt`.
99
+ */
100
+ export async function approveDevice(
101
+ transport: DaaTransport,
102
+ signing: DaaUserSigning,
103
+ kept: KeptApprovals,
104
+ assertOpen: () => void,
105
+ args: ApproveDeviceArgs,
106
+ ): Promise<DeviceStatus> {
107
+ const { requestId, typedCode } = requireArgs(args)
108
+ const id = requestId.toLowerCase()
109
+ const approval =
110
+ kept.get(id) ?? (await prepareApproval(transport, signing.clientEntityId, requestId))
111
+ // `close()` may have run during the read and cleared `kept`. Checked with no
112
+ // await before `kept.set`, so a closed client never keeps the body again.
113
+ assertOpen()
114
+ if (stripSeparators(typedCode) !== approval.code) {
115
+ throw deviceApprovalFailure('matching_code_mismatch')
116
+ }
117
+ kept.set(id, approval)
118
+
119
+ let status: DeviceStatus
120
+ try {
121
+ const authorization = await authorizeSignedPost({
122
+ operation: 'approve_device',
123
+ authKey: await signing.resolveAuthKey(),
124
+ authKeyId: signing.authKeyId,
125
+ bodyBytes: approval.bodyBytes,
126
+ approval: { codeSecret: approval.codeSecret, enteredCode: typedCode },
127
+ })
128
+ status = await postAuthorizedResource({
129
+ transport,
130
+ operation: 'approve_device',
131
+ bodyBytes: approval.bodyBytes,
132
+ authorization,
133
+ expectedStatuses: [200],
134
+ decode: toDeviceStatus,
135
+ failure: approvalFailure,
136
+ })
137
+ } catch (err) {
138
+ if (daaAnswered(err)) {
139
+ kept.delete(id)
140
+ }
141
+ throw err
142
+ }
143
+ // Checked before forgetting the body: DAA may have committed, so a retry
144
+ // must still be able to sign these bytes again and get its saved result.
145
+ if (status.authKeyId.toLowerCase() !== approval.targetAuthKeyId.toLowerCase()) {
146
+ throw contractViolation('the approval result names a different AuthKey')
147
+ }
148
+ kept.delete(id)
149
+ return status
150
+ }
151
+
152
+ /**
153
+ * Read the request from the device list, check the new device's secret
154
+ * against its seal, and serialize the approval body once.
155
+ */
156
+ async function prepareApproval(
157
+ transport: DaaTransport,
158
+ clientEntityId: string,
159
+ requestId: string,
160
+ ): Promise<KeptApproval> {
161
+ const request = await readPendingRequest(transport, clientEntityId, requestId)
162
+ if (request.codeSecret === null) {
163
+ throw deviceApprovalFailure('device_approval_not_ready')
164
+ }
165
+ const thumbprint = requireBytes32(request.publicKeyThumbprint)
166
+ const secret = requireBytes32(request.codeSecret)
167
+ if (toBase64Url(codeSeal(thumbprint, secret)) !== request.codeSeal) {
168
+ throw contractViolation("the new device's code secret does not open its codeSeal")
169
+ }
170
+ return Object.freeze({
171
+ targetAuthKeyId: request.authKeyId,
172
+ codeSecret: secret,
173
+ code: matchingCode(thumbprint, requireBytes32(request.codeNonce), secret),
174
+ bodyBytes: serializeBody({
175
+ requestId: request.requestId,
176
+ targetAuthKeyId: request.authKeyId,
177
+ publicKeyThumbprint: request.publicKeyThumbprint,
178
+ codeSeal: request.codeSeal,
179
+ codeNonce: request.codeNonce,
180
+ idempotencyKey: randomUuidV4(),
181
+ }),
182
+ })
183
+ }
184
+
185
+ /**
186
+ * Whether DAA gave a final answer about this request, so a retry must start
187
+ * over from the device list. Only `device_approval_invalid` says so. Anything
188
+ * else (a transport failure, any other `api` status such as a gateway 401, a
189
+ * response the SDK could not read, a cancelled prompt, a busy account) says
190
+ * nothing about an approval that may already be committed, and a retry signs
191
+ * the same body again.
192
+ */
193
+ function daaAnswered(err: unknown): boolean {
194
+ return err instanceof DaaError && err.detail.kind === 'device_approval_invalid'
195
+ }
196
+
197
+ function requireArgs(args: ApproveDeviceArgs): ApproveDeviceArgs {
198
+ if (typeof args !== 'object' || args === null) {
199
+ throw contractViolation('approveDevice requires { requestId, typedCode }')
200
+ }
201
+ const { requestId, typedCode } = args
202
+ if (typeof requestId !== 'string' || !isUuid(requestId)) {
203
+ throw contractViolation('approveDevice requestId must be a UUID')
204
+ }
205
+ if (typeof typedCode !== 'string') {
206
+ throw contractViolation('approveDevice typedCode must be a string')
207
+ }
208
+ return { requestId, typedCode }
209
+ }
210
+
211
+ /** The code is shown as "482 913", so ASCII spaces and dashes are ignored, as natively. */
212
+ function stripSeparators(typedCode: string): string {
213
+ return typedCode.replace(/[ -]/g, '')
214
+ }
215
+
216
+ async function readPendingRequest(
217
+ transport: DaaTransport,
218
+ clientEntityId: string,
219
+ requestId: string,
220
+ ): Promise<PendingRequest> {
221
+ const id = requestId.toLowerCase()
222
+ const request = await readResource({
223
+ transport,
224
+ path: DEVICE_LIST_PATH,
225
+ query: `clientEntityId=${encodeURIComponent(clientEntityId)}`,
226
+ decode: (value) => findPendingRequest(value, id),
227
+ })
228
+ // DAA leaves a request out of the list once it expires or is decided.
229
+ if (request === null) {
230
+ throw deviceApprovalFailure('device_approval_invalid')
231
+ }
232
+ return request
233
+ }
234
+
235
+ /**
236
+ * The `pendingRequests` entry for `requestId`, or `null` when there is none.
237
+ * Only that entry is decoded: a malformed entry for another request must not
238
+ * stop this approval.
239
+ */
240
+ function findPendingRequest(value: unknown, requestId: string): PendingRequest | null {
241
+ const list = asObject(value, 'payload')
242
+ const pending = list['pendingRequests']
243
+ if (pending === undefined || pending === null) {
244
+ return null
245
+ }
246
+ if (!Array.isArray(pending)) {
247
+ throw new MalformedPayloadError('pendingRequests')
248
+ }
249
+ for (const item of pending) {
250
+ if (typeof item !== 'object' || item === null || Array.isArray(item)) {
251
+ continue
252
+ }
253
+ const entry = item as Record<string, unknown>
254
+ const itemId = entry['requestId']
255
+ if (typeof itemId !== 'string' || itemId.toLowerCase() !== requestId) {
256
+ continue
257
+ }
258
+ const authKeyId = requiredString(entry, 'authKeyId')
259
+ if (!isUuid(authKeyId)) {
260
+ throw new MalformedPayloadError('authKeyId')
261
+ }
262
+ return Object.freeze({
263
+ requestId: requiredString(entry, 'requestId'),
264
+ authKeyId,
265
+ publicKeyThumbprint: requiredBytes32String(entry, 'publicKeyThumbprint'),
266
+ codeSeal: requiredBytes32String(entry, 'codeSeal'),
267
+ codeNonce: requiredBytes32String(entry, 'codeNonce'),
268
+ codeSecret:
269
+ optionalString(entry, 'codeSecret') === null
270
+ ? null
271
+ : requiredBytes32String(entry, 'codeSecret'),
272
+ })
273
+ }
274
+ return null
275
+ }
276
+
277
+ function requiredBytes32String(entry: Record<string, unknown>, name: string): string {
278
+ const value = requiredString(entry, name)
279
+ if (canonicalBytes32(value) === null) {
280
+ throw new MalformedPayloadError(name)
281
+ }
282
+ return value
283
+ }
284
+
285
+ function requireBytes32(value: string): Uint8Array {
286
+ const bytes = canonicalBytes32(value)
287
+ if (bytes === null) {
288
+ throw contractViolation('device approval input must be 32 bytes in canonical Base64URL')
289
+ }
290
+ return bytes
291
+ }
292
+
293
+ function approvalFailure(response: DaaHttpResponse): DaaError | null {
294
+ if (response.status !== 409) {
295
+ return null
296
+ }
297
+ const code = readDaaStatusCode(response.bodyBytes)
298
+ const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
299
+ if (isDaaStatus(code, 'DEVICE_APPROVAL_INVALID')) {
300
+ return deviceApprovalFailure('device_approval_invalid', correlationId)
301
+ }
302
+ if (isDaaStatus(code, 'DEVICE_APPROVAL_BUSY')) {
303
+ return deviceApprovalFailure('device_approval_busy', correlationId)
304
+ }
305
+ return null
306
+ }