@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
@@ -18,29 +18,160 @@
18
18
 
19
19
  import {
20
20
  authorizeRegistrationComplete,
21
- DEVICE_REGISTRATION_COMPLETE_PATH,
21
+ KEY_REGISTRATION_PATH,
22
22
  REGISTRATION_DEVICE_AUTHORIZATION_HEADER,
23
23
  REGISTRATION_FLOW_AUTHORIZATION_HEADER,
24
24
  } from '../auth/registrationAuthorization'
25
25
  import { releaseQuietly, type RegistrationFlowKey } from '../auth/RegistrationFlowKey'
26
+ import { toBase64Url } from '../crypto/base64url'
27
+ import { canonicalBytes32, codeSeal } from '../crypto/matchingCode'
26
28
  import { randomUuidV4 } from '../crypto/random'
27
29
  import { serializeBody } from '../crypto/serialization'
28
- import { contractViolation } from '../errors'
29
- import type { OwnerAuthKey } from '../securekey/SecureKey'
30
- import type { DaaTransport } from '../transport/DaaTransport'
30
+ import { contractViolation, DaaError, registrationNotSaved } from '../errors'
31
+ import { requireBodyObject, requireKnownProperties } from '../validation/requestBody'
32
+ import type { AuthKeyRegistration, OwnerAuthKey } from '../securekey/SecureKey'
33
+ import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
31
34
  import { loginStepFailure } from '../api/loginFailure'
32
35
  import { decodeResourceResponse } from '../api/resourceRequest'
33
- import { toDeviceRegistrationResult } from '../wire/deviceRegistrationResultPayload'
36
+ import {
37
+ toDeviceRegistrationResult,
38
+ type DecodedDeviceRegistration,
39
+ } from '../wire/deviceRegistrationResultPayload'
40
+ import type { DeviceApprovalHint } from '../wire/pendingRegistrationPayload'
34
41
  import { bindAuthKeyToContext, type DeviceRegistrationResult } from './DaaUserContext'
42
+ import {
43
+ codeSecretFor,
44
+ codeSecretForRequest,
45
+ deleteStoredCodeSecret,
46
+ dropCodeSecret,
47
+ holdCodeSecret,
48
+ oneAtATime,
49
+ sealingCodeSecret,
50
+ } from './codeSecrets'
51
+ import { newPendingDeviceApproval } from './PendingDeviceApproval'
35
52
 
36
53
  const AUTH_KEY_PUBLIC_KEY = /^[A-Za-z0-9_-]{122}$/
54
+ /** The `type` that selects device key registration on `/v1/accounts/auth/keys`. */
55
+ const DEVICE_KEY_TYPE = 'deviceKey'
56
+
57
+ /**
58
+ * How long one queued `complete()` may run, authentication prompt and
59
+ * transport included, before it fails and the next step for the key starts.
60
+ * Without it, a `send()` that never settles would hold every later sign-in
61
+ * with the key (and every `sendCodeSecret()`) until the process exits. Reading the AuthKey before queuing has
62
+ * its own deadline of the same length.
63
+ */
64
+ const COMPLETE_DEADLINE_MS = 120_000
65
+
66
+ /**
67
+ * Save failures that mean the key is gone from the device: invalidated, or no
68
+ * longer there (`device_not_initialized` is what both native bridges report
69
+ * for a key not found). No retry could succeed, so these pass through as is.
70
+ */
71
+ const KEY_GONE_KINDS: ReadonlySet<string> = new Set(['key_invalidated', 'device_not_initialized'])
72
+
73
+ /**
74
+ * An `ACTIVE` or `PENDING_ACTIVATION` answer whose identifiers this device
75
+ * hasn't saved yet.
76
+ */
77
+ type UnsavedRegistration = Readonly<{
78
+ result: DeviceRegistrationResult
79
+ authKeyThumbprint: string
80
+ registration: AuthKeyRegistration
81
+ }>
82
+
83
+ /**
84
+ * The newest `ACTIVE` or `PENDING_ACTIVATION` answer per AuthKey thumbprint
85
+ * whose identifiers may not be saved yet. A retried save goes ahead only while
86
+ * its answer is still the newest: once a newer registration of the key
87
+ * answered, that one's
88
+ * identifiers are the ones to keep, and saving the older ones would overwrite
89
+ * them. Kept per process, like the key queue in `codeSecrets.ts`.
90
+ */
91
+ const newestAnswer = new Map<string, UnsavedRegistration>()
92
+
93
+ /**
94
+ * One queued `complete()`: `late` once its deadline passed. `onLate` runs at
95
+ * the deadline if set: a save still running then keeps its answer for the
96
+ * next `complete()`. `afterDeadline` runs once the call settled in time, still
97
+ * in the key's queue, outside the deadline.
98
+ */
99
+ type QueuedComplete = {
100
+ late: boolean
101
+ sentSecret: Uint8Array | null
102
+ onLate: (() => void) | null
103
+ afterDeadline: (() => Promise<void>) | null
104
+ }
105
+
106
+ /**
107
+ * Runs `step` and settles within `COMPLETE_DEADLINE_MS`. At the deadline the
108
+ * call fails and the key's queue moves on, but `step` may still be running.
109
+ * It checks `late`: it doesn't send after it, and it ignores a response that
110
+ * comes back after it, so a late answer can't drop the secret. A secret it
111
+ * already sent is held (`holdCodeSecret`): DAA may still add that request as
112
+ * waiting with its seal after a later Complete for the key was refused.
113
+ */
114
+ async function withDeadline<T>(step: (call: QueuedComplete) => Promise<T>): Promise<T> {
115
+ const call: QueuedComplete = { late: false, sentSecret: null, onLate: null, afterDeadline: null }
116
+ let timer: ReturnType<typeof setTimeout> | undefined
117
+ const deadline = new Promise<never>((_, reject) => {
118
+ timer = setTimeout(() => {
119
+ call.late = true
120
+ if (call.sentSecret !== null) {
121
+ holdCodeSecret(call.sentSecret)
122
+ }
123
+ call.onLate?.()
124
+ reject(completeTimedOut())
125
+ }, COMPLETE_DEADLINE_MS)
126
+ })
127
+ try {
128
+ return await Promise.race([step(call), deadline])
129
+ } finally {
130
+ clearTimeout(timer)
131
+ // Set only by a step that settled before its deadline: nothing is awaited
132
+ // between setting it and settling, so a timer can't fire in between.
133
+ await call.afterDeadline?.()
134
+ }
135
+ }
136
+
137
+ function completeTimedOut(): DaaError {
138
+ return new DaaError(
139
+ { kind: 'transport', retryable: false },
140
+ `DAA: Device Registration Complete did not finish within ${COMPLETE_DEADLINE_MS / 1000} seconds`,
141
+ )
142
+ }
143
+
144
+ const NO_WAITING_REQUEST_KINDS: ReadonlySet<string> = new Set([
145
+ 'device_registration_limit',
146
+ 'device_denied',
147
+ 'device_approval_conflict',
148
+ 'device_approval_unavailable',
149
+ ])
150
+
151
+ const COMPLETE_INPUT_PROPERTIES = Object.freeze(['riskSignals', 'confirmAddDevice'])
152
+ const RISK_SIGNAL_PROPERTIES = Object.freeze(['ipAddress', 'sessionId', 'deviceId'])
153
+
154
+ /**
155
+ * Optional device signals for this registration, passed unchanged. DAA uses
156
+ * them to show the device's model and OS in the device list. None of the
157
+ * members is required.
158
+ */
159
+ export type DeviceRegistrationRiskSignals = Readonly<{
160
+ ipAddress?: string
161
+ sessionId?: string
162
+ deviceId?: string
163
+ }>
164
+
165
+ export type { DeviceApprovalHint }
37
166
 
