@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
@@ -19,17 +19,22 @@
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
20
  exports.postSignedResource = postSignedResource;
21
21
  exports.getSignedResource = getSignedResource;
22
+ exports.authorizeSignedPost = authorizeSignedPost;
23
+ exports.postAuthorizedResource = postAuthorizedResource;
22
24
  // Signed public POST/GET: either serialize-once body bytes, or no body at all,
23
25
  // plus a fresh `X-Device-Authorization` compact JWS.
24
26
  //
25
27
  // Signed v1 operations carry `query = null`. Failures are classified on the
26
28
  // numeric DAA status code only, through `wire/daaStatusCodes.ts`.
27
29
  // An invalid, missing, replayed, or mismatched authorization becomes
28
- // `contract_violation`. A `409` whose body carries `IDEMPOTENCY_KEY_REUSED`
29
- // (`420034`) becomes `idempotency_conflict`, with the key recovered from the
30
- // same request bytes that were signed and sent, not the (unsigned) response
31
- // body; the caller reconciles the original operation rather than replacing the
32
- // key.
30
+ // `contract_violation` — the credential rejection a caller must handle on every
31
+ // signed request. The one exception is a `DEVICE_AUTHORIZATION_INVALID` whose
32
+ // own `iat`/`exp` fail DAA's 60-second freshness rule against the response's
33
+ // HTTP `Date`: that is `clock_skew` (see `isClockSkewed`). A `409` whose
34
+ // body carries `IDEMPOTENCY_KEY_REUSED` (`420034`) becomes
35
+ // `idempotency_conflict`, with the key recovered from the same request bytes
36
+ // that were signed and sent, not the (unsigned) response body; the caller
37
+ // reconciles the original operation rather than replacing the key.
33
38
  //
34
39
  // DAA has no code for an expired device authorization, a missing one, or a
35
40
  // revoked credential: it reports them as `DEVICE_AUTHORIZATION_INVALID` or,
@@ -41,7 +46,12 @@ exports.getSignedResource = getSignedResource;
41
46
  //
42
47
  // `AccountsClient.create` (`create_account`),
43
48
  // `TransfersClient.create` (`transfer`), and `WithdrawalsClient.create`
44
- // (`withdrawal`) call `postSignedResource`. `DaaUserClient.refreshContext`
49
+ // (`withdrawal`) call `postSignedResource`. `ContractExecutionsClient`
50
+ // (`contract_execution`) splits the same POST in two —
51
+ // `authorizeSignedPost` once, then `postAuthorizedResource` for the first send
52
+ // and every retry — because DAA requires a replay to carry the originally
53
+ // accepted authorization, not a fresh one; see
54
+ // `models/PreparedContractExecution.ts`. `DaaUserClient.refreshContext`
45
55
  // (`get_device_context`) calls `getSignedResource` — the device-authorization
46
56
  // contract treats "signed context refresh" alongside protected writes, and
47
57
  // `securekey/SecureKey.ts` lists it alongside them as one of the defined DAA
