@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,13 +27,16 @@ var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (
27
27
  if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it");
28
28
  return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver);
29
29
  };
30
- var _NativeOwnerAuthKey_resolution, _NativeOwnerAuthKey_acknowledging, _NativeOwnerAuthKey_bridge, _NativeOwnerAuthKey_alias, _NativeSecureKeyStore_keys, _NativeSecureKeyStore_bridge;
30
+ var _NativeOwnerAuthKey_resolution, _NativeOwnerAuthKey_ackTail, _NativeOwnerAuthKey_bridge, _NativeOwnerAuthKey_alias, _NativeSecureKeyStore_instances, _NativeSecureKeyStore_keys, _NativeSecureKeyStore_generations, _NativeSecureKeyStore_forgetting, _NativeSecureKeyStore_bridge, _NativeSecureKeyStore_assertNotForgotten, _NativeSecureKeyStore_registeredHandle;
31
31
  Object.defineProperty(exports, "__esModule", { value: true });
32
32
  exports.NativeSecureKeyStore = void 0;
33
+ const config_1 = require("../config");
33
34
  const base64url_1 = require("../crypto/base64url");
34
35
  const jwkThumbprint_1 = require("../crypto/jwkThumbprint");
35
36
  const errors_1 = require("../errors");
37
+ const uuid_1 = require("../validation/uuid");
36
38
  const alias_1 = require("./alias");
39
+ const registration_1 = require("./registration");
37
40
  // Production DAA Owner-key store backed by the platform secure-key module. It
38
41
  // holds no key material itself — every operation delegates to the native bridge,
39
42
  // which keeps the non-exportable private key behind the OS keystore/enclave.
@@ -89,41 +92,81 @@ function parseNativeResolution(value) {
89
92
  }
90
93
  throw (0, errors_1.contractViolation)('native resolveOrCreate must return created or existing');
91
94
  }