38
167
  /**
39
168
  * Pending device registration after Social Session.
40
169
  *
41
- * `complete()` is Device Registration Complete: the four-field body
42
- * (`idempotencyKey`, `registrationHandle`, `registrationCodeVerifier`,
43
- * `authKeyPublicKey`), including the registration code verifier minted before
170
+ * `complete()` is Device Registration Complete: `POST /v1/accounts/auth/keys`
171
+ * with the body (`type: "deviceKey"`, `idempotencyKey`, `registrationHandle`,
172
+ * `registrationCodeVerifier`, `deviceKeyPublicKey`, and `codeSeal` with
173
+ * `addDeviceApproval` on), plus `riskSignals` when the caller passes them,
174
+ * including the registration code verifier minted before
44
175
  * Prepare and redeemed here against the challenge Prepare sent. Two JWSs
45
176
  * authorize it — `X-Device-Authorization` (signed by the proposed AuthKey) and
46
177
  * `X-Registration-Flow-Authorization` (signed by the per-attempt flow key from
@@ -49,14 +180,29 @@ const AUTH_KEY_PUBLIC_KEY = /^[A-Za-z0-9_-]{122}$/
49
180
  * handle, profile, AuthKey thumbprint, code verifier). Building and signing
50
181
  * those proofs is `authorizeRegistrationComplete`.
51
182
  *
52
- * Every device takes this same path, first or additional. A new device on an
53
- * existing Owner does social login and then this same registration, with the
54
- * same body; there is no approval from an already-registered device and
55
- * no mode to select. DAA adds the new AuthKey next to the Owner's existing
56
- * keys (additive registration).
183
+ * Every device takes this same path, first or additional, with the same body
184
+ * and no mode to select. A first device comes back `ACTIVE`. A new device on an
185
+ * Owner that already has an active device comes back `PENDING_APPROVAL`: DAA
186
+ * adds the key as waiting, and an existing device approves it after the user
187
+ * types the matching code this device shows (see `PendingDeviceApproval`).
188
+ * `codeSeal` is what makes that code possible, so it is sent on every
189
+ * registration: the SDK can't know beforehand which outcome DAA will return.
190
+ *
191
+ * With `addDeviceApproval` on, the SDK asks first. When the Session's
192
+ * `deviceApproval.required` says a new device would wait for approval and this
193
+ * device has no AuthKey Circle registered for the end user,
194
+ * `confirmationRequired` is `true` and this sign-in hasn't created a key. Ask
195
+ * the user whether to add this device (`deviceApproval.hasActiveDevice` says
196
+ * whether one of their devices can approve it), and call
197
+ * `complete({ confirmAddDevice: true })` only if they confirm. That creates
198
+ * the key, or reuses the one this device made for an earlier request, and
199
+ * registers it. DAA's answer still decides the outcome: a request already
200
+ * waiting comes back `PENDING_APPROVAL` again, and `ACTIVE` is possible where
201
+ * DAA doesn't add keys as waiting yet.
57
202
  *
58
- * There is no `abandon()`. If the caller backs out after Session without
59
- * calling `complete()`, the native flow-key cache is held until the process
203
+ * There is no `abandon()` here: call `PreparedSocialLogin.abandon()`, which
204
+ * releases the same flow key. If the caller backs out after Session without
205
+ * calling `complete()` or that `abandon()`, the native flow-key cache is held until the process
60
206
  * exits; `complete()` releases it in `finally`. The API has no cancel call for
61
207
  * a pending registration.
62
208
  *
@@ -71,122 +217,503 @@ export class PendingDeviceRegistration {
71
217
  * and normalises it here, so a consumer never sees the wire's disagreement.
72
218
  */
