@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
@@ -0,0 +1,360 @@
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
+ import { toBase64Url } from '../crypto/base64url'
20
+ import { codeSeal } from '../crypto/matchingCode'
21
+ import { randomBytes } from '../crypto/random'
22
+ import { contractViolation, DaaError } from '../errors'
23
+ import type { OwnerAuthKey } from '../securekey/SecureKey'
24
+
25
+ /**
26
+ * The add-a-device code secrets of each AuthKey, by thumbprint, for this
27
+ * process.
28
+ *
29
+ * `unsent` is what the key's next registration seals. When a key whose request
30
+ * is still waiting registers again (the app dropped its
31
+ * `PendingDeviceApproval`, or the response was lost), DAA returns that earlier
32
+ * request with its `codeNonce`, and the enclave keeps the first registration's
33
+ * `codeSeal`. A new secret would then show a code that can't match, so
34
+ * `PendingDeviceRegistration.complete()` keeps sealing the same `unsent`
35
+ * secret until DAA says no request is waiting for the key: it comes back
36
+ * `ACTIVE` or `PENDING_ACTIVATION`, or DAA refuses it with one of the four
37
+ * add-a-device codes (DAA checks for a waiting request before any of them).
38
+ * There is no expiry on this device's clock, which may be wrong.
39
+ *
40
+ * Reusing a secret only commits a later request to the same seal, which is
41
+ * harmless while the secret never left the device. So
42
+ * `PendingDeviceApproval.sendCodeSecret()` sends `unsent` only for
43
+ * `sealedInto`, the request DAA last returned for its seal. Any other request
44
+ * has ended, or was never sealed with it, and DAA would refuse it anyway.
45
+ * `sealedInto` is `null` while a registration that sealed `unsent` has no
46
+ * answer: DAA may have put that seal into a new request. Once sent for request
47
+ * R, the secret moves to `sent` and the next registration seals a fresh
48
+ * `unsent` secret, whether or not this process ever learns that R ended.
49
+ * `sent` is kept so that the send can be retried, and so that if DAA returns R
50
+ * itself (it was still waiting and kept its first seal), the code is shown
51
+ * from the secret R's seal commits to.
52
+ *
53
+ * DAA returns the request's stored `codeSeal`, and a secret that doesn't open
54
+ * it is never shown or sent for that request (`codeSecretForRequest` returns
55
+ * `null`). That happens when the request was sealed with a secret this SDK no
56
+ * longer holds: the process restarted after the secret was sent, or a registration
57
+ * that sealed a secret and got no answer (it passed its deadline, say) reached
58
+ * DAA later, while its signature was valid (five minutes, plus skew), after
59
+ * that secret was sent for an earlier request R that has since expired. The
60
+ * code is unavailable until that request expires. Nothing else learns more
61
+ * than the send already told DAA.
62
+ *
63
+ * Every read and update runs in the key's {@link oneAtATime} queue: a
64
+ * registration holds it from choosing the secret until DAA's answer is
65
+ * recorded, so a send can't reveal a secret a registration in flight is
66
+ * sealing into a new request.
67
+ *
68
+ * Only `unsent` outlives the process: it is read from, and deleted from, the
69
+ * key's own storage (`OwnerAuthKey.codeSecret` / `deleteCodeSecret`, the
70
+ * Keychain or Keystore), so after an app restart a sign-in that DAA answers
71
+ * with the request still waiting shows the same code and can still send it.
72
+ * The send deletes the secret from that storage first, so a secret that left
73
+ * the device is never sealed again, even after a restart; `sent` and
74
+ * `sealedInto` are process memory only. A restart after the send therefore
75
+ * loses the code for that request: the next registration seals a new secret,
76
+ * which doesn't open the request's seal. A key whose store has no
77
+ * `codeSecret` keeps `unsent` in process memory too.
78
+ */
79
+ const codeSecrets = new Map<
80
+ string,
81
+ {
82
+ /** `null` after a send: the next registration reads the key's new one. */
83
+ unsent: Uint8Array | null
84
+ sealedInto: string | null
85
+ sent: { readonly secret: Uint8Array; readonly requestId: string } | null
86
+ }
87
+ >()
88
+
89
+ /**
90
+ * Secrets sealed by a `complete()` that got no answer from DAA: it passed its
91
+ * deadline, `send()` threw, or the response was neither a success nor one of
92
+ * the four add-a-device refusals (a 504 from a relay that timed out). DAA may
93
+ * still add that request as waiting with this secret's seal after a later
94
+ * Complete for the key was refused, so a refusal no longer drops it. Keeping a
95
+ * secret too long is harmless while it was never sent. Process memory only: a
96
+ * restart forgets which secrets are held.
97
+ */
98
+ const heldCodeSecrets = new WeakSet<Uint8Array>()
99
+
100
+ /**
101
+ * Keep `secret` even when a later refusal says no request is waiting. `null`
102
+ * (a registration sent without `addDeviceApproval`, so with no secret) does
103
+ * nothing.
104
+ */
105
+ export function holdCodeSecret(secret: Uint8Array | null): void {
106
+ if (secret !== null) {
107
+ heldCodeSecrets.add(secret)
108
+ }
109
+ }
110
+
111
+ /** The last queued step of each AuthKey, by thumbprint. */
112
+ const keyQueue = new Map<string, Promise<unknown>>()
113
+
114
+ /**
115
+ * Runs `step` once every earlier step for the same key has settled: each
116
+ * `complete()` of the key, and each `sendCodeSecret()` deciding what to send.
117
+ *
118
+ * Two overlapping Completes for one key send the same secret. DAA can refuse
119
+ * the first (say, 409 conflict: another device was waiting, so both requests
120
+ * were cancelled) and then add the second as waiting with that secret's seal.
121
+ * If the refusal reached the app last, it would drop the secret the waiting
122
+ * request needs, and the next login would show a code that can't match.
123
+ */
124
+ export async function oneAtATime<T>(thumbprint: string, step: () => Promise<T>): Promise<T> {
125
+ const previous = keyQueue.get(thumbprint) ?? Promise.resolve()
126
+ const run = previous.then(step)
127
+ const settled = run.then(
128
+ () => undefined,
129
+ () => undefined,
130
+ )
131
+ keyQueue.set(thumbprint, settled)
132
+ try {
133
+ return await run
134
+ } finally {
135
+ if (keyQueue.get(thumbprint) === settled) {
136
+ keyQueue.delete(thumbprint)
137
+ }
138
+ }
139
+ }
140
+
141
+ /**
142
+ * The secret the key's next registration seals: the one this process holds,
143
+ * else the key's stored one (`authKey.codeSecret()`, which creates it on first
144
+ * use), else, for a key without that method, a new 32-byte one. Call it in the
145
+ * key's {@link oneAtATime} queue.
146
+ *
147
+ * A key must have both `codeSecret` and `deleteCodeSecret`, or neither: with
148
+ * only `codeSecret`, the send couldn't delete the secret and the next
149
+ * registration would read the sent secret back and seal it again.
150
+ *
151
+ * Records nothing once `late()` is true: the queue has moved on, and a
152
+ * registration queued after this one may already have its own secret here.
153
+ */
154
+ export async function codeSecretFor(
155
+ thumbprint: string,
156
+ authKey: OwnerAuthKey,
157
+ late: () => boolean,
158
+ ): Promise<Uint8Array> {
159
+ if ((authKey.codeSecret === undefined) !== (authKey.deleteCodeSecret === undefined)) {
160
+ throw contractViolation('an AuthKey needs both codeSecret and deleteCodeSecret, or neither')
161
+ }
162
+ const kept = codeSecrets.get(thumbprint)
163
+ if (kept?.unsent != null) {
164
+ return kept.unsent
165
+ }
166
+ const secret = authKey.codeSecret === undefined ? randomBytes(32) : await authKey.codeSecret()
167
+ if (secret.length !== 32) {
168
+ throw contractViolation('the AuthKey code secret must be 32 bytes')
169
+ }
170
+ if (late()) {
171
+ return secret
172
+ }
173
+ if (kept === undefined) {
174
+ codeSecrets.set(thumbprint, { unsent: secret, sealedInto: null, sent: null })
175
+ } else {
176
+ kept.unsent = secret
177
+ kept.sealedInto = null
178
+ }
179
+ return secret
180
+ }
181
+
182
+ /**
183
+ * A registration that sealed `secret` is about to go out: until DAA answers,
184
+ * the request that seal ends up in is unknown.
185
+ */
186
+ export function sealingCodeSecret(thumbprint: string, secret: Uint8Array): void {
187
+ const kept = codeSecrets.get(thumbprint)
188
+ if (kept?.unsent === secret) {
189
+ kept.sealedInto = null
190
+ }
191
+ }
192
+
193
+ /**
194
+ * The secret behind `requestId`, which DAA returned as waiting after a
195
+ * registration that sealed `sealed`: the sent secret if DAA returned the
196
+ * request it was sent for, else `sealed`, now recorded as sealed into
197
+ * `requestId`. Forgets a sent secret whose request DAA no longer returns,
198
+ * since a key has only one waiting request.
199
+ *
200
+ * `requestSeal` is the request's stored `codeSeal` as DAA returned it. If the
201
+ * chosen secret doesn't open it, returns `null` and records nothing against
202
+ * that request: the request was sealed with a secret this SDK no longer
203
+ * holds, so no code from this device can match it and nothing may be sent for
204
+ * it. `sealed` stays the key's unsent secret, harmless to seal again since it
205
+ * never left the device.
206
+ * A `null` `requestSeal` (a DAA that doesn't return it) is not checked.
207
+ */
208
+ export function codeSecretForRequest(
209
+ thumbprint: string,
210
+ thumbprintBytes: Uint8Array,
211
+ sealed: Uint8Array,
212
+ requestId: string,
213
+ requestSeal: string | null,
214
+ ): Uint8Array | null {
215
+ const opens = (secret: Uint8Array) =>
216
+ requestSeal === null || toBase64Url(codeSeal(thumbprintBytes, secret)) === requestSeal
217
+ const kept = codeSecrets.get(thumbprint)
218
+ if (kept?.sent != null && kept.sent.requestId === requestId) {
219
+ return opens(kept.sent.secret) ? kept.sent.secret : null
220
+ }
221
+ if (kept !== undefined) {
222
+ kept.sent = null
223
+ }
224
+ if (!opens(sealed)) {
225
+ return null
226
+ }
227
+ if (kept?.unsent === sealed) {
228
+ kept.sealedInto = requestId
229
+ }
230
+ return sealed
231
+ }
232
+
233
+ /**
234
+ * Whether `secret` may be sent for `requestId`: it was already sent for that
235
+ * request (a retry), or it is the unsent secret DAA last returned that request
236
+ * for. If so, records it as sent, before the request goes out (a send whose
237
+ * response is lost may still have reached DAA): deletes it from the key's
238
+ * storage, so the key's next registration seals a new secret, then keeps it
239
+ * here as `sent`. If that delete throws or passes its time limit
240
+ * ({@link deleteWithinLimit}), nothing changes and nothing may be sent; a
241
+ * retry deletes again. Compares by reference, so `secret` must be the array
242
+ * this module handed out. Call it in the key's {@link oneAtATime} queue.
243
+ */
244
+ export async function markCodeSecretSent(
245
+ thumbprint: string,
246
+ secret: Uint8Array,
247
+ requestId: string,
248
+ authKey: OwnerAuthKey,
249
+ ): Promise<boolean> {
250
+ const kept = codeSecrets.get(thumbprint)
251
+ if (kept === undefined) {
252
+ return false
253
+ }
254
+ if (kept.sent?.secret === secret && kept.sent.requestId === requestId) {
255
+ return true
256
+ }
257
+ if (kept.unsent !== secret || kept.sealedInto !== requestId) {
258
+ return false
259
+ }
260
+ await deleteWithinLimit(authKey, secret)
261
+ kept.sent = { secret, requestId }
262
+ kept.unsent = null
263
+ kept.sealedInto = null
264
+ return true
265
+ }
266
+
267
+ /**
268
+ * DAA said no request is waiting for the key after a registration that sealed
269
+ * `secret`: forget the key's secrets, unless a later registration or send
270
+ * already replaced `secret`. Compares by reference: don't copy it
271
+ * (`.slice()`) on the way here, or nothing is ever dropped.
272
+ *
273
+ * Returns `true` when it forgot the unsent secret, which the caller then
274
+ * deletes from the key's storage with {@link deleteStoredCodeSecret}. That is
275
+ * left to the caller so a registration can save DAA's answer first.
276
+ */
277
+ export function dropCodeSecret(thumbprint: string, secret: Uint8Array | null): boolean {
278
+ if (secret === null || heldCodeSecrets.has(secret)) {
279
+ return false
280
+ }
281
+ const kept = codeSecrets.get(thumbprint)
282
+ if (kept?.unsent === secret) {
283
+ codeSecrets.delete(thumbprint)
284
+ return true
285
+ } else if (kept?.sent?.secret === secret) {
286
+ // Not reached today: the queue stops a registration from sealing a secret
287
+ // after it was sent, and a late registration holds its secret first (so it
288
+ // returned above). Kept so a future path that does reach it forgets the
289
+ // sent secret rather than leaving it to show a code.
290
+ kept.sent = null
291
+ }
292
+ return false
293
+ }
294
+
295
+ /**
296
+ * Delete a secret {@link dropCodeSecret} forgot from the key's storage. A
297
+ * failure or a timeout is ignored: the secret never left the device, so
298
+ * keeping it is harmless, and the next registration reads it back and seals it
299
+ * again.
300
+ */
301
+ export async function deleteStoredCodeSecret(
302
+ authKey: OwnerAuthKey,
303
+ secret: Uint8Array,
304
+ ): Promise<void> {
305
+ try {
306
+ await deleteWithinLimit(authKey, secret)
307
+ } catch {
308
+ // Kept; see above.
309
+ }
310
+ }
311
+
312
+ /** How long a code-secret delete may take before the key's queue moves on. */
313
+ const CODE_SECRET_DELETE_LIMIT_MS = 5_000
314
+
315
+ /**
316
+ * `authKey.deleteCodeSecret(secret)`, failing with a retryable `transport`
317
+ * error once it takes longer than {@link CODE_SECRET_DELETE_LIMIT_MS}. Both
318
+ * deletes run in the key's {@link oneAtATime} queue, which has no deadline of
319
+ * its own: a Keychain or Keystore delete that hung would hold every later
320
+ * `complete()` and `sendCodeSecret()` of the key until the app is killed.
321
+ *
322
+ * This bounds only the wait here: the native delete is not cancelled. Both
323
+ * native SDKs run it one at a time with the key's other storage calls
324
+ * (Android's `resolutionLock`, iOS's metadata executor), so while storage
325
+ * stays hung the key's next native calls wait behind it too. They still end:
326
+ * `complete()` reads the key and its secret under its own deadline and fails
327
+ * with `transport`, and a retried send hits this limit again. Once storage
328
+ * recovers, the next call succeeds.
329
+ *
330
+ * Accepted trade-off: a delete that timed out may still finish later. The
331
+ * native SDKs delete only a stored secret equal to `secret`, so it can't
332
+ * remove a newer one. But the key's next registration may read `secret` back
333
+ * from storage and seal it again before the late delete removes it. The code
334
+ * still shows in this process, which keeps the secret in memory; only after a
335
+ * restart does that request answer `matching_code_unavailable`, as it did
336
+ * before secrets were stored. This only happens after a hang.
337
+ */
338
+ async function deleteWithinLimit(authKey: OwnerAuthKey, secret: Uint8Array): Promise<void> {
339
+ if (authKey.deleteCodeSecret === undefined) {
340
+ return
341
+ }
342
+ let timer: ReturnType<typeof setTimeout> | undefined
343
+ const limit = new Promise<never>((_, reject) => {
344
+ timer = setTimeout(
345
+ () =>
346
+ reject(
347
+ new DaaError(
348
+ { kind: 'transport', retryable: true },
349
+ `DAA: deleting the code secret from the device key's storage did not finish within ${CODE_SECRET_DELETE_LIMIT_MS / 1000} seconds`,
350
+ ),
351
+ ),
352
+ CODE_SECRET_DELETE_LIMIT_MS,
353
+ )
354
+ })
355
+ try {
356
+ await Promise.race([authKey.deleteCodeSecret(secret), limit])
357
+ } finally {
358
+ clearTimeout(timer)
359
+ }
360
+ }
@@ -19,8 +19,17 @@
19
19
  import { toBase64Url } from '../crypto/base64url'
