@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
package/src/DaaClient.ts CHANGED
@@ -17,22 +17,54 @@
17
17
  */
18
18
 
19
19
  import { AuthClient } from './api/AuthClient'
20
- import { createDaaUserClient, type DaaUserClient } from './api/DaaUserClient'
21
- import { assertDeviceKeyPolicy, assertPublicApiOrigin, DAA_ENVIRONMENTS } from './config'
20
+ import { readDeviceStatus, watchDeviceStatus } from './api/deviceStatus'
21
+ import { asTransportFailure, createDaaUserClient, type DaaUserClient } from './api/DaaUserClient'
22
+ import { getSignedResource } from './api/signedResource'
23
+ import {
24
+ assertAddDeviceApproval,
25
+ assertDeviceKeyPolicy,
26
+ assertPublicApiOrigin,
27
+ DAA_ENVIRONMENTS,
28
+ isRecord,
29
+ } from './config'
22
30
  import type { DaaEnvironment, DaaSdkConfiguration, DeviceKeyPolicy } from './config'
23
31
  import { contractViolation } from './errors'
32
+ import type { DeviceStatus } from './models/DeviceStatus'
24
33
  import {
25
34
  assertAuthKeyMatchesContext,
26
35
  isActiveDaaUserContext,
36
+ restoreDaaUserContext,
27
37
  type DaaUserContext,
38
+ type DeviceContext,
28
39
  } from './models/DaaUserContext'
29
40
  import {
30
- createOwnerAuthKeyResolver,
41
+ createAppOwnerKeys,
31
42
  type AppAuthKeyResolver,
43
+ type AppOwnerKeys,
32
44
  } from './securekey/ownerAuthKeyResolver'
33
- import { assertAppId } from './securekey/alias'
45
+ import { assertAppId, assertClientEntityId } from './securekey/alias'
34
46
  import { assertNativeModuleKeyPolicyIfPresent } from './securekey/resolveNativeBridge'
35
- import type { DaaTransport } from './transport/DaaTransport'
47
+ import type { RegisteredOwnerAuthKey } from './securekey/SecureKey'
48
+ import type { DaaHttpRequest, DaaTransport } from './transport/DaaTransport'
49
+ import { toDeviceContext } from './wire/deviceContextPayload'
50
+
51
+ /**
52
+ * The result of {@link DaaClient.restore}.
53
+ *
54
+ * - `ACTIVE` — Circle confirmed the AuthKey registered on this device; pass
55
+ * `context` to {@link DaaClient.forUser}.
56
+ * - `no_local_key` — this device holds no registered AuthKey for that
57
+ * `clientEntityId`: the app was reinstalled, the key was forgotten, or the
58
+ * `clientEntityId` is not the one this device enrolled. Run the social login
59
+ * ceremony (`auth.prepareSocialLogin`) when the user chooses to sign in.
60
+ *
61
+ * Every other outcome is a thrown `DaaError`, never a variant here, so an app
62
+ * cannot mistake a failure for "no key" and silently start a new login.
63
+ */
64
+ export type SessionRestoreResult =
65
+ Readonly<{ status: 'ACTIVE'; context: DaaUserContext }> | Readonly<{ status: 'no_local_key' }>
66
+
67
+ const NO_LOCAL_KEY: SessionRestoreResult = Object.freeze({ status: 'no_local_key' })
36
68
 
37
69
  /**
38
70
  * Root DAA client.
@@ -60,6 +92,17 @@ export class DaaClient {
60
92
  * from nowhere else.
61
93
  */
62
94
  readonly #authKeys: AppAuthKeyResolver
95
+ /**
96
+ * The same store as {@link #authKeys}, with the read-only and forget
97
+ * operations session restore needs. `#`-private for the same reason.
98
+ */
99
+ readonly #ownerKeys: AppOwnerKeys
100
+ /**
101
+ * One in-flight restore per `clientEntityId`. Concurrent callers share the
102
+ * promise — one user-authentication prompt, one signed request — and the
103
+ * entry is removed once it settles, so a later call starts afresh.
104
+ */
105
+ readonly #restores = new Map<string, Promise<SessionRestoreResult>>()
63
106
 