95
+ // The record resolveExisting returned, validated at the store seam for the same
96
+ // reason as parseNativeResolution: an injected stand-in is untyped at runtime,
97
+ // and these identifiers become a JWS `kid` and an Owner-bound context.
98
+ function parseNativeRegistration(value) {
99
+ if (!(0, config_1.isRecord)(value)) {
100
+ throw (0, errors_1.contractViolation)('native resolveExisting must return a registration record or null');
101
+ }
102
+ const { authKeyId, ownerBindingId } = value;
103
+ if (typeof authKeyId !== 'string' ||
104
+ typeof ownerBindingId !== 'string' ||
105
+ !(0, uuid_1.isUuid)(authKeyId) ||
106
+ !(0, uuid_1.isUuid)(ownerBindingId)) {
107
+ throw (0, errors_1.contractViolation)('native resolveExisting returned malformed registration identifiers');
108
+ }
109
+ return { authKeyId, ownerBindingId };
110
+ }
92
111
  class NativeOwnerAuthKey {
93
112
  constructor(bridge, alias, resolution) {
94
113
  _NativeOwnerAuthKey_resolution.set(this, void 0);
95
- _NativeOwnerAuthKey_acknowledging.set(this, null);
114
+ // The most recently queued acknowledgement. Every acknowledgement chains
115
+ // behind it, so upserts reach native in call order.
116
+ _NativeOwnerAuthKey_ackTail.set(this, null);
96
117
  _NativeOwnerAuthKey_bridge.set(this, void 0);
97
118
  _NativeOwnerAuthKey_alias.set(this, void 0);
98
119
  __classPrivateFieldSet(this, _NativeOwnerAuthKey_bridge, bridge, "f");
99
120
  __classPrivateFieldSet(this, _NativeOwnerAuthKey_alias, alias, "f");
100
121
  __classPrivateFieldSet(this, _NativeOwnerAuthKey_resolution, resolution, "f");
101
122
  }
123
+ /**
124
+ * @internal Native has just confirmed this key's registration
125
+ * (`resolveExisting`). A handle cached as `created` before the key was
126
+ * acknowledged, for example by another `DaaClient`'s store, would otherwise
127
+ * stay `created` and be refused for registered-device signing. Moves it to
128
+ * `existing` and keeps its acknowledgement queue.
129
+ */
130
+ markRegistered() {
131
+ __classPrivateFieldSet(this, _NativeOwnerAuthKey_resolution, 'existing', "f");
132
+ }
102
133
  resolution() {
103
134
  return __classPrivateFieldGet(this, _NativeOwnerAuthKey_resolution, "f");
104
135
  }
105
- async acknowledgeRegistration() {
106
- if (__classPrivateFieldGet(this, _NativeOwnerAuthKey_resolution, "f") === 'existing') {
107
- return;
136
+ async acknowledgeRegistration(registration) {
137
+ const { authKeyId, ownerBindingId } = (0, registration_1.assertRegistration)(registration);
138
+ // No early return once `existing`: native always upserts, which is what
139
+ // lets a re-registration that assigned new identifiers replace the stored
140
+ // ones.
141
+ //
142
+ // Serialized per handle: each acknowledgement waits for the one queued
143
+ // before it (whatever its outcome), so when two calls carry different
144
+ // identifiers the later call's identifiers are the ones native keeps. A
145
+ // call recording the SAME identifiers as the most recently queued one
146
+ // shares it instead of queuing a duplicate round trip — it would write the
147
+ // same record in the same position.
148
+ //
149
+ // The tail is cleared once it settles either way: on success so a later
150
+ // call upserts again rather than trusting an earlier write, and on failure
151
+ // so a transient native error stays retryable instead of being memoized.
152
+ const key = `${authKeyId}\n${ownerBindingId}`;
153
+ const tail = __classPrivateFieldGet(this, _NativeOwnerAuthKey_ackTail, "f");
154
+ if (tail !== null && tail.key === key) {
155
+ return tail.done;
108
156
  }
109
- if (__classPrivateFieldGet(this, _NativeOwnerAuthKey_acknowledging, "f") === null) {
110
- // De-duplicate concurrent callers on one handle to a single native round
111
- // trip, the same way NativeSecureKeyStore.resolveOrCreate does. The
112
- // `existing` check above cannot do it alone: it is synchronous, so two
113
- // callers that do not await between them both observe `created`.
114
- //
115
- // Cleared on failure so a transient native error stays retryable and is
116
- // not memoized as a permanently poisoned acknowledgement.
117
- __classPrivateFieldSet(this, _NativeOwnerAuthKey_acknowledging, guardNative(() => __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").acknowledgeRegistration(__classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f")))
118
- .then(() => {
119
- __classPrivateFieldSet(this, _NativeOwnerAuthKey_resolution, 'existing', "f");
120
- })
121
- .catch((err) => {
122
- __classPrivateFieldSet(this, _NativeOwnerAuthKey_acknowledging, null, "f");
123
- throw err;
124
- }), "f");
125
- }
126
- return __classPrivateFieldGet(this, _NativeOwnerAuthKey_acknowledging, "f");
157
+ const previous = tail === null ? Promise.resolve() : tail.done.catch(() => undefined);
158
+ const done = previous
159
+ .then(() => guardNative(() => __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").acknowledgeRegistration(__classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f"), authKeyId, ownerBindingId)))
160
+ .then(() => {
161
+ __classPrivateFieldSet(this, _NativeOwnerAuthKey_resolution, 'existing', "f");
162
+ })
163
+ .finally(() => {
164
+ if (__classPrivateFieldGet(this, _NativeOwnerAuthKey_ackTail, "f")?.done === done) {
165
+ __classPrivateFieldSet(this, _NativeOwnerAuthKey_ackTail, null, "f");
166
+ }
167
+ });
168
+ __classPrivateFieldSet(this, _NativeOwnerAuthKey_ackTail, { key, done }, "f");
169
+ return done;
127
170
  }
128
171
  async publicKeySpkiBase64Url() {
129
172
  const spki = await guardNative(() => __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").publicKeySpkiBase64Url(__classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f")));
@@ -149,11 +192,51 @@ class NativeOwnerAuthKey {
149
192
  const raw = await guardNative(() => __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").signRegistrationDeviceAuthorization(__classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f"), (0, base64url_1.toBase64Url)(message)));
150
193
  return decodeExact(raw, 64, 'registration signature (JOSE R||S; convert DER ECDSA to R||S)');
151
194
  }