73
219
  readonly expiresAt: string
220
+ /**
221
+ * The Session's `deviceApproval`: whether a new device key for this end user
222
+ * would wait for approval, as DAA saw it when it answered. A hint for what to
223
+ * tell the user, not the outcome. `null` when DAA didn't send it.
224
+ */
225
+ readonly deviceApproval: DeviceApprovalHint | null
226
+ /**
227
+ * `true` when the user must confirm adding this device before `complete()`
228
+ * creates and registers a key: `addDeviceApproval` is on,
229
+ * `deviceApproval.required` is `true`, and this device has no AuthKey Circle
230
+ * registered for the end user. Call `complete({ confirmAddDevice: true })`
231
+ * only after the user confirms, or without asking when the app knows this
232
+ * device's request is still waiting (`DaaClient.getDeviceStatus` on the
233
+ * `authKeyId` it saved says `pending_approval`): a key waiting for approval
234
+ * isn't registered on the device yet, so it reads as no key here. If the
235
+ * user declines, call `abandon()` on the `PreparedSocialLogin` this came
236
+ * from: nothing was created, but its native flow key is otherwise held until
237
+ * the process exits.
238
+ */
239
+ readonly confirmationRequired: boolean
74
240
 
75
241
  readonly #transport: DaaTransport
76
242
  readonly #registrationCodeVerifier: string
77
243
  readonly #registrationFlowKey: RegistrationFlowKey
78
- readonly #authKey: OwnerAuthKey
244
+ /** `null` until `complete()` creates it, when `confirmationRequired`. */
245
+ #authKey: OwnerAuthKey | null
246
+ readonly #resolveAuthKey: () => Promise<OwnerAuthKey>
247
+ readonly #addDeviceApproval: boolean
79
248
  #consumed = false
249
+ // Set when DAA answered ACTIVE but saving its identifiers on this device
250
+ // failed: the next `complete()` retries only that save.
251
+ #unsaved: UnsavedRegistration | null = null
80
252
 
81
253
  /** @internal Constructed only by `PreparedSocialLogin.completeSocialSession`. */
82
254
  constructor(fields: {
83
255
  readonly registrationHandle: string
84
256
  readonly clientEntityId: string
85
257
  readonly expiresAt: string
258
+ readonly deviceApproval: DeviceApprovalHint | null
259
+ readonly confirmationRequired: boolean
86
260
  readonly transport: DaaTransport
87
261
  readonly registrationCodeVerifier: string
88
262
  readonly registrationFlowKey: RegistrationFlowKey
89
- readonly authKey: OwnerAuthKey
263
+ /** The AuthKey, or `null` to create it in `complete()` after confirmation. */
264
+ readonly authKey: OwnerAuthKey | null
265
+ readonly resolveAuthKey: () => Promise<OwnerAuthKey>
266
+ readonly addDeviceApproval: boolean
90
267
  }) {
91
268
  this.registrationHandle = fields.registrationHandle
92
269
  this.clientEntityId = fields.clientEntityId
93
270
  this.expiresAt = fields.expiresAt
271
+ this.deviceApproval = fields.deviceApproval
272
+ this.confirmationRequired = fields.confirmationRequired
94
273
  this.#transport = fields.transport
95
274
  this.#registrationCodeVerifier = fields.registrationCodeVerifier
96
275
  this.#registrationFlowKey = fields.registrationFlowKey
97
276
  this.#authKey = fields.authKey
277
+ this.#resolveAuthKey = fields.resolveAuthKey
278
+ this.#addDeviceApproval = fields.addDeviceApproval
98
279
  Object.freeze(this)
99
280
  }
100
281
 