64
107
  constructor(config: DaaSdkConfiguration) {
65
108
  if (!config.appId) {
@@ -80,6 +123,7 @@ export class DaaClient {
80
123
  assertAppId(config.appId)
81
124
  const publicApiOrigin = assertPublicApiOrigin(config.environment, config.publicApiOrigin)
82
125
  const keyPolicy = assertDeviceKeyPolicy(config.keyPolicy)
126
+ const addDeviceApproval = assertAddDeviceApproval(config.addDeviceApproval)
83
127
  // When DaaSecureKey is present, fail closed if it declares a weaker policy
84
128
  // than the configured closed set. Absent (Node / Jest) is not a pass —
85
129
  // resolveNativeBridge() still checks on first AuthKey use.
@@ -89,19 +133,20 @@ export class DaaClient {
89
133
  // Built eagerly, but it resolves nothing until something asks: the Expo
90
134
  // DaaSecureKey module is reached on first resolution, so constructing a
91
135
  // DaaClient still does not require it.
92
- this.#authKeys = createOwnerAuthKeyResolver(
136
+ this.#ownerKeys = createAppOwnerKeys(
93
137
  { appId: config.appId, environment: config.environment },
94
138
  null,
95
139
  )
140
+ this.#authKeys = this.#ownerKeys.resolveOrCreate
96
141
  // Constructed eagerly. Prepare needs no AuthKey and no DaaSecureKey. The
97
- // Expo DaaRegistration module (CSPRNG, flow key, receipt signature
98
- // verification) is resolved on first prepare, not here — matching
99
- // randomBytes / randomUuidV4. A host missing that module fails closed at
100
- // login. Jest injects a fake. AuthKey selection is lazy on Social Session.
142
+ // Expo DaaRegistration module (CSPRNG, flow key) is resolved on first
143
+ // prepare, not here — matching randomBytes / randomUuidV4. A host missing
144
+ // that module fails closed at login. Jest injects a fake. AuthKey selection
145
+ // is lazy on Social Session.
101
146
  this.#auth = new AuthClient({
102
147
  transport: config.transport,
103
- authKeys: this.#authKeys,
104
- environment: config.environment,
148
+ ownerKeys: this.#ownerKeys,
149
+ addDeviceApproval,
105
150
  })
106
151
  }
107
152
 