195
+ async signDeviceApproval(message, approval) {
196
+ const signDeviceApproval = __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").signDeviceApproval;
197
+ if (typeof signDeviceApproval !== 'function') {
198
+ throw (0, errors_1.contractViolation)('native DaaSecureKey.signDeviceApproval is required');
199
+ }
200
+ const raw = await guardNative(() => signDeviceApproval.call(__classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f"), __classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f"), (0, base64url_1.toBase64Url)(message), (0, base64url_1.toBase64Url)(approval.requestBody), (0, base64url_1.toBase64Url)(approval.codeSecret), approval.enteredCode));
201
+ return decodeExact(raw, 64, 'approval signature (JOSE R||S; convert DER ECDSA to R||S)');
202
+ }
203
+ async codeSecret() {
204
+ const codeSecret = __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").codeSecret;
205
+ if (typeof codeSecret !== 'function') {
206
+ throw (0, errors_1.contractViolation)('native DaaSecureKey.codeSecret is required');
207
+ }
208
+ const raw = await guardNative(() => codeSecret.call(__classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f"), __classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f")));
209
+ return decodeExact(raw, 32, 'code secret');
210
+ }
211
+ async deleteCodeSecret(secret) {
212
+ const deleteCodeSecret = __classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f").deleteCodeSecret;
213
+ if (typeof deleteCodeSecret !== 'function') {
214
+ throw (0, errors_1.contractViolation)('native DaaSecureKey.deleteCodeSecret is required');
215
+ }
216
+ await guardNative(() => deleteCodeSecret.call(__classPrivateFieldGet(this, _NativeOwnerAuthKey_bridge, "f"), __classPrivateFieldGet(this, _NativeOwnerAuthKey_alias, "f"), (0, base64url_1.toBase64Url)(secret)));
217
+ }
152
218
  }
153
- _NativeOwnerAuthKey_resolution = new WeakMap(), _NativeOwnerAuthKey_acknowledging = new WeakMap(), _NativeOwnerAuthKey_bridge = new WeakMap(), _NativeOwnerAuthKey_alias = new WeakMap();
219
+ _NativeOwnerAuthKey_resolution = new WeakMap(), _NativeOwnerAuthKey_ackTail = new WeakMap(), _NativeOwnerAuthKey_bridge = new WeakMap(), _NativeOwnerAuthKey_alias = new WeakMap();
154
220
  class NativeSecureKeyStore {
155
221
  constructor(bridge) {
156
- _NativeSecureKeyStore_keys.set(this, new Map());
222
+ _NativeSecureKeyStore_instances.add(this);
223
+ _NativeSecureKeyStore_keys.set(this, new Map()
224
+ // Bumped by `forget`, per alias. A `resolveExisting` read that started under
225
+ // an older generation raced a forget, and must not cache or return a handle
226
+ // to the key that forget deleted.
227
+ );
228
+ // Bumped by `forget`, per alias. A `resolveExisting` read that started under
229
+ // an older generation raced a forget, and must not cache or return a handle
230
+ // to the key that forget deleted.
231
+ _NativeSecureKeyStore_generations.set(this, new Map()
232
+ // How many `forget` calls are running for each alias. A read that settles
233
+ // while a delete is still in progress fails closed even when the generation
234
+ // still matches: it may have read the record just before native deleted it.
235
+ );
236
+ // How many `forget` calls are running for each alias. A read that settles
237
+ // while a delete is still in progress fails closed even when the generation
238
+ // still matches: it may have read the record just before native deleted it.
239
+ _NativeSecureKeyStore_forgetting.set(this, new Map());
157
240
  _NativeSecureKeyStore_bridge.set(this, void 0);
158
241
  __classPrivateFieldSet(this, _NativeSecureKeyStore_bridge, bridge, "f");
159
242
  }
@@ -166,13 +249,107 @@ class NativeSecureKeyStore {
166
249
  existing = guardNative(() => __classPrivateFieldGet(this, _NativeSecureKeyStore_bridge, "f").resolveOrCreate(alias))
167
250
  .then((raw) => new NativeOwnerAuthKey(__classPrivateFieldGet(this, _NativeSecureKeyStore_bridge, "f"), alias, parseNativeResolution(raw)))
168
251
  .catch((err) => {
169
- __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").delete(alias);
252
+ // Only this call's own entry: `forget` may have evicted it and a
253
+ // newer resolveOrCreate installed its own in the meantime.
254
+ if (__classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").get(alias) === existing) {
255
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").delete(alias);
256
+ }
170
257
  throw err;
171
258
  });
172
259
  __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").set(alias, existing);
173
260
  }
174
261
  return existing;
175
262
  }
