@circle-fin/daa-react-native-sdk 0.0.0-stage → 0.4.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 (304) hide show
  1. package/DaaReactNativeSdk.podspec +63 -0
  2. package/LICENSE +176 -0
  3. package/README.md +217 -2
  4. package/android/build.gradle +97 -0
  5. package/android/src/main/AndroidManifest.xml +1 -0
  6. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
  7. package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +121 -0
  8. package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
  9. package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
  10. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +73 -0
  11. package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +185 -0
  12. package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +73 -0
  13. package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
  14. package/build/DaaClient.d.ts +57 -0
  15. package/build/DaaClient.js +158 -0
  16. package/build/api/AccountLimitsClient.d.ts +79 -0
  17. package/build/api/AccountLimitsClient.js +142 -0
  18. package/build/api/AccountsClient.d.ts +95 -0
  19. package/build/api/AccountsClient.js +276 -0
  20. package/build/api/AchFiatAccountsClient.d.ts +92 -0
  21. package/build/api/AchFiatAccountsClient.js +142 -0
  22. package/build/api/AuthClient.d.ts +120 -0
  23. package/build/api/AuthClient.js +257 -0
  24. package/build/api/DaaUserClient.d.ts +124 -0
  25. package/build/api/DaaUserClient.js +245 -0
  26. package/build/api/DepositAddressesClient.d.ts +112 -0
  27. package/build/api/DepositAddressesClient.js +222 -0
  28. package/build/api/DepositsClient.d.ts +106 -0
  29. package/build/api/DepositsClient.js +183 -0
  30. package/build/api/FiatAccountsClient.d.ts +43 -0
  31. package/build/api/FiatAccountsClient.js +46 -0
  32. package/build/api/TransactionsClient.d.ts +64 -0
  33. package/build/api/TransactionsClient.js +120 -0
  34. package/build/api/TransfersClient.d.ts +104 -0
  35. package/build/api/TransfersClient.js +321 -0
  36. package/build/api/WireFiatAccountsClient.d.ts +99 -0
  37. package/build/api/WireFiatAccountsClient.js +156 -0
  38. package/build/api/WithdrawalsClient.d.ts +94 -0
  39. package/build/api/WithdrawalsClient.js +305 -0
  40. package/build/api/loginFailure.d.ts +43 -0
  41. package/build/api/loginFailure.js +64 -0
  42. package/build/api/pagination.d.ts +29 -0
  43. package/build/api/pagination.js +50 -0
  44. package/build/api/queryParameters.d.ts +23 -0
  45. package/build/api/queryParameters.js +77 -0
  46. package/build/api/resourceRequest.d.ts +60 -0
  47. package/build/api/resourceRequest.js +79 -0
  48. package/build/api/signedResource.d.ts +77 -0
  49. package/build/api/signedResource.js +168 -0
  50. package/build/auth/RegistrationFlowKey.d.ts +93 -0
  51. package/build/auth/RegistrationFlowKey.js +203 -0
  52. package/build/auth/daaRegistrationNative.d.ts +80 -0
  53. package/build/auth/daaRegistrationNative.js +184 -0
  54. package/build/auth/deviceAuthorization.d.ts +73 -0
  55. package/build/auth/deviceAuthorization.js +243 -0
  56. package/build/auth/ownerGrant.d.ts +29 -0
  57. package/build/auth/ownerGrant.js +90 -0
  58. package/build/auth/prepareReceipt.d.ts +150 -0
  59. package/build/auth/prepareReceipt.js +357 -0
  60. package/build/auth/registrationAuthorization.d.ts +48 -0
  61. package/build/auth/registrationAuthorization.js +243 -0
  62. package/build/auth/registrationCodeVerifier.d.ts +31 -0
  63. package/build/auth/registrationCodeVerifier.js +75 -0
  64. package/build/config.d.ts +79 -0
  65. package/build/config.js +116 -0
  66. package/build/crypto/base64url.d.ts +26 -0
  67. package/build/crypto/base64url.js +87 -0
  68. package/build/crypto/bytes.d.ts +27 -0
  69. package/build/crypto/bytes.js +32 -0
  70. package/build/crypto/es256Jws.d.ts +56 -0
  71. package/build/crypto/es256Jws.js +196 -0
  72. package/build/crypto/jwkThumbprint.d.ts +32 -0
  73. package/build/crypto/jwkThumbprint.js +49 -0
  74. package/build/crypto/random.d.ts +35 -0
  75. package/build/crypto/random.js +106 -0
  76. package/build/crypto/serialization.d.ts +26 -0
  77. package/build/crypto/serialization.js +43 -0
  78. package/build/crypto/sha256.d.ts +18 -0
  79. package/build/crypto/sha256.js +100 -0
  80. package/build/errors.d.ts +190 -0
  81. package/build/errors.js +252 -0
  82. package/build/index.d.ts +61 -0
  83. package/build/index.js +67 -0
  84. package/build/models/Account.d.ts +201 -0
  85. package/build/models/Account.js +147 -0
  86. package/build/models/AccountLimitsUsage.d.ts +169 -0
  87. package/build/models/AccountLimitsUsage.js +86 -0
  88. package/build/models/Ach.d.ts +135 -0
  89. package/build/models/Ach.js +184 -0
  90. package/build/models/AddressObject.d.ts +128 -0
  91. package/build/models/AddressObject.js +141 -0
  92. package/build/models/BusinessPii.d.ts +84 -0
  93. package/build/models/BusinessPii.js +142 -0
  94. package/build/models/CreateAccountRequest.d.ts +74 -0
  95. package/build/models/CreateAccountRequest.js +19 -0
  96. package/build/models/CreateTransferRequest.d.ts +91 -0
  97. package/build/models/CreateTransferRequest.js +19 -0
  98. package/build/models/CreateWithdrawalRequest.d.ts +99 -0
  99. package/build/models/CreateWithdrawalRequest.js +19 -0
  100. package/build/models/DaaUserContext.d.ts +96 -0
  101. package/build/models/DaaUserContext.js +133 -0
  102. package/build/models/Deposit.d.ts +241 -0
  103. package/build/models/Deposit.js +149 -0
  104. package/build/models/DepositSummary.d.ts +91 -0
  105. package/build/models/DepositSummary.js +114 -0
  106. package/build/models/FiatAccount.d.ts +99 -0
  107. package/build/models/FiatAccount.js +151 -0
  108. package/build/models/GenerateAddressRequest.d.ts +67 -0
  109. package/build/models/GenerateAddressRequest.js +68 -0
  110. package/build/models/Money.d.ts +76 -0
  111. package/build/models/Money.js +99 -0
  112. package/build/models/Page.d.ts +33 -0
  113. package/build/models/Page.js +57 -0
  114. package/build/models/PendingDeviceRegistration.d.ts +90 -0
  115. package/build/models/PendingDeviceRegistration.js +180 -0
  116. package/build/models/PreparedSocialLogin.d.ts +155 -0
  117. package/build/models/PreparedSocialLogin.js +235 -0
  118. package/build/models/Transaction.d.ts +187 -0
  119. package/build/models/Transaction.js +134 -0
  120. package/build/models/Transfer.d.ts +335 -0
  121. package/build/models/Transfer.js +240 -0
  122. package/build/models/Wire.d.ts +213 -0
  123. package/build/models/Wire.js +264 -0
  124. package/build/models/Withdrawal.d.ts +201 -0
  125. package/build/models/Withdrawal.js +156 -0
  126. package/build/models/redaction.d.ts +18 -0
  127. package/build/models/redaction.js +23 -0
  128. package/build/sca/ScaClient.d.ts +105 -0
  129. package/build/sca/ScaClient.js +193 -0
  130. package/build/securekey/InMemorySecureKey.d.ts +23 -0
  131. package/build/securekey/InMemorySecureKey.js +127 -0
  132. package/build/securekey/NativeSecureKey.d.ts +24 -0
  133. package/build/securekey/NativeSecureKey.js +178 -0
  134. package/build/securekey/NativeSecureKeyBridge.d.ts +83 -0
  135. package/build/securekey/NativeSecureKeyBridge.js +19 -0
  136. package/build/securekey/SecureKey.d.ts +137 -0
  137. package/build/securekey/SecureKey.js +19 -0
  138. package/build/securekey/alias.d.ts +88 -0
  139. package/build/securekey/alias.js +175 -0
  140. package/build/securekey/ownerAuthKeyResolver.d.ts +56 -0
  141. package/build/securekey/ownerAuthKeyResolver.js +63 -0
  142. package/build/securekey/resolveNativeBridge.d.ts +30 -0
  143. package/build/securekey/resolveNativeBridge.js +120 -0
  144. package/build/testing.d.ts +18 -0
  145. package/build/testing.js +34 -0
  146. package/build/transport/DaaTransport.d.ts +35 -0
  147. package/build/transport/DaaTransport.js +19 -0
  148. package/build/transport/headers.d.ts +30 -0
  149. package/build/transport/headers.js +45 -0
  150. package/build/validation/requestBody.d.ts +27 -0
  151. package/build/validation/requestBody.js +56 -0
  152. package/build/validation/uuid.d.ts +25 -0
  153. package/build/validation/uuid.js +33 -0
  154. package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
  155. package/build/wire/accountLimitsUsagePayload.js +130 -0
  156. package/build/wire/accountPayload.d.ts +36 -0
  157. package/build/wire/accountPayload.js +100 -0
  158. package/build/wire/achPayload.d.ts +24 -0
  159. package/build/wire/achPayload.js +82 -0
  160. package/build/wire/addressObjectPayload.d.ts +44 -0
  161. package/build/wire/addressObjectPayload.js +64 -0
  162. package/build/wire/daaStatusCodes.d.ts +64 -0
  163. package/build/wire/daaStatusCodes.js +69 -0
  164. package/build/wire/dataEnvelope.d.ts +40 -0
  165. package/build/wire/dataEnvelope.js +79 -0
  166. package/build/wire/depositPayload.d.ts +42 -0
  167. package/build/wire/depositPayload.js +159 -0
  168. package/build/wire/deviceContextPayload.d.ts +33 -0
  169. package/build/wire/deviceContextPayload.js +57 -0
  170. package/build/wire/deviceRegistrationResultPayload.d.ts +32 -0
  171. package/build/wire/deviceRegistrationResultPayload.js +128 -0
  172. package/build/wire/errorEnvelope.d.ts +43 -0
  173. package/build/wire/errorEnvelope.js +85 -0
  174. package/build/wire/fiatAccountPayload.d.ts +37 -0
  175. package/build/wire/fiatAccountPayload.js +93 -0
  176. package/build/wire/instant.d.ts +27 -0
  177. package/build/wire/instant.js +91 -0
  178. package/build/wire/jsonNumber.d.ts +30 -0
  179. package/build/wire/jsonNumber.js +34 -0
  180. package/build/wire/moneyPayload.d.ts +30 -0
  181. package/build/wire/moneyPayload.js +56 -0
  182. package/build/wire/paginationLinks.d.ts +28 -0
  183. package/build/wire/paginationLinks.js +167 -0
  184. package/build/wire/payload.d.ts +60 -0
  185. package/build/wire/payload.js +121 -0
  186. package/build/wire/pendingRegistrationPayload.d.ts +32 -0
  187. package/build/wire/pendingRegistrationPayload.js +54 -0
  188. package/build/wire/socialLoginRequestPayload.d.ts +31 -0
  189. package/build/wire/socialLoginRequestPayload.js +72 -0
  190. package/build/wire/transactionPayload.d.ts +31 -0
  191. package/build/wire/transactionPayload.js +126 -0
  192. package/build/wire/transferPayload.d.ts +43 -0
  193. package/build/wire/transferPayload.js +218 -0
  194. package/build/wire/wireEnums.d.ts +22 -0
  195. package/build/wire/wireEnums.js +69 -0
  196. package/build/wire/wirePayload.d.ts +29 -0
  197. package/build/wire/wirePayload.js +138 -0
  198. package/build/wire/withdrawalPayload.d.ts +27 -0
  199. package/build/wire/withdrawalPayload.js +179 -0
  200. package/expo-module.config.json +14 -0
  201. package/ios/DaaRegistrationExceptions.swift +58 -0
  202. package/ios/DaaRegistrationModule.swift +143 -0
  203. package/ios/DaaScaExceptions.swift +96 -0
  204. package/ios/DaaScaModule.swift +125 -0
  205. package/ios/DaaSecureKeyExceptions.swift +77 -0
  206. package/ios/DaaSecureKeyModule.swift +162 -0
  207. package/ios/InstallationIdentityStore.swift +126 -0
  208. package/ios/UnpaddedBase64URL.swift +42 -0
  209. package/package.json +114 -4
  210. package/src/DaaClient.ts +171 -0
  211. package/src/api/AccountLimitsClient.ts +146 -0
  212. package/src/api/AccountsClient.ts +305 -0
  213. package/src/api/AchFiatAccountsClient.ts +147 -0
  214. package/src/api/AuthClient.ts +331 -0
  215. package/src/api/DaaUserClient.ts +270 -0
  216. package/src/api/DepositAddressesClient.ts +239 -0
  217. package/src/api/DepositsClient.ts +208 -0
  218. package/src/api/FiatAccountsClient.ts +50 -0
  219. package/src/api/TransactionsClient.ts +137 -0
  220. package/src/api/TransfersClient.ts +361 -0
  221. package/src/api/WireFiatAccountsClient.ts +172 -0
  222. package/src/api/WithdrawalsClient.ts +339 -0
  223. package/src/api/loginFailure.ts +75 -0
  224. package/src/api/pagination.ts +63 -0
  225. package/src/api/queryParameters.ts +82 -0
  226. package/src/api/resourceRequest.ts +135 -0
  227. package/src/api/signedResource.ts +267 -0
  228. package/src/auth/RegistrationFlowKey.ts +274 -0
  229. package/src/auth/daaRegistrationNative.ts +236 -0
  230. package/src/auth/deviceAuthorization.ts +302 -0
  231. package/src/auth/ownerGrant.ts +102 -0
  232. package/src/auth/prepareReceipt.ts +522 -0
  233. package/src/auth/registrationAuthorization.ts +306 -0
  234. package/src/auth/registrationCodeVerifier.ts +76 -0
  235. package/src/config.ts +156 -0
  236. package/src/crypto/base64url.ts +88 -0
  237. package/src/crypto/bytes.ts +30 -0
  238. package/src/crypto/es256Jws.ts +240 -0
  239. package/src/crypto/jwkThumbprint.ts +65 -0
  240. package/src/crypto/random.ts +113 -0
  241. package/src/crypto/serialization.ts +42 -0
  242. package/src/crypto/sha256.ts +105 -0
  243. package/src/errors.ts +319 -0
  244. package/src/index.ts +223 -0
  245. package/src/models/Account.ts +264 -0
  246. package/src/models/AccountLimitsUsage.ts +192 -0
  247. package/src/models/Ach.ts +269 -0
  248. package/src/models/AddressObject.ts +169 -0
  249. package/src/models/BusinessPii.ts +154 -0
  250. package/src/models/CreateAccountRequest.ts +109 -0
  251. package/src/models/CreateTransferRequest.ts +114 -0
  252. package/src/models/CreateWithdrawalRequest.ts +120 -0
  253. package/src/models/DaaUserContext.ts +172 -0
  254. package/src/models/Deposit.ts +307 -0
  255. package/src/models/DepositSummary.ts +142 -0
  256. package/src/models/FiatAccount.ts +195 -0
  257. package/src/models/GenerateAddressRequest.ts +101 -0
  258. package/src/models/Money.ts +91 -0
  259. package/src/models/Page.ts +48 -0
  260. package/src/models/PendingDeviceRegistration.ts +197 -0
  261. package/src/models/PreparedSocialLogin.ts +287 -0
  262. package/src/models/Transaction.ts +247 -0
  263. package/src/models/Transfer.ts +459 -0
  264. package/src/models/Wire.ts +405 -0
  265. package/src/models/Withdrawal.ts +283 -0
  266. package/src/models/redaction.ts +22 -0
  267. package/src/sca/ScaClient.ts +289 -0
  268. package/src/securekey/InMemorySecureKey.ts +138 -0
  269. package/src/securekey/NativeSecureKey.ts +179 -0
  270. package/src/securekey/NativeSecureKeyBridge.ts +109 -0
  271. package/src/securekey/SecureKey.ts +149 -0
  272. package/src/securekey/alias.ts +204 -0
  273. package/src/securekey/ownerAuthKeyResolver.ts +96 -0
  274. package/src/securekey/resolveNativeBridge.ts +185 -0
  275. package/src/testing.ts +32 -0
  276. package/src/transport/DaaTransport.ts +42 -0
  277. package/src/transport/headers.ts +46 -0
  278. package/src/validation/requestBody.ts +60 -0
  279. package/src/validation/uuid.ts +31 -0
  280. package/src/wire/accountLimitsUsagePayload.ts +182 -0
  281. package/src/wire/accountPayload.ts +108 -0
  282. package/src/wire/achPayload.ts +98 -0
  283. package/src/wire/addressObjectPayload.ts +64 -0
  284. package/src/wire/daaStatusCodes.ts +69 -0
  285. package/src/wire/dataEnvelope.ts +80 -0
  286. package/src/wire/depositPayload.ts +186 -0
  287. package/src/wire/deviceContextPayload.ts +58 -0
  288. package/src/wire/deviceRegistrationResultPayload.ts +153 -0
  289. package/src/wire/errorEnvelope.ts +87 -0
  290. package/src/wire/fiatAccountPayload.ts +112 -0
  291. package/src/wire/instant.ts +93 -0
  292. package/src/wire/jsonNumber.ts +33 -0
  293. package/src/wire/moneyPayload.ts +55 -0
  294. package/src/wire/paginationLinks.ts +204 -0
  295. package/src/wire/payload.ts +146 -0
  296. package/src/wire/pendingRegistrationPayload.ts +75 -0
  297. package/src/wire/socialLoginRequestPayload.ts +89 -0
  298. package/src/wire/transactionPayload.ts +145 -0
  299. package/src/wire/transferPayload.ts +249 -0
  300. package/src/wire/wireEnums.ts +74 -0
  301. package/src/wire/wirePayload.ts +160 -0
  302. package/src/wire/withdrawalPayload.ts +219 -0
  303. package/testing.d.ts +19 -0
  304. package/testing.js +25 -0