@@ -129,9 +174,12 @@ export class DaaClient {
129
174
  /**
130
175
  * The authenticated operations surface for one user.
131
176
  *
132
- * Opens only for an `ACTIVE` `DaaUserContext` decoded from Device Registration
133
- * Complete. A fabricated object, a `RECOVERY_PENDING` result, or a missing
134
- * context fail closed — they are not an Owner-bound credential.
177
+ * Opens only for an `ACTIVE` `DaaUserContext` this SDK minted: one decoded
178
+ * from Device Registration Complete, or one returned by {@link restore} after
179
+ * the service confirmed the stored registration. Both are bound to the local
180
+ * AuthKey's thumbprint, which every signed operation re-checks. A fabricated
181
+ * object, a `RECOVERY_PENDING` result, or a missing context fail closed —
182
+ * they are not an Owner-bound credential.
135
183
  *
136
184
  * The context is carried into the surface rather than only checked at the
137
185
  * door. `deviceContext.authKeyId` is the `kid` every signed write's
@@ -164,8 +212,298 @@ export class DaaClient {
164
212
  return authKey
165
213
  },
166
214
  authKeyId: context.deviceContext.authKeyId,
215
+ clientEntityId,
167
216
  },
168
217
  this.#publicApiOrigin,
169
218
  )
170
219
  }
220
+ /**
221
+ * Restore a signed-in user after an app restart with the AuthKey this device
222
+ * already registered, instead of a new social login.
223
+ *
224
+ * `clientEntityId` is the value the app stored, keyed by its own user id,
225
+ * when that user last completed login (`DaaUserContext.clientEntityId`). It
226
+ * only selects which local key to look for; it grants nothing by itself — see
227
+ * the `OwnerKeyIdentity` note in `securekey/SecureKey.ts`.
228
+ *
229
+ * Steps:
230
+ *
231
+ * 1. Look up the registered AuthKey and the `authKeyId` recorded when Circle
232
+ * registered it. This never creates a key and never prompts. None found
233
+ * resolves `{ status: 'no_local_key' }`.
234
+ * 2. Sign `GET /v1/accounts/auth/context` (`get_device_context`) with that
235
+ * key, `kid` = the stored `authKeyId`. This is the one user-authentication
236
+ * prompt (biometrics or device credential).
237
+ * 3. Require the returned `authKeyId` and `ownerBindingId` to equal the
238
+ * stored ones, then return an `ACTIVE` context bound to the key, for
239
+ * {@link forUser}.
240
+ *
241
+ * Call it while the app is in the foreground: iOS cannot show the
242
+ * authentication prompt during a background launch.
243
+ *
244
+ * Concurrent calls for the same `clientEntityId` share one restore.
245
+ *
246
+ * On failure this deletes nothing and starts no login. An application must
247
+ * not do either automatically: keep the key, report the error, and let the
248
+ * user decide (retry, or sign in again). A throw is never "no key" — that is
249
+ * only ever the `no_local_key` result. In particular a native failure while
250
+ * reading the key (for example its local protection metadata is
251
+ * unreadable) throws through the usual native error mapping; it is not
252
+ * turned into `no_local_key`, so it must not start enrollment either.
253
+ *
254
+ * `clientEntityId` must be the lowercase UUID exactly as
255
+ * `DaaUserContext.clientEntityId` returned it. The key slot is derived from
256
+ * those exact characters, so an uppercase copy (for example after a round
257
+ * trip through Swift's `UUID.uuidString`) would find no key; it is rejected
258
+ * instead of being reported as `no_local_key`.
259
+ *
260
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a
261
+ * `clientEntityId` that is not a lowercase UUID, for a returned `authKeyId`
262
+ * or `ownerBindingId` that does not match the stored one, for a key
263
+ * forgotten while the restore was reading it, for a response the SDK
264
+ * cannot read, and when the service rejects the device
265
+ * authorization (the credential is no longer accepted — the same mapping
266
+ * as every signed write; on a revoked or unknown AuthKey the service
267
+ * answers `403` with DAA status `420036`). The application's response is
268
+ * the same for all of them: keep the key and offer sign-in. One exception:
269
+ * on iOS a prompt the system or the app interrupted also arrives as
270
+ * `contract_violation` today, so retry `restore` in the foreground first
271
+ * if the app left it during the prompt (see the README);
272
+ * `user_cancelled` when the user dismisses the authentication prompt:
273
+ * nothing was sent and the key is untouched, so calling `restore` again
274
+ * prompts again; `local_user_authentication_required` when user
275
+ * authentication failed or is unavailable; `clock_skew` when the service
276
+ * rejected the authorization because the device clock is off, the same as
277
+ * `refreshContext`; `api` for any other status besides `200`; `transport` if
278
+ * the consumer's transport throws, with the thrown value as `err.cause`.
279
+ */
280
+ async restore(args: { clientEntityId: string }): Promise<SessionRestoreResult> {
281
+ const clientEntityId = requireClientEntityId(args)
282
+ let inFlight = this.#restores.get(clientEntityId)
283
+ if (inFlight === undefined) {
284
+ inFlight = this.#restoreOnce(clientEntityId).finally(() => {
285
+ this.#restores.delete(clientEntityId)
286
+ })
287
+ this.#restores.set(clientEntityId, inFlight)
288
+ }
289
+ return inFlight
290
+ }
291
+
292
+ /**
293
+ * Delete this device's AuthKey for `clientEntityId`, and its local
294
+ * registration record.
295
+ *
296
+ * Call it only on an explicit user action, such as "remove this device",
297
+ * confirming the removal of a key Circle has revoked, or confirming that the
298
+ * user starts over after this new device was declined (status `denied` from
299
+ * {@link getDeviceStatus}, or a registration refused with `device_denied`) —
300
+ * never as an
301
+ * automatic reaction to a failed {@link restore}, a rejected write, or any
302
+ * other status or error. The SDK never deletes the key by itself.
303
+ *
304
+ * It is local only and does NOT revoke the key with Circle, which keeps the
305
+ * registered public key. It cannot be undone: the next login on this device registers a new
306
+ * AuthKey. Succeeds when no key exists.
307
+ *
308
+ * Contexts and `DaaUserClient`s already handed out are not invalidated by
309
+ * this call. Operations that need a new signature fail once the key is gone,
310
+ * but an authorization signed before the delete stays valid, because Circle
311
+ * still accepts the key: a contract execution prepared earlier can still be
312
+ * sent with `contractExecutions.submit`. Close those clients and drop any
313
+ * prepared value you do not intend to send as part of the same action.
314
+ *
315
+ * Do not call it while a login or a {@link restore} for the same
316
+ * `clientEntityId` is still in flight; finish or abandon that first. A
317
+ * restore that is reading the key when the delete starts fails closed with
318
+ * `contract_violation`. A login ceremony that already holds the key is not
319
+ * cancelled: whether its key survives depends on the order the native SDK
320
+ * runs the two calls in, so the outcome is not defined.
321
+ *
322
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a
323
+ * `clientEntityId` that is not a lowercase UUID, and for a native failure
324
+ * that has no more specific mapping. Native failures go through the same
325
+ * mapping as every other AuthKey operation, so the delete can also report
326
+ * `local_user_authentication_required` or `device_not_initialized` if the
327
+ * platform raises one of those.
328
+ */
329
+ async forgetLocalKey(args: { clientEntityId: string }): Promise<void> {
330
+ const clientEntityId = requireClientEntityId(args)
331
+ await this.#ownerKeys.forget(clientEntityId)
332
+ }
333
+
334
+ /**
335
+ * The add-a-device status of this device's new AuthKey:
336
+ * `GET /v1/accounts/auth/devices/{authKeyId}`, with the `authKeyId` DAA
337
+ * returned when it added the key as waiting. One read, for example when the app is reopened
338
+ * while a request was waiting (the app must have saved `authKeyId`); use
339
+ * {@link watchDeviceStatus} to wait for the outcome.
340
+ *
341
+ * `denied` means the user declined this device on another one. The key
342
+ * can't ask again: after the user confirms, the app may delete it with
343
+ * {@link forgetLocalKey} and sign in again with a new key. The SDK never
344
+ * deletes it by itself.
345
+ *
346
+ * `authKeyId` may be in either case.
347
+ *
348
+ * @throws DaaError with `detail.kind === 'contract_violation'` for an
349
+ * `authKeyId` that is not a UUID string and for a response the SDK cannot read;
350
+ * `transport` (retryable) when the transport throws; `api` for any status
351
+ * but `200`, including `404` when DAA doesn't know the key.
352
+ */
353
+ async getDeviceStatus(args: { authKeyId: string }): Promise<DeviceStatus> {
354
+ return await readDeviceStatus(
355
+ withTransportFailure(this.#config.transport),
356
+ requireAuthKeyId(args),
357
+ )
358
+ }
359
+
360
+ /**
361
+ * Wait for the add-a-device outcome: read {@link getDeviceStatus} until it is
362
+ * no longer `pending_approval` or `pending_activation` (so `active`,
363
+ * `denied`, `expired`, `cancelled`, or `unrecognized`), and resolve with it.
364
+ *
365
+ * Reads every 5 s while `pending_approval`, and during the cool-down
366
+ * (`pending_activation`) at `readyAt` or every 30 s, whichever is sooner.
367
+ * DAA reports `expired` once `expiresAt` passes on its clock, so this
368
+ * device's clock never ends the watch. After a retryable failure the wait
369
+ * doubles, up to 30 s, with a random part so that watches that failed
370
+ * together don't retry together. `onStatus` gets the first status and every
371
+ * change; if it throws, the watch rejects with that error. Aborting `signal`
372
+ * stops the watch at once, even during a read, and rejects with the
373
+ * signal's reason; a late response is ignored.
374
+ *
375
+ * Every call runs its own loop. Run one watch per `authKeyId` and abort it
376
+ * when the screen that started it goes away: each extra watch is another
377
+ * read every 5 s against the partner's rate limit for this route.
378
+ *
379
+ * @throws the same errors as {@link getDeviceStatus}, and
380
+ * `contract_violation` for an `onStatus` that is not a function or a
381
+ * `signal` that is not an `AbortSignal`, before anything is sent.
382
+ * Ones marked `retryable` (`transport`, or `api` with `429`/`5xx`) are
383
+ * retried, and the watch rejects with the last one after 10 in a row; any
384
+ * other, such as a transport's own `DaaError` with `retryable: false`,
385
+ * rejects at once.
386
+ */
387
+ async watchDeviceStatus(args: {
388
+ authKeyId: string
389
+ onStatus?: (status: DeviceStatus) => void
390
+ signal?: AbortSignal
391
+ }): Promise<DeviceStatus> {
392
+ return await watchDeviceStatus(
393
+ withTransportFailure(this.#config.transport),
394
+ requireWatchArgs(args),
395
+ )
396
+ }
397
+
398
+ async #restoreOnce(clientEntityId: string): Promise<SessionRestoreResult> {
399
+ const registered = await this.#ownerKeys.resolveExisting(clientEntityId)
400
+ if (registered === null) {
401
+ return NO_LOCAL_KEY
402
+ }
403
+ // Read before any prompt: the thumbprint comes from the public key.
404
+ const authKeyThumbprint = await registered.authKey.thumbprint()
405
+ const deviceContext = await this.#confirmRegistration(registered)
406
+ return Object.freeze({
407
+ status: 'ACTIVE',
408
+ context: restoreDaaUserContext(clientEntityId, deviceContext, authKeyThumbprint),
409
+ })
410
+ }
411
+
412
+ /**
413
+ * Ask the service for the device context with a registered-device
414
+ * authorization signed by the stored key, through the same
415
+ * `getSignedResource` path as `DaaUserClient.refreshContext`, and require
416
+ * that it names the same `authKeyId` and `ownerBindingId` that were stored
417
+ * when the key was acknowledged.
418
+ *
419
+ * A different `ownerBindingId` fails closed rather than being adopted: the
420
+ * stored record and the service disagree about which Owner binding this key
421
+ * belongs to, and the SDK has no basis to pick one. Re-registration through
422
+ * login is the path that legitimately records new identifiers.
423
+ */
424
+ async #confirmRegistration(registered: RegisteredOwnerAuthKey): Promise<DeviceContext> {
425
+ const deviceContext = await getSignedResource({
426
+ transport: withTransportFailure(this.#config.transport),
427
+ operation: 'get_device_context',
428
+ authKey: registered.authKey,
429
+ authKeyId: registered.authKeyId,
430
+ expectedStatus: 200,
431
+ decode: toDeviceContext,
432
+ })
433
+ if (deviceContext.authKeyId !== registered.authKeyId) {
434
+ throw contractViolation('the restored device context names a different AuthKey')
435
+ }
436
+ if (deviceContext.ownerBindingId !== registered.ownerBindingId) {
437
+ throw contractViolation('the restored device context names a different Owner binding')
438
+ }
439
+ return deviceContext
440
+ }
441
+ }
442
+
443
+ function requireClientEntityId(args: unknown): string {
444
+ const clientEntityId = isRecord(args) ? args['clientEntityId'] : undefined
445
+ if (typeof clientEntityId !== 'string') {
446
+ throw contractViolation('clientEntityId must be a UUID')
447
+ }
448
+ // The same rule enrollment applies when it derives the key alias (lowercase
449
+ // UUID), checked up front so a bad value never reaches the key store.
450
+ assertClientEntityId(clientEntityId)
451
+ return clientEntityId
452
+ }
453
+
454
+ /** The `authKeyId` of a status call; the UUID check itself is `readDeviceStatus`'s. */
455
+ function requireAuthKeyId(args: unknown): string {
456
+ const authKeyId = isRecord(args) ? args['authKeyId'] : undefined
457
+ if (typeof authKeyId !== 'string') {
458
+ throw contractViolation('authKeyId must be a UUID')
459
+ }
460
+ return authKeyId
461
+ }
462
+
463
+ /** `watchDeviceStatus`'s arguments, checked before the first read. */
464
+ function requireWatchArgs(args: unknown): {
465
+ authKeyId: string
466
+ onStatus?: (status: DeviceStatus) => void
467
+ signal?: AbortSignal
468
+ } {
469
+ const authKeyId = requireAuthKeyId(args)
470
+ const { onStatus, signal } = args as Record<string, unknown>
471
+ if (onStatus !== undefined && typeof onStatus !== 'function') {
472
+ throw contractViolation('onStatus must be a function')
473
+ }
474
+ // Everything the watch uses, so a partial object fails here, before the
475
+ // first read, not in a cleanup that would leave the watch never settling.
476
+ if (
477
+ signal !== undefined &&
478
+ !(
479
+ isRecord(signal) &&
480
+ typeof signal['aborted'] === 'boolean' &&
481
+ typeof signal['addEventListener'] === 'function' &&
482
+ typeof signal['removeEventListener'] === 'function'
483
+ )
484
+ ) {
485
+ throw contractViolation('signal must be an AbortSignal')
486
+ }
487
+ return {
488
+ authKeyId,
489
+ ...(onStatus === undefined ? {} : { onStatus: onStatus as (status: DeviceStatus) => void }),
490
+ ...(signal === undefined ? {} : { signal: signal as unknown as AbortSignal }),
491
+ }
492
+ }
493
+
494
+ /**
495
+ * The consumer's transport, with a throw reported as the spec's `transport`
496
+ * error through the same `asTransportFailure` every `DaaUserClient` operation
497
+ * uses.
498
+ */
499
+ function withTransportFailure(transport: DaaTransport): DaaTransport {
500
+ return Object.freeze({
501
+ send: async (request: DaaHttpRequest) => {
502
+ try {
503
+ return await transport.send(request)
504
+ } catch (err) {
505
+ throw asTransportFailure(err, request)
506
+ }
507
+ },
508
+ })
171
509
  }
