@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
@@ -27,16 +27,22 @@
27
27
  // `DeviceContext.authKeyId` supplies the JWS `kid` alongside it.
28
28
  //
29
29
  // The lazy `NativeSecureKeyStore` is why this is a factory rather than a free
30
- // function. Constructing the store requires the Expo `DaaSecureKey` module, and
31
- // `DaaClient` construction deliberately does not; the store is therefore built
32
- // on first resolution and then reused, so login and every later signed write
33
- // share one store — and so share its in-flight `resolveOrCreate` map rather
34
- // than racing two independent handles for the same alias.
30
+ // function. Reaching the store requires the Expo `DaaSecureKey` module, and
31
+ // `DaaClient` construction deliberately does not; the store is therefore looked
32
+ // up on first resolution. It is one store per process, shared by every
33
+ // `DaaClient` (see `resolveNativeSecureKeyStore`), so login, every later signed
34
+ // write, and a forget through any client share one in-flight `resolveOrCreate`
35
+ // map rather than racing independent handles for the same alias.
35
36
 
36
37
  import { contractViolation } from '../errors'
37
- import { NativeSecureKeyStore } from './NativeSecureKey'
38
- import { resolveNativeBridge } from './resolveNativeBridge'
39
- import type { AppKeyIdentity, OwnerAuthKey, SecureKeyStore } from './SecureKey'
38
+ import type { NativeSecureKeyStore } from './NativeSecureKey'
39
+ import { resolveNativeSecureKeyStore } from './resolveNativeBridge'
40
+ import type {
41
+ AppKeyIdentity,
42
+ OwnerAuthKey,
43
+ RegisteredOwnerAuthKey,
44
+ SecureKeyStore,
45
+ } from './SecureKey'
40
46
 
41
47
  /**
42
48
  * Resolves the installation AuthKey for one already-known Owner.
@@ -46,7 +52,7 @@ import type { AppKeyIdentity, OwnerAuthKey, SecureKeyStore } from './SecureKey'
46
52
  * its choosing, and no store to resolve a different one from. This is the
47
53
  * shape `DaaUserSigning.resolveAuthKey` (`api/signedResource.ts`) needs,
48
54
  * because by the time `forUser` builds one it already knows which Owner it is
49
- * signing for. It is NOT the shape {@link createOwnerAuthKeyResolver} returns
55
+ * signing for. It is NOT the shape {@link AppOwnerKeys.resolveOrCreate} has
50
56
  * — see {@link AppAuthKeyResolver}.
51
57
  */
52
58
  export type OwnerAuthKeyResolver = () => Promise<OwnerAuthKey>
@@ -67,30 +73,63 @@ export type OwnerAuthKeyResolver = () => Promise<OwnerAuthKey>
67
73
  export type AppAuthKeyResolver = (clientEntityId: string) => Promise<OwnerAuthKey>
68
74
 
69
75
  /**
70
- * Build the resolver for one application identity.
76
+ * Every AuthKey operation `DaaClient` needs for one application identity,
77
+ * over one shared store: login and `forUser` resolve (or create) the key, while
78
+ * session restore reads an already-registered one, and an explicit
79
+ * `forgetLocalKey` deletes it.
80
+ *
81
+ * `#`-private on `DaaClient` for the same reason {@link AppAuthKeyResolver} is:
82
+ * a holder could reach an {@link OwnerAuthKey} and so a generic signing
83
+ * surface.
84
+ */
85
+ export type AppOwnerKeys = Readonly<{
86
+ /** Resolve the Owner's AuthKey, creating it only when absent. */
87
+ resolveOrCreate: AppAuthKeyResolver
88
+ /** Read-only: the Owner's registered AuthKey and its identifiers, or `null`. */
89
+ resolveExisting: (clientEntityId: string) => Promise<RegisteredOwnerAuthKey | null>
90
+ /** Delete the Owner's AuthKey on this device. Local only; no revocation. */
91
+ forget: (clientEntityId: string) => Promise<void>
92
+ }>
93
+
94
+ /**
95
+ * Build {@link AppOwnerKeys} for one application identity.
71
96
  *
72
97
  * @param identity App-level identity (`appId`, `environment`); `null` when
73
98
  * the SDK has no application identity to select a key with, which fails
74
- * closed at the first resolution rather than at construction —
75
- * `AuthClient` is built for Prepare, and Prepare never touches an
76
- * AuthKey.
77
- * @param secureKeys Injected store, which tests substitute. Absent, the native
78
- * store is constructed on first use and reused.
99
+ * closed at the first use rather than at construction.
100
+ * @param secureKeys Injected store, which tests substitute. Absent, the
101
+ * process-wide native store is looked up on first use and reused by all
102
+ * three operations.
79
103
  */