@@ -58,18 +68,14 @@ async function postSignedResource({ transport, operation, authKey, authKeyId, bo
58
68
  if (profile.method !== 'POST') {
59
69
  throw (0, errors_1.contractViolation)('postSignedResource only sends POST registry operations');
60
70
  }
61
- const response = await sendSignedPost({
71
+ return postAuthorizedResource({
62
72
  transport,
63
73
  operation,
64
- path: profile.canonicalPath,
65
- authKey,
66
- authKeyId,
67
74
  bodyBytes,
75
+ authorization: await authorizeSignedPost({ operation, authKey, authKeyId, bodyBytes }),
76
+ expectedStatuses: [expectedStatus],
77
+ decode,
68
78
  });
69
- if (response.status !== expectedStatus) {
70
- throw mapSignedRequestFailure(response, bodyBytes);
71
- }
72
- return (0, resourceRequest_1.decodeResourceResponse)({ response, expectedStatus, decode });
73
79
  }
74
80
  /** No body to serialize for a bodyless signed read; the signature hashes the empty byte array. */
75
81
  const EMPTY_BODY = new Uint8Array(0);
@@ -87,54 +93,87 @@ async function getSignedResource({ transport, operation, authKey, authKeyId, exp
87
93
  if (profile.method !== 'GET') {
88
94
  throw (0, errors_1.contractViolation)('getSignedResource only sends GET registry operations');
89
95
  }
96
+ const authorization = await (0, deviceAuthorization_1.authorizeExactRequest)({
97
+ authKey,
98
+ authKeyId,
99
+ operation,
100
+ bodyBytes: EMPTY_BODY,
101
+ });
90
102
  const response = await sendSignedGet({
91
103
  transport,
92
- operation,
93
104
  path: profile.canonicalPath,
94
- authKey,
95
- authKeyId,
105
+ authorization,
96
106
  });
97
107
  if (response.status !== expectedStatus) {
98
- throw mapSignedRequestFailure(response, EMPTY_BODY);
108
+ throw mapSignedRequestFailure(response, EMPTY_BODY, authorization);
99
109
  }
100
110
  return (0, resourceRequest_1.decodeResourceResponse)({ response, expectedStatus, decode });
101
111
  }
102
- async function sendSignedGet(args) {
103
- const compactJws = await (0, deviceAuthorization_1.authorizeExactRequest)({
104
- authKey: args.authKey,
105
- authKeyId: args.authKeyId,
106
- operation: args.operation,
107
- bodyBytes: EMPTY_BODY,
108
- });
112
+ function sendSignedGet(args) {
109
113
  return args.transport.send({
110
114
  method: 'GET',
111
115
  path: args.path,
112
116
  query: null,
113
117
  headers: {
114
- [deviceAuthorization_1.DEVICE_AUTHORIZATION_HEADER]: compactJws,
118
+ [deviceAuthorization_1.DEVICE_AUTHORIZATION_HEADER]: args.authorization,
115
119
  },
116
120
  bodyBytes: null,
117
121
  });
118
122
  }
119
- async function sendSignedPost(args) {
120
- const compactJws = await (0, deviceAuthorization_1.authorizeExactRequest)({
121
- authKey: args.authKey,
122
- authKeyId: args.authKeyId,
123
- operation: args.operation,
124
- bodyBytes: args.bodyBytes,
125
- });
123
+ function sendAuthorizedPost(args) {
126
124
  return args.transport.send({
127
125
  method: 'POST',
128
126
  path: args.path,
129
127
  query: null,
130
128
  headers: {
131
129
  'Content-Type': 'application/json',
132
- [deviceAuthorization_1.DEVICE_AUTHORIZATION_HEADER]: compactJws,
130
+ [deviceAuthorization_1.DEVICE_AUTHORIZATION_HEADER]: args.authorization,
133
131
  },
134
132
  bodyBytes: args.bodyBytes,
135
133
  });
136
134
  }
137
- function mapSignedRequestFailure(response, bodyBytes) {
135
+ /**
136
+ * Sign a POST registry operation's authorization over exact bytes, without
137
+ * sending anything. The signing half of {@link postSignedResource}.
138
+ */
139
+ async function authorizeSignedPost({ operation, authKey, authKeyId, bodyBytes, approval, }) {
140
+ if ((0, deviceAuthorization_1.deviceAuthorizationProfile)(operation).method !== 'POST') {
141
+ throw (0, errors_1.contractViolation)('authorizeSignedPost only signs POST registry operations');
142
+ }
143
+ return (0, deviceAuthorization_1.authorizeExactRequest)({
144
+ authKey,
145
+ authKeyId,
146
+ operation,
147
+ bodyBytes,
148
+ ...(approval === undefined ? {} : { approval }),
149
+ });
150
+ }
151
+ /**
152
+ * Send a POST with an authorization signed earlier, unchanged — the sending
153
+ * half of {@link postSignedResource}, and the one to call again on a retry.
154
+ *
155
+ * Nothing here signs, and nothing reads the authorization's `exp`: an exact
156
+ * replay of a request DAA already accepted is answered from its stored result
157
+ * whether or not the JWS has expired, and DAA, not the SDK, decides that.
158
+ * Failures map exactly as {@link postSignedResource}'s do.
159
+ */
160
+ async function postAuthorizedResource({ transport, operation, bodyBytes, authorization, expectedStatuses, decode, failure, }) {
161
+ const profile = (0, deviceAuthorization_1.deviceAuthorizationProfile)(operation);
162
+ if (profile.method !== 'POST') {
163
+ throw (0, errors_1.contractViolation)('postAuthorizedResource only sends POST registry operations');
164
+ }
165
+ const response = await sendAuthorizedPost({
166
+ transport,
167
+ path: profile.canonicalPath,
168
+ bodyBytes,
169
+ authorization,
170
+ });
171
+ if (!expectedStatuses.includes(response.status)) {
172
+ throw failure?.(response) ?? mapSignedRequestFailure(response, bodyBytes, authorization);
173
+ }
174
+ return (0, resourceRequest_1.decodeResourceResponse)({ response, expectedStatus: response.status, decode });
175
+ }
176
+ function mapSignedRequestFailure(response, bodyBytes, authorization) {
138
177
  const correlationId = (0, headers_1.headerValueIgnoringCase)(response.headers, 'X-Request-Id');
139
178
  const daaStatusCode = (0, errorEnvelope_1.readDaaStatusCode)(response.bodyBytes);
140
179
  const fallback = () => (0, errors_1.apiFailure)({
@@ -161,8 +200,68 @@ function mapSignedRequestFailure(response, bodyBytes) {
161
200
  (0, daaStatusCodes_1.isDaaStatus)(daaStatusCode, 'DEVICE_AUTHORIZATION_REQUEST_MISMATCH')) {
162
201
  return (0, errors_1.contractViolation)('the device authorization was replayed or did not match the request', correlationId);
163
202
  }
203
+ if ((0, daaStatusCodes_1.isDaaStatus)(daaStatusCode, 'DEVICE_PENDING')) {
204
+ // The key can't sign yet: approved and in its cool-down, or still
205
+ // waiting for approval. Not a credential problem, so not
206
+ // `contract_violation`. Gated on `409`, where every DAA route sends it,
207
+ // like `IDEMPOTENCY_KEY_REUSED` above.
208
+ return response.status === 409 ? (0, errors_1.devicePending)(correlationId) : fallback();
209
+ }
164
210
  if ((0, daaStatusCodes_1.isDaaStatus)(daaStatusCode, 'DEVICE_AUTHORIZATION_INVALID')) {
165
- return (0, errors_1.contractViolation)('the device authorization was rejected', correlationId);
211
+ // DAA's freshness check reports this code (as a `400`), so only this code
212
+ // is refined; a replayed or mismatched authorization is never a clock
213
+ // problem, and a `401` from something other than DAA carries no DAA code.
214
+ return isClockSkewed(response, authorization)
215
+ ? (0, errors_1.clockSkew)(correlationId)
216
+ : (0, errors_1.contractViolation)('the device authorization was rejected', correlationId);
166
217
  }
167
218
  return fallback();
168
219
  }
220
+ /**
221
+ * DAA's freshness rule for a device authorization
222
+ * (`OwnerAuthorizationPrevalidator.validateFreshness`): it is refused when
223
+ * `iat > now + 60` or `exp < now - 60`, in whole epoch seconds.
224
+ */
225
+ const FRESHNESS_SKEW_SECONDS = 60;
226
+ /**
227
+ * Slack for the time between DAA reading its clock and stamping the response
228
+ * `Date`. Only the `exp` side needs it: `Date` is never earlier than the check,
229
+ * so `iat > Date + 60` already proves `iat > now + 60`.
230
+ */
231
+ const RESPONSE_DATE_SLACK_SECONDS = 5;
232
+ /**
233
+ * Whether DAA refused this authorization because the device clock is wrong,
234
+ * judged from the authorization's own `iat`/`exp` against the response's HTTP
235
+ * `Date`, with DAA's own rule.
236
+ *
237
+ * - `iat` more than 60 s after `Date`: the device clock was ahead when it
238
+ * signed. Compared with the signed `iat`, not `Date.now()`, so neither the
239
+ * whole-second `Date` nor response transit time can push a clock that is
240
+ * within tolerance over the line.
241
+ * - `exp` more than 60 s before `Date`: the authorization had expired, and the
242
+ * device clock now reads more than `exp - iat + 60` seconds (360 s) behind
243
+ * the service — far enough that an authorization signed now would be
244
+ * refused too. A device less far behind passes DAA's rule, so an expiry
245
+ * there is the authorization's age, not the clock: that matters for
246
+ * `contractExecutions.submit`, whose authorization was signed at `prepare`
247
+ * and may simply have aged out, whatever the clock did since.
248
+ *
249
+ * `Date` is unsigned and the transport is the consumer's, so this only chooses
250
+ * between two classifications of a response that has already failed. A
251
+ * missing or unreadable `Date` or claim is not skew.
252
+ */
253
+ function isClockSkewed(response, authorization) {
254
+ const serverMillis = (0, headers_1.httpDateMillis)((0, headers_1.headerValueIgnoringCase)(response.headers, 'Date'));
255
+ const claims = (0, deviceAuthorization_1.jwsSegmentJson)(authorization, 1);
256
+ const iat = claims?.['iat'];
257
+ const exp = claims?.['exp'];
258
+ if (serverMillis === null || typeof iat !== 'number' || typeof exp !== 'number') {
259
+ return false;
260
+ }
261
+ const serverSeconds = serverMillis / 1000;
262
+ if (iat > serverSeconds + FRESHNESS_SKEW_SECONDS) {
263
+ return true;
264
+ }
265
+ return (exp < serverSeconds - FRESHNESS_SKEW_SECONDS - RESPONSE_DATE_SLACK_SECONDS &&
266
+ serverMillis - Date.now() > (exp - iat + FRESHNESS_SKEW_SECONDS) * 1000);
267
+ }
@@ -48,7 +48,7 @@ exports.releaseQuietly = releaseQuietly;
48
48
  // | Lifetime | durable, survives the app | **one login attempt** |
49
49
  // | Scope | `{environment, customer application, Owner (clientEntityId), installation}` | nothing; it is anonymous |
50
50
  // | Storage | Secure Enclave / Android Keystore, via `SecureKeyStore` | process memory only |
51
- // | Exported at | Device Registration Complete (`authKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) |
51
+ // | Exported at | Device Registration Complete (`deviceKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) |
52
52
  // | Selected | only *after* the Social Session response | before Prepare |
53
53
  // | Authorizes | DAA operations, via `X-Device-Authorization` | nothing |
54
54
  //
@@ -29,15 +29,6 @@ export interface DaaRegistrationNativeModule {
29
29
  * key, returning unpadded Base64URL of the 64-byte JOSE `R || S` signature.
30
30
  */
31
31
  signRegistrationAuthorization(id: string, signingInputBase64Url: string): string;
32
- /**
33
- * Native ES256 verification of a Prepare receipt signature, delegated to the
34
- * native SDKs' `DaaPrepareReceiptSignature` (CryptoKit on iOS,
35
- * `java.security` on Android). All three arguments are unpadded
36
- * Base64URL — the uncompressed P-256 point of a pinned key, the exact JWS
37
- * signing input, and the 64-byte JOSE `R || S` signature. Resolves `true`
38
- * only for a valid signature; rejects when the key is not a P-256 point.
39
- */
40
- verifyPrepareReceiptSignature(publicKeyX963Base64Url: string, signingInputBase64Url: string, signatureBase64Url: string): Promise<boolean>;
41
32
  }
42
33
  export declare function optionalDaaRegistrationNative(): DaaRegistrationNativeModule | null;
43
34
  export declare function requireDaaRegistrationNative(): DaaRegistrationNativeModule;
@@ -54,19 +45,6 @@ export declare function nativeRegistrationFlowPublicKeySpkiBase64Url(native: Daa
54
45
  * authorization signing input before it ever touches the private key.
55
46
  */
56
47
  export declare function nativeSignRegistrationAuthorization(native: DaaRegistrationNativeModule, id: string, signingInputBase64Url: string): Uint8Array;
57
- /**
58
- * Verify one ES256 signature with platform crypto.
59
- *
60
- * Only a literal `true` from native counts as verified. Anything else — `false`,
61
- * a non-boolean, a rejection, a missing function on an older host build — is
62
- * not a pass: a rejection or a missing function is a `contract_violation`, and
63
- * any other value is `false`.
64
- */
65
- export declare function nativeVerifyPrepareReceiptSignature(native: DaaRegistrationNativeModule, args: Readonly<{
66
- publicKeyX963: Uint8Array;
67
- signingInput: Uint8Array;
68
- signature: Uint8Array;
69
- }>): Promise<boolean>;
70
48
  /**
71
49
  * Drop a cached native flow key.
72
50
  *
@@ -25,16 +25,14 @@ exports.nativeRandomUuidV4 = nativeRandomUuidV4;
25
25
  exports.nativeGenerateRegistrationFlowKey = nativeGenerateRegistrationFlowKey;
26
26
  exports.nativeRegistrationFlowPublicKeySpkiBase64Url = nativeRegistrationFlowPublicKeySpkiBase64Url;
27
27
  exports.nativeSignRegistrationAuthorization = nativeSignRegistrationAuthorization;
28
- exports.nativeVerifyPrepareReceiptSignature = nativeVerifyPrepareReceiptSignature;
29
28
  exports.nativeReleaseRegistrationFlowKey = nativeReleaseRegistrationFlowKey;
30
29
  const expo_modules_core_1 = require("expo-modules-core");
31
30
  const base64url_1 = require("../crypto/base64url");
32
31
  const errors_1 = require("../errors");
33
32
  // JS shape of the Expo `DaaRegistration` native module. Separate from
34
- // `DaaSecureKey`: this module bridges DaaSecureRandom, DaaRegistrationFlowKey,
35
- // and platform verification of the Prepare receipt signature. The flow-key
36
- // private key stays in the native cache keyed by the handle id; only Base64URL
37
- // strings cross the bridge.
33
+ // `DaaSecureKey`: this module bridges DaaSecureRandom and
34
+ // DaaRegistrationFlowKey. The flow-key private key stays in the native cache
35
+ // keyed by the handle id; only Base64URL strings cross the bridge.
38
36
  exports.DAA_REGISTRATION_MODULE = 'DaaRegistration';
39
37
  function optionalDaaRegistrationNative() {
40
38
  const native = (0, expo_modules_core_1.requireOptionalNativeModule)(exports.DAA_REGISTRATION_MODULE);
@@ -140,30 +138,6 @@ function nativeSignRegistrationAuthorization(native, id, signingInputBase64Url)
140
138
  }
141
139
  return bytes;
142
140
  }
143
- /**
144
- * Verify one ES256 signature with platform crypto.
145
- *
146
- * Only a literal `true` from native counts as verified. Anything else — `false`,
147
- * a non-boolean, a rejection, a missing function on an older host build — is
148
- * not a pass: a rejection or a missing function is a `contract_violation`, and
149
- * any other value is `false`.
150
- */
151
- async function nativeVerifyPrepareReceiptSignature(native, args) {
152
- if (typeof native.verifyPrepareReceiptSignature !== 'function') {
153
- throw (0, errors_1.contractViolation)('native DaaRegistration.verifyPrepareReceiptSignature is required');
154
- }
155
- let result;
156
- try {
157
- result = await native.verifyPrepareReceiptSignature((0, base64url_1.toBase64Url)(args.publicKeyX963), (0, base64url_1.toBase64Url)(args.signingInput), (0, base64url_1.toBase64Url)(args.signature));
158
- }
159
- catch (err) {
160
- if ((0, errors_1.isDaaError)(err)) {
161
- throw err;
162
- }
163
- throw (0, errors_1.contractViolation)('native Prepare receipt signature verification failed');
164
- }
165
- return result === true;
166
- }
167
141
  /**
168
142
  * Drop a cached native flow key.
169
143
  *
@@ -15,17 +15,19 @@
15
15
  * See the License for the specific language governing permissions and
16
16
  * limitations under the License.
17
17
  */
18
- import type { OwnerAuthKey } from '../securekey/SecureKey';
18
+ import type { DeviceApprovalCheck, OwnerAuthKey } from '../securekey/SecureKey';
19
19
  export declare const DEVICE_AUTHORIZATION_HEADER = "X-Device-Authorization";
20
20
  declare const SCHEMA_VERSION = 1;
21
+ /** `register_device_key` is version 3: the device key operation on `/v1/accounts/auth/keys`. */
22
+ declare const REGISTER_DEVICE_KEY_SCHEMA_VERSION = 3;
21
23
  /**
22
24
  * Closed Owner-authorization registry (v1). Wire `discriminator` values from
23
25
  * the registry schema.
24
26
  */
25
- export type DeviceAuthorizationOperation = 'create_account' | 'transfer' | 'withdrawal' | 'complete_social_login' | 'get_device_context' | 'register_device_key';
27
+ export type DeviceAuthorizationOperation = 'create_account' | 'transfer' | 'withdrawal' | 'contract_execution' | 'complete_social_login' | 'get_device_context' | 'register_device_key' | 'approve_device';
26
28
  export type DeviceAuthorizationProfile = Readonly<{
27
29
  discriminator: DeviceAuthorizationOperation;
28
- schemaVersion: typeof SCHEMA_VERSION;
30
+ schemaVersion: typeof SCHEMA_VERSION | typeof REGISTER_DEVICE_KEY_SCHEMA_VERSION;
29
31
  method: 'GET' | 'POST';
30
32
  canonicalPath: string;
31
33
  }>;
@@ -36,6 +38,12 @@ export type DeviceAuthorizationRequest = Readonly<{
36
38
  operation: DeviceAuthorizationOperation;
37
39
  /** Exact bytes that will be hashed and sent. Empty array for a bodyless call. */
38
40
  bodyBytes: Uint8Array;
41
+ /**
42
+ * Required for `approve_device`, and refused for every other operation:
43
+ * the code secret and the code the user typed, which native checks against
44
+ * `bodyBytes` before it shows the biometric prompt.
45
+ */
46
+ approval?: DeviceApprovalCheck;
39
47
  }>;
40
48
  /**
41
49
  * Test-only clock. Production code always uses the system clock. This
@@ -70,4 +78,10 @@ export declare function authorizeExactRequest(request: DeviceAuthorizationReques
70
78
  * second, independent way.
71
79
  */
72
80
  export declare function idempotencyKeyFromExactBody(bodyBytes: Uint8Array): string | undefined;
81
+ /**
82
+ * Decode the protected header (`0`) or payload (`1`) of a compact JWS this SDK
83
+ * signed, or `null` if it is not readable JSON. Reading, not verification: the
84
+ * signature is DAA's to check.
85
+ */
86
+ export declare function jwsSegmentJson(compact: string, index: 0 | 1): Record<string, unknown> | null;
73
87
  export {};
@@ -21,6 +21,7 @@ exports.DEVICE_AUTHORIZATION_HEADER = void 0;
21
21
  exports.deviceAuthorizationProfile = deviceAuthorizationProfile;
22
22
  exports.authorizeExactRequest = authorizeExactRequest;
23
23
  exports.idempotencyKeyFromExactBody = idempotencyKeyFromExactBody;
24
+ exports.jwsSegmentJson = jwsSegmentJson;
24
25
  // Registered-device authorization: a compact ES256 JWS in
25
26
  // `X-Device-Authorization`, bound to the exact body bytes that will be sent.
26
27
  //
@@ -36,16 +37,16 @@ exports.idempotencyKeyFromExactBody = idempotencyKeyFromExactBody;
36
37
  // Operation identity is the digest-pinned Owner-authorization registry:
37
38
  // `discriminator` + `schema_version` are the lookup key. The verifier resolves
38
39
  // method and `canonical_path` from that entry; it does not infer the operation
39
- // from the path. Callers name one of the six closed operations — they cannot
40
+ // from the path. Callers name one of the eight closed operations — they cannot
40
41
  // pass a free-form `/v1` path.
41
42
  //
42
43
  // The header carries the published `typ` (`aw-device-authorization+jws`).
43
44
  //
44
45
  // Production `OwnerAuthKey.signExactBytes` reaches native
45
46
  // `signDeviceAuthorization` via the Expo bridge. Tests use
46
- // `InMemorySecureKeyStore`. The create-account, transfer, and withdrawal
47
- // clients reach this through `api/signedResource.ts` rather than calling it
48
- // directly.
47
+ // `InMemorySecureKeyStore`. The create-account, transfer, withdrawal, and
48
+ // contract-execution clients reach this through `api/signedResource.ts` rather
49
+ // than calling it directly.
49
50
  const base64url_1 = require("../crypto/base64url");
50
51
  const random_1 = require("../crypto/random");
51
52
  const sha256_1 = require("../crypto/sha256");
@@ -58,6 +59,8 @@ const JOSE_SIGNATURE_LENGTH = 64;
58
59
  /** Verifier ceiling: `exp - iat` must be at most 300 seconds. */
59
60
  const AUTHORIZATION_LIFETIME_SECONDS = 300;
60
61
  const SCHEMA_VERSION = 1;
62
+ /** `register_device_key` is version 3: the device key operation on `/v1/accounts/auth/keys`. */
63
+ const REGISTER_DEVICE_KEY_SCHEMA_VERSION = 3;
61
64
  const DEFAULT_CLOCK = {
62
65
  nowEpochSeconds: () => Math.floor(Date.now() / 1000),
63
66
  jti: random_1.randomUuidV4,
@@ -86,6 +89,13 @@ function deviceAuthorizationProfile(operation) {
86
89
  method: 'POST',
87
90
  canonicalPath: '/v1/accounts/withdrawals',
88
91
  };
92
+ case 'contract_execution':
93
+ return {
94
+ discriminator: 'contract_execution',
95
+ schemaVersion: SCHEMA_VERSION,
96
+ method: 'POST',
97
+ canonicalPath: '/v1/accounts/contractExecutions',
98
+ };
89
99
  case 'complete_social_login':
90
100
  return {
91
101
  discriminator: 'complete_social_login',
@@ -103,9 +113,16 @@ function deviceAuthorizationProfile(operation) {
103
113
  case 'register_device_key':
104
114
  return {
105
115
  discriminator: 'register_device_key',
116
+ schemaVersion: REGISTER_DEVICE_KEY_SCHEMA_VERSION,
117
+ method: 'POST',
118
+ canonicalPath: '/v1/accounts/auth/keys',
119
+ };
120
+ case 'approve_device':
121
+ return {
122
+ discriminator: 'approve_device',
106
123
  schemaVersion: SCHEMA_VERSION,
107
124
  method: 'POST',
108
- canonicalPath: '/v1/accounts/auth/deviceKeyRegistration',
125
+ canonicalPath: '/v1/accounts/auth/deviceApprovals',
109
126
  };
110
127
  default: {
111
128
  const exhaustive = operation;
@@ -133,6 +150,9 @@ async function authorizeExactRequest(request, clock = DEFAULT_CLOCK) {
133
150
  if (!(0, uuid_1.isUuid)(request.authKeyId)) {
134
151
  throw (0, errors_1.contractViolation)('authKeyId must be a UUID');
135
152
  }
153
+ if ((request.operation === 'approve_device') !== (request.approval !== undefined)) {
154
+ throw (0, errors_1.contractViolation)('approve_device, and only approve_device, is signed with an approval');
155
+ }
136
156
  const profile = deviceAuthorizationProfile(request.operation);
137
157
  const idempotencyKey = idempotencyKeyFromExactBody(request.bodyBytes);
138
158
  const iat = requireEpochSeconds(clock.nowEpochSeconds());
@@ -153,7 +173,7 @@ async function authorizeExactRequest(request, clock = DEFAULT_CLOCK) {
153
173
  iat,
154
174
  });
155
175
  const signingInput = (0, base64url_1.toBase64Url)(utf8Json(protectedHeader)) + '.' + (0, base64url_1.toBase64Url)(utf8Json(payload));
156
- const signature = await signSigningInput(request.authKey, signingInput);
176
+ const signature = await signSigningInput(request, signingInput);
157
177
  return signingInput + '.' + (0, base64url_1.toBase64Url)(signature);
158
178
  }
159
179
  function payloadClaims(args) {
@@ -185,10 +205,22 @@ function payloadClaims(args) {
185
205
  exp,
186
206
  };
187
207
  }
188
- async function signSigningInput(authKey, signingInput) {
208
+ async function signSigningInput(request, signingInput) {
209
+ const { authKey, approval, bodyBytes } = request;
210
+ const message = new TextEncoder().encode(signingInput);
189
211
  let signature;
190
212
  try {
191
- signature = await authKey.signExactBytes(new TextEncoder().encode(signingInput));
213
+ if (approval === undefined) {
214
+ signature = await authKey.signExactBytes(message);
215
+ }
216
+ else {
217
+ // A separate native call: it checks the typed code against the body
218
+ // and code secret, and shows that code in the biometric prompt.
219
+ if (authKey.signDeviceApproval === undefined) {
220
+ throw (0, errors_1.contractViolation)('this SecureKeyStore cannot sign a device approval');
221
+ }
222
+ signature = await authKey.signDeviceApproval(message, { ...approval, requestBody: bodyBytes });
223
+ }
192
224
  }
193
225
  catch (err) {
194
226
  throw (0, errors_1.mapNativeError)(err);
@@ -241,3 +273,23 @@ function idempotencyKeyFromExactBody(bodyBytes) {
241
273
  function utf8Json(value) {
242
274
  return new TextEncoder().encode(JSON.stringify(value));
243
275
  }
276
+ /**
277
+ * Decode the protected header (`0`) or payload (`1`) of a compact JWS this SDK
278
+ * signed, or `null` if it is not readable JSON. Reading, not verification: the
279
+ * signature is DAA's to check.
280
+ */
281
+ function jwsSegmentJson(compact, index) {
282
+ const segments = compact.split('.');
283
+ if (segments.length !== 3) {
284
+ return null;
285
+ }
286
+ try {
287
+ const value = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode((0, base64url_1.fromBase64Url)(segments[index] ?? '')));
288
+ return typeof value === 'object' && value !== null && !Array.isArray(value)
289
+ ? value
290
+ : null;
291
+ }
292
+ catch {
293
+ return null;
294
+ }
295
+ }
@@ -19,8 +19,8 @@ import type { RegistrationFlowKey } from './RegistrationFlowKey';
19
19
  import type { OwnerAuthKey } from '../securekey/SecureKey';
20
20
  export declare const REGISTRATION_FLOW_AUTHORIZATION_HEADER = "X-Registration-Flow-Authorization";
21
21
  export declare const REGISTRATION_DEVICE_AUTHORIZATION_HEADER = "X-Device-Authorization";
22
- /** Public path of `completeDeviceRegistration` (OpenAPI + signed `canonical_path`). */
23
- export declare const DEVICE_REGISTRATION_COMPLETE_PATH = "/v1/accounts/auth/deviceKeyRegistration";
22
+ /** Public path of Device Registration Complete (OpenAPI + signed `canonical_path`). */
23
+ export declare const KEY_REGISTRATION_PATH = "/v1/accounts/auth/keys";
24
24
  export type RegistrationAuthorizationClock = Readonly<{
25
25
  nowEpochSeconds: () => number;
26
26
  jti: () => string;
@@ -17,10 +17,12 @@
17
17
  * limitations under the License.
18
18
  */
19
19
  Object.defineProperty(exports, "__esModule", { value: true });
20
- exports.DEVICE_REGISTRATION_COMPLETE_PATH = exports.REGISTRATION_DEVICE_AUTHORIZATION_HEADER = exports.REGISTRATION_FLOW_AUTHORIZATION_HEADER = void 0;
20
+ exports.KEY_REGISTRATION_PATH = exports.REGISTRATION_DEVICE_AUTHORIZATION_HEADER = exports.REGISTRATION_FLOW_AUTHORIZATION_HEADER = void 0;
21
21
  exports.authorizeRegistrationComplete = authorizeRegistrationComplete;
22
22
  // Device Registration Complete dual-header proofs.
23
23
  //
24
+ // Complete is `POST /v1/accounts/auth/keys` with `"type": "deviceKey"`, and
25
+ // both proofs name the registry operation `register_device_key` version 3.
24
26
  // Complete sends two JWSs, in two headers:
25
27
  //
26
28
  // X-Registration-Flow-Authorization typ=daa-registration-flow-authorization+jws
@@ -41,9 +43,10 @@ exports.authorizeRegistrationComplete = authorizeRegistrationComplete;
41
43
  // strictly and rejects any field outside that set, so adding a binding claim
42
44
  // to the device proof makes Complete fail. Keep the two builders separate.
43
45
  // Native's registration validator (`DaaRegistrationAuthorizationSigningInput`)
44
- // must accept this request-claims-only device payload: a native SDK that
45
- // requires the binding claims refuses to sign it, and Complete fails on device
46
- // before any request is sent.
46
+ // must accept this request-claims-only device payload, and must allow
47
+ // `register_device_key` version 3 on `/v1/accounts/auth/keys`: a native SDK
48
+ // that requires the binding claims, or allows only another operation, refuses
49
+ // to sign it, and Complete fails on device before any request is sent.
47
50
  //
48
51
  // The only bytes each key signs are its own JWS signing input. This module is
49
52
  // not exported from `index.ts`.
@@ -68,17 +71,17 @@ const uuid_1 = require("../validation/uuid");
68
71
  const registrationCodeVerifier_1 = require("./registrationCodeVerifier");
69
72
  exports.REGISTRATION_FLOW_AUTHORIZATION_HEADER = 'X-Registration-Flow-Authorization';
70
73
  exports.REGISTRATION_DEVICE_AUTHORIZATION_HEADER = 'X-Device-Authorization';
71
- /** Public path of `completeDeviceRegistration` (OpenAPI + signed `canonical_path`). */
72
- exports.DEVICE_REGISTRATION_COMPLETE_PATH = '/v1/accounts/auth/deviceKeyRegistration';
74
+ /** Public path of Device Registration Complete (OpenAPI + signed `canonical_path`). */
75
+ exports.KEY_REGISTRATION_PATH = '/v1/accounts/auth/keys';
73
76
  const FLOW_TYP = 'daa-registration-flow-authorization+jws';
74
77
  const DEVICE_TYP = 'daa-device-authorization+jws';
75
78
  const AUDIENCE = 'circle-digital-asset-accounts';
76
79
  const JOSE_SIGNATURE_LENGTH = 64;
77
80
  /** Verifier ceiling: `exp - iat` must be at most 300 seconds. */
78
81
  const AUTHORIZATION_LIFETIME_SECONDS = 300;
79
- /** The closed discriminator/schema-version pair DAA accepts. */
80
- const DISCRIMINATOR = 'device_key_registration.v1';
81
- const SCHEMA_VERSION = 1;
82
+ /** The registry operation for a device key on `/v1/accounts/auth/keys`. */
83
+ const DISCRIMINATOR = 'register_device_key';
84
+ const SCHEMA_VERSION = 3;
82
85
  const DEFAULT_CLOCK = {
83
86
  nowEpochSeconds: () => Math.floor(Date.now() / 1000),
84
87
  jti: random_1.randomUuidV4,
@@ -168,7 +171,7 @@ function requestTargetClaims(args) {
168
171
  schema_version: SCHEMA_VERSION,
169
172
  body_sha256: (0, base64url_1.toBase64Url)((0, sha256_1.sha256)(args.bodyBytes)),
170
173
  idempotency_key: args.idempotencyKey,
171
- canonical_path: exports.DEVICE_REGISTRATION_COMPLETE_PATH,
174
+ canonical_path: exports.KEY_REGISTRATION_PATH,
172
175
  method: 'POST',
173
176
  aud: AUDIENCE,
174
177
  };
package/build/config.d.ts CHANGED
@@ -66,7 +66,34 @@ export type DaaSdkConfiguration = Readonly<{
66
66
  * anchor.
67
67
  */
68
68
  publicApiOrigin?: string;
69
+ /**
70
+ * Turns on adding a device with approval from an existing device. Off by
71
+ * default. When on, Device Registration Complete signs `codeSeal` into every
72
+ * body, and a new device on an account that already has one comes back
73
+ * `PENDING_APPROVAL` with a matching code. Off, the body has no `codeSeal`.
74
+ *
75
+ * Turn it on after DAA runs enclave 0.1.93 or later (older enclaves refuse
76
+ * every registration that carries `codeSeal`, first devices included) and
77
+ * before DAA turns on device approval in that environment (it then refuses a
78
+ * new device on an existing account without `codeSeal`, so with the switch
79
+ * off a second device can't be added).
80
+ *
81
+ * Keep it off in production for now: after an app restart, signing in again
82
+ * while a request is waiting returns that request, sealed with a code secret
83
+ * the app no longer has. This SDK reports its code as unavailable
84
+ * (`matching_code_unavailable`) only when DAA returns the request's
85
+ * `codeSeal`; without it, the app would show a code that can't match.
86
+ * Temporary: it becomes the default once every DAA environment runs 0.1.93
87
+ * or later and returns `codeSeal`.
88
+ */
89
+ addDeviceApproval?: boolean;
69
90
  }>;
91
+ /**
92
+ * Runtime check for `addDeviceApproval`: `true`, `false`, or unset (off). A
93
+ * JS caller passing anything else (say, the string `'false'`) fails at
94
+ * construction instead of being read as on or off.
95
+ */
96
+ export declare function assertAddDeviceApproval(value: unknown): boolean;
70
97
  /** SDK-owned trust anchor used to authenticate absolute pagination links. */
71
98
  export declare function publicApiOriginFor(environment: DaaEnvironment): string;
72
99
  /**