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