263
+ async resolveExisting(identity) {
264
+ const alias = (0, alias_1.secureKeyAlias)(identity);
265
+ const generation = __classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").get(alias) ?? 0;
266
+ // Never bridge.resolveOrCreate: this is the read-only path. Every call
267
+ // reads native, never joining a read already in flight: an acknowledgement
268
+ // can settle while that read is outstanding, and a caller arriving after it
269
+ // must see the identifiers it recorded.
270
+ const raw = await guardNative(() => __classPrivateFieldGet(this, _NativeSecureKeyStore_bridge, "f").resolveExisting(alias));
271
+ if (raw === null) {
272
+ return null;
273
+ }
274
+ const registration = parseNativeRegistration(raw);
275
+ // Checked before a handle is cached (inside `#registeredHandle`, after each
276
+ // wait), and again before it is returned, since a forget can start after.
277
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_instances, "m", _NativeSecureKeyStore_assertNotForgotten).call(this, alias, generation);
278
+ const authKey = await __classPrivateFieldGet(this, _NativeSecureKeyStore_instances, "m", _NativeSecureKeyStore_registeredHandle).call(this, alias, generation);
279
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_instances, "m", _NativeSecureKeyStore_assertNotForgotten).call(this, alias, generation);
280
+ return Object.freeze({ authKey, ...registration });
281
+ }
282
+ async forget(identity) {
283
+ const alias = (0, alias_1.secureKeyAlias)(identity);
284
+ // Invalidate any resolveExisting already in flight.
285
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").set(alias, (__classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").get(alias) ?? 0) + 1);
286
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").set(alias, (__classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").get(alias) ?? 0) + 1);
287
+ // Evicted before and after: a handle cached here must not outlive the
288
+ // native key it names, even when the native delete fails part-way.
289
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").delete(alias);
290
+ try {
291
+ await guardNative(() => __classPrivateFieldGet(this, _NativeSecureKeyStore_bridge, "f").forgetLocalKey(alias));
292
+ }
293
+ finally {
294
+ // A read that starts while the delete runs fails closed either way: if
295
+ // it settles before the delete does, `#forgetting` is still non-zero;
296
+ // if it settles after, this second bump has changed its generation.
297
+ const pending = (__classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").get(alias) ?? 1) - 1;
298
+ if (pending > 0) {
299
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").set(alias, pending);
300
+ }
301
+ else {
302
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").delete(alias);
303
+ }
304
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").set(alias, (__classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").get(alias) ?? 0) + 1);
305
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").delete(alias);
306
+ }
307
+ }
176
308
  }
177
309
  exports.NativeSecureKeyStore = NativeSecureKeyStore;
178
- _NativeSecureKeyStore_keys = new WeakMap(), _NativeSecureKeyStore_bridge = new WeakMap();
310
+ _NativeSecureKeyStore_keys = new WeakMap(), _NativeSecureKeyStore_generations = new WeakMap(), _NativeSecureKeyStore_forgetting = new WeakMap(), _NativeSecureKeyStore_bridge = new WeakMap(), _NativeSecureKeyStore_instances = new WeakSet(), _NativeSecureKeyStore_assertNotForgotten = function _NativeSecureKeyStore_assertNotForgotten(alias, generation) {
311
+ if ((__classPrivateFieldGet(this, _NativeSecureKeyStore_generations, "f").get(alias) ?? 0) !== generation ||
312
+ (__classPrivateFieldGet(this, _NativeSecureKeyStore_forgetting, "f").get(alias) ?? 0) > 0) {
313
+ throw (0, errors_1.contractViolation)('the local AuthKey was forgotten while it was being read');
314
+ }
315
+ }, _NativeSecureKeyStore_registeredHandle =
316
+ /**
317
+ * The one handle for `alias` that native has just confirmed is registered.
318
+ *
319
+ * One handle per alias, never two: each handle serializes its own
320
+ * acknowledgements, so a second handle for the same key would let upserts
321
+ * reach native out of call order. A cached handle, including a
322
+ * `resolveOrCreate` still in flight, is reused and marked `existing`,
323
+ * since native has just confirmed the registration. Only when nothing usable is
324
+ * cached is a new `existing` handle stored, so a later `resolveOrCreate`
325
+ * (`DaaClient.forUser`) reuses it instead of calling native again.
326
+ *
327
+ * A forget can finish while this waits on a cached resolution. So after
328
+ * every wait, and before touching the cache or a handle, it re-checks
329
+ * `generation`: otherwise it could cache an `existing` handle to the deleted
330
+ * key, or mark a key minted after the forget as `existing`.
331
+ */
332
+ async function _NativeSecureKeyStore_registeredHandle(alias, generation) {
333
+ let cached = __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").get(alias);
334
+ while (cached !== undefined) {
335
+ let handle;
336
+ try {
337
+ handle = await cached;
338
+ }
339
+ catch {
340
+ // That resolveOrCreate failed and has evicted itself. Native has just
341
+ // returned this key's registration, so a failed resolution must not
342
+ // fail this read: reuse whatever replaced it, else mint a fresh handle.
343
+ }
344
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_instances, "m", _NativeSecureKeyStore_assertNotForgotten).call(this, alias, generation);
345
+ if (handle !== undefined) {
346
+ handle.markRegistered();
347
+ return handle;
348
+ }
349
+ const next = __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").get(alias);
350
+ cached = next === cached ? undefined : next;
351
+ }
352
+ const authKey = new NativeOwnerAuthKey(__classPrivateFieldGet(this, _NativeSecureKeyStore_bridge, "f"), alias, 'existing');
353
+ __classPrivateFieldGet(this, _NativeSecureKeyStore_keys, "f").set(alias, Promise.resolve(authKey));
354
+ return authKey;
355
+ };
@@ -17,6 +17,17 @@
17
17
  */