@@ -186,6 +186,9 @@ export class AccountsClient {
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
  * `detail.kind === 'api'` for a status other than the documented `201`; and
190
193
  * `detail.kind === 'transport'` if the consumer's transport throws, with the
191
194
  * thrown value as `err.cause` and the request's `idempotencyKey` on the
@@ -20,30 +20,18 @@ import {
20
20
  newRegistrationCodeVerifier,
21
21
  registrationCodeChallengeS256,
22
22
  } from '../auth/registrationCodeVerifier'
23
- import {
24
- checkPrepareReceipt,
25
- pinnedPrepareReceiptTrustAnchor,
26
- type PrepareReceiptTrustAnchor,
27
- } from '../auth/prepareReceipt'
28
23
  import {
29
24
  defaultRegistrationFlowKeyProvider,
30
25
  releaseQuietly,
31
26
  type RegistrationFlowKeyProvider,
32
27
  } from '../auth/RegistrationFlowKey'
33
- import type { DaaEnvironment } from '../config'
34
- import { fromBase64Url } from '../crypto/base64url'
35
- import { p256JwkThumbprint } from '../crypto/jwkThumbprint'
36
28
  import { randomUuidV4 } from '../crypto/random'
37
29
  import { serializeBody } from '../crypto/serialization'
38
- import { contractViolation, isDaaError, withRequestId } from '../errors'
30
+ import { contractViolation } from '../errors'
39
31
  import { PreparedSocialLogin } from '../models/PreparedSocialLogin'
40
- import {
41
- createOwnerAuthKeyResolver,
42
- type AppAuthKeyResolver,
43
- } from '../securekey/ownerAuthKeyResolver'
32
+ import { createAppOwnerKeys, type AppOwnerKeys } from '../securekey/ownerAuthKeyResolver'
44
33
  import type { AppKeyIdentity, OwnerAuthKey, SecureKeyStore } from '../securekey/SecureKey'
45
34
  import type { DaaTransport } from '../transport/DaaTransport'
46
- import { headerValueIgnoringCase } from '../transport/headers'
47
35
  import { toSocialLoginRequest } from '../wire/socialLoginRequestPayload'
48
36
  import { loginStepFailure } from './loginFailure'
49
37
  import { decodeResourceResponse } from './resourceRequest'
@@ -86,8 +74,7 @@ const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/
86
74
  *
87
75
  * Prepare does not touch an AuthKey. AuthKey selection happens only after
88
76
  * the Social Session response, via the injected store (tests) or the native
89
- * store (production). Prepare does check the DAA-signed Prepare receipt, before
90
- * it returns anything to the application — see `prepareSocialLogin`.
77
+ * store (production).
91
78
  *
92
79
  * Not constructible by a consumer: exported from `index.ts` as a type only, and
93
80
  * the `#transport` field makes the type nominal.
@@ -95,9 +82,8 @@ const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/
95
82
  export class AuthClient {
96
83
  readonly #transport: DaaTransport
97
84
  readonly #registrationFlowKeys: RegistrationFlowKeyProvider
98
- readonly #authKeys: AppAuthKeyResolver
99
- readonly #environment: DaaEnvironment | null
100
- readonly #prepareReceiptTrustAnchor: PrepareReceiptTrustAnchor | null
85
+ readonly #ownerKeys: AppOwnerKeys
86
+ readonly #addDeviceApproval: boolean
101
87
 
102
88
  /** @internal Constructed only through `DaaClient`. */
103
89
  constructor(args: {
@@ -123,37 +109,21 @@ export class AuthClient {
123
109
  */
124
110
  identity?: AppKeyIdentity
125
111
  /**
126
- * The resolver `DaaClient` shares between login and `forUser`, so both reach
127
- * one store and one in-flight `resolveOrCreate` map for this identity.
128
- * Unset, this client builds its own from `identity`/`secureKeys` — which is
129
- * what a test constructing `AuthClient` directly wants, since it has no
130
- * second holder to share with.
112
+ * The key operations `DaaClient` shares between login, `forUser` and
113
+ * `restore`, so all reach one store and one in-flight `resolveOrCreate` map
114
+ * for this identity. Unset, this client builds its own from
115
+ * `identity`/`secureKeys` — which is what a test constructing `AuthClient`
116
+ * directly wants, since it has no second holder to share with.
131
117
  */
132
- authKeys?: AppAuthKeyResolver
133
- /**
134
- * The configured environment: selects the pinned Prepare-receipt trust
135
- * anchor and is the value the receipt's `environment` claim must name.
136
- * Falls back to `identity.environment`.
137
- */
138
- environment?: DaaEnvironment
139
- /**
140
- * Test-only override of the pinned receipt trust anchor. Not reachable from
141
- * `DaaSdkConfiguration`: a consumer cannot choose the key that vouches for
142
- * its own relay's responses.
143
- */
144
- prepareReceiptTrustAnchor?: PrepareReceiptTrustAnchor | null
118
+ ownerKeys?: AppOwnerKeys
119
+ /** `DaaSdkConfiguration.addDeviceApproval`; off when unset. */
120
+ addDeviceApproval?: boolean
145
121
  }) {
146
122
  this.#transport = args.transport
147
123
  this.#registrationFlowKeys = args.registrationFlowKeys ?? defaultRegistrationFlowKeyProvider()
148
- this.#authKeys =
149
- args.authKeys ?? createOwnerAuthKeyResolver(args.identity ?? null, args.secureKeys ?? null)
150
- this.#environment = args.environment ?? args.identity?.environment ?? null
151
- this.#prepareReceiptTrustAnchor =
152
- args.prepareReceiptTrustAnchor !== undefined
153
- ? args.prepareReceiptTrustAnchor
154
- : this.#environment === null
155
- ? null
156
- : pinnedPrepareReceiptTrustAnchor(this.#environment)
124
+ this.#ownerKeys =
125
+ args.ownerKeys ?? createAppOwnerKeys(args.identity ?? null, args.secureKeys ?? null)
126
+ this.#addDeviceApproval = args.addDeviceApproval ?? false
157
127
  Object.freeze(this)
158
128
  }
159
129
 
@@ -166,25 +136,13 @@ export class AuthClient {
166
136
  * bytes. Durable persistence across a restart is not implemented — see
167
137
  * `models/PreparedSocialLogin.ts`.
168
138
  *
169
- * The Prepare receipt is checked before this resolves, so an application
170
- * never holds a nonce from a response that failed that check. With no trust
171
- * anchor pinned for the environment — every environment in this release —
172
- * the SDK does no receipt work: a receipt the service sends is ignored, login
173
- * proceeds as if none arrived, and `prepareReceiptJws` is null. With an
174
- * anchor pinned, the receipt is required and must verify. See
175
- * `checkPrepareReceipt` in
176
- * `auth/prepareReceipt.ts`.
177
- *
178
- * @throws DaaError with `detail.kind === 'prepare_receipt_invalid'` when an
179
- * anchor is pinned and the receipt is missing, malformed, fails its
180
- * signature or claim checks, has expired, or the platform verifier is
181
- * missing or fails; `contract_violation` for a rejected provider, unusable
182
- * local key material, a missing native DaaRegistration module, or a
183
- * response the SDK cannot read;
184
- * `login_request_expired` for `410`; `idempotency_conflict` for a `409`
185
- * with `IDEMPOTENCY_KEY_REUSED` (`420034`); `contract_violation` with the
186
- * correlation id for `LOGIN_REQUEST_CONSUMED` (`420039`); and `api` for any
187
- * other status besides the documented `201`, including any other `409`.
139
+ * @throws DaaError with `detail.kind === 'contract_violation'` for a rejected
140
+ * provider, unusable local key material, a missing native DaaRegistration
141
+ * module, a response the SDK cannot read, and (with the correlation id)
142
+ * `LOGIN_REQUEST_CONSUMED` (`420039`); `login_request_expired` for `410`;
143
+ * `idempotency_conflict` for a `409` with `IDEMPOTENCY_KEY_REUSED`
144
+ * (`420034`); and `api` for any other status besides the documented `201`,
145
+ * including any other `409`.
188
146
  * Whatever the consumer's transport throws is rethrown unchanged.
189
147
  */
190
148
  async prepareSocialLogin(input: { provider: string }): Promise<PreparedSocialLogin> {
@@ -247,41 +205,19 @@ export class AuthClient {
247
205
  expectedStatus: 201,
248
206
  decode: toSocialLoginRequest,
249
207
  })
250
- const verifiedReceipt = await checkPrepareReceipt(
251
- prepared.prepareReceiptJws,
252
- this.#prepareReceiptTrustAnchor,
253
- () => ({
254
- loginRequestId: prepared.loginRequestId,
255
- nonce: prepared.oidcNonce,
256
- provider,
257
- environment: this.#requireEnvironmentForReceipt(),
258
- // The SDK's own values, generated before Prepare was sent: the two a
259
- // relay substituting another attempt cannot make match.
260
- registrationCodeChallenge,
261
- registrationFlowKeyThumbprint: p256JwkThumbprint(
262
- fromBase64Url(registrationFlowPublicKey),
263
- ),
264
- }),
265
- ).catch((err: unknown) => {
266
- // A rejected receipt came from this response, so it names the
267
- // response's request id. A `contract_violation` from the check is this
268
- // SDK's own configuration fault and is left as it is.
269
- throw isDaaError(err) && err.detail.kind === 'prepare_receipt_invalid'
270
- ? withRequestId(err, headerValueIgnoringCase(response.headers, 'X-Request-Id'))
271
- : err
272
- })
273
208
  return new PreparedSocialLogin({
274
209
  loginRequestId: prepared.loginRequestId,
275
210
  oidcNonce: prepared.oidcNonce,
276
211
  oidcState: prepared.oidcState,
277
- // Only a receipt that verified; an ignored one is not handed on.
278
- prepareReceiptJws: verifiedReceipt === null ? null : verifiedReceipt.compactJws,
279
212
  expiresAt: prepared.expiresAt,
280
213
  registrationCodeVerifier,
281
214
  registrationFlowKey,
282
215
  idempotencyKey,
283
216
  transport: this.#transport,
284
217
  resolveAuthKey: (clientEntityId: string) => this.#resolveAuthKey(clientEntityId),
218
+ hasRegisteredAuthKey: (clientEntityId: string) =>
219
+ this.#hasRegisteredAuthKey(clientEntityId),
220
+ addDeviceApproval: this.#addDeviceApproval,
285
221
  })
286
222
  } catch (error) {
287
223
  // Keep the key on a successful PreparedSocialLogin — Complete still needs
@@ -311,18 +247,17 @@ export class AuthClient {
311
247
  * `DaaClient` owns, not through this client.
312
248
  */
313
249
  async #resolveAuthKey(clientEntityId: string): Promise<OwnerAuthKey> {
314
- return this.#authKeys(clientEntityId)
250
+ return this.#ownerKeys.resolveOrCreate(clientEntityId)
315
251
  }
316
252
 
317
253
  /**
318
- * Reached only when a receipt is being verified against an anchor. A missing
319
- * environment is this SDK's own wiring fault, so it stays `contract_violation`.
254
+ * Whether this device holds an AuthKey Circle registered for
255
+ * `clientEntityId`. Read-only: it never creates a key and never prompts.
256
+ * Answers a boolean, not the key, for the same reason as
257
+ * {@link #resolveAuthKey}.
320
258
  */
321
- #requireEnvironmentForReceipt(): DaaEnvironment {
322
- if (this.#environment === null) {
323
- throw contractViolation('verifying a Prepare receipt requires the configured environment')
324
- }
325
- return this.#environment
259
+ async #hasRegisteredAuthKey(clientEntityId: string): Promise<boolean> {
260
+ return (await this.#ownerKeys.resolveExisting(clientEntityId)) !== null
326
261
  }
327
262
  }
328
263