101
282
  /**
102
- * Finish the ceremony: `POST /v1/accounts/auth/deviceKeyRegistration` with
103
- * both `X-Device-Authorization` and `X-Registration-Flow-Authorization`
104
- * bound to the exact body bytes.
283
+ * Finish the ceremony: `POST /v1/accounts/auth/keys` with both
284
+ * `X-Device-Authorization` and `X-Registration-Flow-Authorization` bound to
285
+ * the exact body bytes. Both proofs name `register_device_key` version 3.
286
+ * DAA reads the body strictly and refuses any member outside the set in the
287
+ * class doc.
288
+ *
289
+ * The body is the same fields for every device — see the class doc.
290
+ * `codeSeal` is sent only with `addDeviceApproval` on (off by default). It
291
+ * commits to the AuthKey's 32-byte code secret. The same secret is sealed
292
+ * again until DAA says no request is waiting for this key, because DAA
293
+ * returns a waiting key's request and keeps its first seal; once
294
+ * `sendCodeSecret()` revealed it, the next registration seals a new one (see
295
+ * `codeSecrets.ts`). On `PENDING_APPROVAL` the returned
296
+ * `PendingDeviceApproval` holds the secret that request's seal commits to.
297
+ * DAA returns that seal, and if this SDK doesn't hold its secret (the app
298
+ * restarted after the secret was sent), the `PendingDeviceApproval`
299
+ * reports the code as unavailable (`matching_code_unavailable`) and sends
300
+ * nothing.
301
+ * DAA must run an enclave that accepts `codeSeal` (0.1.93 or later); older
302
+ * enclaves refuse the body. With the switch off, a `pending_approval` answer
303
+ * (a key already waiting from an earlier registration with it on) throws
304
+ * `contract_violation`: there is no secret to show its code from.
305
+ * The only input is the optional `riskSignals`, device signals for this
306
+ * registration. When given, they go into the body both proofs sign, so nothing
307
+ * between the app and DAA can change them. Without them, registration works
308
+ * the same and the device list shows the device without a model or OS.
309
+ *
310
+ * When `confirmationRequired` is `true`, pass `confirmAddDevice: true` once
311
+ * the user confirmed adding this device: only then is the AuthKey created
312
+ * and the registration sent. Without it, `complete()` throws
313
+ * `contract_violation` and nothing is created or sent. When
314
+ * `confirmationRequired` is `false`, `confirmAddDevice` is ignored.
105
315
  *
106
- * Takes no input: the body is the same four fields for every device — see
107
- * the class doc.
316
+ * The input is checked before anything else: a malformed `riskSignals`, a
317
+ * `confirmAddDevice` that is not a boolean, or a missing confirmation throws
318
+ * `contract_violation` and leaves this registration unused, so the caller can
319
+ * call `complete()` again.
108
320
  *
109
- * The service returns a flat `DeviceContext`. A `{ status, context }` /
110
- * `RECOVERY_PENDING` payload is also decoded. On `ACTIVE`, acknowledges
111
- * the AuthKey so later `resolveOrCreate` returns `existing`.
321
+ * The service returns a `KeyCredential` (see
322
+ * `wire/deviceRegistrationResultPayload.ts`): `credentialStatus: "active"`
323
+ * is `ACTIVE`, with `credentialId` as `deviceContext.authKeyId`;
324
+ * `pending_approval` is `PENDING_APPROVAL`; and `pending_activation` is
325
+ * `PENDING_ACTIVATION`. This endpoint never returns
326
+ * `RECOVERY_PENDING`. On `PENDING_APPROVAL`, the
327
+ * AuthKey is not acknowledged: it can't sign until an existing device
328
+ * approves it. On `PENDING_ACTIVATION` (approved, in the account's cool-down
329
+ * until `readyAt`) it is acknowledged but no context is returned: after
330
+ * `readyAt`, `DaaClient.restore` returns it. On `ACTIVE`, acknowledges
331
+ * the AuthKey with the context's `authKeyId` and `ownerBindingId`, so later
332
+ * `resolveOrCreate` returns `existing` and `SecureKeyStore.resolveExisting`
333
+ * can find it.
112
334
  *
113
335
  * @throws DaaError with `detail.kind === 'login_request_expired'` for `410`;
114
336
  * `idempotency_conflict` for a `409` with `IDEMPOTENCY_KEY_REUSED`
115
337
  * (`420034`); `contract_violation` for `LOGIN_REQUEST_CONSUMED` (`420039`),
116
- * for a second call, for unusable key material, and for a response the SDK
117
- * cannot read; and `api` for any other status besides the documented
338
+ * for a second call (except the retry after `registration_not_saved`,
339
+ * below), for unusable key material, for a response the SDK cannot read
340
+ * (including a `credentialStatus` other than `active`, `pending_approval`
341
+ * or `pending_activation`), and for malformed `riskSignals` (nothing is
342
+ * sent and this registration stays unused, so `complete()` can be called
343
+ * again), and for a missing `confirmAddDevice: true` when
344
+ * `confirmationRequired` (likewise nothing is sent and this registration
345
+ * stays unused); and `api` for any other status besides the documented
118
346
  * `200`, including the `409` that DAA sends with `AUTH_KEY_BINDING_CONFLICT`
119
- * (`420038`).
347
+ * (`420038`) or `PASSKEY_OWNER_CREDENTIAL_KIND_MISMATCH` (`420080`);
348
+ * `device_registration_limit`, `device_denied`, `device_approval_conflict`
349
+ * or `device_approval_unavailable` for the four add-a-device refusals (see
350
+ * `deviceRegistrationFailure`); `transport` with `retryable: false` when
351
+ * reading the AuthKey, or the queued prompt and `send()`, takes longer than
352
+ * two minutes (a later read or response is ignored; trying again needs a
353
+ * new login, unless DAA had answered and only saving its answer ran
354
+ * late: `complete()` then retries that save, as after
355
+ * `registration_not_saved`. If that late save finished first, the retry
356
+ * throws `contract_violation` ("already been consumed"): the identifiers
357
+ * are saved, and `DaaClient.restore` finds the key).
358
+ * `user_cancelled` when the user dismisses the authentication
359
+ * prompt: nothing was sent, but this registration is used up, so trying
360
+ * again needs a new login (which reuses the same AuthKey).
361
+ * When `confirmationRequired`, the AuthKey is created here, so a native
362
+ * failure creating it (for example `device_lock_not_set` or
363
+ * `device_not_supported`) is thrown here too; nothing was sent, but this
364
+ * registration is used up, so trying again needs a new login.
365
+ * `registration_not_saved` when DAA answered `ACTIVE` or
366
+ * `PENDING_ACTIVATION` but saving its
367
+ * `authKeyId` and `ownerBindingId` on this device failed (for example a
368
+ * Keychain or Keystore write error). The device is registered with Circle.
369
+ * Call `complete()` again: it sends nothing, retries only the save, and
370
+ * on success returns the same result (its input is ignored).
371
+ * The retry has the same two-minute deadline. If a newer registration of
372
+ * the same key answered in the meantime, the retry throws
373
+ * `contract_violation` and saves nothing: the newer registration's
374
+ * identifiers are the ones to keep.
375
+ * If the key on the device was replaced since (`forgetLocalKey`, then a
376
+ * new sign-in), the retry also throws `contract_violation` and saves
377
+ * nothing. If the save fails with `key_invalidated` or
378
+ * `device_not_initialized` (the key is gone), that kind is thrown as is and
379
+ * nothing is kept to retry: no save can succeed. Other native kinds (for
380
+ * example `device_lock_not_set` or `device_not_supported`, which the user
381
+ * can fix or retry) come as `registration_not_saved`, with the original on
382
+ * `cause`.
120
383
  */