18
18
  import type { AuthKeyResolution } from './SecureKey';
19
19
  export type NativeAuthKeyResolution = AuthKeyResolution;
20
+ /**
21
+ * The registration record native keeps beside a registered key, as the bridge
22
+ * returns it from {@link NativeSecureKeyBridge.resolveExisting}. Untrusted at
23
+ * runtime until `NativeSecureKeyStore` has validated it.
24
+ */
25
+ export type NativeRegisteredAuthKey = Readonly<{
26
+ /** Server-assigned AuthKey id (UUID), exactly as acknowledged. */
27
+ authKeyId: string;
28
+ /** Server-assigned Owner binding id (UUID), exactly as acknowledged. */
29
+ ownerBindingId: string;
30
+ }>;
20
31
  export interface NativeSecureKeyBridge {
21
32
  /**
22
33
  * Ensure a non-exportable P-256 key exists for `alias`, creating it only when
@@ -33,11 +44,29 @@ export interface NativeSecureKeyBridge {
33
44
  /** Unpadded Base64URL DER SubjectPublicKeyInfo of the public key. */
34
45
  publicKeySpkiBase64Url(alias: string): Promise<string>;
35
46
  /**
36
- * Persist that Circle registered the public key for `alias`. Idempotent —
37
- * native no-ops when the key is already acknowledged. After it succeeds,
38
- * later `resolveOrCreate` calls return `'existing'`.
47
+ * Persist that Circle registered the public key for `alias` under
48
+ * `authKeyId` and `ownerBindingId`. Always upserts the stored identifiers,
49
+ * even when the key is already acknowledged, so a re-registration that
50
+ * assigns new identifiers replaces the old ones. After it succeeds, later
51
+ * `resolveOrCreate` calls return `'existing'` and `resolveExisting` returns
52
+ * these identifiers.
53
+ */
54
+ acknowledgeRegistration(alias: string, authKeyId: string, ownerBindingId: string): Promise<void>;
55
+ /**
56
+ * Read the registration record for `alias` without creating a key and
57
+ * without a user-authentication prompt.
58
+ *
59
+ * Returns `null` when no key exists or the key has no recorded identifiers.
60
+ * A non-null result counts as native's explicit resolution of the key, so
61
+ * `publicKeySpkiBase64Url` and `sign` work afterwards without
62
+ * `resolveOrCreate`.
63
+ */
64
+ resolveExisting(alias: string): Promise<NativeRegisteredAuthKey | null>;
65
+ /**
66
+ * Delete the key for `alias` and its local metadata. Local only — it does not
67
+ * revoke the key with Circle. Idempotent: succeeds when no key exists.
39
68
  */
40
- acknowledgeRegistration(alias: string): Promise<void>;
69
+ forgetLocalKey(alias: string): Promise<void>;
41
70
  /**
42
71
  * ES256 signature over the exact message bytes.
43
72
  *
@@ -80,4 +109,43 @@ export interface NativeSecureKeyBridge {
80
109
  * @returns unpadded Base64URL of the 64-byte JOSE `R || S` signature.
81
110
  */
82
111
  signRegistrationDeviceAuthorization(alias: string, messageBase64Url: string): Promise<string>;
112
+ /**
113
+ * ES256 signature over the exact `approve_device` signing input.
114
+ *
115
+ * Production `resolveNativeBridge()` sends it to Expo `signDeviceApproval`
116
+ * (native `DaaDeviceAuthorizationSigningInput` approval initializer on iOS,
117
+ * `forDeviceApproval` on Android), which checks the body, the code secret
118
+ * and the typed code before any biometric prompt, and shows the code in it.
119
+ * A wrong code rejects with `MATCHING_CODE_MISMATCH`.
120
+ *
121
+ * Optional so an injected stand-in written before device approval still
122
+ * type-checks; `NativeSecureKeyStore` fails closed without it.
123
+ *
124
+ * @param messageBase64Url unpadded Base64URL of the exact signing input.
125
+ * @param requestBodyBase64Url unpadded Base64URL of the exact approval body.
126
+ * @param codeSecretBase64Url unpadded Base64URL of the 32-byte code secret.
127
+ * @param enteredCode the code the user typed.
128
+ * @returns unpadded Base64URL of the 64-byte JOSE `R || S` signature.
129
+ */
130
+ signDeviceApproval?(alias: string, messageBase64Url: string, requestBodyBase64Url: string, codeSecretBase64Url: string, enteredCode: string): Promise<string>;
131
+ /**
132
+ * Native `DaaSecureKey.codeSecret()`: the key's stored add-a-device code
133
+ * secret, created on first use, kept across restarts. Needs the key
134
+ * resolved (`resolveOrCreate`, or a non-null `resolveExisting`). Never
135
+ * prompts.
136
+ *
137
+ * Optional so an injected stand-in written before it still type-checks;
138
+ * `NativeSecureKeyStore` fails closed without it.
139
+ *
140
+ * @returns unpadded Base64URL of the 32-byte secret.
141
+ */
142
+ codeSecret?(alias: string): Promise<string>;
143
+ /**
144
+ * Native `DaaSecureKey.deleteCodeSecret(_:)`: deletes the stored code
145
+ * secret only when it equals the given bytes. Succeeds when nothing
146
+ * matches or no key exists. Never prompts and never mints anything.
147
+ *
148
+ * @param secretBase64Url unpadded Base64URL of the 32-byte secret.
149
+ */
150
+ deleteCodeSecret?(alias: string, secretBase64Url: string): Promise<void>;
83
151
  }