@@ -0,0 +1,522 @@
1
+ /**
2
+ * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved.
3
+ *
4
+ * SPDX-License-Identifier: Apache-2.0
5
+ *
6
+ * Licensed under the Apache License, Version 2.0 (the "License");
7
+ * you may not use this file except in compliance with the License.
8
+ * You may obtain a copy of the License at
9
+ *
10
+ * http://www.apache.org/licenses/LICENSE-2.0
11
+ *
12
+ * Unless required by applicable law or agreed to in writing, software
13
+ * distributed under the License is distributed on an "AS IS" BASIS,
14
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15
+ * See the License for the specific language governing permissions and
16
+ * limitations under the License.
17
+ */
18
+
19
+ // The DAA-signed Prepare receipt.
20
+ //
21
+ // When a trust anchor is pinned for the environment, the SDK verifies the
22
+ // returned Prepare receipt before starting provider login and fails closed if
23
+ // the receipt is missing or does not verify. With no anchor pinned, the SDK
24
+ // ignores the receipt (see below).
25
+ //
26
+ // **What it defends against.** The SDK reaches DAA through the application's
27
+ // own backend, which the trust model treats as untrusted. Without a verified
28
+ // receipt that relay can substitute a different login request — another
29
+ // attempt's `loginRequestId` and nonce — and the SDK would hand that nonce to
30
+ // provider login. The receipt is DAA-signed, so the relay cannot mint one for
31
+ // substituted values. What makes the signature an answer is binding its claims
32
+ // to values the relay cannot choose: the registration code challenge and the
33
+ // registration-flow key thumbprint the SDK generated itself, before Prepare
34
+ // was sent. Those two are the load-bearing checks. Tenant scope alone would not
35
+ // be: two attempts under one customer app carry identical tenant claims.
36
+ //
37
+ // **Claims.** The claim set DAA signs under `typ: daa-prepare-receipt+jws`:
38
+ // `iss`, `aud`, `iat`, `exp`, `jti`, `environment`, `customerAppId`,
39
+ // `parentEntityIdDigest`, `provider`, `loginRequestId`, `nonce`,
40
+ // `registrationCodeChallenge`, `registrationFlowKeyThumbprint`. The
41
+ // `nonce` claim carries the value the Prepare response calls `oidcNonce`.
42
+ // There is no state claim: `oidcState` is not bound by the receipt.
43
+ //
44
+ // **Tenant scope is not checked on the login path.** Comparing
45
+ // `customerAppId` / `parentEntityIdDigest` needs the parent entity the SDK
46
+ // expects, and the SDK defines no mapping from `DaaSdkConfiguration.appId` to
47
+ // DAA's parent entity. {@link requirePrepareReceiptTenantScope} is the
48
+ // comparison; the login path does not call it.
49
+ //
50
+ // **No trust anchor is pinned in this release.** The anchor (issuer, audience,
51
+ // signing keys, clock allowance) ships inside the SDK build, and
52
+ // {@link pinnedPrepareReceiptTrustAnchor} returns `null` for every environment.
53
+ // {@link checkPrepareReceipt} defines what login does in each case: with no
54
+ // anchor, the SDK ignores a receipt rather than failing on it. Ignoring loses
55
+ // nothing, because an SDK with no anchor could not verify the receipt anyway.
56
+ // It does mean `oidcNonce` and `oidcState` are not authenticated by the SDK:
57
+ // integrators bind the provider redirect with their own OAuth `state`.
58
+ //
59
+ // **Errors.** Every failure to verify a receipt the SDK needs is
60
+ // `prepare_receipt_invalid`. Faults in the SDK's own inputs — a
61
+ // malformed pinned anchor, an incomplete expectation, a bad test clock, a
62
+ // parent entity id that is not a canonical UUID — are `contract_violation`,
63
+ // because they describe this build, not the receipt.
64
+
65
+ import type { DaaEnvironment } from '../config'
66
+ import { fromBase64Url, toBase64Url } from '../crypto/base64url'
67
+ import { ownMember, verifyCompactEs256, type PinnedEs256Key } from '../crypto/es256Jws'
68
+ import type { P256PublicJwk } from '../crypto/jwkThumbprint'
69
+ import { sha256 } from '../crypto/sha256'
70
+ import { contractViolation, DaaError, isDaaError, prepareReceiptInvalid } from '../errors'
71
+ import { isUuid } from '../validation/uuid'
72
+
73
+ /** Contract bounds on `SocialLoginRequest.prepareReceiptJws`. */
74
+ export const PREPARE_RECEIPT_MIN_LENGTH = 64
75
+ export const PREPARE_RECEIPT_MAX_LENGTH = 8192
76
+
77
+ /** The JWS `typ` DAA signs the receipt with. */
78
+ export const PREPARE_RECEIPT_TYP = 'daa-prepare-receipt+jws'
79
+
80
+ /** Widest clock skew an anchor may allow, so a configuration typo cannot disable expiry. */
81
+ export const PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS = 300
82
+
83
+ /** Compact JWS serialization: three Base64URL segments separated by dots. */
84
+ const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/
85
+
86
+ /** One pinned receipt-signing key, addressed by the `kid` DAA puts in the header. */
87
+ export type PrepareReceiptVerificationKey = Readonly<{ kid: string; jwk: P256PublicJwk }>
88
+
89
+ /**
90
+ * Everything a trust anchor pins, in one value.
91
+ *
92
+ * `verificationKeys` is pinned by the build and never derived from a receipt.
93
+ * More than one entry allows a rotation overlap; the receipt's `kid` selects
94
+ * among them and nothing else.
95
+ */
96
+ export type PrepareReceiptTrustAnchor = Readonly<{
97
+ /** Exact expected `iss`. */
98
+ issuer: string
99
+ /** Exact expected `aud`, or one member of an `aud` array. */
100
+ audience: string
101
+ verificationKeys: readonly PrepareReceiptVerificationKey[]
102
+ /** Allowance on `exp` / `iat` / `nbf`, in seconds. */
103
+ maxClockSkewSeconds: number
104
+ }>
105
+
106
+ /**
107
+ * The build-time pinned anchor for an environment. **`null` for every
108
+ * environment in this release.**
109
+ *
110
+ * A function rather than a `const`, so that its declared return type does not
111
+ * narrow the rest of this module to unreachable code.
112
+ */
113
+ export function pinnedPrepareReceiptTrustAnchor(
114
+ environment: DaaEnvironment,
115
+ ): PrepareReceiptTrustAnchor | null {
116
+ void environment
117
+ return null
118
+ }
119
+
120
+ /**
121
+ * The values this attempt's receipt must name. The first two come from the
122
+ * Prepare response; the rest are the SDK's own.
123
+ */
124
+ export type PrepareReceiptExpectation = Readonly<{
125
+ loginRequestId: string
126
+ /** The Prepare response's `oidcNonce`; the receipt's `nonce` claim. */
127
+ nonce: string
128
+ provider: string
129
+ environment: DaaEnvironment
130
+ registrationCodeChallenge: string
131
+ registrationFlowKeyThumbprint: string
132
+ }>
133
+
134
+ /**
135
+ * Test-only clock, following `auth/deviceAuthorization.ts`: production code
136
+ * always uses the system clock, and no production caller passes one.
137
+ */
138
+ export type PrepareReceiptClock = Readonly<{ nowEpochSeconds: () => number }>
139
+
140
+ const SYSTEM_CLOCK: PrepareReceiptClock = {
141
+ nowEpochSeconds: () => Math.floor(Date.now() / 1000),
142
+ }
143
+
144
+ /** What a verified receipt attested. Only ever returned after every check passed. */
145
+ export type VerifiedPrepareReceipt = Readonly<{
146
+ /** The receipt exactly as received. */
147
+ compactJws: string
148
+ loginRequestId: string
149
+ nonce: string
150
+ expiresAtEpochSeconds: number
151
+ /** Signed but not compared on the login path; see {@link requirePrepareReceiptTenantScope}. */
152
+ tenantScope: Readonly<{ customerAppId: unknown; parentEntityIdDigest: unknown }>
153
+ }>
154
+
155
+ /**
156
+ * Whether a value is shaped like the compact JWS the contract describes and sits
157
+ * within its declared length bounds. Structural only: shape is not trust.
158
+ */
159
+ export function isPrepareReceiptShape(value: string): boolean {
160
+ return (
161
+ value.length >= PREPARE_RECEIPT_MIN_LENGTH &&
162
+ value.length <= PREPARE_RECEIPT_MAX_LENGTH &&
163
+ COMPACT_JWS.test(value)
164
+ )
165
+ }
166
+
167
+ /**
168
+ * What login does with the receipt, given the anchor for this environment.
169
+ *
170
+ * | Anchor | Receipt | Result |
171
+ * | ------ | ------- | ----------------------------------------------------------- |
172
+ * | unset | absent | `null`: nothing to verify, login proceeds |
173
+ * | unset | present | `null`: the receipt is ignored, login proceeds as if absent |
174
+ * | set | absent | `prepare_receipt_invalid`: the receipt is required |
175
+ * | set | present | {@link verifyPrepareReceipt}; any failure throws |
176
+ *
177
+ * `prepareReceiptJws` is the raw response member: `undefined` or `null` is
178
+ * absent, and anything else is present, whatever its type. In the first two
179
+ * rows it is not read at all, and `expected` is a thunk so they compute
180
+ * nothing: with no anchor, the login path does no receipt work.
181
+ *
182
+ * In the second row, an SDK without the anchor ignores the receipt: it could
183
+ * not verify it, so ignoring gives up no protection. An ignored receipt is
184
+ * never passed on as if it were checked: this returns `null` for it exactly as
185
+ * for no receipt, so the login path hands the application no receipt at all.
186
+ */
187
+ export async function checkPrepareReceipt(
188
+ prepareReceiptJws: unknown,
189
+ anchor: PrepareReceiptTrustAnchor | null,
190
+ expected: () => PrepareReceiptExpectation,
191
+ clock: PrepareReceiptClock = SYSTEM_CLOCK,
192
+ ): Promise<VerifiedPrepareReceipt | null> {
193
+ if (anchor === null) {
194
+ return null
195
+ }
196
+ if (prepareReceiptJws === undefined || prepareReceiptJws === null) {
197
+ throw prepareReceiptInvalid(
198
+ 'the Prepare response carries no receipt, and this environment requires one',
199
+ )
200
+ }
201
+ return verifyPrepareReceipt(prepareReceiptJws, anchor, expected(), clock)
202
+ }
203
+
204
+ /**
205
+ * Verify the receipt against a trust anchor and this attempt's expectation.
206
+ *
207
+ * Order: the anchor and the expectation first, because a fault in either is a
208
+ * configuration error; then the receipt's shape; then its header and signature;
209
+ * and only then the claims, because a claim from an unverified token is not
210
+ * evidence of anything.
211
+ *
212
+ * A fault in the anchor, the expectation, or the clock is `contract_violation`;
213
+ * every rejection of the receipt itself, including a platform verifier that is
214
+ * missing or fails, is `prepare_receipt_invalid`.
215
+ *
216
+ * The receipt is never interpolated into an error: it is unverified
217
+ * server-supplied text, and a consumer is likely to log the message verbatim.
218
+ */
219
+ export async function verifyPrepareReceipt(
220
+ prepareReceiptJws: unknown,
221
+ anchor: PrepareReceiptTrustAnchor,
222
+ expected: PrepareReceiptExpectation,
223
+ clock: PrepareReceiptClock = SYSTEM_CLOCK,
224
+ ): Promise<VerifiedPrepareReceipt> {
225
+ const keys = pinnedKeys(anchor)
226
+ requireExpectation(expected)
227
+ const now = clock.nowEpochSeconds()
228
+ if (!Number.isInteger(now) || now <= 0) {
229
+ throw contractViolation('the Prepare receipt clock must yield a positive Unix timestamp')
230
+ }
231
+
232
+ if (typeof prepareReceiptJws !== 'string' || !isPrepareReceiptShape(prepareReceiptJws)) {
233
+ throw prepareReceiptInvalid(
234
+ 'the Prepare receipt is not a compact JWS within the contract length bounds',
235
+ )
236
+ }
237
+
238
+ const result = await platformVerify(prepareReceiptJws, keys)
239
+ if (!result.verified) {
240
+ throw prepareReceiptInvalid(`the Prepare receipt did not verify (${result.reason})`)
241
+ }
242
+
243
+ const claims = result.payload
244
+ requireClaimEquals(claims, 'iss', anchor.issuer)
245
+ requireAudience(claims, anchor.audience)
246
+ requireNonEmptyClaim(claims, 'jti')
247
+ requireClaimEquals(claims, 'environment', expected.environment)
248
+ requireClaimEquals(claims, 'provider', expected.provider)
249
+ requireClaimEquals(claims, 'loginRequestId', expected.loginRequestId)
250
+ requireClaimEquals(claims, 'nonce', expected.nonce)
251
+ requireClaimEquals(claims, 'registrationCodeChallenge', expected.registrationCodeChallenge)
252
+ requireClaimEquals(
253
+ claims,
254
+ 'registrationFlowKeyThumbprint',
255
+ expected.registrationFlowKeyThumbprint,
256
+ )
257
+ const expiresAtEpochSeconds = requireTimeClaims(claims, now, anchor.maxClockSkewSeconds)
258
+
259
+ return {
260
+ compactJws: prepareReceiptJws,
261
+ loginRequestId: expected.loginRequestId,
262
+ nonce: expected.nonce,
263
+ expiresAtEpochSeconds,
264
+ tenantScope: {
265
+ customerAppId: ownMember(claims, 'customerAppId'),
266
+ parentEntityIdDigest: ownMember(claims, 'parentEntityIdDigest'),
267
+ },
268
+ }
269
+ }
270
+
271
+ /**
272
+ * The signature check, with a platform verifier that is missing or fails
273
+ * reported as the receipt failing to verify.
274
+ *
275
+ * `pinnedKeys` has already validated everything {@link verifyCompactEs256}
276
+ * would reject as a configuration error, so the only `DaaError` left to come
277
+ * out of it is the platform's: no `DaaRegistration` module, one without the
278
+ * verify function, or a native rejection. A native rejection also covers a
279
+ * pinned point the platform does not accept as on the curve — the one anchor
280
+ * fault only the platform can see, and indistinguishable here from the rest.
281
+ * The SDK's own message and the original error (as `cause`) are kept.
282
+ */
283
+ async function platformVerify(
284
+ jws: string,
285
+ keys: readonly PinnedEs256Key[],
286
+ ): Promise<Awaited<ReturnType<typeof verifyCompactEs256>>> {
287
+ try {
288
+ return await verifyCompactEs256(jws, { keys, expectedTyp: PREPARE_RECEIPT_TYP })
289
+ } catch (err) {
290
+ if (isDaaError(err) && err.detail.kind === 'contract_violation') {
291
+ throw new DaaError({ kind: 'prepare_receipt_invalid' }, err.message, err)
292
+ }
293
+ throw err
294
+ }
295
+ }
296
+
297
+ /**
298
+ * Domain separator for `parentEntityIdDigest`, byte-for-byte the one DAA
299
+ * signs with. The trailing NUL is part of it.
300
+ */
301
+ export const PARENT_ENTITY_ID_DIGEST_DOMAIN = 'daa-prepare-receipt-parent-entity-digest-v1\0'
302
+
303
+ /**
304
+ * `base64url_nopad(SHA-256(utf8(domain) || utf8(parentEntityId)))`, where the
305
+ * id is the canonical lower-case hyphenated UUID — DAA's pinned formula.
306
+ */
307
+ export function parentEntityIdDigest(parentEntityId: string): string {
308
+ if (
309
+ typeof parentEntityId !== 'string' ||
310
+ !isUuid(parentEntityId) ||
311
+ parentEntityId !== parentEntityId.toLowerCase()
312
+ ) {
313
+ throw contractViolation('parentEntityId must be a canonical lower-case UUID')
314
+ }
315
+ const encoder = new TextEncoder()
316
+ const domain = encoder.encode(PARENT_ENTITY_ID_DIGEST_DOMAIN)
317
+ const id = encoder.encode(parentEntityId)
318
+ const input = new Uint8Array(domain.length + id.length)
319
+ input.set(domain)
320
+ input.set(id, domain.length)
321
+ return toBase64Url(sha256(input))
322
+ }
323
+
324
+ /**
325
+ * Tenant-scope comparison for a verified receipt. **Not called on the login
326
+ * path:** the SDK has no defined way to derive the expected parent entity from
327
+ * its configuration. A caller that has the expected values calls this after
328
+ * {@link verifyPrepareReceipt}.
329
+ */
330
+ export function requirePrepareReceiptTenantScope(
331
+ receipt: VerifiedPrepareReceipt,
332
+ expected: Readonly<{ customerAppId: string; parentEntityId: string }>,
333
+ ): void {
334
+ const { customerAppId, parentEntityIdDigest: digest } = receipt.tenantScope
335
+ if (typeof customerAppId !== 'string' || customerAppId !== expected.customerAppId) {
336
+ throw prepareReceiptInvalid('the Prepare receipt does not bind the expected customerAppId')
337
+ }
338
+ if (typeof digest !== 'string' || digest !== parentEntityIdDigest(expected.parentEntityId)) {
339
+ throw prepareReceiptInvalid(
340
+ 'the Prepare receipt does not bind the expected parentEntityIdDigest',
341
+ )
342
+ }
343
+ }
344
+
345
+ /**
346
+ * Validate the anchor and convert its keys to the points the platform verifies
347
+ * against. A malformed anchor is a configuration error, not a rejected receipt.
348
+ * Whether each point is on the curve is the platform's check.
349
+ */
350
+ function pinnedKeys(anchor: PrepareReceiptTrustAnchor): readonly PinnedEs256Key[] {
351
+ if (typeof anchor !== 'object' || anchor === null) {
352
+ throw contractViolation('the Prepare receipt trust anchor must be an object')
353
+ }
354
+ if (typeof anchor.issuer !== 'string' || anchor.issuer.length === 0) {
355
+ throw contractViolation('the Prepare receipt trust anchor must name an issuer')
356
+ }
357
+ if (typeof anchor.audience !== 'string' || anchor.audience.length === 0) {
358
+ throw contractViolation('the Prepare receipt trust anchor must name an audience')
359
+ }
360
+ if (
361
+ !Number.isInteger(anchor.maxClockSkewSeconds) ||
362
+ anchor.maxClockSkewSeconds < 0 ||
363
+ anchor.maxClockSkewSeconds > PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS
364
+ ) {
365
+ throw contractViolation(
366
+ 'the Prepare receipt trust anchor clock skew must be between 0 and ' +
367
+ `${PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS} seconds`,
368
+ )
369
+ }
370
+ if (!Array.isArray(anchor.verificationKeys) || anchor.verificationKeys.length === 0) {
371
+ throw contractViolation('the Prepare receipt trust anchor must pin at least one P-256 key')
372
+ }
373
+ const kids = new Set<string>()
374
+ for (const key of anchor.verificationKeys) {
375
+ if (typeof key !== 'object' || key === null) {
376
+ throw contractViolation('every Prepare receipt verification key must be an object')
377
+ }
378
+ if (typeof key.kid !== 'string' || key.kid.length === 0) {
379
+ throw contractViolation('every Prepare receipt verification key must have a non-empty kid')
380
+ }
381
+ if (kids.has(key.kid)) {
382
+ throw contractViolation('Prepare receipt verification keys must have distinct kids')
383
+ }
384
+ kids.add(key.kid)
385
+ }
386
+ return anchor.verificationKeys.map((key) => ({
387
+ kid: key.kid,
388
+ publicKeyX963: x963FromJwk(key.jwk),
389
+ }))
390
+ }
391
+
392
+ function x963FromJwk(jwk: P256PublicJwk): Uint8Array {
393
+ if (typeof jwk !== 'object' || jwk === null || jwk.kty !== 'EC' || jwk.crv !== 'P-256') {
394
+ throw contractViolation('a Prepare receipt verification key must be an EC P-256 JWK')
395
+ }
396
+ let x: Uint8Array
397
+ let y: Uint8Array
398
+ try {
399
+ x = fromBase64Url(jwk.x)
400
+ y = fromBase64Url(jwk.y)
401
+ } catch {
402
+ throw contractViolation('a Prepare receipt verification key has a non-Base64URL coordinate')
403
+ }
404
+ if (x.length !== 32 || y.length !== 32) {
405
+ throw contractViolation(
406
+ 'a Prepare receipt verification key must have 32-byte x and y coordinates',
407
+ )
408
+ }
409
+ const point = new Uint8Array(65)
410
+ point[0] = 0x04
411
+ point.set(x, 1)
412
+ point.set(y, 33)
413
+ return point
414
+ }
415
+
416
+ function requireExpectation(expected: PrepareReceiptExpectation): void {
417
+ if (typeof expected !== 'object' || expected === null) {
418
+ throw contractViolation(
419
+ 'verifying a Prepare receipt requires the expected values for this attempt',
420
+ )
421
+ }
422
+ for (const name of [
423
+ 'loginRequestId',
424
+ 'nonce',
425
+ 'provider',
426
+ 'environment',
427
+ 'registrationCodeChallenge',
428
+ 'registrationFlowKeyThumbprint',
429
+ ] as const) {
430
+ const value = expected[name]
431
+ if (typeof value !== 'string' || value.length === 0) {
432
+ throw contractViolation(`verifying a Prepare receipt requires the expected ${name}`)
433
+ }
434
+ }
435
+ }
436
+
437
+ /**
438
+ * Exact string equality on one claim. Not constant-time, and does not need to
439
+ * be: every value compared is one the SDK sent, generated, or relayed to the
440
+ * application; none is a secret. The claim name goes in the message — it is
441
+ * one of this module's literals — and the value never does.
442
+ */
443
+ function requireClaimEquals(
444
+ claims: Readonly<Record<string, unknown>>,
445
+ name: string,
446
+ expected: string,
447
+ ): void {
448
+ const actual = ownMember(claims, name)
449
+ if (typeof actual !== 'string' || actual !== expected) {
450
+ throw prepareReceiptInvalid(`the Prepare receipt does not bind the expected ${name}`)
451
+ }
452
+ }
453
+
454
+ function requireNonEmptyClaim(claims: Readonly<Record<string, unknown>>, name: string): void {
455
+ const actual = ownMember(claims, name)
456
+ if (typeof actual !== 'string' || actual.length === 0) {
457
+ throw prepareReceiptInvalid(`the Prepare receipt does not carry a ${name}`)
458
+ }
459
+ }
460
+
461
+ /** RFC 7519 §4.1.3: `aud` is a string or an array of strings that must contain ours. */
462
+ function requireAudience(claims: Readonly<Record<string, unknown>>, audience: string): void {
463
+ const actual = ownMember(claims, 'aud')
464
+ if (typeof actual === 'string' && actual === audience) {
465
+ return
466
+ }
467
+ if (Array.isArray(actual) && actual.some((value) => value === audience)) {
468
+ return
469
+ }
470
+ throw prepareReceiptInvalid('the Prepare receipt does not bind the expected aud')
471
+ }
472
+
473
+ /**
474
+ * `exp` and `iat` are required (DAA always sets both); `nbf` is checked when
475
+ * present. All are RFC 7519 NumericDates in seconds — deliberately not the
476
+ * epoch-millis tolerance `wire/instant.ts` carries for the Prepare body, since
477
+ * DAA's signer emits seconds. A millisecond value fails the upper bound below
478
+ * instead of passing as an expiry thousands of years out.
479
+ */
480
+ function requireTimeClaims(
481
+ claims: Readonly<Record<string, unknown>>,
482
+ nowEpochSeconds: number,
483
+ maxClockSkewSeconds: number,
484
+ ): number {
485
+ const exp = requireNumericDate(claims, 'exp')
486
+ const iat = requireNumericDate(claims, 'iat')
487
+ if (exp + maxClockSkewSeconds < nowEpochSeconds) {
488
+ throw prepareReceiptInvalid('the Prepare receipt has expired')
489
+ }
490
+ if (iat - maxClockSkewSeconds > nowEpochSeconds) {
491
+ throw prepareReceiptInvalid('the Prepare receipt is not valid yet (iat is in the future)')
492
+ }
493
+ if (iat > exp) {
494
+ throw prepareReceiptInvalid('the Prepare receipt expires before it was issued')
495
+ }
496
+ if (ownMember(claims, 'nbf') !== undefined) {
497
+ const nbf = requireNumericDate(claims, 'nbf')
498
+ if (nbf - maxClockSkewSeconds > nowEpochSeconds) {
499
+ throw prepareReceiptInvalid('the Prepare receipt is not valid yet (nbf is in the future)')
500
+ }
501
+ }
502
+ return exp
503
+ }
504
+
505
+ /** Past year 9999 is not a clock; it is a unit mistake or a receipt that never expires. */
506
+ const MAX_NUMERIC_DATE = 253402300799
507
+
508
+ function requireNumericDate(claims: Readonly<Record<string, unknown>>, name: string): number {
509
+ const value = ownMember(claims, name)
510
+ if (value === undefined) {
511
+ throw prepareReceiptInvalid(`the Prepare receipt does not carry an ${name}`)
512
+ }
513
+ if (
514
+ typeof value !== 'number' ||
515
+ !Number.isInteger(value) ||
516
+ value <= 0 ||
517
+ value > MAX_NUMERIC_DATE
518
+ ) {
519
+ throw prepareReceiptInvalid(`the Prepare receipt carries a malformed ${name}`)
520
+ }
521
+ return value
522
+ }