121
- async complete(): Promise<DeviceRegistrationResult> {
384
+ async complete(input?: {
385
+ readonly riskSignals?: DeviceRegistrationRiskSignals
386
+ readonly confirmAddDevice?: boolean
387
+ }): Promise<DeviceRegistrationResult> {
388
+ const unsaved = this.#unsaved
389
+ if (unsaved !== null) {
390
+ this.#unsaved = null
391
+ return await this.#save(unsaved)
392
+ }
122
393
  if (this.#consumed) {
123
394
  throw contractViolation('this pending device registration has already been consumed')
124
395
  }
396
+ const riskSignals = completeRiskSignals(input)
397
+ const confirmed = completeConfirmation(input)
398
+ if (this.confirmationRequired && !confirmed) {
399
+ throw contractViolation(
400
+ 'adding this device needs the user to confirm first; call complete({ confirmAddDevice: true }) after they do',
401
+ )
402
+ }
125
403
  this.#consumed = true
126
404
 
127
405
  try {
128
- const authKeyPublicKey = await this.#authKey.publicKeySpkiBase64Url()
129
- if (!AUTH_KEY_PUBLIC_KEY.test(authKeyPublicKey)) {
130
- throw contractViolation(
131
- 'AuthKey public key must be a 122-character unpadded Base64URL P-256 SPKI',
132
- )
133
- }
406
+ // Reading the key (native) has its own deadline: the call isn't queued
407
+ // yet, and a read that finishes late can't go on to queue and send.
408
+ // Creating it, after the user confirmed, is under the same deadline.
409
+ const authKey =
410
+ this.#authKey ?? (this.#authKey = await withDeadline(() => this.#resolveAuthKey()))
411
+ const { deviceKeyPublicKey, authKeyThumbprint, thumbprintBytes } = await withDeadline(() =>
412
+ readAuthKey(authKey),
413
+ )
414
+ return await oneAtATime(authKeyThumbprint, () =>
415
+ withDeadline(async (call) => {
416
+ // Without `addDeviceApproval` the body is what it was before add-a-device:
417
+ // no secret and no codeSeal, which an enclave older than 0.1.93 accepts.
418
+ const codeSecret = this.#addDeviceApproval
419
+ ? await codeSecretFor(authKeyThumbprint, authKey, () => call.late)
420
+ : null
421
+ if (call.late) {
422
+ throw completeTimedOut()
423
+ }
424
+ const idempotencyKey = randomUuidV4()
425
+ const bodyBytes = serializeBody({
426
+ type: DEVICE_KEY_TYPE,
427
+ idempotencyKey,
428
+ registrationHandle: this.registrationHandle,
429
+ registrationCodeVerifier: this.#registrationCodeVerifier,
430
+ deviceKeyPublicKey,
431
+ ...(codeSecret === null
432
+ ? {}
433
+ : { codeSeal: toBase64Url(codeSeal(thumbprintBytes, codeSecret)) }),
434
+ ...(riskSignals === undefined ? {} : { riskSignals }),
435
+ })
436
+ const { deviceJws, flowJws } = await authorizeRegistrationComplete({
437
+ bodyBytes,
438
+ registrationHandle: this.registrationHandle,
439
+ registrationCodeVerifier: this.#registrationCodeVerifier,
440
+ clientEntityId: this.clientEntityId,
441
+ flowKey: this.#registrationFlowKey,
442
+ authKey,
443
+ })
134
444
 
135
- const idempotencyKey = randomUuidV4()
136
- const bodyBytes = serializeBody({
137
- idempotencyKey,
138
- registrationHandle: this.registrationHandle,
139
- registrationCodeVerifier: this.#registrationCodeVerifier,
140
- authKeyPublicKey,
141
- })
142
- const { deviceJws, flowJws } = await authorizeRegistrationComplete({
143
- bodyBytes,
144
- registrationHandle: this.registrationHandle,
145
- registrationCodeVerifier: this.#registrationCodeVerifier,
146
- clientEntityId: this.clientEntityId,
147
- flowKey: this.#registrationFlowKey,
148
- authKey: this.#authKey,
149
- })
150
-
151
- const response = await this.#transport.send({
152
- method: 'POST',
153
- path: DEVICE_REGISTRATION_COMPLETE_PATH,
154
- query: null,
155
- headers: {
156
- 'Content-Type': 'application/json',
157
- [REGISTRATION_DEVICE_AUTHORIZATION_HEADER]: deviceJws,
158
- [REGISTRATION_FLOW_AUTHORIZATION_HEADER]: flowJws,
159
- },
160
- bodyBytes,
161
- })
162
-
163
- const failure = loginStepFailure(response, idempotencyKey)
164
- if (failure !== null) {
165
- throw failure
166
- }
445
+ if (call.late) {
446
+ throw completeTimedOut()
447
+ }
448
+ call.sentSecret = codeSecret
449
+ if (codeSecret !== null) {
450
+ sealingCodeSecret(authKeyThumbprint, codeSecret)
451
+ }
452
+ let response: DaaHttpResponse
453
+ try {
454
+ response = await this.#transport.send({
455
+ method: 'POST',
456
+ path: KEY_REGISTRATION_PATH,
457
+ query: null,
458
+ headers: {
459
+ 'Content-Type': 'application/json',
460
+ [REGISTRATION_DEVICE_AUTHORIZATION_HEADER]: deviceJws,
461
+ [REGISTRATION_FLOW_AUTHORIZATION_HEADER]: flowJws,
462
+ },
463
+ bodyBytes,
464
+ })
465
+ } catch (error) {
466
+ // No answer (say, the relay timed out): DAA may still add the
467
+ // request with this secret's seal.
468
+ holdCodeSecret(codeSecret)
469
+ throw error
470
+ }
471
+ if (call.late) {
472
+ throw completeTimedOut()
473
+ }
474
+
475
+ const failure = loginStepFailure(response, idempotencyKey)
476
+ if (failure !== null && NO_WAITING_REQUEST_KINDS.has(failure.detail.kind)) {
477
+ // Not late: checked just above, with nothing awaited since.
478
+ if (dropCodeSecret(authKeyThumbprint, codeSecret) && codeSecret !== null) {
479
+ call.afterDeadline = () => deleteStoredCodeSecret(authKey, codeSecret)
480
+ }
481
+ throw failure
482
+ }
483
+ if (response.status < 200 || response.status >= 300) {
484
+ // Any other refusal, or a status from something between the app and
485
+ // DAA (a 504 from a relay that timed out), doesn't say whether DAA
486
+ // added the request, so keep the secret as for no answer.
487
+ holdCodeSecret(codeSecret)
488
+ }
489
+ if (failure !== null) {
490
+ throw failure
491
+ }
167
492
 
168
- const result = decodeResourceResponse({
169
- response,
170
- expectedStatus: 200,
171
- decode: (value) => toDeviceRegistrationResult(value, this.clientEntityId),
172
- })
173
- return await this.#finish(result)
493
+ const result = decodeResourceResponse({
494
+ response,
495
+ expectedStatus: 200,
496
+ decode: (value) => toDeviceRegistrationResult(value, this.clientEntityId),
497
+ })
498
+ const dropped =
499
+ result.status !== 'PENDING_APPROVAL' && dropCodeSecret(authKeyThumbprint, codeSecret)
500
+ try {
501
+ return await this.#finish(result, authKeyThumbprint, thumbprintBytes, codeSecret, call)
502
+ } finally {
503
+ // After the save: nothing may be awaited between DAA's answer and
504
+ // the acknowledgement (see `ACTIVE` in `#finish`). Outside the
505
+ // deadline, so a slow delete can't fail a call whose answer was
506
+ // saved, but before the key's queue moves on, so the next
507
+ // registration can't read this secret back first, unless the
508
+ // delete passes its time limit (`deleteWithinLimit` in
509
+ // `codeSecrets.ts`). Skipped once the deadline passed: the queue
510
+ // already moved on.
511
+ if (dropped && codeSecret !== null && !call.late) {
512
+ call.afterDeadline = () => deleteStoredCodeSecret(authKey, codeSecret)
513
+ }
514
+ }
515
+ }),
516
+ )
174
517
  } finally {
175
518
  await releaseQuietly(this.#registrationFlowKey)
176
519
  }
177
520
  }