80
- export function createOwnerAuthKeyResolver(
104
+ export function createAppOwnerKeys(
81
105
  identity: AppKeyIdentity | null,
82
106
  secureKeys: SecureKeyStore | null,
83
- ): AppAuthKeyResolver {
84
- // The mutable slot the lazily-constructed native store fills. A closure
85
- // variable rather than a field because the clients holding this resolver are
86
- // sealed with `Object.freeze`.
107
+ ): AppOwnerKeys {
108
+ // The mutable slot the process-wide native store fills on first use. A closure
109
+ // variable rather than a field because the clients holding this are sealed
110
+ // with `Object.freeze`.
87
111
  let nativeStore: NativeSecureKeyStore | null = null
88
-
89
- return async (clientEntityId: string) => {
112
+ const store = (): { store: SecureKeyStore; identity: AppKeyIdentity } => {
90
113
  if (identity === null) {
91
114
  throw contractViolation('AuthKey selection requires the DaaClient application identity')
92
115
  }
93
- const store = secureKeys ?? (nativeStore ??= new NativeSecureKeyStore(resolveNativeBridge()))
94
- return store.resolveOrCreate({ ...identity, clientEntityId })
116
+ return {
117
+ store: secureKeys ?? (nativeStore ??= resolveNativeSecureKeyStore()),
118
+ identity,
119
+ }
95
120
  }
121
+ return Object.freeze({
122
+ resolveOrCreate: async (clientEntityId: string) => {
123
+ const resolved = store()
124
+ return resolved.store.resolveOrCreate({ ...resolved.identity, clientEntityId })
125
+ },
126
+ resolveExisting: async (clientEntityId: string) => {
127
+ const resolved = store()
128
+ return resolved.store.resolveExisting({ ...resolved.identity, clientEntityId })
129
+ },
130
+ forget: async (clientEntityId: string) => {
131
+ const resolved = store()
132
+ return resolved.store.forget({ ...resolved.identity, clientEntityId })
133
+ },
134
+ })
96
135
  }
@@ -0,0 +1,40 @@
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 { isRecord } from '../config'
20
+ import { contractViolation } from '../errors'
21
+ import { isUuid } from '../validation/uuid'
22
+ import type { AuthKeyRegistration } from './SecureKey'
23
+
24
+ // Both identifiers are UUIDs on the wire (the DeviceContext decoder already
25
+ // requires it) and native rejects anything else; checking here fails closed on
26
+ // both platforms the same way, before the bridge is reached. Shared by the
27
+ // native and in-memory stores so both reject a bad argument with the same
28
+ // error, without the in-memory double importing the native store.
29
+ export function assertRegistration(registration: AuthKeyRegistration): AuthKeyRegistration {
30
+ if (
31
+ !isRecord(registration) ||
32
+ typeof registration.authKeyId !== 'string' ||
33
+ typeof registration.ownerBindingId !== 'string' ||
34
+ !isUuid(registration.authKeyId) ||
35
+ !isUuid(registration.ownerBindingId)
36
+ ) {
37
+ throw contractViolation('AuthKey registration identifiers must be UUIDs')
38
+ }
39
+ return registration
40
+ }
@@ -21,7 +21,12 @@ import { DEVICE_KEY_POLICY, isRecord } from '../config'
21
21
  import type { DeviceKeyPolicy } from '../config'
22
22
  import { contractViolation } from '../errors'
23
23
  import { parseSecureKeyAlias } from './alias'
24
- import type { NativeAuthKeyResolution, NativeSecureKeyBridge } from './NativeSecureKeyBridge'
24
+ import { NativeSecureKeyStore } from './NativeSecureKey'
25
+ import type {
26
+ NativeAuthKeyResolution,
27
+ NativeRegisteredAuthKey,
28
+ NativeSecureKeyBridge,
29
+ } from './NativeSecureKeyBridge'
25
30
 
26
31
  // JS shape of the Expo `DaaSecureKey` native module. Identity is passed as
27
32
  // structured `{appId, environment}` fields after TypeScript parses the RN
@@ -40,7 +45,26 @@ interface DaaSecureKeyNativeModule {
40
45
  declaredKeyPolicy?: () => unknown
41
46
  resolveOrCreate(appId: string, environment: string): Promise<string>
42
47
  publicKeySpkiBase64Url(appId: string, environment: string): Promise<string>
43
- acknowledgeRegistration(appId: string, environment: string): Promise<void>
48
+ acknowledgeRegistration(
49
+ appId: string,
50
+ environment: string,
51
+ authKeyId: string,
52
+ ownerBindingId: string,
53
+ ): Promise<void>
54
+ /**
55
+ * Native `DaaSecureKey.resolveExisting()`: the registration record as
56
+ * `{ authKeyId, ownerBindingId }`, or `null`.
57
+ * Read-only; never mints a key and never prompts. Optional at the type level
58
+ * so a native module built before it existed fails closed in the wrapper
59
+ * below rather than with an untyped `undefined is not a function`.
60
+ */
61
+ resolveExisting?: (appId: string, environment: string) => Promise<unknown>
62
+ /**
63
+ * Native `DaaSecureKey.forgetLocalKey()`: deletes the key and its local
64
+ * metadata. Local only, idempotent. Optional for the same reason as
65
+ * {@link resolveExisting}.
66
+ */
67
+ forgetLocalKey?: (appId: string, environment: string) => Promise<void>
44
68
  signDeviceAuthorization(
45
69
  appId: string,
46
70
  environment: string,
@@ -57,6 +81,30 @@ interface DaaSecureKeyNativeModule {
57
81
  environment: string,
58
82
  signingInputBase64Url: string,
59
83
  ): Promise<string>
84
+ /**
85
+ * The `approve_device` counterpart of {@link signDeviceAuthorization}: native
86
+ * checks the approval body, code secret and typed code against the signing
87
+ * input before any biometric prompt. Optional for the same reason as
88
+ * {@link resolveExisting}.
89
+ */
90
+ signDeviceApproval?: (
91
+ appId: string,
92
+ environment: string,
93
+ signingInputBase64Url: string,
94
+ requestBodyBase64Url: string,
95
+ codeSecretBase64Url: string,
96
+ enteredCode: string,
97
+ ) => Promise<string>
98
+ /**
99
+ * Native `DaaSecureKey.codeSecret()`, as unpadded Base64URL. Optional for
100
+ * the same reason as {@link resolveExisting}.
101
+ */
102
+ codeSecret?: (appId: string, environment: string) => Promise<string>
103
+ /**
104
+ * Native `DaaSecureKey.deleteCodeSecret(_:)`. Optional for the same reason
105
+ * as {@link resolveExisting}.
106
+ */
107
+ deleteCodeSecret?: (appId: string, environment: string, secretBase64Url: string) => Promise<void>
60
108
  }
61
109
 
62
110
  /**
@@ -102,6 +150,28 @@ function assertNativeDeclaredKeyPolicy(
102
150
  // Node / Jest have no native module: fail closed rather than silently no-op.
103
151
  // Tests inject a NativeSecureKeyBridge explicitly.
104
152
  export function resolveNativeBridge(): NativeSecureKeyBridge {
153
+ return wrapNativeModule(requireNativeModule())
154
+ }
155
+
156
+ // One store per native module, so per process in an app. Native keeps one key
157
+ // per alias for the whole process, so every DaaClient must share one handle
158
+ // cache: a forget through one client otherwise leaves another client's cached
159
+ // handle pointing at the deleted key. Keyed by the module object rather than
160
+ // a plain singleton so a test that installs a fresh fake gets a fresh store.
161
+ const nativeStores = new WeakMap<DaaSecureKeyNativeModule, NativeSecureKeyStore>()
162
+
163
+ /** The process-wide {@link NativeSecureKeyStore} over the DaaSecureKey module. */
164
+ export function resolveNativeSecureKeyStore(): NativeSecureKeyStore {
165
+ const native = requireNativeModule()
166
+ let store = nativeStores.get(native)
167
+ if (store === undefined) {
168
+ store = new NativeSecureKeyStore(wrapNativeModule(native))
169
+ nativeStores.set(native, store)
170
+ }
171
+ return store
172
+ }
173
+
174
+ function requireNativeModule(): DaaSecureKeyNativeModule {
105
175
  const native = requireOptionalNativeModule<DaaSecureKeyNativeModule>('DaaSecureKey')
106
176
  if (native === null) {
107
177
  throw contractViolation(
@@ -111,7 +181,7 @@ export function resolveNativeBridge(): NativeSecureKeyBridge {
111
181
  )
112
182
  }
113
183
  assertNativeDeclaredKeyPolicy(native, DEVICE_KEY_POLICY)
114
- return wrapNativeModule(native)
184
+ return native
115
185
  }
116
186
 
117
187
  function wrapNativeModule(native: DaaSecureKeyNativeModule): NativeSecureKeyBridge {
@@ -130,13 +200,55 @@ function wrapNativeModule(native: DaaSecureKeyNativeModule): NativeSecureKeyBrid
130
200
  return await native.publicKeySpkiBase64Url(identity.appId, identity.environment)
131
201
  },
132
202
 
133
- async acknowledgeRegistration(alias: string): Promise<void> {
134
- // Calls the acknowledgeRegistration the Expo module already exposes on
135
- // both platforms; no parallel native API is introduced. Native owns
136
- // idempotence and persistence (Data Protection Keychain on iOS,
137
- // app-private storage on Android).
203
+ async acknowledgeRegistration(
204
+ alias: string,
205
+ authKeyId: string,
206
+ ownerBindingId: string,
207
+ ): Promise<void> {
208
+ // Native `acknowledgeRegistration(authKeyId, ownerBindingId)`, which
209
+ // always upserts the identifiers into the durable registration record
210
+ // (Data Protection Keychain on iOS, app-private storage on Android). The
211
+ // no-identifier variant is not reached from here: it records no ids, so
212
+ // a key acknowledged only that way has nothing for resolveExisting to read.
213
+ const identity = parseSecureKeyAlias(alias)
214
+ await native.acknowledgeRegistration(
215
+ identity.appId,
216
+ identity.environment,
217
+ authKeyId,
218
+ ownerBindingId,
219
+ )
220
+ },
221
+
222
+ async resolveExisting(alias: string): Promise<NativeRegisteredAuthKey | null> {
223
+ // Read-only on purpose: this lookup must never reach
224
+ // resolveOrCreate, which would mint a fresh, unregistered key.
225
+ const resolveExisting = native.resolveExisting
226
+ if (typeof resolveExisting !== 'function') {
227
+ throw contractViolation('native DaaSecureKey.resolveExisting is required')
228
+ }
229
+ const identity = parseSecureKeyAlias(alias)
230
+ const record = await resolveExisting.call(native, identity.appId, identity.environment)
231
+ // Only an explicit null is "no key": Expo delivers a Swift nil or a
232
+ // Kotlin null return as JS null. `undefined` is not a shape native
233
+ // sends, so it fails closed below instead of becoming "no key".
234
+ if (record === null) {
235
+ return null
236
+ }
237
+ if (!isRecord(record)) {
238
+ throw contractViolation('native resolveExisting returned an unknown shape')
239
+ }
240
+ // Field-level validation happens once, at the store seam
241
+ // (NativeSecureKeyStore), which also covers injected stand-ins.
242
+ return record as NativeRegisteredAuthKey
243
+ },
244
+
245
+ async forgetLocalKey(alias: string): Promise<void> {
246
+ const forgetLocalKey = native.forgetLocalKey
247
+ if (typeof forgetLocalKey !== 'function') {
248
+ throw contractViolation('native DaaSecureKey.forgetLocalKey is required')
249
+ }
138
250
  const identity = parseSecureKeyAlias(alias)
139
- await native.acknowledgeRegistration(identity.appId, identity.environment)
251
+ await forgetLocalKey.call(native, identity.appId, identity.environment)
140
252
  },
141
253
 
142
254
  async sign(alias: string, messageBase64Url: string): Promise<string> {
@@ -148,6 +260,8 @@ function wrapNativeModule(native: DaaSecureKeyNativeModule): NativeSecureKeyBrid
148
260
  if (typeof native.signDeviceAuthorization !== 'function') {
149
261
  throw contractViolation('native DaaSecureKey.signDeviceAuthorization is required')
150
262
  }
263
+ // No prompt text crosses the bridge: the native SDK derives the
264
+ // biometric prompt from the validated operation itself.
151
265
  const identity = parseSecureKeyAlias(alias)
152
266
  return await native.signDeviceAuthorization(
153
267
  identity.appId,
@@ -156,6 +270,50 @@ function wrapNativeModule(native: DaaSecureKeyNativeModule): NativeSecureKeyBrid
156
270
  )
157
271
  },
158
272
 
273
+ async signDeviceApproval(
274
+ alias: string,
275
+ messageBase64Url: string,
276
+ requestBodyBase64Url: string,
277
+ codeSecretBase64Url: string,
278
+ enteredCode: string,
279
+ ): Promise<string> {
280
+ // Native `DaaDeviceAuthorizationSigningInput` approval initializer (iOS)
281
+ // or `forDeviceApproval` (Android). Like `sign`, no prompt text crosses
282
+ // the bridge: native shows the matching code it derived itself.
283
+ const signDeviceApproval = native.signDeviceApproval
284
+ if (typeof signDeviceApproval !== 'function') {
285
+ throw contractViolation('native DaaSecureKey.signDeviceApproval is required')
286
+ }
287
+ const identity = parseSecureKeyAlias(alias)
288
+ return await signDeviceApproval.call(
289
+ native,
290
+ identity.appId,
291
+ identity.environment,
292
+ messageBase64Url,
293
+ requestBodyBase64Url,
294
+ codeSecretBase64Url,
295
+ enteredCode,
296
+ )
297
+ },
298
+
299
+ async codeSecret(alias: string): Promise<string> {
300
+ const codeSecret = native.codeSecret
301
+ if (typeof codeSecret !== 'function') {
302
+ throw contractViolation('native DaaSecureKey.codeSecret is required')
303
+ }
304
+ const identity = parseSecureKeyAlias(alias)
305
+ return await codeSecret.call(native, identity.appId, identity.environment)
306
+ },
307
+
308
+ async deleteCodeSecret(alias: string, secretBase64Url: string): Promise<void> {
309
+ const deleteCodeSecret = native.deleteCodeSecret
310
+ if (typeof deleteCodeSecret !== 'function') {
311
+ throw contractViolation('native DaaSecureKey.deleteCodeSecret is required')
312
+ }
313
+ const identity = parseSecureKeyAlias(alias)
314
+ await deleteCodeSecret.call(native, identity.appId, identity.environment, secretBase64Url)
315
+ },
316
+
159
317
  async signRegistrationDeviceAuthorization(
160
318
  alias: string,
161
319
  messageBase64Url: string,
@@ -44,3 +44,50 @@ export function headerValueIgnoringCase(
44
44
  }
45
45
  return null
46
46
  }
47
+
48
+ const MONTHS = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
49
+ const IMF_FIXDATE =
50
+ /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), (\d{2}) (Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) (\d{4}) (\d{2}):(\d{2}):(\d{2}) GMT$/
51
+
52
+ /**
53
+ * Parse an HTTP `Date` header value (RFC 9110 IMF-fixdate, e.g.
54
+ * `Sun, 06 Nov 1994 08:49:37 GMT`) to epoch milliseconds.
55
+ *
56
+ * Parsed by hand rather than with `Date.parse`, whose handling of this format
57
+ * is implementation-defined and differs across JavaScript engines. Returns
58
+ * `null` for an absent header or any value that is not a valid IMF-fixdate
59
+ * (including the obsolete RFC 850 and asctime forms), so a caller treats an
60
+ * unreadable `Date` exactly like a missing one.
61
+ */
62
+ export function httpDateMillis(value: string | null): number | null {
63
+ if (value === null) {
64
+ return null
65
+ }
66
+ const match = IMF_FIXDATE.exec(value.trim())
67
+ if (match === null) {
68
+ return null
69
+ }
70
+ const [, day, month, year, hour, minute, second] = match
71
+ const monthIndex = MONTHS.indexOf(month ?? '')
72
+ const millis = Date.UTC(
73
+ Number(year),
74
+ monthIndex,
75
+ Number(day),
76
+ Number(hour),
77
+ Number(minute),
78
+ Number(second),
79
+ )
80
+ // Reject a calendar-invalid value such as `31 Feb`, which Date.UTC would
81
+ // otherwise silently roll over into the next month.
82
+ const parsed = new Date(millis)
83
+ if (
84
+ parsed.getUTCDate() !== Number(day) ||
85
+ parsed.getUTCMonth() !== monthIndex ||
86
+ Number(hour) > 23 ||
87
+ Number(minute) > 59 ||
88
+ Number(second) > 60
89
+ ) {
90
+ return null
91
+ }
92
+ return millis
93
+ }
@@ -0,0 +1,152 @@
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 {
20
+ type AbiParameter,
21
+ ContractExecution,
22
+ type ContractExecutionErrorCode,
23
+ type ContractExecutionInvocation,
24
+ type ContractExecutionSource,
25
+ type ContractExecutionStatus,
26
+ } from '../models/ContractExecution'
27
+ import { optionalMoney, requiredMoney } from './moneyPayload'
28
+ import {
29
+ asObject,
30
+ MalformedPayloadError,
31
+ optionalString,
32
+ requiredString,
33
+ unrecognized,
34
+ } from './payload'
35
+
36
+ /**
37
+ * Wire payload -> public `ContractExecution` model, and the required/optional
38
+ * line.
39
+ *
40
+ * The service omits null fields, so an absent `transactionHash`, `networkFee`,
41
+ * or `errorCode` is the ordinary "not known yet" / "not failed" case and
42
+ * decodes to `null`. The invocation is required in exactly one mode: a
43
+ * response carrying both or neither is not one the service produces, and is
44
+ * rejected rather than guessed at.
45
+ */
46
+
47
+ // `Map` rather than an object literal, for the reason `wire/transferPayload.ts`
48
+ // gives: a wire value spelled like an `Object.prototype` member must not be
49
+ // "recognised".
50
+ const STATUSES = new Map<string, ContractExecutionStatus>([
51
+ ['pending', Object.freeze({ kind: 'pending' })],
52
+ ['complete', Object.freeze({ kind: 'complete' })],
53
+ ['failed', Object.freeze({ kind: 'failed' })],
54
+ ])
55
+
56
+ const ERROR_CODES = new Map<string, ContractExecutionErrorCode>([
57
+ ['authorization_failed', Object.freeze({ kind: 'authorization_failed' })],
58
+ ['execution_denied', Object.freeze({ kind: 'execution_denied' })],
59
+ ['insufficient_funds', Object.freeze({ kind: 'insufficient_funds' })],
60
+ ['insufficient_network_fee', Object.freeze({ kind: 'insufficient_network_fee' })],
61
+ ['blockchain_error', Object.freeze({ kind: 'blockchain_error' })],
62
+ ['contract_execution_failed', Object.freeze({ kind: 'contract_execution_failed' })],
63
+ ])
64
+
65
+ function toStatus(raw: string): ContractExecutionStatus {
66
+ return STATUSES.get(raw) ?? unrecognized(raw)
67
+ }
68
+
69
+ /** Present only when the status is `failed`; absent is `null`, not `unrecognized`. */
70
+ function toErrorCode(raw: string | null): ContractExecutionErrorCode | null {
71
+ if (raw === null) {
72
+ return null
73
+ }
74
+ return ERROR_CODES.get(raw) ?? unrecognized(raw)
75
+ }
76
+
77
+ function toSource(value: unknown): ContractExecutionSource {
78
+ const payload = asObject(value, 'source')
79
+ const type = requiredString(payload, 'type', 'source.type')
80
+ if (type !== 'account') {
81
+ return unrecognized(type)
82
+ }
83
+ return Object.freeze({
84
+ kind: 'account' as const,
85
+ accountId: requiredString(payload, 'id', 'source.id'),
86
+ })
87
+ }
88
+
89
+ /**
90
+ * One ABI input as the service echoes it: the stored request's own values.
91
+ *
92
+ * The service accepted only strings, booleans, safe JSON integers, and nested
93
+ * arrays of those, so anything else — and in particular a JSON number that is
94
+ * not a safe integer, which `JSON.parse` has already rounded — is malformed
95
+ * rather than passed on as a value the Owner never authorized.
96
+ */
97
+ function toAbiParameter(value: unknown): AbiParameter {
98
+ if (typeof value === 'string' || typeof value === 'boolean') {
99
+ return value
100
+ }
101
+ if (typeof value === 'number' && Number.isSafeInteger(value)) {
102
+ return value
103
+ }
104
+ if (Array.isArray(value)) {
105
+ return Object.freeze(value.map(toAbiParameter))
106
+ }
107
+ throw new MalformedPayloadError('abiParameters')
108
+ }
109
+
110
+ function toInvocation(payload: Record<string, unknown>): ContractExecutionInvocation {
111
+ const callData = optionalString(payload, 'callData')
112
+ const abiFunctionSignature = optionalString(payload, 'abiFunctionSignature')
113
+ const abiParameters = payload['abiParameters']
114
+ const hasAbiParameters = abiParameters !== undefined && abiParameters !== null
115
+
116
+ if (callData !== null && abiFunctionSignature === null && !hasAbiParameters) {
117
+ return Object.freeze({ kind: 'raw' as const, callData })
118
+ }
119
+ if (callData === null && abiFunctionSignature !== null && Array.isArray(abiParameters)) {
120
+ return Object.freeze({
121
+ kind: 'abi' as const,
122
+ abiFunctionSignature,
123
+ abiParameters: Object.freeze(abiParameters.map(toAbiParameter)),
124
+ })
125
+ }
126
+ throw new MalformedPayloadError('invocation')
127
+ }
128
+
129
+ /**
130
+ * Map a decoded `ContractExecution` payload onto the public model.
131
+ *
132
+ * @throws MalformedPayloadError
133
+ */
134
+ export function toContractExecution(value: unknown): ContractExecution {
135
+ const payload = asObject(value, 'contractExecution')
136
+
137
+ return new ContractExecution({
138
+ id: requiredString(payload, 'id'),
139
+ status: toStatus(requiredString(payload, 'status')),
140
+ errorCode: toErrorCode(optionalString(payload, 'errorCode')),
141
+ source: toSource(payload['source']),
142
+ custodyType: requiredString(payload, 'custodyType'),
143
+ blockchain: requiredString(payload, 'blockchain'),
144
+ contractAddress: requiredString(payload, 'contractAddress'),
145
+ invocation: toInvocation(payload),
146
+ amount: requiredMoney(payload, 'amount'),
147
+ networkFee: optionalMoney(payload, 'networkFee'),
148
+ transactionHash: optionalString(payload, 'transactionHash'),
149
+ createDate: requiredString(payload, 'createDate'),
150
+ updateDate: requiredString(payload, 'updateDate'),
151
+ })
152
+ }
@@ -34,9 +34,18 @@
34
34
  *
35
35
  * The signed-request mapping (`api/signedResource.ts`) matches
36
36
  * `DEVICE_AUTHORIZATION_INVALID`, `IDEMPOTENCY_KEY_REUSED`,
37
- * `DEVICE_AUTHORIZATION_REQUEST_MISMATCH` and `DEVICE_AUTHORIZATION_REPLAYED`.
38
- * The login mapping (`api/loginFailure.ts`) matches `IDEMPOTENCY_KEY_REUSED`
39
- * and `LOGIN_REQUEST_CONSUMED`. The unsigned deposit-address create
37
+ * `DEVICE_AUTHORIZATION_REQUEST_MISMATCH`, `DEVICE_AUTHORIZATION_REPLAYED` and
38
+ * `DEVICE_PENDING` (the signing key is still waiting for approval or in its
39
+ * cool-down).
40
+ * The login mapping (`api/loginFailure.ts`) matches `IDEMPOTENCY_KEY_REUSED`,
41
+ * `LOGIN_REQUEST_CONSUMED` and, on Device Registration Complete, the four
42
+ * add-a-device codes (`DEVICE_REGISTRATION_LIMIT`, `DEVICE_DENIED`,
43
+ * `DEVICE_APPROVAL_CONFLICT`, `DEVICE_APPROVAL_UNAVAILABLE`). The device
44
+ * approval (`api/deviceApproval.ts`) matches `DEVICE_APPROVAL_INVALID` and
45
+ * `DEVICE_APPROVAL_BUSY`.
46
+ * `PASSKEY_OWNER_CREDENTIAL_KIND_MISMATCH` is in the table because DAA returns
47
+ * it with `409` from Device Registration Complete when the Owner's credential
48
+ * is a passkey; like `AUTH_KEY_BINDING_CONFLICT` it classifies as `api`. The unsigned deposit-address create
40
49
  * (`api/DepositAddressesClient.ts`) matches `IDEMPOTENCY_KEY_REUSED`.
41
50
  * `AUTH_KEY_BINDING_CONFLICT` is in the table because DAA returns it with `409`
42
51
  * from Device Registration Complete. It classifies as `api`, so no mapping
@@ -51,6 +60,14 @@ export const DAA_STATUS_CODES = Object.freeze({
51
60
  AUTH_KEY_BINDING_CONFLICT: 420038,
52
61
  LOGIN_REQUEST_CONSUMED: 420039,
53
62
  DEVICE_AUTHORIZATION_REPLAYED: 420043,
63
+ PASSKEY_OWNER_CREDENTIAL_KIND_MISMATCH: 420080,
64
+ DEVICE_REGISTRATION_LIMIT: 420109,
65
+ DEVICE_DENIED: 420111,
66
+ DEVICE_APPROVAL_CONFLICT: 420112,
67
+ DEVICE_APPROVAL_UNAVAILABLE: 420113,
68
+ DEVICE_APPROVAL_INVALID: 420117,
69
+ DEVICE_PENDING: 420118,
70
+ DEVICE_APPROVAL_BUSY: 420120,
54
71
  } as const satisfies Readonly<Record<string, number>>)
55
72
 
56
73
  export type DaaStatusName = keyof typeof DAA_STATUS_CODES
@@ -30,14 +30,16 @@ function requiredUuidField(payload: Record<string, unknown>, name: string): stri
30
30
  }
31
31
 
32
32
  /**
33
- * Decode the wire `DeviceContext`: the shape Device Registration
34
- * Complete's `context` carries and `get_device_context`
35
- * (`GET /v1/accounts/auth/context`, `DaaUserClient.refreshContext`) returns.
33
+ * Decode the wire `DeviceContext`: the shape `get_device_context`
34
+ * (`GET /v1/accounts/auth/context`, `DaaUserClient.refreshContext`) returns,
35
+ * and the shape Device Registration Complete's `KeyCredential` is renamed to
36
+ * (`wire/deviceRegistrationResultPayload.ts`).
36
37
  *
37
- * One decoder for both, rather than two copies: they are the same
38
- * `DeviceContext` response type, so a divergence between "the shape Complete
39
- * returns" and "the shape refresh returns" would be a service defect, not
40
- * something two independent decoders should each get to interpret.
38
+ * One decoder for both, rather than two copies: DAA builds the
39
+ * `KeyCredential` from the same `DeviceContext`, so a divergence between "the
40
+ * shape Complete returns" and "the shape refresh returns" would be a service
41
+ * defect, not something two independent decoders should each get to
42
+ * interpret.
41
43
  *
42
44
  * `DeviceContext.resolvedAt` is one of the timestamps the service sends in its
43
45
  * default number form, the same as `PreparedSocialLogin.expiresAt`, so the