20
20
  import { toArrayBuffer } from '../crypto/bytes'
21
21
  import { p256JwkThumbprint } from '../crypto/jwkThumbprint'
22
+ import { randomBytes } from '../crypto/random'
22
23
  import { secureKeyAlias } from './alias'
23
- import type { AuthKeyResolution, OwnerAuthKey, OwnerKeyIdentity, SecureKeyStore } from './SecureKey'
24
+ import { assertRegistration } from './registration'
25
+ import type {
26
+ AuthKeyRegistration,
27
+ AuthKeyResolution,
28
+ OwnerAuthKey,
29
+ OwnerKeyIdentity,
30
+ RegisteredOwnerAuthKey,
31
+ SecureKeyStore,
32
+ } from './SecureKey'
24
33
 
25
34
  // A WebCrypto-backed, in-memory implementation of the DAA Owner-key API. It
26
35
  // produces real P-256/ES256 signatures so it can drive golden vectors and unit
@@ -59,7 +68,8 @@ class InMemoryOwnerAuthKey implements OwnerAuthKey {
59
68
  // There is no durable store behind this double, so a handle always starts
60
69
  // unacknowledged and the state lives only as long as the handle does. The
61
70
  // native store persists the equivalent state in the OS keystore.
62
- #acknowledged = false
71
+ #registration: Omit<RegisteredOwnerAuthKey, 'authKey'> | null = null
72
+ #codeSecret: Uint8Array | null = null
63
73
  readonly #keyPair: CryptoKeyPair
64
74
 
65
75
  constructor(keyPair: CryptoKeyPair) {
@@ -67,11 +77,18 @@ class InMemoryOwnerAuthKey implements OwnerAuthKey {
67
77
  }
68
78
 
69
79
  resolution(): AuthKeyResolution {
70
- return this.#acknowledged ? 'existing' : 'created'
80
+ return this.#registration === null ? 'created' : 'existing'
71
81
  }
72
82
 
73
- async acknowledgeRegistration(): Promise<void> {
74
- this.#acknowledged = true
83
+ /** @internal The recorded registration, read by the store's `resolveExisting`. */
84
+ registration(): Omit<RegisteredOwnerAuthKey, 'authKey'> | null {
85
+ return this.#registration
86
+ }
87
+
88
+ async acknowledgeRegistration(registration: AuthKeyRegistration): Promise<void> {
89
+ // Same contract as the native store: UUID identifiers, always an upsert.
90
+ const { authKeyId, ownerBindingId } = assertRegistration(registration)
91
+ this.#registration = Object.freeze({ authKeyId, ownerBindingId })
75
92
  }
76
93
 
77
94
  async publicKeySpkiBase64Url(): Promise<string> {
@@ -102,10 +119,30 @@ class InMemoryOwnerAuthKey implements OwnerAuthKey {
102
119
  // caller reached; native's two validators are what actually diverge.
103
120
  return this.signExactBytes(message)
104
121
  }
122
+
123
+ async signDeviceApproval(message: Uint8Array): Promise<Uint8Array> {
124
+ // Same as above: one WebCrypto key. Native's body, seal and typed-code
125
+ // checks are not repeated here; `approveDevice` runs its own before it
126
+ // signs, and the native SDKs' tests pin theirs.
127
+ return this.signExactBytes(message)
128
+ }
129
+
130
+ async codeSecret(): Promise<Uint8Array> {
131
+ // Same contract as native: kept until deleted, a copy on every read.
132
+ this.#codeSecret ??= randomBytes(32)
133
+ return this.#codeSecret.slice()
134
+ }
135
+
136
+ async deleteCodeSecret(secret: Uint8Array): Promise<void> {
137
+ const kept = this.#codeSecret
138
+ if (kept !== null && kept.length === secret.length && kept.every((b, i) => b === secret[i])) {
139
+ this.#codeSecret = null
140
+ }
141
+ }
105
142
  }
106
143
 
107
144
  export class InMemorySecureKeyStore implements SecureKeyStore {
108
- readonly #keys = new Map<string, Promise<OwnerAuthKey>>()
145
+ readonly #keys = new Map<string, Promise<InMemoryOwnerAuthKey>>()
109
146
 
110
147
  constructor() {
111
148
  assertDevelopmentEnvironment()
@@ -126,7 +163,24 @@ export class InMemorySecureKeyStore implements SecureKeyStore {
126
163
  return existing
127
164
  }
128
165
 
129
- async #generate(): Promise<OwnerAuthKey> {
166
+ async resolveExisting(identity: OwnerKeyIdentity): Promise<RegisteredOwnerAuthKey | null> {
167
+ // Read-only, like the native store: an absent or unacknowledged key is
168
+ // `null`, and nothing is generated. A failed generation rethrows, as a
169
+ // native read failure does — a failure is never "no key".
170
+ const pending = this.#keys.get(secureKeyAlias(identity))
171
+ if (pending === undefined) {
172
+ return null
173
+ }
174
+ const authKey = await pending
175
+ const registration = authKey.registration()
176
+ return registration === null ? null : Object.freeze({ authKey, ...registration })
177
+ }
178
+
179
+ async forget(identity: OwnerKeyIdentity): Promise<void> {
180
+ this.#keys.delete(secureKeyAlias(identity))
181
+ }
182
+
183
+ async #generate(): Promise<InMemoryOwnerAuthKey> {
130
184
  const keyPair = (await getSubtle().generateKey(
131
185
  { name: 'ECDSA', namedCurve: 'P-256' },
132
186
  // Non-exportable private key; the public key is still exportable.