178
521
 
179
- async #finish(result: DeviceRegistrationResult): Promise<DeviceRegistrationResult> {
522
+ /**
523
+ * The AuthKey `complete()` registered. Set before anything is sent, so every
524
+ * step after DAA answered has it.
525
+ */
526
+ #key(): OwnerAuthKey {
527
+ if (this.#authKey === null) {
528
+ throw contractViolation('this pending device registration has no AuthKey yet')
529
+ }
530
+ return this.#authKey
531
+ }
532
+
533
+ /**
534
+ * Save the identifiers DAA assigned. If that fails, keep them so the next
535
+ * `complete()` can retry the save without sending Complete again: DAA already
536
+ * answered, and the spent registration handle can't be sent twice. The
537
+ * caller sets `onLate` first, so a save still running at the deadline is
538
+ * kept for retry too.
539
+ *
540
+ * A native save that runs past the deadline can't be cancelled, but it can't
541
+ * overwrite a newer one either: the AuthKey handle queues each save behind
542
+ * the one before it (`#ackTail`), so a newer registration's save lands last.
543
+ */
544
+ async #acknowledge(unsaved: UnsavedRegistration): Promise<DeviceRegistrationResult> {
545
+ try {
546
+ await this.#key().acknowledgeRegistration(unsaved.registration)
547
+ } catch (error) {
548
+ throw this.#notSaved(unsaved, error)
549
+ }
550
+ this.#forget(unsaved)
551
+ return unsaved.result
552
+ }
553
+
554
+ /**
555
+ * Nothing left to retry for this answer: it was saved, or its key is gone.
556
+ * Also drops what the deadline kept, if the save ran past it.
557
+ */
558
+ #forget(unsaved: UnsavedRegistration): void {
559
+ if (this.#unsaved === unsaved) {
560
+ this.#unsaved = null
561
+ }
562
+ if (newestAnswer.get(unsaved.authKeyThumbprint) === unsaved) {
563
+ newestAnswer.delete(unsaved.authKeyThumbprint)
564
+ }
565
+ }
566
+
567
+ /**
568
+ * The error for a save that failed. A key that is gone from the device
569
+ * passes through as is and nothing is kept: no retry could succeed. Anything
570
+ * else keeps the save for the next `complete()`.
571
+ */
572
+ #notSaved(unsaved: UnsavedRegistration, error: unknown): DaaError {
573
+ if (error instanceof DaaError && KEY_GONE_KINDS.has(error.detail.kind)) {
574
+ this.#forget(unsaved)
575
+ return error
576
+ }
577
+ this.#unsaved = unsaved
578
+ return registrationNotSaved(error)
579
+ }
580
+
581
+ /**
582
+ * A retried save: queued behind any registration in flight for the same key,
583
+ * under the same deadline as `complete()`, and refused once a newer
584
+ * registration of the key answered, or once the key on the device
585
+ * is no longer this registration's.
586
+ */
587
+ async #save(unsaved: UnsavedRegistration): Promise<DeviceRegistrationResult> {
588
+ return await oneAtATime(unsaved.authKeyThumbprint, () =>
589
+ withDeadline(async (call) => {
590
+ if (newestAnswer.get(unsaved.authKeyThumbprint) !== unsaved) {
591
+ throw contractViolation(
592
+ 'a newer registration of this AuthKey replaced this one; use its result',
593
+ )
594
+ }
595
+ call.onLate = () => {
596
+ this.#unsaved = unsaved
597
+ }
598
+ // The native save writes to whatever key the slot holds now. After
599
+ // `forgetLocalKey` and a new sign-in that is a different key, and
600
+ // these identifiers would overwrite its own.
601
+ let current: string
602
+ try {
603
+ current = await this.#key().thumbprint()
604
+ } catch (error) {
605
+ throw this.#notSaved(unsaved, error)
606
+ }
607
+ if (call.late) {
608
+ // The key's queue moved on at the deadline, so a newer Complete may
609
+ // have saved since the check above. Save nothing now: `onLate` kept
610
+ // the save, and the next `complete()` checks again.
611
+ throw completeTimedOut()
612
+ }
613
+ if (current !== unsaved.authKeyThumbprint) {
614
+ newestAnswer.delete(unsaved.authKeyThumbprint)
615
+ throw contractViolation(
616
+ "this device's AuthKey was replaced since this registration; sign in again",
617
+ )
618
+ }
619
+ return await this.#acknowledge(unsaved)
620
+ }),
621
+ )
622
+ }
623
+
624
+ /**
625
+ * Save a final answer's identifiers as the newest answer for its key. If
626
+ * the deadline passes while the save runs, the answer is kept for the next
627
+ * `complete()`.
628
+ */
629
+ async #saveAnswer(answer: UnsavedRegistration, call: QueuedComplete) {
630
+ newestAnswer.set(answer.authKeyThumbprint, answer)
631
+ call.onLate = () => {
632
+ this.#unsaved = answer
633
+ }
634
+ return await this.#acknowledge(answer)
635
+ }
636
+
637
+ async #finish(
638
+ result: DecodedDeviceRegistration,
639
+ authKeyThumbprint: string,
640
+ thumbprintBytes: Uint8Array,
641
+ codeSecret: Uint8Array | null,
642
+ call: QueuedComplete,
643
+ ): Promise<DeviceRegistrationResult> {
180
644
  switch (result.status) {
181
645
  case 'ACTIVE':
182
646
  // Keep the server-assigned authKeyId as the JWS kid, but retain the
183
647
  // local key's thumbprint alongside it. `DaaClient.forUser` checks this
184
648
  // pairing every time it resolves the key for a signed operation.
185
- const boundContext = bindAuthKeyToContext(result.context, await this.#authKey.thumbprint())
186
- await this.#authKey.acknowledgeRegistration()
187
- return Object.freeze({ ...result, context: boundContext })
188
- case 'RECOVERY_PENDING':
189
- return result
649
+ //
650
+ // The acknowledgement records the server-assigned identifiers beside
651
+ // the key. That record is what `SecureKeyStore.resolveExisting` reads
652
+ // back without creating a key: `authKeyId` is the `kid` the service
653
+ // looks the key up by. It is an upsert, so a re-registration of the
654
+ // same key that assigned new identifiers replaces the stored ones.
655
+ //
656
+ // No await before the acknowledgement: the queued call's deadline can
657
+ // only pass at an await, and a late call must not overwrite the
658
+ // identifiers a newer Complete for the key stored.
659
+ const boundContext = bindAuthKeyToContext(result.context, authKeyThumbprint)
660
+ const answer: UnsavedRegistration = Object.freeze({
661
+ result: Object.freeze({ ...result, context: boundContext }),
662
+ authKeyThumbprint,
663
+ registration: {
664
+ authKeyId: result.context.deviceContext.authKeyId,
665
+ ownerBindingId: result.context.deviceContext.ownerBindingId,
666
+ },
667
+ })
668
+ return await this.#saveAnswer(answer, call)
669
+ case 'PENDING_ACTIVATION':
670
+ // Approved from another device: the key is the account's, so its
671
+ // identifiers are final and are stored now, letting
672
+ // `DaaClient.restore` return the ACTIVE context once `readyAt` passes
673
+ // (before then DAA answers it with `device_pending`). No context is
674
+ // returned here, so nothing can sign before `readyAt`. A failed save
675
+ // is retried as for `ACTIVE`.
676
+ return await this.#saveAnswer(
677
+ Object.freeze({
678
+ result: Object.freeze({
679
+ status: 'PENDING_ACTIVATION',
680
+ authKeyId: result.authKeyId,
681
+ readyAt: result.readyAt,
682
+ }),
683
+ authKeyThumbprint,
684
+ registration: { authKeyId: result.authKeyId, ownerBindingId: result.ownerBindingId },
685
+ }),
686
+ call,
687
+ )
688
+ case 'PENDING_APPROVAL':
689
+ if (codeSecret === null) {
690
+ // Only a key already waiting from a registration sent with
691
+ // `addDeviceApproval` on: there is no secret to show its code from.
692
+ throw contractViolation(
693
+ 'DAA returned pending_approval for a registration sent without codeSeal; turn on addDeviceApproval',
694
+ )
695
+ }
696
+ return Object.freeze({
697
+ status: 'PENDING_APPROVAL',
698
+ pendingApproval: newPendingDeviceApproval({
699
+ requestId: result.requestId,
700
+ authKeyId: result.authKeyId,
701
+ expiresAt: result.expiresAt,
702
+ codeNonce: result.codeNonce,
703
+ authKeyThumbprint,
704
+ authKey: this.#key(),
705
+ // `null` when DAA's seal for the request isn't this device's:
706
+ // the code is unavailable and nothing is sent for it.
707
+ codeSecret: codeSecretForRequest(
708
+ authKeyThumbprint,
709
+ thumbprintBytes,
710
+ codeSecret,
711
+ result.requestId,
712
+ result.codeSeal,
713
+ ),
714
+ transport: this.#transport,
715
+ }),
716
+ })
190
717
  default: {
191
718
  const exhaustive: never = result
192
719
  void exhaustive
@@ -195,3 +722,70 @@ export class PendingDeviceRegistration {
195
722
  }
196
723
  }
197
724
  }
725
+
726
+ async function readAuthKey(authKey: OwnerAuthKey): Promise<{
727
+ deviceKeyPublicKey: string
728
+ authKeyThumbprint: string
729
+ thumbprintBytes: Uint8Array
730
+ }> {
731
+ const deviceKeyPublicKey = await authKey.publicKeySpkiBase64Url()
732
+ if (!AUTH_KEY_PUBLIC_KEY.test(deviceKeyPublicKey)) {
733
+ throw contractViolation(
734
+ 'AuthKey public key must be a 122-character unpadded Base64URL P-256 SPKI',
735
+ )
736
+ }
737
+ const authKeyThumbprint = await authKey.thumbprint()
738
+ const thumbprintBytes = canonicalBytes32(authKeyThumbprint)
739
+ if (thumbprintBytes === null) {
740
+ throw contractViolation('AuthKey thumbprint must be a 43-character unpadded Base64URL digest')
741
+ }
742
+ return { deviceKeyPublicKey, authKeyThumbprint, thumbprintBytes }
743
+ }
744
+
745
+ /**
746
+ * Check the optional `complete()` input and build the `riskSignals` member.
747
+ *
748
+ * The enclave refuses a registration body whose `riskSignals` has any member
749
+ * besides these three, or a member that is not a string, so an unknown or
750
+ * malformed member is refused here rather than dropped: the caller learns of
751
+ * it before a registration is spent. Building a new object rather than
752
+ * forwarding the caller's also fixes the member order in the signed bytes.
753
+ */
754
+ function completeRiskSignals(
755
+ input: { readonly riskSignals?: DeviceRegistrationRiskSignals } | undefined,
756
+ ): DeviceRegistrationRiskSignals | undefined {
757
+ if (input === undefined) return undefined
758
+ requireBodyObject(input, 'complete input')
759
+ requireKnownProperties(input, COMPLETE_INPUT_PROPERTIES, 'complete input')
760
+ const { riskSignals } = input
761
+ if (riskSignals === undefined) return undefined
762
+ requireBodyObject(riskSignals, 'registration risk signals')
763
+ requireKnownProperties(riskSignals, RISK_SIGNAL_PROPERTIES, 'registration risk signals')
764
+ const { ipAddress, sessionId, deviceId } = riskSignals
765
+ requireOptionalRiskSignal(ipAddress, 'ipAddress')
766
+ requireOptionalRiskSignal(sessionId, 'sessionId')
767
+ requireOptionalRiskSignal(deviceId, 'deviceId')
768
+ // None of the members is required, so `{}` is a valid `riskSignals` (the
769
+ // enclave and DAA both accept it) and is sent as the empty object the caller
770
+ // passed, as on transfers and withdrawals.
771
+ return {
772
+ ...(ipAddress === undefined ? {} : { ipAddress }),
773
+ ...(sessionId === undefined ? {} : { sessionId }),
774
+ ...(deviceId === undefined ? {} : { deviceId }),
775
+ }
776
+ }
777
+
778
+ /** `complete()`'s `confirmAddDevice`: whether the user confirmed adding this device. */
779
+ function completeConfirmation(input: { readonly confirmAddDevice?: boolean } | undefined): boolean {
780
+ const confirmAddDevice = input?.confirmAddDevice
781
+ if (confirmAddDevice !== undefined && typeof confirmAddDevice !== 'boolean') {
782
+ throw contractViolation('confirmAddDevice must be a boolean')
783
+ }
784
+ return confirmAddDevice === true
785
+ }
786
+
787
+ function requireOptionalRiskSignal(value: string | undefined, name: string): void {
788
+ if (value !== undefined && (typeof value !== 'string' || value.length === 0)) {
789
+ throw contractViolation(`registration risk signal ${name} must be a non-empty string`)
790
+ }
791
+ }