@circle-fin/daa-react-native-sdk 0.0.0-stage → 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.
- package/DaaReactNativeSdk.podspec +69 -0
- package/LICENSE +176 -0
- package/README.md +691 -2
- package/android/build.gradle +102 -0
- package/android/src/main/AndroidManifest.xml +1 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt +47 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt +104 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt +60 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt +179 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt +107 -0
- package/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt +318 -0
- package/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt +122 -0
- package/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt +45 -0
- package/build/DaaClient.d.ts +237 -0
- package/build/DaaClient.js +442 -0
- package/build/api/AccountLimitsClient.d.ts +79 -0
- package/build/api/AccountLimitsClient.js +142 -0
- package/build/api/AccountsClient.d.ts +98 -0
- package/build/api/AccountsClient.js +279 -0
- package/build/api/AchFiatAccountsClient.d.ts +92 -0
- package/build/api/AchFiatAccountsClient.js +142 -0
- package/build/api/AuthClient.d.ts +95 -0
- package/build/api/AuthClient.js +221 -0
- package/build/api/ContractExecutionsClient.d.ts +114 -0
- package/build/api/ContractExecutionsClient.js +462 -0
- package/build/api/DaaUserClient.d.ts +187 -0
- package/build/api/DaaUserClient.js +312 -0
- package/build/api/DepositAddressesClient.d.ts +112 -0
- package/build/api/DepositAddressesClient.js +222 -0
- package/build/api/DepositsClient.d.ts +106 -0
- package/build/api/DepositsClient.js +183 -0
- package/build/api/FiatAccountsClient.d.ts +43 -0
- package/build/api/FiatAccountsClient.js +46 -0
- package/build/api/TransactionsClient.d.ts +64 -0
- package/build/api/TransactionsClient.js +121 -0
- package/build/api/TransfersClient.d.ts +107 -0
- package/build/api/TransfersClient.js +324 -0
- package/build/api/WireFiatAccountsClient.d.ts +99 -0
- package/build/api/WireFiatAccountsClient.js +156 -0
- package/build/api/WithdrawalsClient.d.ts +97 -0
- package/build/api/WithdrawalsClient.js +308 -0
- package/build/api/deviceApproval.d.ts +48 -0
- package/build/api/deviceApproval.js +247 -0
- package/build/api/deviceStatus.d.ts +61 -0
- package/build/api/deviceStatus.js +216 -0
- package/build/api/loginFailure.d.ts +51 -0
- package/build/api/loginFailure.js +95 -0
- package/build/api/pagination.d.ts +29 -0
- package/build/api/pagination.js +50 -0
- package/build/api/queryParameters.d.ts +23 -0
- package/build/api/queryParameters.js +77 -0
- package/build/api/resourceRequest.d.ts +60 -0
- package/build/api/resourceRequest.js +79 -0
- package/build/api/signedResource.d.ts +124 -0
- package/build/api/signedResource.js +267 -0
- package/build/auth/RegistrationFlowKey.d.ts +93 -0
- package/build/auth/RegistrationFlowKey.js +203 -0
- package/build/auth/daaRegistrationNative.d.ts +58 -0
- package/build/auth/daaRegistrationNative.js +158 -0
- package/build/auth/deviceAuthorization.d.ts +87 -0
- package/build/auth/deviceAuthorization.js +295 -0
- package/build/auth/ownerGrant.d.ts +29 -0
- package/build/auth/ownerGrant.js +90 -0
- package/build/auth/registrationAuthorization.d.ts +48 -0
- package/build/auth/registrationAuthorization.js +246 -0
- package/build/auth/registrationCodeVerifier.d.ts +31 -0
- package/build/auth/registrationCodeVerifier.js +75 -0
- package/build/config.d.ts +106 -0
- package/build/config.js +131 -0
- package/build/crypto/base64url.d.ts +26 -0
- package/build/crypto/base64url.js +87 -0
- package/build/crypto/bytes.d.ts +27 -0
- package/build/crypto/bytes.js +32 -0
- package/build/crypto/jwkThumbprint.d.ts +32 -0
- package/build/crypto/jwkThumbprint.js +49 -0
- package/build/crypto/matchingCode.d.ts +47 -0
- package/build/crypto/matchingCode.js +93 -0
- package/build/crypto/random.d.ts +35 -0
- package/build/crypto/random.js +106 -0
- package/build/crypto/serialization.d.ts +26 -0
- package/build/crypto/serialization.js +43 -0
- package/build/crypto/sha256.d.ts +18 -0
- package/build/crypto/sha256.js +100 -0
- package/build/errors.d.ts +307 -0
- package/build/errors.js +413 -0
- package/build/index.d.ts +69 -0
- package/build/index.js +67 -0
- package/build/models/Account.d.ts +201 -0
- package/build/models/Account.js +147 -0
- package/build/models/AccountLimitsUsage.d.ts +169 -0
- package/build/models/AccountLimitsUsage.js +86 -0
- package/build/models/Ach.d.ts +135 -0
- package/build/models/Ach.js +184 -0
- package/build/models/AddressObject.d.ts +128 -0
- package/build/models/AddressObject.js +141 -0
- package/build/models/BusinessPii.d.ts +84 -0
- package/build/models/BusinessPii.js +142 -0
- package/build/models/ContractExecution.d.ts +197 -0
- package/build/models/ContractExecution.js +130 -0
- package/build/models/CreateAccountRequest.d.ts +74 -0
- package/build/models/CreateAccountRequest.js +19 -0
- package/build/models/CreateContractExecutionRequest.d.ts +81 -0
- package/build/models/CreateContractExecutionRequest.js +19 -0
- package/build/models/CreateTransferRequest.d.ts +91 -0
- package/build/models/CreateTransferRequest.js +19 -0
- package/build/models/CreateWithdrawalRequest.d.ts +99 -0
- package/build/models/CreateWithdrawalRequest.js +19 -0
- package/build/models/DaaUserContext.d.ts +146 -0
- package/build/models/DaaUserContext.js +164 -0
- package/build/models/Deposit.d.ts +241 -0
- package/build/models/Deposit.js +149 -0
- package/build/models/DepositSummary.d.ts +91 -0
- package/build/models/DepositSummary.js +114 -0
- package/build/models/DeviceStatus.d.ts +69 -0
- package/build/models/DeviceStatus.js +19 -0
- package/build/models/FiatAccount.d.ts +99 -0
- package/build/models/FiatAccount.js +151 -0
- package/build/models/GenerateAddressRequest.d.ts +67 -0
- package/build/models/GenerateAddressRequest.js +68 -0
- package/build/models/Money.d.ts +76 -0
- package/build/models/Money.js +99 -0
- package/build/models/Page.d.ts +33 -0
- package/build/models/Page.js +57 -0
- package/build/models/PendingDeviceApproval.d.ts +121 -0
- package/build/models/PendingDeviceApproval.js +208 -0
- package/build/models/PendingDeviceRegistration.d.ts +229 -0
- package/build/models/PendingDeviceRegistration.js +636 -0
- package/build/models/PreparedContractExecution.d.ts +70 -0
- package/build/models/PreparedContractExecution.js +77 -0
- package/build/models/PreparedSocialLogin.d.ts +148 -0
- package/build/models/PreparedSocialLogin.js +252 -0
- package/build/models/Transaction.d.ts +233 -0
- package/build/models/Transaction.js +182 -0
- package/build/models/Transfer.d.ts +335 -0
- package/build/models/Transfer.js +240 -0
- package/build/models/Wire.d.ts +213 -0
- package/build/models/Wire.js +264 -0
- package/build/models/Withdrawal.d.ts +201 -0
- package/build/models/Withdrawal.js +156 -0
- package/build/models/codeSecrets.d.ts +100 -0
- package/build/models/codeSecrets.js +321 -0
- package/build/models/redaction.d.ts +18 -0
- package/build/models/redaction.js +23 -0
- package/build/sca/ScaClient.d.ts +105 -0
- package/build/sca/ScaClient.js +193 -0
- package/build/securekey/InMemorySecureKey.d.ts +25 -0
- package/build/securekey/InMemorySecureKey.js +168 -0
- package/build/securekey/NativeSecureKey.d.ts +26 -0
- package/build/securekey/NativeSecureKey.js +355 -0
- package/build/securekey/NativeSecureKeyBridge.d.ts +151 -0
- package/build/securekey/NativeSecureKeyBridge.js +19 -0
- package/build/securekey/SecureKey.d.ts +257 -0
- package/build/securekey/SecureKey.js +19 -0
- package/build/securekey/alias.d.ts +97 -0
- package/build/securekey/alias.js +184 -0
- package/build/securekey/ownerAuthKeyResolver.d.ts +73 -0
- package/build/securekey/ownerAuthKeyResolver.js +78 -0
- package/build/securekey/registration.d.ts +19 -0
- package/build/securekey/registration.js +38 -0
- package/build/securekey/resolveNativeBridge.d.ts +33 -0
- package/build/securekey/resolveNativeBridge.js +201 -0
- package/build/testing.d.ts +18 -0
- package/build/testing.js +34 -0
- package/build/transport/DaaTransport.d.ts +35 -0
- package/build/transport/DaaTransport.js +19 -0
- package/build/transport/headers.d.ts +41 -0
- package/build/transport/headers.js +81 -0
- package/build/validation/requestBody.d.ts +27 -0
- package/build/validation/requestBody.js +56 -0
- package/build/validation/uuid.d.ts +25 -0
- package/build/validation/uuid.js +33 -0
- package/build/wire/accountLimitsUsagePayload.d.ts +30 -0
- package/build/wire/accountLimitsUsagePayload.js +130 -0
- package/build/wire/accountPayload.d.ts +36 -0
- package/build/wire/accountPayload.js +100 -0
- package/build/wire/achPayload.d.ts +24 -0
- package/build/wire/achPayload.js +82 -0
- package/build/wire/addressObjectPayload.d.ts +44 -0
- package/build/wire/addressObjectPayload.js +64 -0
- package/build/wire/contractExecutionPayload.d.ts +24 -0
- package/build/wire/contractExecutionPayload.js +130 -0
- package/build/wire/daaStatusCodes.d.ts +81 -0
- package/build/wire/daaStatusCodes.js +86 -0
- package/build/wire/dataEnvelope.d.ts +40 -0
- package/build/wire/dataEnvelope.js +79 -0
- package/build/wire/depositPayload.d.ts +42 -0
- package/build/wire/depositPayload.js +159 -0
- package/build/wire/deviceContextPayload.d.ts +35 -0
- package/build/wire/deviceContextPayload.js +59 -0
- package/build/wire/deviceRegistrationResultPayload.d.ts +77 -0
- package/build/wire/deviceRegistrationResultPayload.js +162 -0
- package/build/wire/deviceStatusPayload.d.ts +20 -0
- package/build/wire/deviceStatusPayload.js +66 -0
- package/build/wire/errorEnvelope.d.ts +43 -0
- package/build/wire/errorEnvelope.js +85 -0
- package/build/wire/fiatAccountPayload.d.ts +37 -0
- package/build/wire/fiatAccountPayload.js +93 -0
- package/build/wire/instant.d.ts +27 -0
- package/build/wire/instant.js +94 -0
- package/build/wire/jsonNumber.d.ts +30 -0
- package/build/wire/jsonNumber.js +34 -0
- package/build/wire/moneyPayload.d.ts +30 -0
- package/build/wire/moneyPayload.js +56 -0
- package/build/wire/paginationLinks.d.ts +28 -0
- package/build/wire/paginationLinks.js +167 -0
- package/build/wire/payload.d.ts +60 -0
- package/build/wire/payload.js +121 -0
- package/build/wire/pendingRegistrationPayload.d.ts +48 -0
- package/build/wire/pendingRegistrationPayload.js +72 -0
- package/build/wire/socialLoginRequestPayload.d.ts +26 -0
- package/build/wire/socialLoginRequestPayload.js +55 -0
- package/build/wire/transactionPayload.d.ts +31 -0
- package/build/wire/transactionPayload.js +149 -0
- package/build/wire/transferPayload.d.ts +43 -0
- package/build/wire/transferPayload.js +218 -0
- package/build/wire/wireEnums.d.ts +22 -0
- package/build/wire/wireEnums.js +69 -0
- package/build/wire/wirePayload.d.ts +29 -0
- package/build/wire/wirePayload.js +138 -0
- package/build/wire/withdrawalPayload.d.ts +27 -0
- package/build/wire/withdrawalPayload.js +179 -0
- package/expo-module.config.json +14 -0
- package/ios/DaaRegistrationExceptions.swift +58 -0
- package/ios/DaaRegistrationModule.swift +125 -0
- package/ios/DaaScaExceptions.swift +96 -0
- package/ios/DaaScaModule.swift +125 -0
- package/ios/DaaSecureKeyExceptions.swift +125 -0
- package/ios/DaaSecureKeyModule.swift +306 -0
- package/ios/InstallationIdentityStore.swift +162 -0
- package/ios/UnpaddedBase64URL.swift +42 -0
- package/package.json +114 -4
- package/src/DaaClient.ts +509 -0
- package/src/api/AccountLimitsClient.ts +146 -0
- package/src/api/AccountsClient.ts +308 -0
- package/src/api/AchFiatAccountsClient.ts +147 -0
- package/src/api/AuthClient.ts +266 -0
- package/src/api/ContractExecutionsClient.ts +527 -0
- package/src/api/DaaUserClient.ts +345 -0
- package/src/api/DepositAddressesClient.ts +239 -0
- package/src/api/DepositsClient.ts +208 -0
- package/src/api/FiatAccountsClient.ts +50 -0
- package/src/api/TransactionsClient.ts +138 -0
- package/src/api/TransfersClient.ts +364 -0
- package/src/api/WireFiatAccountsClient.ts +172 -0
- package/src/api/WithdrawalsClient.ts +342 -0
- package/src/api/deviceApproval.ts +306 -0
- package/src/api/deviceStatus.ts +238 -0
- package/src/api/loginFailure.ts +112 -0
- package/src/api/pagination.ts +63 -0
- package/src/api/queryParameters.ts +82 -0
- package/src/api/resourceRequest.ts +135 -0
- package/src/api/signedResource.ts +427 -0
- package/src/auth/RegistrationFlowKey.ts +274 -0
- package/src/auth/daaRegistrationNative.ts +191 -0
- package/src/auth/deviceAuthorization.ts +365 -0
- package/src/auth/ownerGrant.ts +102 -0
- package/src/auth/registrationAuthorization.ts +309 -0
- package/src/auth/registrationCodeVerifier.ts +76 -0
- package/src/config.ts +192 -0
- package/src/crypto/base64url.ts +88 -0
- package/src/crypto/bytes.ts +30 -0
- package/src/crypto/jwkThumbprint.ts +65 -0
- package/src/crypto/matchingCode.ts +100 -0
- package/src/crypto/random.ts +113 -0
- package/src/crypto/serialization.ts +42 -0
- package/src/crypto/sha256.ts +105 -0
- package/src/errors.ts +576 -0
- package/src/index.ts +258 -0
- package/src/models/Account.ts +264 -0
- package/src/models/AccountLimitsUsage.ts +192 -0
- package/src/models/Ach.ts +269 -0
- package/src/models/AddressObject.ts +169 -0
- package/src/models/BusinessPii.ts +154 -0
- package/src/models/ContractExecution.ts +250 -0
- package/src/models/CreateAccountRequest.ts +109 -0
- package/src/models/CreateContractExecutionRequest.ts +100 -0
- package/src/models/CreateTransferRequest.ts +114 -0
- package/src/models/CreateWithdrawalRequest.ts +120 -0
- package/src/models/DaaUserContext.ts +228 -0
- package/src/models/Deposit.ts +307 -0
- package/src/models/DepositSummary.ts +142 -0
- package/src/models/DeviceStatus.ts +50 -0
- package/src/models/FiatAccount.ts +195 -0
- package/src/models/GenerateAddressRequest.ts +101 -0
- package/src/models/Money.ts +91 -0
- package/src/models/Page.ts +48 -0
- package/src/models/PendingDeviceApproval.ts +229 -0
- package/src/models/PendingDeviceRegistration.ts +791 -0
- package/src/models/PreparedContractExecution.ts +128 -0
- package/src/models/PreparedSocialLogin.ts +297 -0
- package/src/models/Transaction.ts +322 -0
- package/src/models/Transfer.ts +459 -0
- package/src/models/Wire.ts +405 -0
- package/src/models/Withdrawal.ts +283 -0
- package/src/models/codeSecrets.ts +360 -0
- package/src/models/redaction.ts +22 -0
- package/src/sca/ScaClient.ts +289 -0
- package/src/securekey/InMemorySecureKey.ts +192 -0
- package/src/securekey/NativeSecureKey.ts +388 -0
- package/src/securekey/NativeSecureKeyBridge.ts +189 -0
- package/src/securekey/SecureKey.ts +279 -0
- package/src/securekey/alias.ts +212 -0
- package/src/securekey/ownerAuthKeyResolver.ts +135 -0
- package/src/securekey/registration.ts +40 -0
- package/src/securekey/resolveNativeBridge.ts +343 -0
- package/src/testing.ts +32 -0
- package/src/transport/DaaTransport.ts +42 -0
- package/src/transport/headers.ts +93 -0
- package/src/validation/requestBody.ts +60 -0
- package/src/validation/uuid.ts +31 -0
- package/src/wire/accountLimitsUsagePayload.ts +182 -0
- package/src/wire/accountPayload.ts +108 -0
- package/src/wire/achPayload.ts +98 -0
- package/src/wire/addressObjectPayload.ts +64 -0
- package/src/wire/contractExecutionPayload.ts +152 -0
- package/src/wire/daaStatusCodes.ts +86 -0
- package/src/wire/dataEnvelope.ts +80 -0
- package/src/wire/depositPayload.ts +186 -0
- package/src/wire/deviceContextPayload.ts +60 -0
- package/src/wire/deviceRegistrationResultPayload.ts +211 -0
- package/src/wire/deviceStatusPayload.ts +68 -0
- package/src/wire/errorEnvelope.ts +87 -0
- package/src/wire/fiatAccountPayload.ts +112 -0
- package/src/wire/instant.ts +96 -0
- package/src/wire/jsonNumber.ts +33 -0
- package/src/wire/moneyPayload.ts +55 -0
- package/src/wire/paginationLinks.ts +204 -0
- package/src/wire/payload.ts +146 -0
- package/src/wire/pendingRegistrationPayload.ts +118 -0
- package/src/wire/socialLoginRequestPayload.ts +66 -0
- package/src/wire/transactionPayload.ts +181 -0
- package/src/wire/transferPayload.ts +249 -0
- package/src/wire/wireEnums.ts +74 -0
- package/src/wire/wirePayload.ts +160 -0
- package/src/wire/withdrawalPayload.ts +219 -0
- package/testing.d.ts +19 -0
- package/testing.js +25 -0
|
@@ -0,0 +1,427 @@
|
|
|
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
|
+
// Signed public POST/GET: either serialize-once body bytes, or no body at all,
|
|
20
|
+
// plus a fresh `X-Device-Authorization` compact JWS.
|
|
21
|
+
//
|
|
22
|
+
// Signed v1 operations carry `query = null`. Failures are classified on the
|
|
23
|
+
// numeric DAA status code only, through `wire/daaStatusCodes.ts`.
|
|
24
|
+
// An invalid, missing, replayed, or mismatched authorization becomes
|
|
25
|
+
// `contract_violation` — the credential rejection a caller must handle on every
|
|
26
|
+
// signed request. The one exception is a `DEVICE_AUTHORIZATION_INVALID` whose
|
|
27
|
+
// own `iat`/`exp` fail DAA's 60-second freshness rule against the response's
|
|
28
|
+
// HTTP `Date`: that is `clock_skew` (see `isClockSkewed`). A `409` whose
|
|
29
|
+
// body carries `IDEMPOTENCY_KEY_REUSED` (`420034`) becomes
|
|
30
|
+
// `idempotency_conflict`, with the key recovered from the same request bytes
|
|
31
|
+
// that were signed and sent, not the (unsigned) response body; the caller
|
|
32
|
+
// reconciles the original operation rather than replacing the key.
|
|
33
|
+
//
|
|
34
|
+
// DAA has no code for an expired device authorization, a missing one, or a
|
|
35
|
+
// revoked credential: it reports them as `DEVICE_AUTHORIZATION_INVALID` or,
|
|
36
|
+
// on context refresh, `DEVICE_AUTHORIZATION_REQUEST_MISMATCH`, and the SDK
|
|
37
|
+
// classifies the code it receives. So a signed call is sent once, with no
|
|
38
|
+
// fresh-JWS retry, and no DAA response produces `device_revoked`. A
|
|
39
|
+
// non-numeric string `code` is `api`, even when it is the name of one of these
|
|
40
|
+
// conditions or of a row this mapping classifies.
|
|
41
|
+
//
|
|
42
|
+
// `AccountsClient.create` (`create_account`),
|
|
43
|
+
// `TransfersClient.create` (`transfer`), and `WithdrawalsClient.create`
|
|
44
|
+
// (`withdrawal`) call `postSignedResource`. `ContractExecutionsClient`
|
|
45
|
+
// (`contract_execution`) splits the same POST in two —
|
|
46
|
+
// `authorizeSignedPost` once, then `postAuthorizedResource` for the first send
|
|
47
|
+
// and every retry — because DAA requires a replay to carry the originally
|
|
48
|
+
// accepted authorization, not a fresh one; see
|
|
49
|
+
// `models/PreparedContractExecution.ts`. `DaaUserClient.refreshContext`
|
|
50
|
+
// (`get_device_context`) calls `getSignedResource` — the device-authorization
|
|
51
|
+
// contract treats "signed context refresh" alongside protected writes, and
|
|
52
|
+
// `securekey/SecureKey.ts` lists it alongside them as one of the defined DAA
|
|
53
|
+
// operations signing is reachable for.
|
|
54
|
+
|
|
55
|
+
import {
|
|
56
|
+
authorizeExactRequest,
|
|
57
|
+
DEVICE_AUTHORIZATION_HEADER,
|
|
58
|
+
deviceAuthorizationProfile,
|
|
59
|
+
idempotencyKeyFromExactBody,
|
|
60
|
+
jwsSegmentJson,
|
|
61
|
+
type DeviceAuthorizationOperation,
|
|
62
|
+
} from '../auth/deviceAuthorization'
|
|
63
|
+
import {
|
|
64
|
+
apiFailure,
|
|
65
|
+
clockSkew,
|
|
66
|
+
contractViolation,
|
|
67
|
+
devicePending,
|
|
68
|
+
idempotencyConflict,
|
|
69
|
+
type DaaError,
|
|
70
|
+
} from '../errors'
|
|
71
|
+
import type { OwnerAuthKeyResolver } from '../securekey/ownerAuthKeyResolver'
|
|
72
|
+
import type { DeviceApprovalCheck, OwnerAuthKey } from '../securekey/SecureKey'
|
|
73
|
+
import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport'
|
|
74
|
+
import { headerValueIgnoringCase, httpDateMillis } from '../transport/headers'
|
|
75
|
+
import { isDaaStatus } from '../wire/daaStatusCodes'
|
|
76
|
+
import { readDaaStatusCode } from '../wire/errorEnvelope'
|
|
77
|
+
import { decodeResourceResponse } from './resourceRequest'
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* What a resource client needs to authorize a signed write: the same pair
|
|
81
|
+
* `postSignedResource` takes, except the key is resolved when a write is
|
|
82
|
+
* actually made rather than held from the moment `forUser` returns.
|
|
83
|
+
*
|
|
84
|
+
* The two halves come from the same `ACTIVE` Device Registration Complete.
|
|
85
|
+
* `authKeyId` is the `DeviceContext` value the service assigned; the key itself
|
|
86
|
+
* is enclave-held and is not a field on that decoded result, so it is
|
|
87
|
+
* re-resolved by the `{appId, environment, clientEntityId}` alias login
|
|
88
|
+
* already used.
|
|
89
|
+
*
|
|
90
|
+
* Passed as one required value, because the failure this prevents is
|
|
91
|
+
* `DaaClient.forUser` validating a user context and then building the
|
|
92
|
+
* operations surface without it — leaving every write with nothing to sign
|
|
93
|
+
* with. A required constructor parameter makes that omission a compile error.
|
|
94
|
+
*
|
|
95
|
+
* Not on the public entry. A consumer holding one could reach
|
|
96
|
+
* `OwnerAuthKey.signExactBytes`, which is the generic signing surface this SDK
|
|
97
|
+
* deliberately does not expose.
|
|
98
|
+
*/
|
|
99
|
+
export type DaaUserSigning = Readonly<{
|
|
100
|
+
/** Resolves the installation AuthKey. Signing fails closed until it is registered. */
|
|
101
|
+
resolveAuthKey: OwnerAuthKeyResolver
|
|
102
|
+
/** `DeviceContext.authKeyId`, which becomes the authorization JWS `kid`. */
|
|
103
|
+
authKeyId: string
|
|
104
|
+
/**
|
|
105
|
+
* The Owner this key signs for, from the same context. Unsigned reads that
|
|
106
|
+
* DAA scopes by Owner, such as the device list an approval reads, need it.
|
|
107
|
+
*/
|
|
108
|
+
clientEntityId: string
|
|
109
|
+
}>
|
|
110
|
+
|
|
111
|
+
export type PostSignedResourceOptions<T> = Readonly<{
|
|
112
|
+
transport: DaaTransport
|
|
113
|
+
operation: DeviceAuthorizationOperation
|
|
114
|
+
authKey: OwnerAuthKey
|
|
115
|
+
authKeyId: string
|
|
116
|
+
/** Final serialized bytes. Hashed and sent as this same slice. */
|
|
117
|
+
bodyBytes: Uint8Array
|
|
118
|
+
expectedStatus: number
|
|
119
|
+
decode: (value: unknown) => T
|
|
120
|
+
}>
|
|
121
|
+
|
|
122
|
+
/** Execute a public POST with a fresh registered-device authorization header. */
|
|
123
|
+
export async function postSignedResource<T>({
|
|
124
|
+
transport,
|
|
125
|
+
operation,
|
|
126
|
+
authKey,
|
|
127
|
+
authKeyId,
|
|
128
|
+
bodyBytes,
|
|
129
|
+
expectedStatus,
|
|
130
|
+
decode,
|
|
131
|
+
}: PostSignedResourceOptions<T>): Promise<T> {
|
|
132
|
+
const profile = deviceAuthorizationProfile(operation)
|
|
133
|
+
if (profile.method !== 'POST') {
|
|
134
|
+
throw contractViolation('postSignedResource only sends POST registry operations')
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
return postAuthorizedResource({
|
|
138
|
+
transport,
|
|
139
|
+
operation,
|
|
140
|
+
bodyBytes,
|
|
141
|
+
authorization: await authorizeSignedPost({ operation, authKey, authKeyId, bodyBytes }),
|
|
142
|
+
expectedStatuses: [expectedStatus],
|
|
143
|
+
decode,
|
|
144
|
+
})
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
export type GetSignedResourceOptions<T> = Readonly<{
|
|
148
|
+
transport: DaaTransport
|
|
149
|
+
operation: DeviceAuthorizationOperation
|
|
150
|
+
authKey: OwnerAuthKey
|
|
151
|
+
authKeyId: string
|
|
152
|
+
expectedStatus: number
|
|
153
|
+
decode: (value: unknown) => T
|
|
154
|
+
}>
|
|
155
|
+
|
|
156
|
+
/** No body to serialize for a bodyless signed read; the signature hashes the empty byte array. */
|
|
157
|
+
const EMPTY_BODY = new Uint8Array(0)
|
|
158
|
+
|
|
159
|
+
/**
|
|
160
|
+
* Execute a public GET with a fresh registered-device authorization header.
|
|
161
|
+
*
|
|
162
|
+
* The only registry operation this reaches is `get_device_context`
|
|
163
|
+
* (`DaaUserClient.refreshContext`). There is no request body to serialize or
|
|
164
|
+
* sign over: `authorizeExactRequest` hashes the empty byte array per the
|
|
165
|
+
* bodyless-request rule, and nothing is sent as a request entity — the same
|
|
166
|
+
* bodyless shape `resourceRequest.ts`'s unsigned `readResource` sends.
|
|
167
|
+
*/
|
|
168
|
+
export async function getSignedResource<T>({
|
|
169
|
+
transport,
|
|
170
|
+
operation,
|
|
171
|
+
authKey,
|
|
172
|
+
authKeyId,
|
|
173
|
+
expectedStatus,
|
|
174
|
+
decode,
|
|
175
|
+
}: GetSignedResourceOptions<T>): Promise<T> {
|
|
176
|
+
const profile = deviceAuthorizationProfile(operation)
|
|
177
|
+
if (profile.method !== 'GET') {
|
|
178
|
+
throw contractViolation('getSignedResource only sends GET registry operations')
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const authorization = await authorizeExactRequest({
|
|
182
|
+
authKey,
|
|
183
|
+
authKeyId,
|
|
184
|
+
operation,
|
|
185
|
+
bodyBytes: EMPTY_BODY,
|
|
186
|
+
})
|
|
187
|
+
const response = await sendSignedGet({
|
|
188
|
+
transport,
|
|
189
|
+
path: profile.canonicalPath,
|
|
190
|
+
authorization,
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
if (response.status !== expectedStatus) {
|
|
194
|
+
throw mapSignedRequestFailure(response, EMPTY_BODY, authorization)
|
|
195
|
+
}
|
|
196
|
+
return decodeResourceResponse({ response, expectedStatus, decode })
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
function sendSignedGet(args: {
|
|
200
|
+
transport: DaaTransport
|
|
201
|
+
path: string
|
|
202
|
+
authorization: string
|
|
203
|
+
}): Promise<DaaHttpResponse> {
|
|
204
|
+
return args.transport.send({
|
|
205
|
+
method: 'GET',
|
|
206
|
+
path: args.path,
|
|
207
|
+
query: null,
|
|
208
|
+
headers: {
|
|
209
|
+
[DEVICE_AUTHORIZATION_HEADER]: args.authorization,
|
|
210
|
+
},
|
|
211
|
+
bodyBytes: null,
|
|
212
|
+
})
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function sendAuthorizedPost(args: {
|
|
216
|
+
transport: DaaTransport
|
|
217
|
+
path: string
|
|
218
|
+
bodyBytes: Uint8Array
|
|
219
|
+
authorization: string
|
|
220
|
+
}): Promise<DaaHttpResponse> {
|
|
221
|
+
return args.transport.send({
|
|
222
|
+
method: 'POST',
|
|
223
|
+
path: args.path,
|
|
224
|
+
query: null,
|
|
225
|
+
headers: {
|
|
226
|
+
'Content-Type': 'application/json',
|
|
227
|
+
[DEVICE_AUTHORIZATION_HEADER]: args.authorization,
|
|
228
|
+
},
|
|
229
|
+
bodyBytes: args.bodyBytes,
|
|
230
|
+
})
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
export type AuthorizeSignedPostOptions = Readonly<{
|
|
234
|
+
operation: DeviceAuthorizationOperation
|
|
235
|
+
authKey: OwnerAuthKey
|
|
236
|
+
authKeyId: string
|
|
237
|
+
/** Final serialized bytes. The returned authorization is bound to this slice. */
|
|
238
|
+
bodyBytes: Uint8Array
|
|
239
|
+
/** Required for `approve_device` only; see `DeviceAuthorizationRequest.approval`. */
|
|
240
|
+
approval?: DeviceApprovalCheck
|
|
241
|
+
}>
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Sign a POST registry operation's authorization over exact bytes, without
|
|
245
|
+
* sending anything. The signing half of {@link postSignedResource}.
|
|
246
|
+
*/
|
|
247
|
+
export async function authorizeSignedPost({
|
|
248
|
+
operation,
|
|
249
|
+
authKey,
|
|
250
|
+
authKeyId,
|
|
251
|
+
bodyBytes,
|
|
252
|
+
approval,
|
|
253
|
+
}: AuthorizeSignedPostOptions): Promise<string> {
|
|
254
|
+
if (deviceAuthorizationProfile(operation).method !== 'POST') {
|
|
255
|
+
throw contractViolation('authorizeSignedPost only signs POST registry operations')
|
|
256
|
+
}
|
|
257
|
+
return authorizeExactRequest({
|
|
258
|
+
authKey,
|
|
259
|
+
authKeyId,
|
|
260
|
+
operation,
|
|
261
|
+
bodyBytes,
|
|
262
|
+
...(approval === undefined ? {} : { approval }),
|
|
263
|
+
})
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
export type PostAuthorizedResourceOptions<T> = Readonly<{
|
|
267
|
+
transport: DaaTransport
|
|
268
|
+
operation: DeviceAuthorizationOperation
|
|
269
|
+
/** The exact bytes `authorization` was signed over. */
|
|
270
|
+
bodyBytes: Uint8Array
|
|
271
|
+
/** A compact JWS from {@link authorizeSignedPost}, sent unchanged. */
|
|
272
|
+
authorization: string
|
|
273
|
+
/** Every status that is a success for this operation, each decoded the same way. */
|
|
274
|
+
expectedStatuses: readonly number[]
|
|
275
|
+
decode: (value: unknown) => T
|
|
276
|
+
/**
|
|
277
|
+
* Endpoint-specific classification of an unexpected status, as on
|
|
278
|
+
* `postResource`. A non-`null` result is thrown; `null` leaves the response
|
|
279
|
+
* to the common signed-request mapping.
|
|
280
|
+
*/
|
|
281
|
+
failure?: (response: DaaHttpResponse) => DaaError | null
|
|
282
|
+
}>
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* Send a POST with an authorization signed earlier, unchanged — the sending
|
|
286
|
+
* half of {@link postSignedResource}, and the one to call again on a retry.
|
|
287
|
+
*
|
|
288
|
+
* Nothing here signs, and nothing reads the authorization's `exp`: an exact
|
|
289
|
+
* replay of a request DAA already accepted is answered from its stored result
|
|
290
|
+
* whether or not the JWS has expired, and DAA, not the SDK, decides that.
|
|
291
|
+
* Failures map exactly as {@link postSignedResource}'s do.
|
|
292
|
+
*/
|
|
293
|
+
export async function postAuthorizedResource<T>({
|
|
294
|
+
transport,
|
|
295
|
+
operation,
|
|
296
|
+
bodyBytes,
|
|
297
|
+
authorization,
|
|
298
|
+
expectedStatuses,
|
|
299
|
+
decode,
|
|
300
|
+
failure,
|
|
301
|
+
}: PostAuthorizedResourceOptions<T>): Promise<T> {
|
|
302
|
+
const profile = deviceAuthorizationProfile(operation)
|
|
303
|
+
if (profile.method !== 'POST') {
|
|
304
|
+
throw contractViolation('postAuthorizedResource only sends POST registry operations')
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const response = await sendAuthorizedPost({
|
|
308
|
+
transport,
|
|
309
|
+
path: profile.canonicalPath,
|
|
310
|
+
bodyBytes,
|
|
311
|
+
authorization,
|
|
312
|
+
})
|
|
313
|
+
|
|
314
|
+
if (!expectedStatuses.includes(response.status)) {
|
|
315
|
+
throw failure?.(response) ?? mapSignedRequestFailure(response, bodyBytes, authorization)
|
|
316
|
+
}
|
|
317
|
+
return decodeResourceResponse({ response, expectedStatus: response.status, decode })
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
function mapSignedRequestFailure(
|
|
321
|
+
response: DaaHttpResponse,
|
|
322
|
+
bodyBytes: Uint8Array,
|
|
323
|
+
authorization: string,
|
|
324
|
+
): DaaError {
|
|
325
|
+
const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id')
|
|
326
|
+
const daaStatusCode = readDaaStatusCode(response.bodyBytes)
|
|
327
|
+
const fallback = (): DaaError =>
|
|
328
|
+
apiFailure({
|
|
329
|
+
httpStatus: response.status,
|
|
330
|
+
daaStatusCode,
|
|
331
|
+
correlationId,
|
|
332
|
+
})
|
|
333
|
+
if (isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) {
|
|
334
|
+
// Gated on both the status code and the HTTP status, so a body that
|
|
335
|
+
// carries this code on some other status falls through to the generic
|
|
336
|
+
// `api` failure below rather than being trusted. The contract puts this
|
|
337
|
+
// code at `409`, which is where DAA's transfer and withdrawal
|
|
338
|
+
// create routes send it. Non-custodial account create never sends it (a
|
|
339
|
+
// reused key returns the original account). Recovered from the signed
|
|
340
|
+
// request's own bytes, not the response — `idempotencyKeyFromExactBody`
|
|
341
|
+
// returns `undefined` for a bodyless request (`getSignedResource`), so this
|
|
342
|
+
// never fires for `get_device_context`.
|
|
343
|
+
const idempotencyKey =
|
|
344
|
+
response.status === 409 ? idempotencyKeyFromExactBody(bodyBytes) : undefined
|
|
345
|
+
return idempotencyKey !== undefined
|
|
346
|
+
? idempotencyConflict(idempotencyKey, correlationId)
|
|
347
|
+
: fallback()
|
|
348
|
+
}
|
|
349
|
+
if (
|
|
350
|
+
isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REPLAYED') ||
|
|
351
|
+
isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REQUEST_MISMATCH')
|
|
352
|
+
) {
|
|
353
|
+
return contractViolation(
|
|
354
|
+
'the device authorization was replayed or did not match the request',
|
|
355
|
+
correlationId,
|
|
356
|
+
)
|
|
357
|
+
}
|
|
358
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_PENDING')) {
|
|
359
|
+
// The key can't sign yet: approved and in its cool-down, or still
|
|
360
|
+
// waiting for approval. Not a credential problem, so not
|
|
361
|
+
// `contract_violation`. Gated on `409`, where every DAA route sends it,
|
|
362
|
+
// like `IDEMPOTENCY_KEY_REUSED` above.
|
|
363
|
+
return response.status === 409 ? devicePending(correlationId) : fallback()
|
|
364
|
+
}
|
|
365
|
+
if (isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_INVALID')) {
|
|
366
|
+
// DAA's freshness check reports this code (as a `400`), so only this code
|
|
367
|
+
// is refined; a replayed or mismatched authorization is never a clock
|
|
368
|
+
// problem, and a `401` from something other than DAA carries no DAA code.
|
|
369
|
+
return isClockSkewed(response, authorization)
|
|
370
|
+
? clockSkew(correlationId)
|
|
371
|
+
: contractViolation('the device authorization was rejected', correlationId)
|
|
372
|
+
}
|
|
373
|
+
return fallback()
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
/**
|
|
377
|
+
* DAA's freshness rule for a device authorization
|
|
378
|
+
* (`OwnerAuthorizationPrevalidator.validateFreshness`): it is refused when
|
|
379
|
+
* `iat > now + 60` or `exp < now - 60`, in whole epoch seconds.
|
|
380
|
+
*/
|
|
381
|
+
const FRESHNESS_SKEW_SECONDS = 60
|
|
382
|
+
|
|
383
|
+
/**
|
|
384
|
+
* Slack for the time between DAA reading its clock and stamping the response
|
|
385
|
+
* `Date`. Only the `exp` side needs it: `Date` is never earlier than the check,
|
|
386
|
+
* so `iat > Date + 60` already proves `iat > now + 60`.
|
|
387
|
+
*/
|
|
388
|
+
const RESPONSE_DATE_SLACK_SECONDS = 5
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Whether DAA refused this authorization because the device clock is wrong,
|
|
392
|
+
* judged from the authorization's own `iat`/`exp` against the response's HTTP
|
|
393
|
+
* `Date`, with DAA's own rule.
|
|
394
|
+
*
|
|
395
|
+
* - `iat` more than 60 s after `Date`: the device clock was ahead when it
|
|
396
|
+
* signed. Compared with the signed `iat`, not `Date.now()`, so neither the
|
|
397
|
+
* whole-second `Date` nor response transit time can push a clock that is
|
|
398
|
+
* within tolerance over the line.
|
|
399
|
+
* - `exp` more than 60 s before `Date`: the authorization had expired, and the
|
|
400
|
+
* device clock now reads more than `exp - iat + 60` seconds (360 s) behind
|
|
401
|
+
* the service — far enough that an authorization signed now would be
|
|
402
|
+
* refused too. A device less far behind passes DAA's rule, so an expiry
|
|
403
|
+
* there is the authorization's age, not the clock: that matters for
|
|
404
|
+
* `contractExecutions.submit`, whose authorization was signed at `prepare`
|
|
405
|
+
* and may simply have aged out, whatever the clock did since.
|
|
406
|
+
*
|
|
407
|
+
* `Date` is unsigned and the transport is the consumer's, so this only chooses
|
|
408
|
+
* between two classifications of a response that has already failed. A
|
|
409
|
+
* missing or unreadable `Date` or claim is not skew.
|
|
410
|
+
*/
|
|
411
|
+
function isClockSkewed(response: DaaHttpResponse, authorization: string): boolean {
|
|
412
|
+
const serverMillis = httpDateMillis(headerValueIgnoringCase(response.headers, 'Date'))
|
|
413
|
+
const claims = jwsSegmentJson(authorization, 1)
|
|
414
|
+
const iat = claims?.['iat']
|
|
415
|
+
const exp = claims?.['exp']
|
|
416
|
+
if (serverMillis === null || typeof iat !== 'number' || typeof exp !== 'number') {
|
|
417
|
+
return false
|
|
418
|
+
}
|
|
419
|
+
const serverSeconds = serverMillis / 1000
|
|
420
|
+
if (iat > serverSeconds + FRESHNESS_SKEW_SECONDS) {
|
|
421
|
+
return true
|
|
422
|
+
}
|
|
423
|
+
return (
|
|
424
|
+
exp < serverSeconds - FRESHNESS_SKEW_SECONDS - RESPONSE_DATE_SLACK_SECONDS &&
|
|
425
|
+
serverMillis - Date.now() > (exp - iat + FRESHNESS_SKEW_SECONDS) * 1000
|
|
426
|
+
)
|
|
427
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
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 ephemeral registration-flow key.
|
|
20
|
+
//
|
|
21
|
+
// ============================================================================
|
|
22
|
+
// THIS IS NOT AN AuthKey. Do not treat it as one, and do not route it through
|
|
23
|
+
// `SecureKeyStore`.
|
|
24
|
+
// ============================================================================
|
|
25
|
+
//
|
|
26
|
+
// The login contract uses two different P-256 keys, and confusing
|
|
27
|
+
// them is the failure this file's naming exists to prevent:
|
|
28
|
+
//
|
|
29
|
+
// | | AuthKey (`OwnerAuthKey`, `securekey/`) | registration-flow key (this file) |
|
|
30
|
+
// | --- | --- | --- |
|
|
31
|
+
// | Lifetime | durable, survives the app | **one login attempt** |
|
|
32
|
+
// | Scope | `{environment, customer application, Owner (clientEntityId), installation}` | nothing; it is anonymous |
|
|
33
|
+
// | Storage | Secure Enclave / Android Keystore, via `SecureKeyStore` | process memory only |
|
|
34
|
+
// | Exported at | Device Registration Complete (`deviceKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) |
|
|
35
|
+
// | Selected | only *after* the Social Session response | before Prepare |
|
|
36
|
+
// | Authorizes | DAA operations, via `X-Device-Authorization` | nothing |
|
|
37
|
+
//
|
|
38
|
+
// The contract says the same thing in one line on
|
|
39
|
+
// `PrepareSocialLoginRequest.registrationFlowPublicKey`: "Unpadded Base64URL DER
|
|
40
|
+
// SubjectPublicKeyInfo for an ephemeral P-256 flow key; **it is not an AuthKey**".
|
|
41
|
+
//
|
|
42
|
+
// Its whole job is to prove, at Device Registration Complete, that the caller
|
|
43
|
+
// completing the registration is the caller that prepared it — the flow-key JWS
|
|
44
|
+
// is one of the two fresh proofs over the exact Complete request bytes. Because
|
|
45
|
+
// it is per-attempt and anonymous, it deliberately does NOT go into the
|
|
46
|
+
// enclave: a key in the Secure Enclave is a key that outlives the attempt and
|
|
47
|
+
// acquires a namespace, which is exactly what this one must not have.
|
|
48
|
+
//
|
|
49
|
+
// Signing is a **typed Complete-only helper**, not a public `sign(bytes)`. The
|
|
50
|
+
// member is `signExactBytes` of the JWS signing input for
|
|
51
|
+
// `X-Registration-Flow-Authorization`. It is not exported from `index.ts`.
|
|
52
|
+
// Both the native Expo bridge (`DaaRegistrationFlowKey.signRegistrationAuthorization`
|
|
53
|
+
// on iOS and Android) and the WebCrypto test stand-in sign for real, so Device
|
|
54
|
+
// Registration Complete can finish on a physical device.
|
|
55
|
+
|
|
56
|
+
import { fromBase64Url, toBase64Url } from '../crypto/base64url'
|
|
57
|
+
import { toArrayBuffer } from '../crypto/bytes'
|
|
58
|
+
import { contractViolation } from '../errors'
|
|
59
|
+
import {
|
|
60
|
+
nativeGenerateRegistrationFlowKey,
|
|
61
|
+
nativeRegistrationFlowPublicKeySpkiBase64Url,
|
|
62
|
+
nativeReleaseRegistrationFlowKey,
|
|
63
|
+
nativeSignRegistrationAuthorization,
|
|
64
|
+
requireDaaRegistrationNative,
|
|
65
|
+
type DaaRegistrationNativeModule,
|
|
66
|
+
} from './daaRegistrationNative'
|
|
67
|
+
|
|
68
|
+
/** Byte length of a P-256 SubjectPublicKeyInfo. */
|
|
69
|
+
const P256_SPKI_BYTE_LENGTH = 91
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* One attempt's registration-flow key. Not an AuthKey; see the file header.
|
|
73
|
+
*
|
|
74
|
+
* The interface carries the public-key export for Prepare, the Complete-only
|
|
75
|
+
* signing helper, and an explicit release: the native implementations hold the
|
|
76
|
+
* private key in a process-lifetime cache, so something has to say when it is
|
|
77
|
+
* no longer needed.
|
|
78
|
+
*/
|
|
79
|
+
export interface RegistrationFlowKey {
|
|
80
|
+
/**
|
|
81
|
+
* Unpadded Base64URL DER SubjectPublicKeyInfo of the public key, the exact
|
|
82
|
+
* form `PrepareSocialLoginRequest.registrationFlowPublicKey` wants.
|
|
83
|
+
*/
|
|
84
|
+
publicKeySpkiBase64Url(): Promise<string>
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* ES256 signature (JOSE `R || S`, 64 bytes) over the exact Device Registration
|
|
88
|
+
* Complete flow-JWS signing input. Not a public generic sign API.
|
|
89
|
+
*/
|
|
90
|
+
signExactBytes(message: Uint8Array): Promise<Uint8Array>
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Discard the key, so a native implementation stops holding its private half.
|
|
94
|
+
*
|
|
95
|
+
* Safe to call more than once and safe to call on a key that was never used.
|
|
96
|
+
* The key is dead afterwards: `publicKeySpkiBase64Url()` on a released native
|
|
97
|
+
* key fails closed rather than returning a stale value.
|
|
98
|
+
*
|
|
99
|
+
* Device Registration Complete is the owner of this call: it signs, then
|
|
100
|
+
* releases. `PreparedSocialLogin.abandon()` is the other caller when the user
|
|
101
|
+
* backs out of provider login. `PendingDeviceRegistration` has no
|
|
102
|
+
* `abandon()`: after Session, the key is held until Complete or until the
|
|
103
|
+
* process exits.
|
|
104
|
+
*/
|
|
105
|
+
release(): Promise<void>
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Source of per-attempt registration-flow keys.
|
|
110
|
+
*
|
|
111
|
+
* A seam so `AuthClient` can switch providers without changing callers.
|
|
112
|
+
* Production generation is `DaaRegistrationFlowKey` in `daa-ios-sdk` /
|
|
113
|
+
* `daa-android-sdk` — not `DaaSecureKey`, which is the Owner AuthKey. The Expo
|
|
114
|
+
* `DaaRegistration` module bridges that type and keeps the private key in
|
|
115
|
+
* native memory. WebCrypto is an explicit test stand-in
|
|
116
|
+
* (`webCryptoRegistrationFlowKeyProvider`), never a fallback. A host missing
|
|
117
|
+
* the Expo module fails closed. The seam is not exported from `index.ts`: a
|
|
118
|
+
* consumer cannot substitute the key that proves its own registration handoff.
|
|
119
|
+
*/
|
|
120
|
+
export interface RegistrationFlowKeyProvider {
|
|
121
|
+
generate(): Promise<RegistrationFlowKey>
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
class WebCryptoRegistrationFlowKey implements RegistrationFlowKey {
|
|
125
|
+
readonly #keyPair: CryptoKeyPair
|
|
126
|
+
|
|
127
|
+
constructor(keyPair: CryptoKeyPair) {
|
|
128
|
+
this.#keyPair = keyPair
|
|
129
|
+
Object.freeze(this)
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
// Nothing to free: the CryptoKey is ordinary garbage once the handle is
|
|
133
|
+
// dropped, and WebCrypto exposes no destroy. Present so the two providers
|
|
134
|
+
// satisfy one interface.
|
|
135
|
+
async release(): Promise<void> {}
|
|
136
|
+
|
|
137
|
+
async publicKeySpkiBase64Url(): Promise<string> {
|
|
138
|
+
const spki = await subtle().exportKey('spki', this.#keyPair.publicKey)
|
|
139
|
+
const bytes = new Uint8Array(spki)
|
|
140
|
+
if (bytes.length !== P256_SPKI_BYTE_LENGTH) {
|
|
141
|
+
throw contractViolation(
|
|
142
|
+
'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo',
|
|
143
|
+
)
|
|
144
|
+
}
|
|
145
|
+
return toBase64Url(bytes)
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
async signExactBytes(message: Uint8Array): Promise<Uint8Array> {
|
|
149
|
+
const signature = await subtle().sign(
|
|
150
|
+
{ name: 'ECDSA', hash: 'SHA-256' },
|
|
151
|
+
this.#keyPair.privateKey,
|
|
152
|
+
toArrayBuffer(message),
|
|
153
|
+
)
|
|
154
|
+
return new Uint8Array(signature)
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
class NativeRegistrationFlowKey implements RegistrationFlowKey {
|
|
159
|
+
readonly #native: DaaRegistrationNativeModule
|
|
160
|
+
readonly #id: string
|
|
161
|
+
|
|
162
|
+
constructor(native: DaaRegistrationNativeModule, id: string) {
|
|
163
|
+
this.#native = native
|
|
164
|
+
this.#id = id
|
|
165
|
+
Object.freeze(this)
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
async publicKeySpkiBase64Url(): Promise<string> {
|
|
169
|
+
const spki = nativeRegistrationFlowPublicKeySpkiBase64Url(this.#native, this.#id)
|
|
170
|
+
const bytes = decodeSpki(spki)
|
|
171
|
+
return toBase64Url(bytes)
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
async release(): Promise<void> {
|
|
175
|
+
nativeReleaseRegistrationFlowKey(this.#native, this.#id)
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
async signExactBytes(message: Uint8Array): Promise<Uint8Array> {
|
|
179
|
+
// The Expo module holds the private key; only the exact bytes and the
|
|
180
|
+
// resulting signature cross the bridge as Base64URL strings.
|
|
181
|
+
const signingInputBase64Url = toBase64Url(message)
|
|
182
|
+
return nativeSignRegistrationAuthorization(this.#native, this.#id, signingInputBase64Url)
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Production React Native provider: native `DaaRegistrationFlowKey` via the
|
|
188
|
+
* Expo `DaaRegistration` module. The private key never crosses the bridge.
|
|
189
|
+
*/
|
|
190
|
+
export function nativeRegistrationFlowKeyProvider(
|
|
191
|
+
native: DaaRegistrationNativeModule,
|
|
192
|
+
): RegistrationFlowKeyProvider {
|
|
193
|
+
return {
|
|
194
|
+
async generate(): Promise<RegistrationFlowKey> {
|
|
195
|
+
const id = nativeGenerateRegistrationFlowKey(native)
|
|
196
|
+
return new NativeRegistrationFlowKey(native, id)
|
|
197
|
+
},
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Node/Jest stand-in: a non-extractable WebCrypto P-256 keypair per attempt.
|
|
203
|
+
*
|
|
204
|
+
* `extractable: false` is set even though the key never leaves the process. It
|
|
205
|
+
* costs nothing, and it means a future bug that hands the handle somewhere else
|
|
206
|
+
* still cannot export the private key.
|
|
207
|
+
*
|
|
208
|
+
* **Not the production RN path.** Production `defaultRegistrationFlowKeyProvider`
|
|
209
|
+
* never calls this. Absent `crypto.subtle`, `generate()` fails closed with
|
|
210
|
+
* `contract_violation` rather than weaker key generation.
|
|
211
|
+
*/
|
|
212
|
+
export function webCryptoRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider {
|
|
213
|
+
return {
|
|
214
|
+
async generate(): Promise<RegistrationFlowKey> {
|
|
215
|
+
const keyPair = (await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [
|
|
216
|
+
'sign',
|
|
217
|
+
'verify',
|
|
218
|
+
])) as CryptoKeyPair
|
|
219
|
+
return new WebCryptoRegistrationFlowKey(keyPair)
|
|
220
|
+
},
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Native `DaaRegistrationFlowKey` via the Expo module. A missing module is a
|
|
226
|
+
* `contract_violation` — WebCrypto is never a fallback. The native module is
|
|
227
|
+
* resolved on `generate()`, not when this provider is constructed, so building
|
|
228
|
+
* a `DaaClient` does not require the Expo module to be linked.
|
|
229
|
+
*/
|
|
230
|
+
export function defaultRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider {
|
|
231
|
+
return {
|
|
232
|
+
async generate(): Promise<RegistrationFlowKey> {
|
|
233
|
+
return nativeRegistrationFlowKeyProvider(requireDaaRegistrationNative()).generate()
|
|
234
|
+
},
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
/** Drop the key without replacing the failure that triggered cleanup. */
|
|
239
|
+
export async function releaseQuietly(key: RegistrationFlowKey): Promise<void> {
|
|
240
|
+
try {
|
|
241
|
+
await key.release()
|
|
242
|
+
} catch {
|
|
243
|
+
// Intentionally empty: a throwing release must not mask the originating error.
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function decodeSpki(spki: string): Uint8Array {
|
|
248
|
+
let bytes: Uint8Array
|
|
249
|
+
try {
|
|
250
|
+
bytes = fromBase64Url(spki)
|
|
251
|
+
} catch {
|
|
252
|
+
throw contractViolation(
|
|
253
|
+
'registration-flow key did not export valid Base64URL SubjectPublicKeyInfo',
|
|
254
|
+
)
|
|
255
|
+
}
|
|
256
|
+
if (bytes.length !== P256_SPKI_BYTE_LENGTH) {
|
|
257
|
+
throw contractViolation(
|
|
258
|
+
'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo',
|
|
259
|
+
)
|
|
260
|
+
}
|
|
261
|
+
return bytes
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
function subtle(): SubtleCrypto {
|
|
265
|
+
const host = (globalThis as { crypto?: Crypto }).crypto
|
|
266
|
+
if (host === undefined || host.subtle === undefined) {
|
|
267
|
+
throw contractViolation(
|
|
268
|
+
'crypto.subtle is required to generate the ephemeral registration-flow key; ' +
|
|
269
|
+
'install a WebCrypto polyfill in the host app or supply a native ' +
|
|
270
|
+
'DaaRegistrationFlowKey provider',
|
|
271
|
+
)
|
|
272
|
+
}
|
|
273
|
+
return host.subtle
|
|
274
|
+
}
|