@@ -35,9 +35,12 @@ export type AppKeyIdentity = Readonly<{
35
35
  * P-256/ES256 key per `{appId, environment, clientEntityId (Owner),
36
36
  * installation}`.
37
37
  *
38
- * `clientEntityId` must be the SERVER-CONFIRMED value the Social Session
39
- * response echoed back — never a caller-supplied value the SDK has not
40
- * validated. See `models/PreparedSocialLogin.ts#completeSocialSession`.
38
+ * When a key is CREATED, `clientEntityId` must be the SERVER-CONFIRMED value
39
+ * the Social Session response echoed back — never a caller-supplied value the
40
+ * SDK has not validated. See `models/PreparedSocialLogin.ts#completeSocialSession`.
41
+ *
42
+ * {@link SecureKeyStore.resolveExisting} takes the same identity but never
43
+ * creates a key: it only finds one already registered under the derived alias.
41
44
  *
42
45
  * The raw value never reaches native or the alias in the clear: `alias.ts`
43
46
  * only ever folds it into `deriveKeyScope`'s SHA-256 digest.
@@ -58,9 +61,52 @@ export type OwnerKeyIdentity = AppKeyIdentity & Readonly<{
58
61
  * all resolve to `created` rather than silently presenting an unregistered
59
62
  * key as registered.
60
63
  * - `existing` — returned only for a key with a durable acknowledgement, i.e.
61
- * after {@link OwnerAuthKey.acknowledgeRegistration} has succeeded.
64
+ * after {@link OwnerAuthKey.acknowledgeRegistration} has succeeded, or for a
65
+ * key {@link SecureKeyStore.resolveExisting} found registered.
62
66
  */
63
67
  export type AuthKeyResolution = 'created' | 'existing';
68
+ /**
69
+ * The server-assigned identifiers Circle returned when it registered an
70
+ * AuthKey: `DeviceContext.authKeyId` (the JWS `kid` the service looks the key
71
+ * up by) and `DeviceContext.ownerBindingId`. Both are UUIDs.
72
+ *
73
+ * Neither is secret, but both identify the Owner, so keep them out of logs.
74
+ */
75
+ export type AuthKeyRegistration = Readonly<{
76
+ authKeyId: string;
77
+ ownerBindingId: string;
78
+ }>;
79
+ /**
80
+ * A registered AuthKey found on this device, with the identifiers recorded
81
+ * when Circle's registration was acknowledged.
82
+ *
83
+ * Returned by {@link SecureKeyStore.resolveExisting}. `authKey` is already
84
+ * `existing`, so it can sign a registered-device authorization straight away
85
+ * with `authKeyId` as the `kid`.
86
+ */
87
+ export type RegisteredOwnerAuthKey = Readonly<{
88
+ authKey: OwnerAuthKey;
89
+ /** The server-assigned AuthKey id, exactly as it was acknowledged. */
90
+ authKeyId: string;
91
+ /** The server-assigned Owner binding id, exactly as it was acknowledged. */
92
+ ownerBindingId: string;
93
+ }>;
94
+ /**
95
+ * What the approving device's key needs, beyond the signing input, to sign an
96
+ * `approve_device` authorization: the new device's 32-byte code secret and the
97
+ * code the user typed from its screen.
98
+ */
99
+ export type DeviceApprovalCheck = Readonly<{
100
+ codeSecret: Uint8Array;
101
+ enteredCode: string;
102
+ }>;
103
+ /**
104
+ * {@link DeviceApprovalCheck} plus the exact approval body the signing input's
105
+ * `body_sha256` commits to.
106
+ */
107
+ export type DeviceApprovalSigning = DeviceApprovalCheck & Readonly<{
108
+ requestBody: Uint8Array;
109
+ }>;
64
110
  /**
65
111
  * The DAA Owner AuthKey.
66
112
  *
@@ -88,14 +134,23 @@ export interface OwnerAuthKey {
88
134
  */
89
135
  resolution(): AuthKeyResolution;
90
136
  /**
91
- * Persist that Circle registered this public key, moving the handle from
92
- * `created` to `existing`. Idempotent: a no-op once the handle is `existing`.
137
+ * Persist that Circle registered this public key under `registration`'s
138
+ * identifiers, moving the handle from `created` to `existing`.
139
+ *
140
+ * Always an upsert, never a no-op: when Circle registers the same key again
141
+ * and assigns new identifiers, the stored ones are replaced, so a later
142
+ * {@link SecureKeyStore.resolveExisting} never returns a stale `authKeyId`
143
+ * the service would no longer accept as a `kid`. Calls on one handle reach
144
+ * native in call order, so the last call's identifiers are the ones kept.
145
+ * The ordering is per handle: the built-in stores hand out one handle per
146
+ * key, and a custom {@link SecureKeyStore} must do the same to keep it.
93
147
  *
94
148
  * Per the native SDK contract the caller invokes this only AFTER Circle has
95
149
  * successfully registered the exported SPKI. Device Registration Complete
96
- * calls it on an `ACTIVE` result. `RECOVERY_PENDING` must not.
150
+ * calls it on an `ACTIVE` result with that result's `DeviceContext`
151
+ * identifiers. `RECOVERY_PENDING` must not.
97
152
  */
98
- acknowledgeRegistration(): Promise<void>;
153
+ acknowledgeRegistration(registration: AuthKeyRegistration): Promise<void>;
99
154
  /**
100
155
  * Produce an ES256 signature (JOSE `R || S`, 64 bytes) over the exact message
101
156
  * bytes. The caller passes the already-serialized signing input; this method
@@ -130,8 +185,73 @@ export interface OwnerAuthKey {
130
185
  * in this SDK's own JWS construction.
131
186
  */
132
187
  signRegistrationDeviceAuthorization(message: Uint8Array): Promise<Uint8Array>;
188
+ /**
189
+ * Produce an ES256 signature (JOSE `R || S`, 64 bytes) over the exact
190
+ * `approve_device` signing input, after checking that `approval.requestBody`
191
+ * is the body the input commits to, that `approval.codeSecret` opens the
192
+ * body's `codeSeal`, and that `approval.enteredCode` is the matching code
193
+ * they produce (spaces and dashes ignored).
194
+ *
195
+ * A third native seam: production `NativeSecureKeyStore` reaches native
196
+ * `DaaDeviceAuthorizationSigningInput`'s approval initializer, which refuses
197
+ * a wrong code before any biometric prompt and shows the code in it.
198
+ * `signExactBytes` refuses an `approve_device` input.
199
+ *
200
+ * Optional so a custom {@link SecureKeyStore} written before device approval
201
+ * keeps compiling; `DaaUserClient.approveDevice` fails closed with
202
+ * `contract_violation` on a key without it.
203
+ */
204
+ signDeviceApproval?(message: Uint8Array, approval: DeviceApprovalSigning): Promise<Uint8Array>;
205
+ /**
206
+ * This key's add-a-device code secret: 32 random bytes, created on the first
207
+ * call and returned unchanged by later calls, across app restarts, until
208
+ * {@link deleteCodeSecret} deletes it, the key is forgotten, or a new key
209
+ * replaces it. Device Registration Complete seals it into `codeSeal`, and
210
+ * DAA keeps a waiting request's first seal, so a restart must not lose it.
211
+ * No user-authentication prompt. Each call returns a new array; never log it.
212
+ *
213
+ * Production `NativeSecureKeyStore` reaches native `codeSecret()` (Keychain
214
+ * on iOS, Keystore-encrypted storage on Android), which needs the key
215
+ * resolved first. Optional, with {@link deleteCodeSecret}, so a custom
216
+ * {@link SecureKeyStore} written before it keeps compiling: without them the
217
+ * secret lives in process memory only, and after a restart a waiting
218
+ * request's code is unavailable (`matching_code_unavailable`). Implement
219
+ * both or neither: with only one, `complete()` fails with
220
+ * `contract_violation` before it sends anything.
221
+ */
222
+ codeSecret?(): Promise<Uint8Array>;
223
+ /**
224
+ * Delete the stored code secret only when its bytes equal `secret`, so an
225
+ * answer to an older registration can't delete a newer secret. Succeeds when
226
+ * nothing is stored, the stored secret differs, or the key is gone.
227
+ */
228
+ deleteCodeSecret?(secret: Uint8Array): Promise<void>;
133
229
  }
134
230
  export interface SecureKeyStore {
135
231
  /** Resolve the installation AuthKey, creating it only when absent. */
136
232
  resolveOrCreate(identity: OwnerKeyIdentity): Promise<OwnerAuthKey>;
233
+ /**
234
+ * Find the AuthKey Circle registered for `identity` on this device, with the
235
+ * identifiers recorded when that registration was acknowledged.
236
+ *
237
+ * Read-only: it never creates a key and never shows a user-authentication
238
+ * prompt. Returns `null` when there is no key, when the key that exists
239
+ * has no recorded registration identifiers (it was never acknowledged, or
240
+ * was acknowledged before identifiers were recorded), or when native does
241
+ * not trust the recorded metadata (malformed, an unknown version, or
242
+ * written for a different key); `resolveOrCreate` reports that metadata
243
+ * problem as an error. A failure to read storage throws; it is never
244
+ * `null`. Each call reads native, so a call made after an acknowledgement
245
+ * settles sees the identifiers it recorded.
246
+ */
247
+ resolveExisting(identity: OwnerKeyIdentity): Promise<RegisteredOwnerAuthKey | null>;
248
+ /**
249
+ * Delete this installation's AuthKey for `identity`, and its local
250
+ * registration record.
251
+ *
252
+ * Local only: it does NOT revoke the key with Circle, which still holds the
253
+ * registered public key. Idempotent: succeeds when no key exists. The next
254
+ * {@link resolveOrCreate} mints a new key that must be registered again.
255
+ */
256
+ forget(identity: OwnerKeyIdentity): Promise<void>;
137
257
  }
@@ -86,3 +86,12 @@ export declare function parseSecureKeyAlias(alias: string): NativeKeyIdentity;
86
86
  * without a `DaaClient`.
87
87
  */
88
88
  export declare function assertAppId(appId: string): void;
89
+ /**
90
+ * The one rule for a `clientEntityId` that names a key, on enrollment and
91
+ * session restore alike. {@link deriveKeyScope} hashes the exact string, so
92
+ * the same UUID in another letter case would name a different key. DAA
93
+ * serializes UUIDs in lowercase, so only that form is accepted: a
94
+ * differently cased value fails here, loudly, instead of enrolling under one
95
+ * alias and later restoring from another.
96
+ */
97
+ export declare function assertClientEntityId(clientEntityId: string): void;
@@ -21,6 +21,7 @@ exports.deriveKeyScope = deriveKeyScope;
21
21
  exports.secureKeyAlias = secureKeyAlias;
22
22
  exports.parseSecureKeyAlias = parseSecureKeyAlias;
23
23
  exports.assertAppId = assertAppId;
24
+ exports.assertClientEntityId = assertClientEntityId;
24
25
  const config_1 = require("../config");
25
26
  const base64url_1 = require("../crypto/base64url");
26
27
  const sha256_1 = require("../crypto/sha256");
@@ -160,9 +161,17 @@ function assertAppIdWithin(value, maxLength) {
160
161
  `characters to namespace the secure key (got a ${value.length}-char value)`);
161
162
  }
162
163
  }
164
+ /**
165
+ * The one rule for a `clientEntityId` that names a key, on enrollment and
166
+ * session restore alike. {@link deriveKeyScope} hashes the exact string, so
167
+ * the same UUID in another letter case would name a different key. DAA
168
+ * serializes UUIDs in lowercase, so only that form is accepted: a
169
+ * differently cased value fails here, loudly, instead of enrolling under one
170
+ * alias and later restoring from another.
171
+ */
163
172
  function assertClientEntityId(clientEntityId) {
164
- if (!(0, uuid_1.isUuid)(clientEntityId)) {
165
- throw (0, errors_1.contractViolation)('clientEntityId must be a UUID to namespace the secure key');
173
+ if (!(0, uuid_1.isUuid)(clientEntityId) || clientEntityId !== clientEntityId.toLowerCase()) {
174
+ throw (0, errors_1.contractViolation)('clientEntityId must be a lowercase UUID to namespace the secure key');
166
175
  }
167
176
  }
168
177
  function parseEnvironment(value) {