diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..11789f5 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,6 @@ +# Byte-pinned cross-platform conformance artifact. Its SHA-256 is asserted by +# the fixture loader, so EOL normalization on checkout (Git for Windows installs +# with core.autocrlf=true by default) would rewrite every line ending and fail +# the digest guard — with advice to re-copy the file, which cannot help because +# re-copying reproduces the same normalized bytes. +src/__test__/fixtures/AuthKeyWireV1.json -text diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..dd1f730 --- /dev/null +++ b/.gitignore @@ -0,0 +1,30 @@ +# Dependencies +node_modules/ + +# Build output +build/ +*.tsbuildinfo + +# Packed SDK tarball (produced by `npm pack` in CI) +*.tgz + +# Test / coverage +coverage/ + +# Native build artifacts +ios/Pods/ +ios/build/ +android/build/ +android/.gradle/ +*.xcworkspace/xcuserdata/ + +# Logs & OS +*.log +.DS_Store + +# Editor +.idea/ +*.swp + +# Agent tooling +.claude/ diff --git a/.nvmrc b/.nvmrc new file mode 100644 index 0000000..2bd5a0a --- /dev/null +++ b/.nvmrc @@ -0,0 +1 @@ +22 diff --git a/.prettierignore b/.prettierignore new file mode 100644 index 0000000..598565a --- /dev/null +++ b/.prettierignore @@ -0,0 +1,22 @@ +build/ +coverage/ +node_modules/ +yarn.lock + +# Vendored byte-for-byte from daa-ios-sdk; reformatting it breaks the pinned +# SHA-256 that makes it a cross-platform conformance artifact. +src/__test__/fixtures/AuthKeyWireV1.json + +# `expo prebuild` output in the native compile harness. Generated, gitignored, +# and thousands of files of upstream React Native / CocoaPods scaffolding — +# formatting it is both meaningless and slow. The harness sources one level up +# (example/*.js, example/plugins/**) are NOT ignored and are formatted normally. +example/android/ +example/ios/ +example/.expo/ +example/yarn.lock + +# Generated by release-please on every release; it does not emit +# Prettier-formatted Markdown, so `format:check` fails on the release PR and +# the release cannot merge. release-please owns this file — leave it alone. +CHANGELOG.md diff --git a/.prettierrc b/.prettierrc new file mode 100644 index 0000000..fa5ca3f --- /dev/null +++ b/.prettierrc @@ -0,0 +1,7 @@ +{ + "singleQuote": true, + "trailingComma": "all", + "printWidth": 100, + "semi": false, + "endOfLine": "lf" +} diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md new file mode 100644 index 0000000..a139ea8 --- /dev/null +++ b/CONTRIBUTING.md @@ -0,0 +1,24 @@ +# Contributing to daa-react-native-sdk + +Thank you for your interest in contributing to this project! + +## How to Contribute + +All contributions to this project are made subject to the terms of the +[Apache License 2.0](LICENSE). By submitting a contribution, you agree that +your contribution is licensed under those terms. + +## Reporting Issues + +Please open a GitHub issue for bug reports, feature requests, or questions. + +## Security Vulnerabilities + +Please do **not** file public GitHub issues for security vulnerabilities. +Report them privately through Circle's +[Vulnerability Disclosure Program](https://hackerone.com/circle-bbp). +See [SECURITY.md](SECURITY.md) for the full policy. + +## Code of Conduct + +Please be respectful and constructive in all interactions. diff --git a/COPYRIGHT b/COPYRIGHT new file mode 100644 index 0000000..e2000da --- /dev/null +++ b/COPYRIGHT @@ -0,0 +1,15 @@ +Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + +SPDX-License-Identifier: Apache-2.0 + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/DaaReactNativeSdk.podspec b/DaaReactNativeSdk.podspec new file mode 100644 index 0000000..e80581c --- /dev/null +++ b/DaaReactNativeSdk.podspec @@ -0,0 +1,63 @@ +# Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +# +# SPDX-License-Identifier: Apache-2.0 +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +require 'json' + +package = JSON.parse(File.read(File.join(__dir__, 'package.json'))) + +Pod::Spec.new do |s| + s.name = 'DaaReactNativeSdk' + s.version = package['version'] + s.summary = package['description'] + s.description = package['description'] + s.license = package['license'] + s.author = package['author'] + s.homepage = package['homepage'] + s.platforms = { :ios => '15.0' } + s.swift_version = '5.9' + s.source = { :git => 'https://github.com/circlefin/daa-react-native-sdk.git', :tag => "v#{s.version}" } + s.static_framework = true + + s.dependency 'ExpoModulesCore' + + # Expo module sources only. DaaSdk is the native iOS SDK (daa-ios-sdk), + # consumed as a published CocoaPods dependency rather than vendored at pack + # time. Integrators add the daa-ios-sdk spec-source repo to their Podfile + # `source` — see README.md. + # Pin the native SDK so dependency resolution is reproducible and updates are + # deliberate. 0.7.1 provides the APIs and behaviour this module relies on: + # it sets all of the Face ID / Touch ID prompt text itself from the validated + # operation, so signDeviceAuthorization and signRegistrationDeviceAuthorization + # take no caller prompt and DaaSecureKeyModule.swift passes none; it defaults + # the AuthKey Keychain group to the app's own application-identifier group + # (this module passes no keychainAccessGroup) and fails closed if that group + # cannot be resolved; its registration signer accepts the minimal + # device-proof claim set this package sends; it has the native SCA ceremony + # (`DaaSca`), which DaaScaModule.swift bridges and which also needs + # AuthenticationServices below; and it has DaaPrepareReceiptSignature, + # DaaSecureRandom, DaaRegistrationFlowKey, and + # DaaRegistrationFlowKeyError.invalidSigningInput, which + # DaaRegistrationModule.swift and DaaRegistrationExceptions.swift use. + s.source_files = 'ios/*.{h,m,mm,swift}' + s.dependency 'DaaSdk', '0.7.1' + s.frameworks = 'Security', 'LocalAuthentication', 'CryptoKit', 'AuthenticationServices' + + s.pod_target_xcconfig = { + 'DEFINES_MODULE' => 'YES', + 'SWIFT_COMPILATION_MODE' => 'wholemodule', + 'OTHER_SWIFT_FLAGS' => '$(inherited) -enable-upcoming-feature StrictConcurrency' + } +end diff --git a/LICENSE b/LICENSE new file mode 100644 index 0000000..d9a10c0 --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS diff --git a/README.md b/README.md index 5479f8e..eda86da 100644 --- a/README.md +++ b/README.md @@ -1 +1,218 @@ -# daa-react-native-sdk \ No newline at end of file +# @circle-fin/daa-react-native-sdk + +React Native SDK for **Digital Asset Accounts (DAA)** — attested authentication +and self-custody DAA API access. + +Login is a three-call ceremony — Prepare, Social Session, Device Registration +Complete. Tests can finish the ceremony with `./testing`. + +## Features + +- `DaaClient` + `DaaSdkConfiguration`, including the closed `keyPolicy` + (`DEVICE_KEY_POLICY`: hardware-backed, per-signature user verification). +- Injected `DaaTransport` boundary (`DaaHttpRequest` / `DaaHttpResponse`) — the + SDK never embeds a service credential. +- Deterministic **exact-byte** body serialization (serialize once, sign/send the + same immutable bytes). +- **Registered-device authorization**: compact ES256 JWS in + `X-Device-Authorization` (`authorizeExactRequest` / `postSignedResource`). + Not on the public `.` entry. Tests use the `./testing` in-memory store; + production `signExactBytes` reaches Expo `signDeviceAuthorization`. Account, + transfer, and withdrawal `create` are wired through it. +- The DAA **Owner-key** interfaces (P-256 / ES256) on the public entry. No + generic signing API. The concrete WebCrypto-backed in-memory **test double** + is exported only from the `./testing` subpath and fails closed in a React + Native release bundle. +- `DaaSdkError` model. +- Typed reads for accounts, account limits/usage, deposit addresses, deposits, + transfers, withdrawals, and wire/ACH fiat accounts (plus their receiving + instructions) behind `DaaUserClient`, plus unsigned deposit-address + create-or-resolve and the Owner-authorized `accounts.create` / + `transfers.create` / `withdrawals.create`. + All three signed creates take their request shape from the Owner-authorization + registry, reject a property it does not name before anything is signed, and + fail closed until the AuthKey carries Circle's registration acknowledgement. + Account, deposit-address, deposit, transfer, and withdrawal listings return + trusted pages: navigation accepts only same-origin links for the originating + collection and preserves the API's opaque query exactly. + `accountLimits.get(accountId, query?)` reads + `GET /v1/accounts/{accountId}/limits/usage`; the public API reference + ([list-account-limits-usage](https://developers.circle.com/api-reference/digital-asset-accounts/all/list-account-limits-usage)) + is its contract. `usd_cents` and `count` values are returned + unconverted: + + ```ts + const usage = await daaUserClient.accountLimits.get('1000662322', { + operation: 'withdrawal', + window: 'P30D', + }) + for (const item of usage.items) { + console.log(item.operation.kind, item.effectiveThreshold, item.usagePercent) + } + ``` + + Response models are exported as **types only**: every instance a caller holds + came from a response the SDK decoded. Reached through `DaaClient.forUser(context)`, + which opens only for an `ACTIVE` `DaaUserContext` from Device Registration + Complete. + +- `DaaUserClient.refreshContext()` and `.close()` — the lifecycle methods. + `refreshContext` is a signed `get_device_context` read + (`GET /v1/accounts/auth/context`), not an unsigned one: it carries a fresh + `X-Device-Authorization` over the empty body byte array and decodes the same + `DeviceContext` shape Device Registration Complete returns. This SDK holds + no retained context object and no cancellable in-flight work, so `close()` + refuses all further work through this instance: `refreshContext`, + every signed `create` on `accounts` / `transfers` / `withdrawals`, every + unsigned read, the unsigned `depositAddresses.create`, and `next()` / + `previous()` on a previously returned `Page` fail closed with + `contract_violation` afterward. A request already sent completes. The + registered AuthKey itself is untouched. +- `AuthClient.prepareSocialLogin` — the Prepare call. Mints a registration code + verifier and an ephemeral P-256 registration-flow key, then + `POST /v1/accounts/auth/loginRequests` with the S256 challenge and the flow + public key. It touches **no AuthKey**: AuthKey selection comes after the + Social Session response, so nothing at Prepare reads the secure-key store. + Returns a `PreparedSocialLogin` (`loginRequestId`, `oidcNonce`, `oidcState`, + `prepareReceiptJws`, `expiresAt`). No Prepare-receipt trust anchor is pinned + in this release, so the SDK ignores any receipt the service sends and login + proceeds as if none arrived (`prepareReceiptJws` is null). `oidcNonce` and + `oidcState` are therefore not authenticated by the SDK, and the receipt never + signs `oidcState`: bind the provider redirect with your app's own OAuth + `state`, and carry `oidcState` inside or next to it. `completeSocialSession` posts + `POST /v1/accounts/auth/sessions` and selects the AuthKey only after that + response. It takes the provider `idToken` **and** the `clientEntityId` of an + end user the application's own backend has already onboarded: the service + requires that field and Circle never creates the entity, so an application + onboards first and passes the id here. + `PendingDeviceRegistration.complete` sends Device Registration + Complete with `X-Registration-Flow-Authorization` and + `X-Device-Authorization` over the exact four-field body. + +Prepare mints the verifier and flow key through the Expo `DaaRegistration` +module (`DaaSecureRandom` / `DaaRegistrationFlowKey` in the native SDKs), not +through `DaaSecureKey` and not through host WebCrypto. The same module checks +the receipt signature by delegating to the native SDKs' +`DaaPrepareReceiptSignature`. A React Native host missing that module fails +closed with `contract_violation` when minting, and a receipt it cannot verify +for want of the module is `prepare_receipt_invalid`. +Node tests inject a fake in `jest.setup.js`. + +The Expo `DaaSecureKey` module (`ios/`, `android/`, `expo-module.config.json`) +delegates Owner AuthKey operations to the native SDKs, and +`resolveNativeBridge()` loads it via `requireOptionalNativeModule` — failing +closed in Node and Jest where no native module exists. +`X-Device-Authorization` is minted in TypeScript (`authorizeExactRequest`); +production `signExactBytes` reaches Expo `signDeviceAuthorization`. + +## Installing + +``` +yarn add @circle-fin/daa-react-native-sdk +``` + +### The native SDKs are separate artifacts + +This package bridges to two native SDKs published as coordinates rather than +vendoring them. The +tarball ships `DaaReactNativeSdk.podspec` and `android/build.gradle`, which only +_declare_ the native dependencies — installing from npm does not fetch them. The +host app's own CocoaPods and Gradle resolve them at build time. + +**iOS.** `daa-ios-sdk` is a CocoaPods spec source, not published to the public +trunk. Add it alongside the CDN in your `Podfile`, then `pod install`: + +```ruby +source 'https://github.com/circlefin/daa-ios-sdk.git' +source 'https://cdn.cocoapods.org/' +``` + +**Android.** `com.circle.daa:daa-android-sdk` is published to GitHub Packages, +which needs a GitHub token even for public packages. Add a `maven {}` block to +your app's root `build.gradle`, sourced from the environment so nothing is +committed: + +```gradle +allprojects { + repositories { + // ...your existing repositories + maven { + url System.getenv('DAA_ANDROID_MAVEN_URL') + credentials { + username System.getenv('DAA_ANDROID_MAVEN_USERNAME') + password System.getenv('DAA_ANDROID_MAVEN_PASSWORD') + } + } + } +} +``` + +| Variable | Value | +| ---------------------------- | -------------------------------------------------------- | +| `DAA_ANDROID_MAVEN_URL` | `https://maven.pkg.github.com/circlefin/daa-android-sdk` | +| `DAA_ANDROID_MAVEN_USERNAME` | your GitHub username | +| `DAA_ANDROID_MAVEN_PASSWORD` | a GitHub PAT with `read:packages` scope | + +### Upgrading to `DaaSdk` 0.5.1 and `daa-android-sdk` 0.5.0 + +- **The biometric prompt text belongs to the native SDKs.** Face ID, Touch ID + and the Android BiometricPrompt show text that the native SDK sets from the + operation being signed, for example `Authorizing: transfer`. The text is + English only. Your app cannot set or change it. +- **iOS apps that share Keychain items may lose their AuthKey.** The AuthKey now + lives in your app's own application-identifier Keychain group + (`.`). Before, it lived in the first group + of your `keychain-access-groups` entitlement. If you use Keychain Sharing and + a shared group is first in that list, the SDK does not find the AuthKey that + an earlier version created. `resolveOrCreate` returns `"created"`, and the + device must register again. Apps without Keychain Sharing, and apps that list + their own group first, are not affected. +- **iOS fails closed when the AuthKey Keychain group cannot be resolved.** If + the SDK cannot resolve your app's own group, for example in a background + launch before the first unlock after boot, the call throws instead of running + an unscoped Keychain query. Nothing is cached, so a later call tries again. +- **Android needs an Auth Tab browser for a custom-scheme enrollment + redirect.** A custom-scheme `redirectUri` for `enroll` now runs only in an + Auth Tab. On a device with no allowed browser that offers one, `enroll` + rejects with a `ScaError` whose `code` is `Unsupported` and whose `reason` is + `InsecureRedirect`, and nothing opens. An `https` App Link is not affected, + and `approve` already refuses a custom scheme. + +## Layout + +``` +src/ + index.ts Public surface — `.` (types + client + serialization) + testing.ts `./testing` subpath — in-memory secure-key test double + DaaClient.ts Root client + configuration + api/ AuthClient, DaaUserClient + typed resource clients + auth/ Login-attempt material (registration-flow key, verifier, receipt) + models/ Typed account, page, address, deposit, transfer, withdrawal, fiat-account (wire/ACH), money, and prepared-login models + wire/ Response decoding: `data` envelope, payload mapping + transport/ Injected transport boundary + crypto/ Exact-byte serialization, Base64URL, SHA-256, JWK thumbprint, native-backed CSPRNG + securekey/ DAA Owner-key interfaces + in-memory & native-bridge stores + errors.ts DaaSdkError model + DaaError +DaaReactNativeSdk.podspec Declares the DaaSdk CocoaPods dependency +android/build.gradle Declares the com.circle.daa:daa-android-sdk dependency +ios/ Expo DaaSecureKey + DaaRegistration Swift modules +android/src/ Expo DaaSecureKey + DaaRegistration Kotlin modules +expo-module.config.json Expo autolinking +``` + +## Develop + +```bash +yarn install +yarn test # unit tests (jest + ts-jest) +yarn check:type # tsc --noEmit +``` + +## References + +- Reporting a security vulnerability: [`SECURITY.md`](./SECURITY.md) +- Contributing: [`CONTRIBUTING.md`](./CONTRIBUTING.md) + +## License + +[Apache License 2.0](LICENSE) diff --git a/SECURITY.md b/SECURITY.md new file mode 100644 index 0000000..73a5672 --- /dev/null +++ b/SECURITY.md @@ -0,0 +1,8 @@ +# Security Policy + +## Reporting a Vulnerability + +Please do not file public issues on GitHub for security vulnerabilities. +All security vulnerabilities should be reported to Circle privately, through +Circle's [Vulnerability Disclosure Program](https://hackerone.com/circle-bbp). +Please read through the program policy before submitting a report. diff --git a/android/build.gradle b/android/build.gradle new file mode 100644 index 0000000..c2d0369 --- /dev/null +++ b/android/build.gradle @@ -0,0 +1,97 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +apply plugin: 'com.android.library' + +import groovy.json.JsonSlurper + +def getPackageJsonVersion() { + def packageJsonFile = file("${projectDir}/../package.json") + def packageJson = new JsonSlurper().parseText(packageJsonFile.text) + return packageJson.version +} + +group = 'com.circle.daa.reactnative' +version = getPackageJsonVersion() + +def expoModulesCorePlugin = new File(project(":expo-modules-core").projectDir.absolutePath, "ExpoModulesCorePlugin.gradle") +if (expoModulesCorePlugin.exists()) { + apply from: expoModulesCorePlugin + applyKotlinExpoModulesCorePlugin() + useCoreDependencies() + useExpoPublishing() +} + +def useManagedAndroidSdkVersions = false +if (useManagedAndroidSdkVersions) { + useDefaultAndroidSdkVersions() +} else { + buildscript { + ext.safeExtGet = { prop, fallback -> + rootProject.ext.has(prop) ? rootProject.ext.get(prop) : fallback + } + } + project.android { + compileSdkVersion safeExtGet("compileSdkVersion", 36) + defaultConfig { + minSdkVersion safeExtGet("minSdkVersion", 23) + targetSdkVersion safeExtGet("targetSdkVersion", 36) + } + } +} + +android { + namespace "com.circle.daa.reactnative" + defaultConfig { + versionCode 1 + versionName getPackageJsonVersion() + } + compileOptions { + sourceCompatibility JavaVersion.VERSION_17 + targetCompatibility JavaVersion.VERSION_17 + } + lintOptions { + abortOnError false + } +} + +// com.circle.daa:daa-android-sdk is a published Maven coordinate (GitHub +// Packages). This module declares no `repositories {}` block; the host +// application supplies the credentialed repository. See README.md for the +// Podfile-equivalent Gradle setup (DAA_ANDROID_MAVEN_URL / _USERNAME / +// _PASSWORD). + +dependencies { + // Pin the native SDK so dependency resolution is reproducible and updates + // are deliberate. 0.6.0 provides the APIs and behaviour this module relies + // on: it sets all of the BiometricPrompt text itself from the validated + // operation, so signDeviceAuthorization and + // signRegistrationDeviceAuthorization take the FragmentActivity directly + // and DaaSecureKeyModule.kt passes no prompt text; its registration signer + // accepts the minimal device-proof claim set this package sends; it has + // the native SCA ceremony (DaaScaApproveContract / DaaScaEnrollContract) + // with strict callback parsing, which DaaScaModule.kt bridges, and runs a + // custom-scheme enrollment redirect only in an Auth Tab (with no allowed + // Auth Tab browser the ceremony fails Unsupported(InsecureRedirect)); and + // it has DaaPrepareReceiptSignature, DaaSecureRandom, and + // DaaRegistrationFlowKey, which DaaRegistrationModule.kt calls. The SCA + // ceremony requires compileSdk 36 and AGP 8.9.1+ of every consumer + // (androidx.browser 1.9.0), hence the 36 defaults above. + api("com.circle.daa:daa-android-sdk:0.6.0") + // This module calls runBlocking. daa-android-sdk scopes coroutines as + // implementation, so it is not on this compile classpath transitively. + implementation("org.jetbrains.kotlinx:kotlinx-coroutines-android:1.10.2") +} diff --git a/android/src/main/AndroidManifest.xml b/android/src/main/AndroidManifest.xml new file mode 100644 index 0000000..94cbbcf --- /dev/null +++ b/android/src/main/AndroidManifest.xml @@ -0,0 +1 @@ + diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt b/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt new file mode 100644 index 0000000..2bdd17c --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationExceptions.kt @@ -0,0 +1,47 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import com.circle.daa.sdk.DaaRegistrationFlowKeyError +import com.circle.daa.sdk.DaaRegistrationFlowKeyException +import expo.modules.kotlin.exception.CodedException + +internal class RegistrationContractViolationException : + CodedException("CONTRACT_VIOLATION", "Native registration operation failed", null) + +// No DaaSecureRandomError branch here, unlike the Swift mapper. That is a real +// platform divergence, not an omission: `SecRandomCopyBytes` returns a failable +// OSStatus, so daa-ios-sdk needs a DaaSecureRandomError type, while Kotlin's +// `SecureRandom.nextBytes` cannot fail and daa-android-sdk therefore declares no +// such type — there is nothing to match on. An invalid byte count arrives as +// IllegalArgumentException and is caught by the fallthrough below, which maps it +// to the same CONTRACT_VIOLATION the Swift side would produce. The JS-visible +// behaviour is identical; only the shape of the mapper differs. +internal fun mappedRegistrationException(error: Throwable): CodedException { + if (error is CodedException) { + return error + } + if (error is DaaRegistrationFlowKeyException) { + return when (error.error) { + DaaRegistrationFlowKeyError.KeyGenerationFailed, + DaaRegistrationFlowKeyError.PublicKeyUnavailable, + DaaRegistrationFlowKeyError.SigningFailed, + -> RegistrationContractViolationException() + } + } + return RegistrationContractViolationException() +} diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt b/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt new file mode 100644 index 0000000..6984673 --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaRegistrationModule.kt @@ -0,0 +1,121 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import com.circle.daa.sdk.DaaPrepareReceiptSignature +import com.circle.daa.sdk.DaaRegistrationAuthorizationSigningInput +import com.circle.daa.sdk.DaaRegistrationFlowKey +import com.circle.daa.sdk.DaaSecureRandom +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap + +// Thin Expo bridge to the native registration primitives. THIS IS NOT +// DaaSecureKey. Verifier bytes come from DaaSecureRandom; the ephemeral +// flow key is DaaRegistrationFlowKey, cached here so the private key never +// crosses into JavaScript; the Prepare receipt signature is checked by +// DaaPrepareReceiptSignature. + +class DaaRegistrationModule : Module() { + private val flowKeys = ConcurrentHashMap() + + override fun definition() = + ModuleDefinition { + Name("DaaRegistration") + + Function("randomBytes") { count: Int -> + runRegistration { unpaddedBase64Url(DaaSecureRandom.bytes(count)) } + } + + Function("randomUuidV4") { + UUID.randomUUID().toString() + } + + Function("generateRegistrationFlowKey") { + runRegistration { + val key = DaaRegistrationFlowKey.generate() + val id = UUID.randomUUID().toString() + flowKeys[id] = key + id + } + } + + Function("registrationFlowPublicKeySpkiBase64Url") { id: String -> + runRegistration { + val key = + flowKeys[id] + ?: throw RegistrationContractViolationException() + key.publicKeySpkiBase64Url() + } + } + + // Drops the cached key so its private half is no longer reachable and + // becomes collectable. Without this the map grows by one P-256 private + // key per login attempt and never shrinks, which contradicts the point + // of generating the key natively: shortening how long key material is + // resident. Idempotent, and deliberately silent about an unknown id — + // release is cleanup, and a caller releasing twice (or in a `finally` + // after a failure) must not turn tidying up into an error. + Function("releaseRegistrationFlowKey") { id: String -> + flowKeys.remove(id) + Unit + } + + // Typed native signRegistrationAuthorization — not a generic + // sign(bytes). The Base64URL payload is the exact Device + // Registration Complete flow-JWS signing input already built in + // TypeScript; native validates those bytes and signs that same + // slice. Synchronous and prompt-free: the flow key is in process + // memory, not the Keystore, so there is no biometric gate. + Function("signRegistrationAuthorization") { id: String, signingInputBase64Url: String -> + runRegistration { + val key = flowKeys[id] ?: throw RegistrationContractViolationException() + val signature = + key.signRegistrationAuthorization( + DaaRegistrationAuthorizationSigningInput( + decodeUnpaddedBase64Url(signingInputBase64Url), + ), + ) + unpaddedBase64Url(signature) + } + } + + // Verify-only, against a key JS pinned from the SDK's own trust + // anchor — never a key from the token. DaaPrepareReceiptSignature + // (daa-android-sdk) does the check with java.security: a signature + // problem is `false`, and a key that is not a P-256 point throws + // and maps to CONTRACT_VIOLATION. + AsyncFunction("verifyPrepareReceiptSignature") { publicKeyX963Base64Url: String, signingInputBase64Url: String, signatureBase64Url: String -> + runRegistration { + DaaPrepareReceiptSignature.verify( + decodeUnpaddedBase64Url(publicKeyX963Base64Url), + decodeUnpaddedBase64Url(signingInputBase64Url), + decodeUnpaddedBase64Url(signatureBase64Url), + ) + } + } + } + + private fun runRegistration(block: () -> T): T { + return try { + block() + } catch (error: Throwable) { + throw mappedRegistrationException(error) + } + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt b/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt new file mode 100644 index 0000000..5824a5c --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaScaExceptions.kt @@ -0,0 +1,60 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import com.circle.daa.sdk.sca.DaaScaError +import com.circle.daa.sdk.sca.DaaScaResult +import expo.modules.kotlin.exception.CodedException + +// JS reads `error.code`. The codes match the iOS bridge exactly, so the +// TypeScript layer maps one vocabulary. A reason, where there is one, rides in +// the code as ":", which Expo passes through unchanged (the +// message may be wrapped). The message also starts with the code in brackets, +// matching iOS, where the rejection reaches JS without a code. + +private fun tagged(code: String, message: String) = "[$code] $message" + +internal class ScaCancelledException : + CodedException("SCA_CANCELLED", tagged("SCA_CANCELLED", "The ceremony was cancelled"), null) + +internal class ScaFailedException( + code: String, + message: String, +) : CodedException(code, tagged(code, message), null) + +internal class ScaInvalidConfigurationException( + message: String, +) : CodedException("SCA_INVALID_CONFIGURATION", tagged("SCA_INVALID_CONFIGURATION", message), null) + +internal class ScaCeremonyInProgressException : + CodedException( + "SCA_CEREMONY_IN_PROGRESS", + tagged("SCA_CEREMONY_IN_PROGRESS", "Another SCA ceremony is still open"), + null, + ) + +internal fun mappedScaFailure(result: DaaScaResult.Failed): CodedException { + val message = result.message ?: result.error.name + return when (result.error) { + DaaScaError.Expired -> ScaFailedException("SCA_EXPIRED", message) + DaaScaError.Unsupported -> + ScaFailedException("SCA_UNSUPPORTED:${result.unsupportedReason?.name ?: "PasskeyUnavailable"}", message) + DaaScaError.AlreadyEnrolled -> ScaFailedException("SCA_ALREADY_ENROLLED", message) + DaaScaError.Protocol -> ScaFailedException("SCA_PROTOCOL", message) + DaaScaError.Transport -> ScaFailedException("SCA_TRANSPORT", message) + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt b/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt new file mode 100644 index 0000000..f85fd8d --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaScaModule.kt @@ -0,0 +1,179 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import androidx.activity.result.contract.ActivityResultContract +import com.circle.daa.sdk.DaaEnvironment +import com.circle.daa.sdk.sca.DaaSca +import com.circle.daa.sdk.sca.DaaScaApproveContract +import com.circle.daa.sdk.sca.DaaScaConfig +import com.circle.daa.sdk.sca.DaaScaEnrollContract +import com.circle.daa.sdk.sca.DaaScaResult +import expo.modules.kotlin.Promise +import expo.modules.kotlin.functions.Queues +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import expo.modules.kotlin.records.Field +import expo.modules.kotlin.records.Record + +// Thin bridge over daa-android-sdk's SCA contracts. No ceremony logic lives here: +// the native SDK opens the hosted page, validates the callback and returns the +// page's response text, which is passed to JS unchanged (the exact +// X-Sca-Assertion value for approve, the registration response JSON for enroll). +// The bridge only translates configuration, the activity result and errors. + +internal class ScaConfigRecord : Record { + @Field val environment: String = "" + + @Field val redirectUri: String = "" + + @Field val circleOrigin: String? = null + + @Field val approveTimeoutMs: Double? = null + + @Field val enrollTimeoutMs: Double? = null +} + +class DaaScaModule : Module() { + private class Pending( + val contract: ActivityResultContract, + val promise: Promise, + ) + + // One ceremony at a time across the whole app. The native SDK ends an open + // ceremony when a second launch arrives; the bridge refuses the second call up + // front instead, so both platforms behave the same in JS. Main thread only. + private var pending: Pending? = null + + override fun definition() = + ModuleDefinition { + Name("DaaSca") + + AsyncFunction("capabilities") { config: ScaConfigRecord -> + val context = appContext.reactContext ?: throw ScaInvalidConfigurationException("No React context") + val capabilities = DaaSca.capabilities(context, scaConfig(config)) + mapOf( + "protocolVersion" to capabilities.protocolVersion, + "surface" to capabilities.surface.name.replaceFirstChar { it.lowercase() }, + "callbackReady" to capabilities.callbackRegistered, + "callbackVerified" to capabilities.callbackVerified, + "callbackTaskIsolated" to capabilities.callbackTaskIsolated, + "platformPasskeys" to capabilities.platformPasskeys, + ) + } + + AsyncFunction("approve") { config: ScaConfigRecord, frameToken: String, promise: Promise -> + launch(promise, frameToken) { DaaScaApproveContract(scaConfig(config)) } + }.runOnQueue(Queues.MAIN) + + AsyncFunction("enroll") { config: ScaConfigRecord, frameToken: String, promise: Promise -> + launch(promise, frameToken) { DaaScaEnrollContract(scaConfig(config)) } + }.runOnQueue(Queues.MAIN) + + OnActivityResult { _, payload -> + if (payload.requestCode != REQUEST_CODE) return@OnActivityResult + val current = pending ?: return@OnActivityResult + pending = null + settle(current.promise, current.contract.parseResult(payload.resultCode, payload.data)) + } + } + + private fun launch( + promise: Promise, + frameToken: String, + contract: () -> ActivityResultContract, + ) { + if (pending != null) { + promise.reject(ScaCeremonyInProgressException()) + return + } + val built = + try { + contract() + } catch (error: IllegalArgumentException) { + // A custom-scheme redirect URI for approve, or an invalid config. + promise.reject(ScaInvalidConfigurationException(error.message ?: "Invalid SCA configuration")) + return + } catch (error: ScaInvalidConfigurationException) { + promise.reject(error) + return + } + val activity = appContext.currentActivity + if (activity == null) { + promise.reject(ScaFailedException("SCA_UNSUPPORTED:SessionUnavailable", "No foreground activity")) + return + } + // Building the intent validates the frame token (blank or too long): a caller + // bug, reported like iOS, never as "unsupported". + val intent = + try { + built.createIntent(activity, frameToken) + } catch (error: IllegalArgumentException) { + val detail = error.message ?: "frameToken is invalid" + promise.reject(ScaFailedException("SCA_PROTOCOL:InvalidFrameToken", detail)) + return + } + pending = Pending(built, promise) + try { + activity.startActivityForResult(intent, REQUEST_CODE) + } catch (error: RuntimeException) { + // OnActivityResult never fires for a ceremony that did not start, so the + // slot must be released here or every later call would be refused. + pending = null + val detail = error.message ?: "the ceremony could not start" + promise.reject(ScaFailedException("SCA_UNSUPPORTED:SessionUnavailable", detail)) + } + } + + private fun settle( + promise: Promise, + result: DaaScaResult, + ) { + when (result) { + is DaaScaResult.Completed -> promise.resolve(result.response) + is DaaScaResult.Cancelled -> promise.reject(ScaCancelledException()) + is DaaScaResult.Failed -> promise.reject(mappedScaFailure(result)) + } + } + + private companion object { + // Distinct from any request code the host app is likely to use. + const val REQUEST_CODE = 0x5CA1 + } +} + +private fun scaConfig(config: ScaConfigRecord): DaaScaConfig { + // Only the public environments; any other Circle host goes through + // `circleOrigin`, which the native configuration validates. + val environment = + when (config.environment) { + "sandbox" -> DaaEnvironment.Sandbox + "production" -> DaaEnvironment.Production + else -> throw ScaInvalidConfigurationException("environment must be 'sandbox' or 'production'") + } + return try { + DaaScaConfig( + environment = environment, + redirectUri = config.redirectUri, + circleOrigin = config.circleOrigin, + approveTimeoutMillis = config.approveTimeoutMs?.toLong() ?: DaaScaConfig.DEFAULT_APPROVE_TIMEOUT_MILLIS, + enrollTimeoutMillis = config.enrollTimeoutMs?.toLong() ?: DaaScaConfig.DEFAULT_ENROLL_TIMEOUT_MILLIS, + ) + } catch (error: IllegalArgumentException) { + throw ScaInvalidConfigurationException(error.message ?: "Invalid SCA configuration") + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt b/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt new file mode 100644 index 0000000..4b94a22 --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyExceptions.kt @@ -0,0 +1,73 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import com.circle.daa.sdk.DaaSecureKeyError +import com.circle.daa.sdk.DaaSecureKeyException +import expo.modules.kotlin.exception.CodedException + +internal class UserAuthRequiredException : + CodedException("USER_AUTH_REQUIRED", "User authentication is required", null) + +internal class NotInitializedException : + CodedException("NOT_INITIALIZED", "Secure key is not initialized", null) + +internal class ContractViolationException( + message: String = "Native secure-key operation failed", +) : CodedException("CONTRACT_VIOLATION", message, null) + +internal fun mappedSecureKeyException(error: Throwable): CodedException { + if (error is CodedException) { + return error + } + val keyError = + if (error is DaaSecureKeyException) { + error.error + } else { + return ContractViolationException() + } + return when (keyError) { + DaaSecureKeyError.UserCancelled, + DaaSecureKeyError.AuthenticationFailed, + DaaSecureKeyError.DeviceCredentialNotSet, + -> UserAuthRequiredException() + DaaSecureKeyError.KeyNotFound, + DaaSecureKeyError.ResolutionRequired, + -> NotInitializedException() + DaaSecureKeyError.InvalidAppId, + DaaSecureKeyError.InvalidSigningInput, + DaaSecureKeyError.AuthKeyRegistrationRequired, + DaaSecureKeyError.SecureHardwareUnavailable, + DaaSecureKeyError.KeyCreationFailed, + DaaSecureKeyError.KeyInvalidated, + DaaSecureKeyError.KeyAccessFailed, + DaaSecureKeyError.KeyMetadataUnavailable, + DaaSecureKeyError.KeyMetadataVersionUnsupported, + DaaSecureKeyError.ProtectionMismatch, + DaaSecureKeyError.ProtectionUnavailable, + DaaSecureKeyError.PublicKeyUnavailable, + DaaSecureKeyError.SigningAlgorithmUnavailable, + DaaSecureKeyError.SigningFailed, + DaaSecureKeyError.SigningInputExpired, + // Thrown when a registration device proof's header `jwk` is not the + // signing key's own (its RFC 7638 thumbprint differs). An upstream + // contract violation, not something to retry — the same mapping the + // Swift bridge gives `authKeyThumbprintMismatch`. + DaaSecureKeyError.AuthKeyThumbprintMismatch, + -> ContractViolationException() + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt b/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt new file mode 100644 index 0000000..9ca93e3 --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt @@ -0,0 +1,185 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import android.content.Context +import androidx.fragment.app.FragmentActivity +import com.circle.daa.sdk.DaaAuthKeyIdentity +import com.circle.daa.sdk.DaaAuthKeyResolution +import com.circle.daa.sdk.DaaDeviceAuthorizationSigningInput +import com.circle.daa.sdk.DaaEnvironment +import com.circle.daa.sdk.DaaRegistrationAuthorizationSigningInput +import com.circle.daa.sdk.DaaSecureKey +import expo.modules.kotlin.modules.Module +import expo.modules.kotlin.modules.ModuleDefinition +import java.util.UUID +import java.util.concurrent.ConcurrentHashMap +import kotlinx.coroutines.runBlocking + +class DaaSecureKeyModule : Module() { + private val keys = ConcurrentHashMap() + private val installationLock = Any() + + @Volatile + private var installationId: UUID? = null + + override fun definition() = ModuleDefinition { + Name("DaaSecureKey") + + // Mirrors `DEVICE_KEY_POLICY` in src/config.ts. This is a compiled-in + // constant, not a live readback of a specific key's real Keystore + // protection: it is a version-skew guard between this module and the + // TypeScript it ships with, so a mismatch means the two disagree + // about the closed set, not that a key was inspected and found + // wanting. daa-android-sdk's public `SecureKey` does not expose the + // key's `KeyInfo`, so this module has no per-key protection to read + // back. + Function("declaredKeyPolicy") { + mapOf( + "hardwareBacked" to true, + "userVerification" to "REQUIRED_FOR_EACH_SIGNATURE", + ) + } + + AsyncFunction("resolveOrCreate") { appId: String, environment: String -> + runKey { + when (keyFor(appId, environment).resolveOrCreate()) { + DaaAuthKeyResolution.Created -> "created" + DaaAuthKeyResolution.Existing -> "existing" + } + } + } + + AsyncFunction("publicKeySpkiBase64Url") { appId: String, environment: String -> + runKey { keyFor(appId, environment).publicKeySpkiBase64Url() } + } + + // Reached from OwnerAuthKey.acknowledgeRegistration() via the TS bridge. + // This is the only registration-ack entry point; do not add a parallel one. + AsyncFunction("acknowledgeRegistration") { appId: String, environment: String -> + runKey { keyFor(appId, environment).acknowledgeRegistration() } + } + + // Typed native signDeviceAuthorization — not a generic sign(bytes). The + // Base64URL payload is the exact compact-JWS signing input already built + // in TypeScript; native validates those bytes and signs that same slice. + // There is no prompt argument: daa-android-sdk sets all of the + // BiometricPrompt text from the validated operation and shows it over + // the current FragmentActivity; nothing here can change that text. + AsyncFunction("signDeviceAuthorization") { + appId: String, + environment: String, + signingInputBase64Url: String, + -> + val activity = + appContext.currentActivity as? FragmentActivity + ?: throw ContractViolationException( + "signDeviceAuthorization requires a FragmentActivity", + ) + runKey { + val signature = + keyFor(appId, environment).signDeviceAuthorization( + DaaDeviceAuthorizationSigningInput( + decodeUnpaddedBase64Url(signingInputBase64Url), + ), + activity, + ) + unpaddedBase64Url(signature) + } + } + + // Typed native signRegistrationDeviceAuthorization — the registration + // counterpart of signDeviceAuthorization above, NOT the same call. The + // Base64URL payload is the exact Device Registration Complete + // device-proof signing input from `auth/registrationAuthorization.ts`; + // it is validated by DaaRegistrationAuthorizationSigningInput, a + // different validator from DaaDeviceAuthorizationSigningInput + // (registration `typ`s, an embedded JWK header, no acknowledged-key + // gate). Do not route this input through signDeviceAuthorization + // above, and do not route that input through here. Like + // signDeviceAuthorization, it takes no prompt: daa-android-sdk shows + // its own device-registration prompt text. + AsyncFunction("signRegistrationDeviceAuthorization") { + appId: String, + environment: String, + signingInputBase64Url: String, + -> + val activity = + appContext.currentActivity as? FragmentActivity + ?: throw ContractViolationException( + "signRegistrationDeviceAuthorization requires a FragmentActivity", + ) + runKey { + val signature = + keyFor(appId, environment).signRegistrationDeviceAuthorization( + DaaRegistrationAuthorizationSigningInput( + decodeUnpaddedBase64Url(signingInputBase64Url), + ), + activity, + ) + unpaddedBase64Url(signature) + } + } + } + + private fun runKey(block: suspend () -> T): T { + return try { + runBlocking { block() } + } catch (error: Throwable) { + throw mappedSecureKeyException(error) + } + } + + private fun keyFor(appId: String, environmentWire: String): DaaSecureKey { + val environment = + DaaEnvironment.entries.find { it.wireValue == environmentWire } + ?: throw ContractViolationException() + val alias = "$appId.${environment.wireValue}" + val existing = keys[alias] + if (existing != null) { + return existing + } + val context = + appContext.reactContext?.applicationContext + ?: throw ContractViolationException() + val identity = + DaaAuthKeyIdentity( + appId = appId, + environment = environment, + installationId = installationId(context), + ) + val created = DaaSecureKey(context, identity) + val raced = keys.putIfAbsent(alias, created) + return raced ?: created + } + + private fun installationId(context: Context): UUID { + val cached = installationId + if (cached != null) { + return cached + } + synchronized(installationLock) { + val locked = installationId + if (locked != null) { + return locked + } + val loaded = InstallationIdentityStore.loadOrCreate(context) + installationId = loaded + return loaded + } + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt b/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt new file mode 100644 index 0000000..8a4ce44 --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/InstallationIdentityStore.kt @@ -0,0 +1,73 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import android.content.Context +import java.io.File +import java.util.UUID + +// Durable per-install UUID for DaaAuthKeyIdentity.installationId. +// Native docs: the caller persists the UUID; a new install gets a new UUID. +// App-private no-backup storage is wiped on uninstall, so a reinstall mints a +// new UUID and therefore a new Keystore AuthKey. + +internal object InstallationIdentityStore { + private const val FILE_NAME = "daa-installation-id" + private val lock = Any() + + fun loadOrCreate(context: Context): UUID { + // One tmp path for all writers. Serialize so a first-run race cannot + // persist id_B after a caller already returned id_A (two Keystore + // aliases). iOS gets the same exclusivity from its actor / SecItemAdd. + synchronized(lock) { + val dir = context.noBackupFilesDir + val file = File(dir, FILE_NAME) + readUuid(file)?.let { + return it + } + + val id = UUID.randomUUID() + val tmp = File(dir, "$FILE_NAME.tmp") + tmp.writeText(id.toString().lowercase()) + if (!tmp.renameTo(file)) { + tmp.delete() + readUuid(file)?.let { + return it + } + throw ContractViolationException() + } + return readUuid(file) ?: id + } + } + + // Truncated or garbage files are wiped so the next mint is a new UUID. + // That does NOT uninstall: the previous Keystore key remains under the + // old alias, still registered with Circle if enrollment happened, never + // revoked. The SDK silently creates a new AuthKey. This keeps + // resolveOrCreate usable; it is not equivalent to wiping app data. + private fun readUuid(file: File): UUID? { + if (!file.exists()) { + return null + } + val parsed = runCatching { UUID.fromString(file.readText().trim()) }.getOrNull() + if (parsed == null) { + file.delete() + return null + } + return parsed + } +} diff --git a/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt b/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt new file mode 100644 index 0000000..72b5c4e --- /dev/null +++ b/android/src/main/java/com/circle/daa/reactnative/UnpaddedBase64Url.kt @@ -0,0 +1,45 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +package com.circle.daa.reactnative + +import android.util.Base64 + +// Shared by DaaSecureKey and DaaRegistration. One canonicalization so a +// round-trip check on the signing-input decoder cannot drift from encode. + +internal fun unpaddedBase64Url(bytes: ByteArray): String { + return Base64.encodeToString( + bytes, + Base64.NO_WRAP or Base64.URL_SAFE or Base64.NO_PADDING, + ) +} + +internal fun decodeUnpaddedBase64Url(encoded: String): ByteArray { + if (encoded.length % 4 == 1) { + throw ContractViolationException() + } + val decoded = + try { + Base64.decode(encoded, Base64.URL_SAFE or Base64.NO_WRAP or Base64.NO_PADDING) + } catch (_: IllegalArgumentException) { + throw ContractViolationException() + } + if (unpaddedBase64Url(decoded) != encoded) { + throw ContractViolationException() + } + return decoded +} diff --git a/babel.config.js b/babel.config.js new file mode 100644 index 0000000..0159dbf --- /dev/null +++ b/babel.config.js @@ -0,0 +1,24 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Test-only. The shipped build is produced by `tsc` (see tsconfig.build.json); +// Babel exists solely so Jest can transform JSX and React Native's own ESM +// sources. Nothing here affects `yarn build`. +module.exports = { + presets: ['@react-native/babel-preset'], +} diff --git a/eslint.config.js b/eslint.config.js new file mode 100644 index 0000000..23e2e1f --- /dev/null +++ b/eslint.config.js @@ -0,0 +1,129 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Flat ESLint config (ESLint 9). Formatting is owned by Prettier, so +// eslint-config-prettier disables any stylistic rules that would conflict. +const tseslint = require('typescript-eslint') +const prettier = require('eslint-config-prettier') +const reactHooks = require('eslint-plugin-react-hooks') + +module.exports = tseslint.config( + { ignores: ['**/build/**', 'coverage/**', '**/node_modules/**', 'android/**', 'ios/**'] }, + { + files: ['**/*.{ts,tsx}'], + extends: [...tseslint.configs.recommended], + plugins: { + 'react-hooks': reactHooks, + }, + rules: { + ...reactHooks.configs.recommended.rules, + }, + }, + // Production and native code must not reach a Node API. `tsconfig.json` + // narrows `types` to `["jest"]` for that reason, but the ambient declarations + // in `src/__test__/node.d.ts` are program-global and would otherwise let a + // `node:fs` import in `src/crypto/` or `src/securekey/` pass `check:type`. + // Excluding `src/__test__/` from `tsconfig.build.json` only moves that + // failure to the build step; this keeps it at the lint step, where the + // message says what the rule is. + { + files: ['src/**/*.{ts,tsx}', 'packages/*/src/**/*.{ts,tsx}'], + ignores: ['src/__test__/**', 'packages/*/src/__test__/**'], + rules: { + // `paths` matches an exact specifier; `patterns` is a glob. The bare + // built-ins have to go in `paths`, because as a pattern `crypto` also + // matches this repo's own `../crypto/base64url`. + 'no-restricted-imports': ['error', { paths: ['fs', 'path', 'crypto'], patterns: ['node:*'] }], + }, + }, + // TypeScript's `private` keyword is a compile-time annotation only — `tsc` + // erases it at build time (this repo targets ES2020 with no downlevel + // transform), leaving an ordinary callable/readable member on the + // prototype. Scoped to all of `src/`, not just `src/api/` and + // `src/securekey/`: `DaaClient` (`src/DaaClient.ts`) is the SDK's actual + // public entry point — more public than `AuthClient`, which is only + // reachable via `DaaClient.auth` — so an erased `private` field or method + // anywhere in production source is a candidate public surface, not just in + // the two directories that hold the signing/key-access primitives + // directly. Use ECMAScript `#` private fields and methods instead, which + // are enforced at runtime and cannot be erased by the compiler. + // `src/__test__/` is excluded: erasure in a test double carries no risk, + // and it is where the repo's ordinary TS `private` constructor parameters + // legitimately live (recording fixtures, in-memory doubles). + { + files: ['src/**/*.{ts,tsx}', 'packages/*/src/**/*.{ts,tsx}'], + ignores: ['src/__test__/**', 'packages/*/src/__test__/**'], + rules: { + 'no-restricted-syntax': [ + 'error', + { + selector: "MethodDefinition[accessibility='private']", + message: + "TypeScript 'private' is erased at build time. Use an ECMAScript '#' private method instead.", + }, + { + selector: "PropertyDefinition[accessibility='private']", + message: + "TypeScript 'private' is erased at build time. Use an ECMAScript '#' private field instead.", + }, + { + selector: "TSParameterProperty[accessibility='private']", + message: + "TypeScript 'private' parameter properties are erased at build time. Declare a '#' private field and assign it in the constructor body instead.", + }, + ], + }, + }, + // The harness's config plugins and their tests are load-bearing JavaScript. + // The TypeScript block above does not match these files, so this block gives + // them a small core-rule set. It is deliberately not + // `tseslint.configs.recommended`: those are TypeScript rules, and keeping + // `example/` out of the TypeScript program is the reason these files are + // JavaScript in the first place. + // + // Scoped to `plugins/` rather than all of `example/`: `index.js` is an ES + // module (Metro/Babel own it, and `sourceType: 'commonjs'` would fail to parse + // its `import`), and `example/android/` and `example/ios/` are prebuild output. + // + // Node and Jest globals have to be declared for `no-undef`, because flat + // config supplies only the ES built-ins. + { + files: ['example/plugins/**/*.js'], + languageOptions: { + sourceType: 'commonjs', + globals: { + __dirname: 'readonly', + afterEach: 'readonly', + beforeEach: 'readonly', + console: 'readonly', + describe: 'readonly', + expect: 'readonly', + it: 'readonly', + jest: 'readonly', + module: 'writable', + process: 'readonly', + require: 'readonly', + }, + }, + rules: { + 'no-undef': 'error', + 'no-unused-vars': 'error', + }, + }, + prettier, +) diff --git a/expo-module.config.json b/expo-module.config.json new file mode 100644 index 0000000..736cbdf --- /dev/null +++ b/expo-module.config.json @@ -0,0 +1,14 @@ +{ + "platforms": ["apple", "android"], + "apple": { + "podspecPath": "DaaReactNativeSdk.podspec", + "modules": ["DaaSecureKeyModule", "DaaRegistrationModule", "DaaScaModule"] + }, + "android": { + "modules": [ + "com.circle.daa.reactnative.DaaSecureKeyModule", + "com.circle.daa.reactnative.DaaRegistrationModule", + "com.circle.daa.reactnative.DaaScaModule" + ] + } +} diff --git a/ios/DaaRegistrationExceptions.swift b/ios/DaaRegistrationExceptions.swift new file mode 100644 index 0000000..a495f63 --- /dev/null +++ b/ios/DaaRegistrationExceptions.swift @@ -0,0 +1,58 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore + +// Stable `code` values for the JS wrapper. Reasons are canned — never copy +// CSPRNG / key-generation text into the JS message. Distinct from the +// AuthKey mapper: this module never touches DaaSecureKey. + +internal final class RegistrationContractViolationException: Exception { + override var code: String { "CONTRACT_VIOLATION" } + override var reason: String { "Native registration operation failed" } +} + +internal func mappedRegistrationException(_ error: Error) -> Exception { + if let exception = error as? Exception { + return exception + } + if let randomError = error as? DaaSecureRandomError { + switch randomError { + case .invalidByteCount, .randomnessUnavailable: + return RegistrationContractViolationException() + } + } + if let flowError = error as? DaaRegistrationFlowKeyError { + // Every case maps the same way: this bridge discloses no distinction + // between flow-key error causes to JS. The switch is exhaustive against + // the pinned DaaSdk, so a DaaSdk release that adds a case fails to compile + // here with `switch must be exhaustive`. + switch flowError { + case .publicKeyUnavailable, .signingFailed, .invalidSigningInput: + return RegistrationContractViolationException() + } + } + // DaaRegistrationAuthorizationSigningInput's initializer validates against + // the shared AuthKey error type rather than declaring its own, since the + // validated-input shape is shared with DaaSecureKey. Named explicitly here + // (rather than left to the generic fallthrough below) so a reader can see + // this module already accounts for it. + if let secureKeyError = error as? DaaSecureKeyError, secureKeyError == .invalidSigningInput { + return RegistrationContractViolationException() + } + return RegistrationContractViolationException() +} diff --git a/ios/DaaRegistrationModule.swift b/ios/DaaRegistrationModule.swift new file mode 100644 index 0000000..e58197e --- /dev/null +++ b/ios/DaaRegistrationModule.swift @@ -0,0 +1,143 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore +import Foundation + +// Thin Expo bridge to the native registration primitives. THIS IS NOT +// DaaSecureKey. Verifier bytes come from DaaSecureRandom; the ephemeral +// flow key is DaaRegistrationFlowKey, cached here so the private key never +// crosses into JavaScript; the Prepare receipt signature is checked by +// DaaPrepareReceiptSignature. + +public class DaaRegistrationModule: Module { + private let flowKeys = RegistrationFlowKeyCache() + + public func definition() -> ModuleDefinition { + Name("DaaRegistration") + + Function("randomBytes") { (count: Int) throws -> String in + do { + return unpaddedBase64URL(try DaaSecureRandom.bytes(count: count)) + } catch { + throw mappedRegistrationException(error) + } + } + + Function("randomUuidV4") { () -> String in + UUID().uuidString.lowercased() + } + + Function("generateRegistrationFlowKey") { () -> String in + flowKeys.store(DaaRegistrationFlowKey.generate()) + } + + Function("registrationFlowPublicKeySpkiBase64Url") { (id: String) throws -> String in + do { + return try flowKeys.publicKeySPKIBase64URL(id: id) + } catch { + throw mappedRegistrationException(error) + } + } + + // Drops the cached key so its private half is no longer reachable and can be + // released. Without this the cache grows by one P-256 private key per login + // attempt and never shrinks, which contradicts the point of generating the + // key natively: shortening how long key material is resident. Idempotent, + // and deliberately silent about an unknown id — release is cleanup, and a + // caller releasing twice (or in a `finally` after a failure) must not turn + // tidying up into an error. + Function("releaseRegistrationFlowKey") { (id: String) -> Void in + flowKeys.release(id: id) + } + + // Typed native signRegistrationAuthorization — not a generic sign(bytes). + // The Base64URL payload is the exact Device Registration Complete flow-JWS + // signing input already built in TypeScript; native validates those bytes + // and signs that same slice. Synchronous and prompt-free: the flow key is + // in process memory, not the Secure Enclave, so there is no biometric gate. + Function("signRegistrationAuthorization") { (id: String, signingInputBase64Url: String) throws -> String in + do { + let exactBytes = try decodeUnpaddedBase64URL(signingInputBase64Url) + let signingInput = try DaaRegistrationAuthorizationSigningInput(exactBytes: exactBytes) + let signature = try flowKeys.signRegistrationAuthorization(id: id, signingInput: signingInput) + return unpaddedBase64URL(signature) + } catch { + throw mappedRegistrationException(error) + } + } + + // Verify-only, against a key JS pinned from the SDK's own trust anchor — + // never a key from the token. DaaPrepareReceiptSignature (daa-ios-sdk) does + // the check with CryptoKit: a signature problem is `false`, and a key that + // is not a P-256 point throws and maps to CONTRACT_VIOLATION. + AsyncFunction("verifyPrepareReceiptSignature") { + (publicKeyX963Base64Url: String, signingInputBase64Url: String, signatureBase64Url: String) throws -> Bool in + do { + return try DaaPrepareReceiptSignature.verify( + publicKeyX963: try decodeUnpaddedBase64URL(publicKeyX963Base64Url), + signingInput: try decodeUnpaddedBase64URL(signingInputBase64Url), + signature: try decodeUnpaddedBase64URL(signatureBase64Url) + ) + } catch { + throw mappedRegistrationException(error) + } + } + } +} + +private final class RegistrationFlowKeyCache: @unchecked Sendable { + private let lock = NSLock() + private var keys: [String: DaaRegistrationFlowKey] = [:] + + func store(_ key: DaaRegistrationFlowKey) -> String { + let id = UUID().uuidString.lowercased() + lock.lock() + keys[id] = key + lock.unlock() + return id + } + + func publicKeySPKIBase64URL(id: String) throws -> String { + lock.lock() + let key = keys[id] + lock.unlock() + guard let key else { + throw RegistrationContractViolationException() + } + return try key.publicKeySPKIBase64URL() + } + + func release(id: String) { + lock.lock() + keys.removeValue(forKey: id) + lock.unlock() + } + + func signRegistrationAuthorization( + id: String, + signingInput: DaaRegistrationAuthorizationSigningInput + ) throws -> Data { + lock.lock() + let key = keys[id] + lock.unlock() + guard let key else { + throw RegistrationContractViolationException() + } + return try key.signRegistrationAuthorization(signingInput: signingInput) + } +} diff --git a/ios/DaaScaExceptions.swift b/ios/DaaScaExceptions.swift new file mode 100644 index 0000000..cd6bba3 --- /dev/null +++ b/ios/DaaScaExceptions.swift @@ -0,0 +1,96 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore + +// The codes match the Android bridge exactly, so the TypeScript layer maps one +// vocabulary. A reason, where there is one, rides in the code as +// ":". An async function's rejection reaches JS without the +// exception's code, and Expo wraps its message ("Calling the 'approve' function +// has failed → Caused by: …"), so the message also starts with the code in +// brackets; the TypeScript layer reads it from the innermost cause. + +private func tagged(_ code: String, _ detail: String) -> String { + "[\(code)] \(detail)" +} + +internal final class ScaCancelledException: Exception { + override var code: String { "SCA_CANCELLED" } + override var reason: String { tagged(code, "The ceremony was cancelled") } +} + +internal final class ScaFailedException: Exception { + private let scaCode: String + private let detail: String + + init(code: String, detail: String) { + self.scaCode = code + self.detail = detail + super.init() + } + + override var code: String { scaCode } + override var reason: String { tagged(code, detail) } +} + +internal final class ScaInvalidConfigurationException: Exception { + private let detail: String + + init(_ detail: String) { + self.detail = detail + super.init() + } + + override var code: String { "SCA_INVALID_CONFIGURATION" } + override var reason: String { tagged(code, detail) } +} + +internal final class ScaCeremonyInProgressException: Exception { + override var code: String { "SCA_CEREMONY_IN_PROGRESS" } + override var reason: String { tagged(code, "Another SCA ceremony is still open") } +} + +internal func mappedScaException(_ error: Error) -> Exception { + if let exception = error as? Exception { + return exception + } + guard let scaError = error as? DaaScaError else { + return ScaFailedException(code: "SCA_PROTOCOL", detail: "Unexpected native error") + } + switch scaError { + case .cancelled: + return ScaCancelledException() + case let .expired(message): + return ScaFailedException(code: "SCA_EXPIRED", detail: message ?? "The ceremony expired") + case let .unsupported(message): + return ScaFailedException(code: "SCA_UNSUPPORTED:PasskeyUnavailable", detail: message ?? "Passkeys are unavailable") + case let .alreadyEnrolled(message): + return ScaFailedException(code: "SCA_ALREADY_ENROLLED", detail: message ?? "A passkey is already enrolled") + case .stateMismatch: + return ScaFailedException(code: "SCA_PROTOCOL:StateMismatch", detail: "The callback did not belong to this ceremony") + case let .sessionUnavailable(message): + return ScaFailedException(code: "SCA_UNSUPPORTED:SessionUnavailable", detail: message ?? "No session could be presented") + case let .protocol(message): + // The SDK checks the frame token before opening anything; those are caller + // bugs, reported the same way as Android's argument checks. + if let message, message.hasPrefix("frameToken") { + return ScaFailedException(code: "SCA_PROTOCOL:InvalidFrameToken", detail: message) + } + return ScaFailedException(code: "SCA_PROTOCOL", detail: message ?? "Protocol error") + } +} + diff --git a/ios/DaaScaModule.swift b/ios/DaaScaModule.swift new file mode 100644 index 0000000..694708e --- /dev/null +++ b/ios/DaaScaModule.swift @@ -0,0 +1,125 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore +import Foundation + +// Thin bridge over daa-ios-sdk's `DaaSca`. No ceremony logic lives here: the +// native SDK opens the hosted page, validates the callback and returns the +// page's response text, which is passed to JS unchanged (it is the exact +// X-Sca-Assertion value for approve, and the registration response JSON for +// enroll). The bridge only translates configuration and errors. + +internal struct ScaConfigRecord: Record { + @Field var environment: String = "" + @Field var redirectUri: String = "" + @Field var circleOrigin: String? + @Field var approveTimeoutMs: Double? + @Field var enrollTimeoutMs: Double? +} + +public class DaaScaModule: Module { + private let gate = ScaCeremonyGate() + + public func definition() -> ModuleDefinition { + Name("DaaSca") + + AsyncFunction("capabilities") { (config: ScaConfigRecord) async throws -> [String: Any] in + let configuration = try scaConfiguration(config) + return await MainActor.run { + let capabilities = DaaSca(configuration: configuration).capabilities() + return [ + "protocolVersion": capabilities.protocolVersion, + "surface": capabilities.surface == .webAuthenticationSession ? "webAuthenticationSession" : "none", + "callbackReady": capabilities.callbackSupported, + "platformPasskeys": capabilities.platformPasskeys, + "ceremonySupported": capabilities.isCeremonySupported, + ] + } + } + + AsyncFunction("approve") { (config: ScaConfigRecord, frameToken: String) async throws -> String in + try await self.run(config) { sca in try await sca.approve(frameToken: frameToken) } + } + + AsyncFunction("enroll") { (config: ScaConfigRecord, frameToken: String) async throws -> String in + try await self.run(config) { sca in try await sca.enroll(frameToken: frameToken) } + } + } + + // One ceremony at a time across the whole app. The native SDK replaces an open + // ceremony when a second starts on the same instance; the bridge refuses the + // second call up front instead, so both platforms behave the same in JS. + private func run( + _ config: ScaConfigRecord, + _ ceremony: @escaping @MainActor (DaaSca) async throws -> String + ) async throws -> String { + let configuration = try scaConfiguration(config) + guard gate.enter() else { + throw ScaCeremonyInProgressException() + } + defer { gate.leave() } + do { + return try await Task { @MainActor in + try await ceremony(DaaSca(configuration: configuration)) + }.value + } catch { + throw mappedScaException(error) + } + } +} + +private func scaConfiguration(_ config: ScaConfigRecord) throws -> DaaScaConfiguration { + // Only the public environments; any other Circle host goes through + // `circleOrigin`, which the native configuration validates. + let environment: DaaEnvironment + switch config.environment { + case "sandbox": environment = .sandbox + case "production": environment = .production + default: throw ScaInvalidConfigurationException("environment must be 'sandbox' or 'production'") + } + do { + return try DaaScaConfiguration( + environment: environment, + redirectURI: config.redirectUri, + circleOrigin: config.circleOrigin, + approveTimeout: (config.approveTimeoutMs.map { $0 / 1000 }) ?? DaaScaConfiguration.defaultApproveTimeout, + enrollTimeout: (config.enrollTimeoutMs.map { $0 / 1000 }) ?? DaaScaConfiguration.defaultEnrollTimeout + ) + } catch let error as DaaScaConfigurationError { + throw ScaInvalidConfigurationException(String(describing: error)) + } +} + +private final class ScaCeremonyGate: @unchecked Sendable { + private let lock = NSLock() + private var open = false + + func enter() -> Bool { + lock.lock() + defer { lock.unlock() } + guard !open else { return false } + open = true + return true + } + + func leave() { + lock.lock() + open = false + lock.unlock() + } +} diff --git a/ios/DaaSecureKeyExceptions.swift b/ios/DaaSecureKeyExceptions.swift new file mode 100644 index 0000000..b759b54 --- /dev/null +++ b/ios/DaaSecureKeyExceptions.swift @@ -0,0 +1,77 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore + +// Stable `code` values for mapNativeError. Reasons are canned — never copy +// Keychain / Secure Enclave text into the JS message. + +internal final class UserAuthRequiredException: Exception, @unchecked Sendable { + override var code: String { "USER_AUTH_REQUIRED" } + override var reason: String { "User authentication is required" } +} + +internal final class NotInitializedException: Exception, @unchecked Sendable { + override var code: String { "NOT_INITIALIZED" } + override var reason: String { "Secure key is not initialized" } +} + +internal final class ContractViolationException: Exception, @unchecked Sendable { + override var code: String { "CONTRACT_VIOLATION" } + override var reason: String { "Native secure-key operation failed" } +} + +internal func mappedSecureKeyException(_ error: Error) -> Exception { + if let exception = error as? Exception { + return exception + } + guard let keyError = error as? DaaSecureKeyError else { + return ContractViolationException() + } + switch keyError { + case .authenticationFailed, .userCancelled, .deviceLocked, .devicePasscodeNotSet: + return UserAuthRequiredException() + case .keyNotFound, .resolutionRequired: + return NotInitializedException() + case .invalidAppID, + .invalidKeychainAccessGroup, + .invalidSigningInput, + .secureEnclaveUnavailable, + .keyCreationFailed, + .keyAccessFailed, + .keychainEntitlementMissing, + .keyMetadataUnavailable, + .keyMetadataVersionUnsupported, + .protectionMismatch, + .publicKeyUnavailable, + .operationCancelled, + .signingAlgorithmUnavailable, + .signingFailed, + .authKeyRegistrationRequired, + // protectionUnavailable is thrown for a DeviceUnlocked-protected key + // signing a consequential operation — DeviceUnlocked itself is gated + // behind @_spi, which this bridge never imports, so this is unreachable + // from RN, same as the other cases in this bucket. + // authKeyThumbprintMismatch is thrown when a registration device + // proof's header jwk is not the signing key's own (its RFC 7638 + // thumbprint differs) — an upstream contract violation, not something + // to retry. + .protectionUnavailable, + .authKeyThumbprintMismatch: + return ContractViolationException() + } +} diff --git a/ios/DaaSecureKeyModule.swift b/ios/DaaSecureKeyModule.swift new file mode 100644 index 0000000..2009bc7 --- /dev/null +++ b/ios/DaaSecureKeyModule.swift @@ -0,0 +1,162 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import DaaSdk +import ExpoModulesCore +import Foundation + +public class DaaSecureKeyModule: Module, @unchecked Sendable { + private let cache = SecureKeyCache() + + public func definition() -> ModuleDefinition { + Name("DaaSecureKey") + let cache = self.cache + + // Mirrors `DEVICE_KEY_POLICY` in src/config.ts. This is a compiled-in + // constant, not a live readback of a specific key's real Secure Enclave + // protection: it is a version-skew guard between this module and the + // TypeScript it ships with, so a mismatch means the two disagree about + // the closed set, not that a key was inspected and found wanting. No + // Keychain/Security API exposes the true `SecAccessControl` of an + // existing key on iOS, so daa-ios-sdk's public `SecureKey` has no real + // readback to expose here even in principle. + Function("declaredKeyPolicy") { () -> [String: Any] in + [ + "hardwareBacked": true, + "userVerification": "REQUIRED_FOR_EACH_SIGNATURE", + ] + } + + AsyncFunction("resolveOrCreate") { (appId: String, environment: String) async throws -> String in + do { + let key = try await cache.secureKey(appId: appId, environment: environment) + let resolution = try await key.resolveOrCreate() + switch resolution { + case .created: + return "created" + case .existing: + return "existing" + } + } catch { + throw mappedSecureKeyException(error) + } + } + + AsyncFunction("publicKeySpkiBase64Url") { (appId: String, environment: String) async throws -> String in + do { + let key = try await cache.secureKey(appId: appId, environment: environment) + return try await key.publicKeySPKIBase64URL() + } catch { + throw mappedSecureKeyException(error) + } + } + + // Reached from OwnerAuthKey.acknowledgeRegistration() via the TS bridge. + // This is the only registration-ack entry point; do not add a parallel one. + AsyncFunction("acknowledgeRegistration") { (appId: String, environment: String) async throws in + do { + let key = try await cache.secureKey(appId: appId, environment: environment) + try await key.acknowledgeRegistration() + } catch { + throw mappedSecureKeyException(error) + } + } + + // Typed native signDeviceAuthorization — not a generic sign(bytes). The + // Base64URL payload is the exact compact-JWS signing input already built in + // TypeScript; native validates those bytes and signs that same slice. + // There is no prompt argument: DaaSdk sets all of the Face ID / Touch ID + // text from the validated operation, and nothing here can change it. + AsyncFunction("signDeviceAuthorization") { ( + appId: String, + environment: String, + signingInputBase64Url: String + ) async throws -> String in + do { + let exactBytes = try decodeUnpaddedBase64URL(signingInputBase64Url) + let signingInput = try DaaDeviceAuthorizationSigningInput(exactBytes: exactBytes) + let key = try await cache.secureKey(appId: appId, environment: environment) + let signature = try await key.signDeviceAuthorization(signingInput: signingInput) + return unpaddedBase64URL(signature) + } catch { + throw mappedSecureKeyException(error) + } + } + + // Typed native signRegistrationDeviceAuthorization — the registration + // counterpart of signDeviceAuthorization above, NOT the same call. The + // Base64URL payload is the exact Device Registration Complete device-proof + // signing input from `auth/registrationAuthorization.ts`; it is validated + // by DaaRegistrationAuthorizationSigningInput, a different validator from + // DaaDeviceAuthorizationSigningInput (registration `typ`s, an embedded + // JWK header, no acknowledged-key gate). Do not route this input through + // signDeviceAuthorization above, and do not route that input through here. + // Like signDeviceAuthorization, it takes no prompt: DaaSdk shows its own + // device-registration prompt text. + AsyncFunction("signRegistrationDeviceAuthorization") { ( + appId: String, + environment: String, + signingInputBase64Url: String + ) async throws -> String in + do { + let exactBytes = try decodeUnpaddedBase64URL(signingInputBase64Url) + let signingInput = try DaaRegistrationAuthorizationSigningInput(exactBytes: exactBytes) + let key = try await cache.secureKey(appId: appId, environment: environment) + let signature = try await key.signRegistrationDeviceAuthorization(signingInput: signingInput) + return unpaddedBase64URL(signature) + } catch { + throw mappedSecureKeyException(error) + } + } + } +} + +private actor SecureKeyCache { + private var keys: [String: DaaSecureKey] = [:] + private var installationID: UUID? + + func secureKey(appId: String, environment raw: String) throws -> DaaSecureKey { + guard let environment = DaaEnvironment(rawValue: raw) else { + throw ContractViolationException() + } + let alias = "\(appId).\(environment.rawValue)" + if let existing = keys[alias] { + return existing + } + let identity = try DaaAuthKeyIdentity( + appID: appId, + environment: environment, + installationID: try installationUUID() + ) + let key = DaaSecureKey(identity: identity) + keys[alias] = key + return key + } + + private func installationUUID() throws -> UUID { + if let installationID { + return installationID + } + let id: UUID + do { + id = try InstallationIdentityStore.live().loadOrCreate() + } catch { + throw ContractViolationException() + } + installationID = id + return id + } +} diff --git a/ios/InstallationIdentityStore.swift b/ios/InstallationIdentityStore.swift new file mode 100644 index 0000000..de12f94 --- /dev/null +++ b/ios/InstallationIdentityStore.swift @@ -0,0 +1,126 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation + +// Durable per-install UUID for DaaAuthKeyIdentity.installationID. +// Native docs: the caller persists the UUID; a new install gets a new UUID. +// +// Stored as a file in the app container's Application Support directory, +// excluded from backup. The container survives app updates and is deleted +// when the app is deleted, so a reinstall mints a new UUID and therefore a +// new Enclave AuthKey — the same lifetime Android gets from noBackupFilesDir. +// Excluding it from backup keeps a restore onto another device (or the same +// device after an erase) from carrying the UUID over. UserDefaults is not +// used because it is always included in backups. The Keychain is not used +// because iOS does not reliably purge it when the app is deleted. +// +// Keys minted under an earlier installation UUID stay in this app's Keychain +// access group: they are unreachable from this store, and they are not +// deleted here or revoked at Circle. + +enum InstallationIdentityStoreError: Error, Equatable { + case applicationSupportUnavailable + case unreadable + case unwritable +} + +struct InstallationIdentityStore { + static let fileName = "installation-id.v1" + private static let directoryName = "com.circle.daa.reactnative" + // Process-wide: concurrent first runs must not each write a different UUID. + private static let lock = NSLock() + + let directory: URL + + static func live() throws -> InstallationIdentityStore { + guard let applicationSupport = try? FileManager.default.url( + for: .applicationSupportDirectory, + in: .userDomainMask, + appropriateFor: nil, + create: true + ) else { + throw InstallationIdentityStoreError.applicationSupportUnavailable + } + return InstallationIdentityStore( + directory: applicationSupport.appendingPathComponent(directoryName, isDirectory: true) + ) + } + + func loadOrCreate() throws -> UUID { + Self.lock.lock() + defer { Self.lock.unlock() } + + let file = directory.appendingPathComponent(Self.fileName, isDirectory: false) + if let existing = try read(file) { + return existing + } + let id = UUID() + try write(id, to: file) + return id + } + + private func read(_ file: URL) throws -> UUID? { + guard FileManager.default.fileExists(atPath: file.path) else { + return nil + } + let data: Data + do { + data = try Data(contentsOf: file) + } catch { + // Present but unreadable (for example before the first unlock after + // boot): fail and let the next call retry. Never remint over it. + throw InstallationIdentityStoreError.unreadable + } + guard let string = String(data: data, encoding: .utf8), + let id = UUID(uuidString: string.trimmingCharacters(in: .whitespacesAndNewlines)) + else { + // Malformed file: delete and remint. The previous Enclave key is not + // deleted and is not revoked at Circle. This keeps resolveOrCreate + // usable; it is not equivalent to an uninstall. + do { + try FileManager.default.removeItem(at: file) + } catch { + throw InstallationIdentityStoreError.unwritable + } + return nil + } + return id + } + + private func write(_ id: UUID, to file: URL) throws { + do { + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try Self.excludeFromBackup(directory) + try Data(id.uuidString.lowercased().utf8).write( + to: file, + options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication] + ) + // The atomic write replaces the file, so mark the file itself as well + // as its directory. + try Self.excludeFromBackup(file) + } catch { + throw InstallationIdentityStoreError.unwritable + } + } + + private static func excludeFromBackup(_ url: URL) throws { + var url = url + var values = URLResourceValues() + values.isExcludedFromBackup = true + try url.setResourceValues(values) + } +} diff --git a/ios/Tests/main.swift b/ios/Tests/main.swift new file mode 100644 index 0000000..2548226 --- /dev/null +++ b/ios/Tests/main.swift @@ -0,0 +1,124 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +// Host-side tests for InstallationIdentityStore, built with swiftc on macOS +// outside the pod (`yarn test:ios-native`, or +// `xcrun swiftc ios/InstallationIdentityStore.swift ios/Tests/main.swift` +// and run the output). Not part of the pod or the npm package: the store +// has no ExpoModulesCore or DaaSdk dependency. Uninstall/reinstall itself +// can only be checked on a device. + +import Foundation + +var failures = 0 + +func check(_ condition: @autoclosure () -> Bool, _ message: String, line: Int = #line) { + if !condition() { + failures += 1 + print("FAIL (line \(line)): \(message)") + } +} + +func freshDirectory() -> URL { + FileManager.default.temporaryDirectory + .appendingPathComponent("installation-identity-tests-\(UUID().uuidString)", isDirectory: true) +} + +func fileURL(_ directory: URL) -> URL { + directory.appendingPathComponent(InstallationIdentityStore.fileName) +} + +func contents(_ directory: URL) -> String? { + try? String(contentsOf: fileURL(directory), encoding: .utf8) +} + +func test(_ name: String, _ body: () throws -> Void) { + do { + try body() + print("ok - \(name)") + } catch { + failures += 1 + print("FAIL: \(name) threw \(error)") + } +} + +test("new install mints a UUID and persists it, excluded from backup") { + let directory = freshDirectory() + let store = InstallationIdentityStore(directory: directory) + let id = try store.loadOrCreate() + check(contents(directory) == id.uuidString.lowercased(), "file holds the minted UUID") + let excluded = try fileURL(directory).resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup + check(excluded == true, "file is excluded from backup") + let directoryExcluded = try directory.resourceValues(forKeys: [.isExcludedFromBackupKey]).isExcludedFromBackup + check(directoryExcluded == true, "directory is excluded from backup") +} + +test("load returns the persisted UUID on later runs") { + let directory = freshDirectory() + let first = try InstallationIdentityStore(directory: directory).loadOrCreate() + let second = try InstallationIdentityStore(directory: directory).loadOrCreate() + check(first == second, "same UUID across store instances (app update / restart)") +} + +test("an emptied container (reinstall) mints a new UUID") { + let directory = freshDirectory() + let first = try InstallationIdentityStore(directory: directory).loadOrCreate() + try FileManager.default.removeItem(at: directory) + let second = try InstallationIdentityStore(directory: directory).loadOrCreate() + check(first != second, "reinstall gets a different UUID") +} + +test("a malformed file is replaced by a new UUID") { + let directory = freshDirectory() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + try Data("not-a-uuid".utf8).write(to: fileURL(directory)) + let id = try InstallationIdentityStore(directory: directory).loadOrCreate() + check(contents(directory) == id.uuidString.lowercased(), "file rewritten with the new UUID") +} + +test("an unreadable file throws and is left in place") { + let directory = freshDirectory() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + // A directory at the file's path cannot be read as data. + try FileManager.default.createDirectory(at: fileURL(directory), withIntermediateDirectories: true) + var thrown: Error? + do { + _ = try InstallationIdentityStore(directory: directory).loadOrCreate() + } catch { + thrown = error + } + check((thrown as? InstallationIdentityStoreError) == .unreadable, "throws unreadable") + check(FileManager.default.fileExists(atPath: fileURL(directory).path), "not removed") +} + +test("concurrent first runs agree on one UUID") { + let directory = freshDirectory() + let resultsLock = NSLock() + var results: [UUID?] = [] + DispatchQueue.concurrentPerform(iterations: 16) { _ in + let id = try? InstallationIdentityStore(directory: directory).loadOrCreate() + resultsLock.lock() + results.append(id) + resultsLock.unlock() + } + check(results.count == 16 && Set(results).count == 1 && results[0] != nil, "all callers got the same UUID") +} + +if failures > 0 { + print("\(failures) failure(s)") + exit(1) +} +print("all passed") diff --git a/ios/UnpaddedBase64URL.swift b/ios/UnpaddedBase64URL.swift new file mode 100644 index 0000000..f7dc793 --- /dev/null +++ b/ios/UnpaddedBase64URL.swift @@ -0,0 +1,42 @@ +// Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. +// +// SPDX-License-Identifier: Apache-2.0 +// +// Licensed under the Apache License, Version 2.0 (the "License"); +// you may not use this file except in compliance with the License. +// You may obtain a copy of the License at +// +// http://www.apache.org/licenses/LICENSE-2.0 +// +// Unless required by applicable law or agreed to in writing, software +// distributed under the License is distributed on an "AS IS" BASIS, +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +// See the License for the specific language governing permissions and +// limitations under the License. + +import Foundation + +// Shared by DaaSecureKey and DaaRegistration. One canonicalization so a +// round-trip check on the signing-input decoder cannot drift from encode. + +func unpaddedBase64URL(_ data: Data) -> String { + data.base64EncodedString() + .replacingOccurrences(of: "+", with: "-") + .replacingOccurrences(of: "/", with: "_") + .replacingOccurrences(of: "=", with: "") +} + +func decodeUnpaddedBase64URL(_ encoded: String) throws -> Data { + guard encoded.count % 4 != 1 else { + throw ContractViolationException() + } + let padding = String(repeating: "=", count: (4 - encoded.count % 4) % 4) + let standard = encoded + .replacingOccurrences(of: "-", with: "+") + .replacingOccurrences(of: "_", with: "/") + guard let decoded = Data(base64Encoded: standard + padding), + unpaddedBase64URL(decoded) == encoded else { + throw ContractViolationException() + } + return decoded +} diff --git a/jest.config.js b/jest.config.js new file mode 100644 index 0000000..d6b569b --- /dev/null +++ b/jest.config.js @@ -0,0 +1,97 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +const fs = require('fs') +const path = require('path') + +/** + * Separate projects, deliberately. + * + * The DAA core is plain TypeScript with no React in it, and its several hundred + * tests run in a bare node environment in a couple of seconds. The onboarding + * widget (`packages/onboarding`, its own npm package) needs React Native's Babel + * transform, its jest preset, and a DOM-ish renderer — all of which are slower and + * none of which the core has any use for. Splitting them keeps the core suite + * fast, and keeps a React Native transform from being imposed on files that do + * not need it. Onboarding's own React-free + * logic (the machine, decoders, launchers, poll loop) runs under ts-jest in node, + * like the core. + * + * A project or root is added only when its directory exists. Jest fails at + * startup on a root that does not. + */ + +const exists = (dir) => fs.existsSync(path.join(__dirname, dir)) + +const ONBOARDING = '/packages/onboarding' + +/** @type {import('jest').Config} */ +const core = { + displayName: 'core', + preset: 'ts-jest', + testEnvironment: 'node', + // `example/plugins` is a second root rather than a second Jest project or a + // runner of its own under `example/`: the config-plugin tests need no Expo + // install and no build step, so folding them in here means `yarn test:ci` + // covers them, with no new script, workflow, or lockfile to keep in step. + roots: ['/src', ...(exists('example/plugins') ? ['/example/plugins'] : [])], + // The SDK's tests are TypeScript; the harness's config plugins and their + // tests are JavaScript, because Expo requires the plugins by path at prebuild + // time and `example/` is outside the TypeScript program on purpose. + testMatch: ['**/__test__/**/*.test.ts', '**/__test__/**/*.test.js'], + moduleNameMapper: { + // `expo` is an optional peer dependency and is installed only in + // `example/node_modules`, so the plugins' own import cannot resolve from + // here. See example/plugins/__test__/support/expoConfigPlugins.js. + '^expo/config-plugins$': '/example/plugins/__test__/support/expoConfigPlugins.js', + }, + setupFiles: ['/jest.setup.js'], + clearMocks: true, +} + +/** @type {import('jest').Config} */ +const onboarding = { + displayName: 'onboarding', + testEnvironment: 'node', + roots: [`${ONBOARDING}/src`], + testMatch: ['**/__test__/**/*.test.ts'], + // The package has its own tsconfig (its `include` is its own `src`), so point + // ts-jest at it rather than letting it pick up the root one. + transform: { + '^.+\\.tsx?$': ['ts-jest', { tsconfig: `${ONBOARDING}/tsconfig.json` }], + }, + clearMocks: true, +} + +/** @type {import('jest').Config} */ +const onboardingUi = { + displayName: 'onboarding-ui', + // Carries the `react-native` moduleNameMapper this project needs. Jest MERGES a + // preset's mapper into the project's rather than replacing it (`setupPreset` in + // jest-config's normalize), so there is nothing to re-declare here — a local + // `moduleNameMapper` would only need to name the entries it ADDS. + preset: '@react-native/jest-preset', + roots: [`${ONBOARDING}/src`], + testMatch: ['**/__test__/**/*.test.tsx'], + setupFilesAfterEnv: [`${ONBOARDING}/jest.setup.js`], + clearMocks: true, +} + +module.exports = { + projects: [core, ...(exists('packages/onboarding') ? [onboarding, onboardingUi] : [])], +} diff --git a/jest.setup.js b/jest.setup.js new file mode 100644 index 0000000..e2e38e8 --- /dev/null +++ b/jest.setup.js @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Test-only: ensure a WebCrypto implementation is available on globalThis so the +// in-memory secure-key test double (P-256/ES256) works in the Jest node +// environment. Production/native code never imports node:crypto. +const { webcrypto } = require('node:crypto') + +if (!globalThis.crypto) { + globalThis.crypto = webcrypto +} + +// Node has no Expo native module. Tests get a WebCrypto-backed fake for +// `DaaRegistration` (randomness, flow key, receipt signature verification) so +// production code can require the module without a silent JS fallback. +// `DaaSecureKey` stays absent unless a test injects it. +jest.mock('expo-modules-core', () => { + const { generateKeyPairSync: generateEc, webcrypto: crypto } = require('node:crypto') + const flowKeys = new Map() + const jestDaaRegistration = { + randomBytes(count) { + const buf = crypto.getRandomValues(new Uint8Array(count)) + return Buffer.from(buf).toString('base64url') + }, + randomUuidV4() { + return crypto.randomUUID() + }, + generateRegistrationFlowKey() { + const { publicKey } = generateEc('ec', { namedCurve: 'prime256v1' }) + const spki = publicKey.export({ type: 'spki', format: 'der' }) + const id = crypto.randomUUID() + flowKeys.set(id, Buffer.from(spki).toString('base64url')) + return id + }, + registrationFlowPublicKeySpkiBase64Url(id) { + const encoded = flowKeys.get(id) + if (typeof encoded !== 'string') { + throw new Error(`no flow key ${id}`) + } + return encoded + }, + releaseRegistrationFlowKey(id) { + flowKeys.delete(id) + }, + // Stand-in for native DaaPrepareReceiptSignature verification, with the same + // contract: an uncompressed P-256 point the platform must accept (WebCrypto + // rejects an off-curve point on import), exactly 64 bytes of JOSE R || S, + // and a boolean result. + async verifyPrepareReceiptSignature(publicKeyX963, signingInput, signature) { + const point = Buffer.from(publicKeyX963, 'base64url') + if (point.length !== 65 || point[0] !== 0x04) { + throw new Error('not an uncompressed P-256 point') + } + const rs = Buffer.from(signature, 'base64url') + if (rs.length !== 64) { + return false + } + const key = await crypto.subtle.importKey( + 'raw', + point, + { name: 'ECDSA', namedCurve: 'P-256' }, + false, + ['verify'], + ) + return crypto.subtle.verify( + { name: 'ECDSA', hash: 'SHA-256' }, + key, + rs, + Buffer.from(signingInput, 'base64url'), + ) + }, + } + return { + requireOptionalNativeModule: jest.fn((name) => { + if (name === 'DaaRegistration') { + return jestDaaRegistration + } + return null + }), + } +}) diff --git a/package.json b/package.json new file mode 100644 index 0000000..8026eeb --- /dev/null +++ b/package.json @@ -0,0 +1,116 @@ +{ + "name": "@circle-fin/daa-react-native-sdk", + "version": "0.4.0", + "description": "React Native SDK for Digital Asset Accounts (DAA) — attested authentication and self-custody DAA API access", + "main": "build/index.js", + "source": "src/index.ts", + "types": "build/index.d.ts", + "exports": { + ".": { + "types": "./build/index.d.ts", + "default": "./build/index.js" + }, + "./testing": { + "types": "./build/testing.d.ts", + "default": "./build/testing.js" + }, + "./package.json": "./package.json" + }, + "license": "Apache-2.0", + "homepage": "https://github.com/circlefin/daa-react-native-sdk", + "repository": { + "type": "git", + "url": "https://github.com/circlefin/daa-react-native-sdk.git" + }, + "//private": "The release workflows set private to false when they publish, so a local npm publish cannot run by accident.", + "private": true, + "author": "", + "packageManager": "yarn@1.22.22", + "engines": { + "node": ">=22" + }, + "scripts": { + "build": "tsc -p tsconfig.build.json", + "build:onboarding": "tsc -p packages/onboarding/tsconfig.build.json", + "prepack": "yarn build", + "test": "jest", + "test:ci": "jest --ci --runInBand", + "check:type": "tsc --noEmit && { [ ! -d packages/onboarding ] || tsc --noEmit -p packages/onboarding; }", + "lint": "eslint .", + "format": "prettier --write .", + "format:check": "prettier --check .", + "check:license": "bash scripts/check-license-headers.sh", + "test:ios-native": "bash scripts/test-ios-native.sh" + }, + "files": [ + "build", + "src", + "ios", + "android", + "expo-module.config.json", + "DaaReactNativeSdk.podspec", + "testing.js", + "testing.d.ts", + "README.md", + "!**/__test__", + "!**/*.test.ts", + "!android/build/", + "!android/.gradle/", + "!ios/Pods/", + "!ios/build/", + "!ios/Tests/" + ], + "keywords": [ + "react-native", + "circle", + "daa", + "digital-asset-accounts", + "usdc", + "self-custody", + "attested" + ], + "peerDependencies": { + "expo": ">=54.0.0", + "expo-modules-core": ">=3.0.0", + "react": ">=18.0.0", + "react-native": ">=0.81.0" + }, + "peerDependenciesMeta": { + "expo": { + "optional": true + }, + "expo-modules-core": { + "optional": true + } + }, + "devDependencies": { + "@cyclonedx/cyclonedx-npm": "6.0.1", + "@sumsub/react-native-mobilesdk-module": "1.46.1", + "@react-native/babel-preset": "0.85.3", + "@react-native/jest-preset": "0.85.3", + "@testing-library/react-native": "14.0.1", + "@types/jest": "29.5.14", + "@types/react": "19.2.3", + "babel-jest": "29.7.0", + "eslint": "^9.39.0", + "eslint-config-prettier": "^10.1.8", + "eslint-plugin-react-hooks": "^7.1.1", + "expo-modules-core": "~3.0.29", + "jest": "^29.7.0", + "prettier": "^3.6.2", + "react": "19.2.3", + "react-native": "0.85.3", + "react-native-persona": "2.48.0", + "test-renderer": "^1.0.0", + "ts-jest": "^29.4.5", + "typescript": "^5.9.3", + "typescript-eslint": "^8.38.0" + }, + "resolutions": { + "**/@eslint/eslintrc/js-yaml": "^4.3.2", + "**/@istanbuljs/load-nyc-config/js-yaml": "^3.15.2", + "typescript-eslint/**/brace-expansion": "5.0.12", + "@cyclonedx/cyclonedx-npm/**/brace-expansion": "2.1.7", + "**/minimatch/brace-expansion": "1.1.21" + } +} diff --git a/src/DaaClient.ts b/src/DaaClient.ts new file mode 100644 index 0000000..b0201c1 --- /dev/null +++ b/src/DaaClient.ts @@ -0,0 +1,171 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AuthClient } from './api/AuthClient' +import { createDaaUserClient, type DaaUserClient } from './api/DaaUserClient' +import { assertDeviceKeyPolicy, assertPublicApiOrigin, DAA_ENVIRONMENTS } from './config' +import type { DaaEnvironment, DaaSdkConfiguration, DeviceKeyPolicy } from './config' +import { contractViolation } from './errors' +import { + assertAuthKeyMatchesContext, + isActiveDaaUserContext, + type DaaUserContext, +} from './models/DaaUserContext' +import { + createOwnerAuthKeyResolver, + type AppAuthKeyResolver, +} from './securekey/ownerAuthKeyResolver' +import { assertAppId } from './securekey/alias' +import { assertNativeModuleKeyPolicyIfPresent } from './securekey/resolveNativeBridge' +import type { DaaTransport } from './transport/DaaTransport' + +/** + * Root DAA client. + * + * `auth.prepareSocialLogin` starts the three-call login. Social Session and + * Device Registration Complete live on the values that returns. `forUser` + * opens the authenticated operations surface only for an `ACTIVE` + * `DaaUserContext`. + */ +export class DaaClient { + readonly #config: DaaSdkConfiguration + /** The validated `publicApiOrigin`, or `undefined` for the environment's origin. */ + readonly #publicApiOrigin: string | undefined + readonly #auth: AuthClient + /** + * One resolver for the installation AuthKey, shared by login and `forUser`. + * Takes the Owner's `clientEntityId` per call rather than baking + * one in, since this `DaaClient` may serve more than one Owner over its + * lifetime. + * + * Held here rather than inside `AuthClient` because both need it and neither + * may hand it to a consumer: `AuthClient` is reachable as `client.auth`, so an + * `OwnerAuthKey` returned from a method on it would be a generic signing + * surface. This field is `#`-private, so it is reachable from `forUser` and + * from nowhere else. + */ + readonly #authKeys: AppAuthKeyResolver + + constructor(config: DaaSdkConfiguration) { + if (!config.appId) { + throw new Error('DAA: appId is required') + } + if (!config.transport) { + throw new Error('DAA: transport is required') + } + if (!(DAA_ENVIRONMENTS as readonly string[]).includes(config.environment)) { + throw new Error( + `DAA: unknown environment "${config.environment}"; expected one of ${DAA_ENVIRONMENTS.join(', ')}`, + ) + } + // The key-namespace limits, checked here rather than first on key + // resolution: that runs after Social Session, so a bad appId would fail + // only once the service had bound the end user. After the presence checks, + // so a missing field is reported first. + assertAppId(config.appId) + const publicApiOrigin = assertPublicApiOrigin(config.environment, config.publicApiOrigin) + const keyPolicy = assertDeviceKeyPolicy(config.keyPolicy) + // When DaaSecureKey is present, fail closed if it declares a weaker policy + // than the configured closed set. Absent (Node / Jest) is not a pass — + // resolveNativeBridge() still checks on first AuthKey use. + assertNativeModuleKeyPolicyIfPresent(keyPolicy) + this.#config = Object.freeze({ ...config, keyPolicy }) + this.#publicApiOrigin = publicApiOrigin + // Built eagerly, but it resolves nothing until something asks: the Expo + // DaaSecureKey module is reached on first resolution, so constructing a + // DaaClient still does not require it. + this.#authKeys = createOwnerAuthKeyResolver( + { appId: config.appId, environment: config.environment }, + null, + ) + // Constructed eagerly. Prepare needs no AuthKey and no DaaSecureKey. The + // Expo DaaRegistration module (CSPRNG, flow key, receipt signature + // verification) is resolved on first prepare, not here — matching + // randomBytes / randomUuidV4. A host missing that module fails closed at + // login. Jest injects a fake. AuthKey selection is lazy on Social Session. + this.#auth = new AuthClient({ + transport: config.transport, + authKeys: this.#authKeys, + environment: config.environment, + }) + } + + get appId(): string { + return this.#config.appId + } + + get environment(): DaaEnvironment { + return this.#config.environment + } + + get transport(): DaaTransport { + return this.#config.transport + } + + get keyPolicy(): DeviceKeyPolicy { + return this.#config.keyPolicy + } + + /** Starts one social-login attempt (Prepare). */ + get auth(): AuthClient { + return this.#auth + } + + /** + * The authenticated operations surface for one user. + * + * Opens only for an `ACTIVE` `DaaUserContext` decoded from Device Registration + * Complete. A fabricated object, a `RECOVERY_PENDING` result, or a missing + * context fail closed — they are not an Owner-bound credential. + * + * The context is carried into the surface rather than only checked at the + * door. `deviceContext.authKeyId` is the `kid` every signed write's + * `X-Device-Authorization` announces, and the AuthKey it names is re-resolved + * by the `{appId, environment}` alias login already used, together with + * THIS context's own `clientEntityId` — the key itself is + * enclave-held and is not a field on a decoded server result. Validating the + * context and then dropping it would leave this surface with no credential + * to sign with at all. + */ + forUser(context: DaaUserContext): DaaUserClient { + if (!isActiveDaaUserContext(context)) { + throw contractViolation( + 'forUser requires an ACTIVE DaaUserContext from Device Registration Complete', + ) + } + // Bound to this context's clientEntityId now, once, rather than passed + // through: `DaaUserSigning.resolveAuthKey` is a zero-arg + // `OwnerAuthKeyResolver` (api/signedResource.ts) because a resource client + // has no Owner concept of its own — it only ever signs for the user this + // `forUser` call already validated. + const clientEntityId = context.clientEntityId + return createDaaUserClient( + this.#config.transport, + this.#config.environment, + { + resolveAuthKey: async () => { + const authKey = await this.#authKeys(clientEntityId) + await assertAuthKeyMatchesContext(context, authKey) + return authKey + }, + authKeyId: context.deviceContext.authKeyId, + }, + this.#publicApiOrigin, + ) + } +} diff --git a/src/__test__/accountLimitsClient.test.ts b/src/__test__/accountLimitsClient.test.ts new file mode 100644 index 0000000..7ec4a94 --- /dev/null +++ b/src/__test__/accountLimitsClient.test.ts @@ -0,0 +1,376 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The account limits/usage read, end to end through the client: request + * shape, query serialization, envelope, decoding, and status mapping. + * Mirrors `accountsClient.test.ts` and `depositsClient.test.ts`. + * + * The public API reference + * (https://developers.circle.com/api-reference/digital-asset-accounts/all/list-account-limits-usage) + * is the source of truth these tests pin. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const ACCOUNT_ID = '1000662322' + +/** A complete transaction-limit item: every field a `comparisonType: transaction` row carries. */ +const TRANSACTION_ITEM = + '{"operation":"withdrawal","assetType":"fiat","comparisonType":"transaction",' + + '"unit":"usd_cents","effectiveThreshold":5000000}' + +/** A complete aggregation-limit item: every field the public reference documents. */ +const AGGREGATION_ITEM = + '{"operation":"send","assetType":"crypto","comparisonType":"aggregation","window":"PT24H",' + + '"unit":"usd_cents","effectiveThreshold":1000000,"currentAggregate":1234567,"usagePercent":24.69}' + +const COMPLETE_LIMITS_USAGE = + `{"type":"limitsUsage","accountId":"${ACCOUNT_ID}","currency":"USD",` + + `"watermark":"2026-05-12T10:29:58.000Z","items":[${TRANSACTION_ITEM},${AGGREGATION_ITEM}]}` + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + accountLimits: ReturnType['accountLimits'] + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { + accountLimits: createDaaUserClient(transport, 'production', NO_SIGNING).accountLimits, + transport, + } +} + +function okClient(payload = COMPLETE_LIMITS_USAGE) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + it('reads account limits/usage over the public path with no query by default', async () => { + const { accountLimits, transport } = okClient() + + const usage = await accountLimits.get(ACCOUNT_ID) + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.method).toBe('GET') + expect(sent.path).toBe(`/v1/accounts/${ACCOUNT_ID}/limits/usage`) + expect(sent.query).toBeNull() + expect(sent.bodyBytes).toBeNull() + expect(sent.headers).toEqual({}) + expect(usage.accountId).toBe(ACCOUNT_ID) + expect(usage.currency).toBe('USD') + }) + + it('accepts every accountId length the documented pattern allows', async () => { + for (const good of ['1', '12', '1234567890']) { + const { accountLimits, transport } = okClient() + await accountLimits.get(good) + expect(transport.sent[0]?.path).toBe(`/v1/accounts/${good}/limits/usage`) + } + }) + + /** + * The public reference documents this path parameter as `^\d{1,10}$` — + * stricter than `AccountsClient.get`'s broader path-segment guard. An + * accountId that would address a different route, one with too many + * digits, or one that is not purely numeric is all rejected locally. + */ + it('rejects an accountId that does not match the documented numeric pattern', async () => { + const { accountLimits, transport } = okClient() + + for (const bad of [ + '', + '01234567890', // 11 digits + '12345678901', // 11 digits + 'acct-1', + '1000662322/transfers', + '1000662322/', + '/1000662322', + '1000662322%2Ftransfers', + '1000662322?x=1', + '1000662322#frag', + ' 1000662322', + '1000662322 ', + '1000662322\r\nX-Injected: 1', + '-1', + '1.0', + '1e5', + ]) { + const detail = await detailOf(accountLimits.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + describe('query serialization', () => { + it('sends no query when none is supplied', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID) + expect(transport.sent[0]?.query).toBeNull() + }) + + it('sends no query for an explicitly empty query object', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, {}) + expect(transport.sent[0]?.query).toBeNull() + }) + + it('serializes operation alone', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { operation: 'fiat_linking' }) + expect(transport.sent[0]?.query).toBe('operation=fiat_linking') + }) + + it('serializes assetType alone', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { assetType: 'crypto' }) + expect(transport.sent[0]?.query).toBe('assetType=crypto') + }) + + it('serializes window alone', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { window: 'P30D' }) + expect(transport.sent[0]?.query).toBe('window=P30D') + }) + + it('serializes all three filters together in one deterministic order', async () => { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { + operation: 'withdrawal', + assetType: 'fiat', + window: 'PT24H', + }) + expect(transport.sent[0]?.query).toBe('operation=withdrawal&assetType=fiat&window=PT24H') + }) + + it('accepts every documented operation value', async () => { + for (const operation of [ + 'deposit', + 'withdrawal', + 'receive', + 'send', + 'send_count', + 'address_linking', + 'fiat_linking', + 'deposit_return_count', + 'balance_cap', + ] as const) { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { operation }) + expect(transport.sent[0]?.query).toBe(`operation=${operation}`) + } + }) + + it('accepts both documented window values', async () => { + for (const window of ['PT24H', 'P30D'] as const) { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { window }) + expect(transport.sent[0]?.query).toBe(`window=${window}`) + } + }) + + it('rejects an unsupported operation value without sending a request', async () => { + const { accountLimits, transport } = okClient() + const detail = await detailOf( + accountLimits.get(ACCOUNT_ID, { + operation: 'wire' as unknown as 'deposit', + }), + ) + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('rejects an unsupported window value without sending a request', async () => { + const { accountLimits, transport } = okClient() + const detail = await detailOf( + accountLimits.get(ACCOUNT_ID, { window: 'P7D' as unknown as 'P30D' }), + ) + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + /** + * The API rejects `window=PT24H` combined with + * `operation=fiat_linking`/`deposit_return_count` server-side (a `400`). + * This SDK does not pre-validate that combination locally — see + * `AccountLimitsClient`'s class note — so the request still goes out and + * the service's rejection surfaces as an ordinary `api` failure. + */ + it('does not pre-validate the window=PT24H + fiat_linking/deposit_return_count combination', async () => { + for (const operation of ['fiat_linking', 'deposit_return_count'] as const) { + const { accountLimits, transport } = okClient() + await accountLimits.get(ACCOUNT_ID, { operation, window: 'PT24H' }) + expect(transport.sent[0]?.query).toBe(`operation=${operation}&window=PT24H`) + } + }) + + it('rejects a non-object query', async () => { + const { accountLimits, transport } = okClient() + const detail = await detailOf(accountLimits.get(ACCOUNT_ID, null as unknown as undefined)) + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + }) +}) + +describe('the success path', () => { + it('rejects undocumented 2xx statuses as API failures', async () => { + for (const status of [201, 204, 299]) { + const { accountLimits } = clientFor({ status, bodyBytes: envelope(COMPLETE_LIMITS_USAGE) }) + expect(await detailOf(accountLimits.get(ACCOUNT_ID))).toMatchObject({ + kind: 'api', + httpStatus: status, + }) + } + }) + + it('rejects a body whose payload sits at the root instead of the envelope', async () => { + const { accountLimits } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes(COMPLETE_LIMITS_USAGE), + }) + + expect(await detailOf(accountLimits.get(ACCOUNT_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-2', + }) + }) + + it('rejects an empty envelope, an empty body, and no body at all', async () => { + for (const bodyBytes of [bytes('{"data":null}'), bytes(''), null]) { + const { accountLimits } = clientFor({ status: 200, bodyBytes }) + expect((await detailOf(accountLimits.get(ACCOUNT_ID))).kind).toBe('contract_violation') + } + }) + + it('reports a response missing guaranteed fields as a broken contract with the correlation id', async () => { + const payloads = [ + '{}', + `{"type":"limitsUsage","accountId":"${ACCOUNT_ID}"}`, + `{"type":"limitsUsage","accountId":"${ACCOUNT_ID}","currency":"USD"}`, + `{"type":"limitsUsage","accountId":"${ACCOUNT_ID}","currency":"USD",` + + `"watermark":"2026-05-12T10:29:58.000Z"}`, + ] + + for (const payload of payloads) { + const { accountLimits } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-13' }, + bodyBytes: envelope(payload), + }) + expect(await detailOf(accountLimits.get(ACCOUNT_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-13', + }) + } + }) +}) + +describe('the failure path', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + for (const status of [400, 401, 404, 409, 500, 503]) { + const { accountLimits } = clientFor({ + status, + headers: { 'X-Request-Id': `req-${status}` }, + bodyBytes: bytes(`{"status":{"code":${status * 10},"message":"nope"}}`), + }) + + const detail = await detailOf(accountLimits.get(ACCOUNT_ID)) + expect(detail).toEqual({ + kind: 'api', + httpStatus: status, + daaStatusCode: status * 10, + retryable: status === 429 || status >= 500, + }) + } + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).accountLimits.get(ACCOUNT_ID), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) + +describe('reachability', () => { + it('is reached only through the internal user-client factory', () => { + const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, + } + const user = createDaaUserClient(transport, 'production', NO_SIGNING) + expect(typeof user.accountLimits.get).toBe('function') + expect(Object.isFrozen(user)).toBe(true) + expect(Object.isFrozen(user.accountLimits)).toBe(true) + }) +}) diff --git a/src/__test__/accountLimitsUsagePayload.test.ts b/src/__test__/accountLimitsUsagePayload.test.ts new file mode 100644 index 0000000..0eede0f --- /dev/null +++ b/src/__test__/accountLimitsUsagePayload.test.ts @@ -0,0 +1,380 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import { AccountLimitsUsage } from '../models/AccountLimitsUsage' +import { toAccountLimitsUsage } from '../wire/accountLimitsUsagePayload' +import { MalformedPayloadError } from '../wire/payload' + +/** + * Decoding tests for the account limits/usage model. These go through the + * real parse and mapping rather than constructing a payload object directly — + * the wire spellings, the number handling, and the required/optional line are + * the things under test. Mirrors `depositPayload.test.ts`. + * + * The public API reference + * (https://developers.circle.com/api-reference/digital-asset-accounts/all/list-account-limits-usage) + * is the source of truth these fixtures follow. + */ + +const ACCOUNT_ID = '1000662322' + +/** A transaction-limit item: window, currentAggregate, and usagePercent all absent. */ +const TRANSACTION_ITEM = + '{"operation":"withdrawal","assetType":"fiat","comparisonType":"transaction",' + + '"unit":"usd_cents","effectiveThreshold":5000000}' + +/** A count-based transaction-limit item, for the count unit. */ +const COUNT_ITEM = + '{"operation":"send_count","assetType":"crypto","comparisonType":"transaction",' + + '"unit":"count","effectiveThreshold":10}' + +/** An aggregation-limit item: every field the public reference documents. */ +const AGGREGATION_ITEM = + '{"operation":"send","assetType":"crypto","comparisonType":"aggregation","window":"PT24H",' + + '"unit":"usd_cents","effectiveThreshold":1000000,"currentAggregate":1234567,"usagePercent":24.69}' + +const REQUIRED = + `"type":"limitsUsage","accountId":"${ACCOUNT_ID}","currency":"USD",` + + '"watermark":"2026-05-12T10:29:58.000Z"' + +function decode(body: string): AccountLimitsUsage { + return toAccountLimitsUsage(JSON.parse(body) as unknown) +} + +function decodeWithItems(items: string): AccountLimitsUsage { + return decode(`{${REQUIRED},"items":[${items}]}`) +} + +describe('required and optional fields', () => { + it('rejects a response missing any guaranteed top-level field', () => { + const complete: Record = { + type: '"limitsUsage"', + accountId: `"${ACCOUNT_ID}"`, + currency: '"USD"', + watermark: '"2026-05-12T10:29:58.000Z"', + items: `[${TRANSACTION_ITEM}]`, + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + // Sanity: the complete body decodes, or every assertion below is vacuous. + expect(decode(body(complete)).accountId).toBe(ACCOUNT_ID) + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toAccountLimitsUsage(null)).toThrow(MalformedPayloadError) + expect(() => toAccountLimitsUsage([])).toThrow(MalformedPayloadError) + }) + + it('rejects an items value that is not an array', () => { + expect(() => decode(`{${REQUIRED},"items":{}}`)).toThrow(MalformedPayloadError) + expect(() => decode(`{${REQUIRED},"items":"nope"}`)).toThrow(MalformedPayloadError) + expect(() => decode(`{${REQUIRED},"items":null}`)).toThrow(MalformedPayloadError) + }) + + it('accepts an empty items array', () => { + expect(decodeWithItems('').items).toEqual([]) + }) + + it('rejects an item missing a guaranteed field', () => { + const complete: Record = { + operation: '"withdrawal"', + assetType: '"fiat"', + comparisonType: '"transaction"', + unit: '"usd_cents"', + effectiveThreshold: '5000000', + } + const item = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + expect(decodeWithItems(item(complete)).items).toHaveLength(1) + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decodeWithItems(item(partial))).toThrow(MalformedPayloadError) + } + }) + + describe('a transaction-limit item', () => { + it('decodes with window, currentAggregate, and usagePercent all absent', () => { + const [item] = decodeWithItems(TRANSACTION_ITEM).items + expect(item?.window).toBeNull() + expect(item?.currentAggregate).toBeNull() + expect(item?.usagePercent).toBeNull() + expect(item?.comparisonType).toEqual({ kind: 'transaction' }) + }) + + it('does not require window, currentAggregate, or usagePercent regardless of comparisonType', () => { + // Nothing in the decoder branches on comparisonType — an aggregation + // item that (unusually) omits all three still decodes rather than + // throwing. See the doc comment on `toAccountLimitsUsageItem`. + const sparse = + '{"operation":"deposit","assetType":"fiat","comparisonType":"aggregation",' + + '"unit":"usd_cents","effectiveThreshold":100}' + const [item] = decodeWithItems(sparse).items + expect(item?.window).toBeNull() + expect(item?.currentAggregate).toBeNull() + expect(item?.usagePercent).toBeNull() + }) + }) + + describe('an aggregation-limit item', () => { + it('decodes every field present, unconverted from its documented unit', () => { + const [item] = decodeWithItems(AGGREGATION_ITEM).items + expect(item).toEqual({ + operation: { kind: 'send' }, + assetType: { kind: 'crypto' }, + comparisonType: { kind: 'aggregation' }, + window: { kind: 'PT24H' }, + unit: { kind: 'usd_cents' }, + effectiveThreshold: 1000000, + currentAggregate: 1234567, + usagePercent: 24.69, + }) + }) + + it('accepts the other documented window value', () => { + const [item] = decodeWithItems(AGGREGATION_ITEM.replace('PT24H', 'P30D')).items + expect(item?.window).toEqual({ kind: 'P30D' }) + }) + }) + + it('decodes a count-based item without converting the count', () => { + const [item] = decodeWithItems(COUNT_ITEM).items + expect(item?.unit).toEqual({ kind: 'count' }) + expect(item?.effectiveThreshold).toBe(10) + }) + + it('decodes a monetary (usd_cents) item as whole cents, not dollars', () => { + const [item] = decodeWithItems(TRANSACTION_ITEM).items + expect(item?.unit).toEqual({ kind: 'usd_cents' }) + expect(item?.effectiveThreshold).toBe(5000000) + }) + + it('decodes a full response carrying both a transaction and an aggregation item', () => { + const usage = decodeWithItems(`${TRANSACTION_ITEM},${AGGREGATION_ITEM}`) + expect(usage.items).toHaveLength(2) + expect(usage.items[0]?.comparisonType).toEqual({ kind: 'transaction' }) + expect(usage.items[1]?.comparisonType).toEqual({ kind: 'aggregation' }) + }) +}) + +describe('numeric fields', () => { + it('rejects effectiveThreshold sent as a string rather than a JSON number', () => { + expect(() => decodeWithItems(TRANSACTION_ITEM.replace('5000000', '"5000000"'))).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects a negative effectiveThreshold', () => { + expect(() => decodeWithItems(TRANSACTION_ITEM.replace('5000000', '-1'))).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects a non-integer effectiveThreshold', () => { + expect(() => decodeWithItems(TRANSACTION_ITEM.replace('5000000', '5000000.5'))).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects a negative currentAggregate', () => { + expect(() => + decodeWithItems( + AGGREGATION_ITEM.replace('"currentAggregate":1234567', '"currentAggregate":-1'), + ), + ).toThrow(MalformedPayloadError) + }) + + it('rejects a non-integer currentAggregate', () => { + expect(() => + decodeWithItems( + AGGREGATION_ITEM.replace('"currentAggregate":1234567', '"currentAggregate":1.5'), + ), + ).toThrow(MalformedPayloadError) + }) + + it('rejects a negative usagePercent', () => { + expect(() => + decodeWithItems(AGGREGATION_ITEM.replace('"usagePercent":24.69', '"usagePercent":-0.01')), + ).toThrow(MalformedPayloadError) + }) + + it('accepts a non-integer usagePercent (it is a decimal, not a count)', () => { + const [item] = decodeWithItems(AGGREGATION_ITEM).items + expect(item?.usagePercent).toBe(24.69) + }) + + it('accepts a zero effectiveThreshold, currentAggregate, and usagePercent', () => { + const zeroed = AGGREGATION_ITEM.replace('1000000', '0') + .replace('1234567', '0') + .replace('24.69', '0') + const [item] = decodeWithItems(zeroed).items + expect(item?.effectiveThreshold).toBe(0) + expect(item?.currentAggregate).toBe(0) + expect(item?.usagePercent).toBe(0) + }) +}) + +describe('closed-set fields', () => { + it('maps every documented operation and falls back for the rest', () => { + const operations = [ + 'deposit', + 'withdrawal', + 'receive', + 'send', + 'send_count', + 'address_linking', + 'fiat_linking', + 'deposit_return_count', + 'balance_cap', + ] + for (const operation of operations) { + const [item] = decodeWithItems(TRANSACTION_ITEM.replace('withdrawal', operation)).items + expect(item?.operation).toEqual({ kind: operation }) + } + + const [unknown] = decodeWithItems(TRANSACTION_ITEM.replace('withdrawal', 'teleport')).items + expect(unknown?.operation).toEqual({ kind: 'unrecognized', rawValue: 'teleport' }) + }) + + it('maps every documented assetType and falls back for the rest', () => { + expect(decodeWithItems(TRANSACTION_ITEM.replace('fiat', 'crypto')).items[0]?.assetType).toEqual( + { kind: 'crypto' }, + ) + const [unknown] = decodeWithItems(TRANSACTION_ITEM.replace('"fiat"', '"stablecoin"')).items + expect(unknown?.assetType).toEqual({ kind: 'unrecognized', rawValue: 'stablecoin' }) + }) + + it('maps every documented comparisonType and falls back for the rest', () => { + expect( + decodeWithItems(TRANSACTION_ITEM.replace('transaction', 'aggregation')).items[0] + ?.comparisonType, + ).toEqual({ kind: 'aggregation' }) + const [unknown] = decodeWithItems( + TRANSACTION_ITEM.replace('"transaction"', '"cumulative"'), + ).items + expect(unknown?.comparisonType).toEqual({ kind: 'unrecognized', rawValue: 'cumulative' }) + }) + + it('maps every documented unit and falls back for the rest', () => { + expect(decodeWithItems(COUNT_ITEM).items[0]?.unit).toEqual({ kind: 'count' }) + const [unknown] = decodeWithItems( + TRANSACTION_ITEM.replace('"usd_cents"', '"usd_dollars"'), + ).items + expect(unknown?.unit).toEqual({ kind: 'unrecognized', rawValue: 'usd_dollars' }) + }) + + it('maps every documented window and falls back for the rest', () => { + const [unknown] = decodeWithItems(AGGREGATION_ITEM.replace('"PT24H"', '"PT1H"')).items + expect(unknown?.window).toEqual({ kind: 'unrecognized', rawValue: 'PT1H' }) + }) + + it('maps the documented resource type and falls back for the rest', () => { + expect(decode(`{${REQUIRED},"items":[]}`).type).toEqual({ kind: 'limitsUsage' }) + const unknown = decode(`{${REQUIRED.replace('"limitsUsage"', '"somethingElse"')},"items":[]}`) + expect(unknown.type).toEqual({ kind: 'unrecognized', rawValue: 'somethingElse' }) + }) + + it('treats a value spelled like an Object.prototype member as unrecognized', () => { + for (const hostile of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) { + const [item] = decodeWithItems(TRANSACTION_ITEM.replace('withdrawal', hostile)).items + expect(item?.operation).toEqual({ kind: 'unrecognized', rawValue: hostile }) + } + }) +}) + +describe('forward compatibility', () => { + it('ignores an unknown response field wherever it appears', () => { + const usage = decode( + `{${REQUIRED},"tier":"gold","items":[${TRANSACTION_ITEM.slice(0, -1)},"extra":"nope"}]}`, + ) + expect(usage.accountId).toBe(ACCOUNT_ID) + expect(usage.items).toHaveLength(1) + expect(Object.keys(usage)).not.toContain('tier') + }) +}) + +describe('immutability', () => { + it('freezes the decoded resource and its items', () => { + const usage = decodeWithItems(`${TRANSACTION_ITEM},${AGGREGATION_ITEM}`) + expect(Object.isFrozen(usage)).toBe(true) + expect(Object.isFrozen(usage.items)).toBe(true) + expect(Object.isFrozen(usage.items[0])).toBe(true) + expect(Object.isFrozen(usage.items[0]?.operation)).toBe(true) + }) + + it('refuses a write to the resource through a cast', () => { + const usage = decodeWithItems(TRANSACTION_ITEM) + const mutable = usage as unknown as Record + expect(() => { + mutable['accountId'] = 'forged' + }).toThrow(TypeError) + expect(usage.accountId).toBe(ACCOUNT_ID) + }) + + it('refuses a write to an item through a cast', () => { + const usage = decodeWithItems(TRANSACTION_ITEM) + const mutable = usage.items[0] as unknown as Record + expect(() => { + mutable['effectiveThreshold'] = 0 + }).toThrow(TypeError) + expect(usage.items[0]?.effectiveThreshold).toBe(5000000) + }) +}) + +describe('no redaction', () => { + /** + * Unlike `Money.amount` or a fiat account's `billingDetails`, nothing on + * this model falls under the SDK's restricted-PII redaction rules or any + * comparable rule — these are the account's own limit thresholds and usage + * figures, not a transaction amount or bank/PII detail. So, unlike + * `Deposit`/`Account`, every value is visible through ordinary rendering. + */ + it('renders every field through JSON.stringify, util.inspect, and toString', () => { + const usage = decodeWithItems(AGGREGATION_ITEM) + for (const rendered of [ + JSON.stringify(usage), + inspect(usage, { getters: true }), + String(usage), + ]) { + expect(rendered).toContain(ACCOUNT_ID) + } + expect(JSON.stringify(usage)).toContain('1234567') + expect(JSON.stringify(usage)).toContain('24.69') + }) +}) + +describe('consumer construction', () => { + it('does not accept a look-alike object as an AccountLimitsUsage', () => { + const fabricated = { accountId: 'forged', items: [] } + expect(fabricated instanceof AccountLimitsUsage).toBe(false) + expect(decodeWithItems('') instanceof AccountLimitsUsage).toBe(true) + }) +}) diff --git a/src/__test__/accountPayload.test.ts b/src/__test__/accountPayload.test.ts new file mode 100644 index 0000000..cc1d687 --- /dev/null +++ b/src/__test__/accountPayload.test.ts @@ -0,0 +1,657 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import * as sdk from '../index' +import { Account } from '../models/Account' +import type { Money } from '../models/Money' +import { toAccount } from '../wire/accountPayload' +import { MalformedPayloadError } from '../wire/payload' + +/** + * Decoding tests for the account model. + * + * These go through the real parse and mapping rather than constructing a payload + * object directly, because the wire spellings, the number handling, and the + * required/optional line are the things under test. + */ + +/** The fields the service guarantees, so a test about one optional field is not also a test about a missing required one. */ +const REQUIRED = + '"accountId":"acct-1","balances":[],"entityId":"e",' + + '"purpose":"custody","status":"active","type":"first_party"' + +function decode(body: string): Account { + return toAccount(JSON.parse(body) as unknown) +} + +function decodeComplete(extra = ''): Account { + return decode(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) +} + +function accountWith(field: string, value: string): Account { + return decodeComplete(`"${field}":${value}`) +} + +describe('closed-set fields', () => { + it('maps every known custody type and falls back for the rest', () => { + expect(accountWith('custodyType', '"omnibus"').custodyType).toEqual({ kind: 'omnibus' }) + expect(accountWith('custodyType', '"segregated"').custodyType).toEqual({ kind: 'segregated' }) + expect(accountWith('custodyType', '"self"').custodyType).toEqual({ kind: 'self' }) + // A value the service adds later must read as unrecognized rather than + // failing the whole account — and must keep the string, which is the + // difference between support being able to answer "why did this read as + // unknown" and not. + expect(accountWith('custodyType', '"mpc"').custodyType).toEqual({ + kind: 'unrecognized', + rawValue: 'mpc', + }) + }) + + it('maps every known purpose, status and party type', () => { + expect(accountWith('purpose', '"custody"').purpose).toEqual({ kind: 'custody' }) + expect(accountWith('purpose', '"payments"').purpose).toEqual({ kind: 'payments' }) + expect(accountWith('status', '"active"').status).toEqual({ kind: 'active' }) + expect(accountWith('status', '"pending"').status).toEqual({ kind: 'pending' }) + expect(accountWith('status', '"rejected"').status).toEqual({ kind: 'rejected' }) + expect(accountWith('status', '"archived"').status).toEqual({ kind: 'archived' }) + expect(accountWith('type', '"first_party"').type).toEqual({ kind: 'first_party' }) + expect(accountWith('type', '"third_party"').type).toEqual({ kind: 'third_party' }) + }) + + /** + * The contract requires an unrecognised value be preserved "as an unknown/raw-value + * case instead of failing the entire response". Not failing is half of it; a bare + * marker satisfies that half and silently discards what the service sent. + */ + it('keeps the string the service sent on every closed-set field', () => { + const account = decode( + '{"accountId":"acct-1","balances":[],"entityId":"e",' + + '"custodyType":"mpc","purpose":"treasury","status":"frozen","type":"fourth_party"}', + ) + + expect(account.custodyType).toEqual({ kind: 'unrecognized', rawValue: 'mpc' }) + expect(account.purpose).toEqual({ kind: 'unrecognized', rawValue: 'treasury' }) + expect(account.status).toEqual({ kind: 'unrecognized', rawValue: 'frozen' }) + expect(account.type).toEqual({ kind: 'unrecognized', rawValue: 'fourth_party' }) + }) + + /** + * `custodyType` is outside the guaranteed set, so it is the one closed-set field + * whose absence is tolerated, and the only way to reach a null raw value. An + * absent `purpose`, `status`, or `type` is a missing required value. + */ + it('tolerates an absent custody type with a null raw value', () => { + expect(decodeComplete().custodyType).toEqual({ kind: 'unrecognized', rawValue: null }) + }) + + /** + * The wire spellings are lower snake_case; none of the multi-word `kind` values + * matches its own wire value's casing, so nothing would catch a mapper written + * from the public type instead of from the wire. + */ + it('does not accept a public kind spelling as a wire value', () => { + expect(accountWith('type', '"firstParty"').type).toEqual({ + kind: 'unrecognized', + rawValue: 'firstParty', + }) + expect(accountWith('custodyType', '"SELF"').custodyType).toEqual({ + kind: 'unrecognized', + rawValue: 'SELF', + }) + }) + + /** + * A JavaScript hazard with no Kotlin or Swift equivalent: an object literal used + * as a lookup table inherits from `Object.prototype`, so `table['constructor']` + * returns a function rather than `undefined` and a value spelled like a + * prototype member would be "recognised" as something that is not a custody type + * at all. + */ + it('treats a value spelled like an Object.prototype member as unrecognized', () => { + for (const hostile of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) { + expect(accountWith('custodyType', `"${hostile}"`).custodyType).toEqual({ + kind: 'unrecognized', + rawValue: hostile, + }) + expect(accountWith('status', `"${hostile}"`).status).toEqual({ + kind: 'unrecognized', + rawValue: hostile, + }) + } + }) +}) + +describe('required and optional fields', () => { + /** + * A response missing something the service guarantees is malformed, not an + * account with holes in it. Accepting it would turn a service defect into an SDK + * success and push the null handling onto every caller. + */ + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + accountId: '"acct-1"', + balances: '[]', + entityId: '"e"', + purpose: '"custody"', + status: '"active"', + type: '"first_party"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + // Sanity: the complete body decodes, or every assertion below is vacuous. + expect(decode(body(complete)).accountId).toBe('acct-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + // The degenerate case, and a non-object payload. + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toAccount(null)).toThrow(MalformedPayloadError) + expect(() => toAccount([])).toThrow(MalformedPayloadError) + }) + + /** An explicit `null` on a guaranteed field is the same defect as omitting it. */ + it('rejects an explicit null on a guaranteed field', () => { + expect(() => + decode( + '{"accountId":null,"balances":[],"entityId":"e","purpose":"custody","status":"active","type":"first_party"}', + ), + ).toThrow(MalformedPayloadError) + }) + + /** A present field in a shape the contract does not describe is malformed, not coerced. */ + it('rejects a field carried in the wrong shape', () => { + expect(() => accountWith('accountId', '{}')).toThrow(MalformedPayloadError) + expect(() => accountWith('accountId', 'true')).toThrow(MalformedPayloadError) + expect(() => accountWith('description', 'true')).toThrow(MalformedPayloadError) + expect(() => accountWith('description', '[]')).toThrow(MalformedPayloadError) + expect(() => accountWith('balances', '{}')).toThrow(MalformedPayloadError) + expect(() => accountWith('businessPii', '"nope"')).toThrow(MalformedPayloadError) + }) + + /** + * A JSON **number** in a field the contract types as a string is a shape error, + * not a value to coerce. + * + * The decoder reads the parsed JSON as-is, with no pre-parse pass that quotes + * number literals (the service sends `Money.amount` as a JSON string), so a + * JSON number and a genuine string stay distinguishable. + */ + it('rejects a JSON number in a field the contract types as a string', () => { + expect(() => accountWith('description', '7')).toThrow(MalformedPayloadError) + expect(() => accountWith('accountId', '7')).toThrow(MalformedPayloadError) + }) + + /** + * `amount` in particular. `JSON.parse` would already have rounded a JSON number + * to an IEEE-754 double before this code saw the token, so there would be no + * exact value left to report — and reporting a rounded balance as though the + * service had sent it is the one thing this decoder must not do. The service + * sends the field as a string, so this shape should never arrive. + */ + it('rejects a balance amount sent as a JSON number rather than coercing it', () => { + expect(() => decodeComplete('"balances":[{"amount":10.5,"currency":"USD"}]')).toThrow( + MalformedPayloadError, + ) + expect(() => + decodeComplete('"balances":[{"amount":1234567890123456.78,"currency":"USD"}]'), + ).toThrow(MalformedPayloadError) + }) + + /** + * `description` is absent on real accounts — the service treats it as + * nullable, and accounts can be created with none — so requiring it would + * fail an ordinary read. Trusting the OpenAPI's `required:` block here would + * be a defect. + */ + it('tolerates an account with no description', () => { + expect(decodeComplete().description).toBeNull() + expect(accountWith('description', '"labelled"').description).toBe('labelled') + }) + + it('reports every other absent optional field as absent', () => { + const account = decodeComplete() + expect(account.blockchain).toBeNull() + expect(account.clientEntityId).toBeNull() + expect(account.depositAddress).toBeNull() + expect(account.groupId).toBeNull() + expect(account.businessPii).toBeNull() + }) +}) + +describe('balances', () => { + /** + * The service sends `amount` as a JSON string holding a decimal literal. + * Converting it to a JavaScript number would round this value; carrying the + * string as sent does not. + */ + it('preserves an amount that a JavaScript number would round', () => { + const account = decodeComplete('"balances":[{"amount":"1234567890123456.78","currency":"USD"}]') + + expect(account.balances).toHaveLength(1) + expect((account.balances[0] as Money).amount).toBe('1234567890123456.78') + expect((account.balances[0] as Money).currency).toBe('USD') + }) + + /** Scale survives, because a caller rendering `1.50` must not be handed `1.5`. */ + it('preserves the scale the service sent', () => { + const account = decodeComplete('"balances":[{"amount":"1.50","currency":"USD"}]') + expect((account.balances[0] as Money).amount).toBe('1.50') + }) + + /** + * `Money.currency` is typed in the OpenAPI as a closed enum of twenty-two + * currencies that omits USD. Carrying it as a string is the whole point — the + * balance this SDK exists to report must survive. + */ + it('accepts a currency the schema enum does not list', () => { + for (const currency of ['USD', 'EURC', 'SOME_NEW_TOKEN']) { + const account = decodeComplete(`"balances":[{"amount":"1","currency":"${currency}"}]`) + expect((account.balances[0] as Money).currency).toBe(currency) + } + }) + + /** An unreadable balance is malformed too — the contract guarantees both money fields. */ + it('rejects a balance whose amount or currency cannot be read', () => { + expect(() => decodeComplete('"balances":[{"amount":"not-a-number","currency":"USD"}]')).toThrow( + MalformedPayloadError, + ) + expect(() => decodeComplete('"balances":[{"currency":"USD"}]')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"balances":[{"amount":"1"}]')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"balances":["1.00"]')).toThrow(MalformedPayloadError) + }) + + /** + * The number grammar is the *only* thing standing between a string field and a + * caller's decimal library, so its edges are worth pinning. Each of these is a + * shape a hand-rolled or lenient check tends to wave through: JavaScript's own + * `Number()` accepts every one of them, and `parseFloat` truncates the rest to a + * prefix. A caller that trusted `amount` to be a number would then get `NaN`, + * `Infinity`, or a silently different value out of its decimal library. + */ + it('rejects text that is not an RFC 8259 number', () => { + const notNumbers = [ + '', // absent-but-present + ' 1', // leading space + '1 ', // trailing space + '+1', // JSON has no unary plus + '01', // leading zero + '-01', + '.5', // no integer part + '1.', // trailing decimal point + '1..2', + '1e', // truncated exponent + '1e+', + '0x10', // hex + '1_000', // digit separator + 'Infinity', + '-Infinity', + 'NaN', + '1,50', // decimal comma + '1.5.5', + '--1', + '1e1.5', // fractional exponent + ] + + for (const amount of notNumbers) { + expect(() => + decodeComplete(`"balances":[{"amount":${JSON.stringify(amount)},"currency":"USD"}]`), + ).toThrow(MalformedPayloadError) + } + }) + + /** The other side of the same line: every shape the grammar does allow. */ + it('accepts the number shapes the grammar allows', () => { + const numbers = [ + '0', + '-0', + '1', + '-1', + '0.0', + '1.50', + '-0.01', + '1e10', + '1E10', + '1e+10', + '1e-10', + '0.5e-3', + ] + + for (const amount of numbers) { + const account = decodeComplete(`"balances":[{"amount":"${amount}","currency":"USD"}]`) + expect((account.balances[0] as Money).amount).toBe(amount) + } + }) + + it('decodes an empty balance list as an empty list', () => { + expect(decodeComplete().balances).toEqual([]) + }) +}) + +describe('forward compatibility', () => { + /** + * Forward-compatible decoding of an unknown + * response field, alongside the unknown closed-set value covered above. The + * pairing is the point — the service adding a field and the service adding an + * enum value are the two ways a response outruns a shipped SDK, and neither + * may fail the read. + * + * Unknown *fields* are the half with no other test. A mapper that validated + * the key set instead of reading the keys it knows would pass every other test + * in this file and still break every consumer the day a field is added. + */ + it('ignores an unknown response field wherever it appears', () => { + const account = decode( + '{"accountId":"acct-1","entityId":"e","purpose":"custody","status":"active",' + + '"type":"first_party","settlementTier":"gold","riskScore":7,"flags":null,' + + '"balances":[{"amount":"1.00","currency":"USD","provisionalAmount":"0.25"}],' + + '"businessPii":{"businessName":"Acme","taxRegime":{"nested":true}}}', + ) + + // The known fields still decode, and the unknown ones are simply absent. + expect(account.accountId).toBe('acct-1') + expect(account.balances).toHaveLength(1) + expect((account.balances[0] as Money).amount).toBe('1.00') + expect(Object.keys(account)).not.toContain('settlementTier') + expect(Object.keys(account)).not.toContain('riskScore') + }) + + /** + * The other half of the requirement, asserted together with the first so the + * pair cannot drift apart: an unrecognised value and an unrecognised field in + * the same response still yield a readable account. + */ + it('decodes a response carrying an unknown field and an unknown value at once', () => { + const account = decode( + '{"accountId":"acct-1","balances":[],"entityId":"e","purpose":"custody",' + + '"status":"settling","type":"first_party","tierMetadata":{"a":1}}', + ) + + expect(account.accountId).toBe('acct-1') + expect(account.status).toEqual({ kind: 'unrecognized', rawValue: 'settling' }) + }) +}) + +describe('fields the OpenAPI omits', () => { + /** + * `blockchain` is the account's immutable home chain, a plain string because new + * chains ship without an SDK release. + */ + it('carries the home chain including one this version has never heard of', () => { + expect(accountWith('blockchain', '"ETH"').blockchain).toBe('ETH') + expect(accountWith('blockchain', '"SOME_NEW_CHAIN"').blockchain).toBe('SOME_NEW_CHAIN') + // Absent is reported as absent. The contract says DAA provisions on ARC when + // the field is omitted at creation, but that is the service's default to + // apply — inventing it here would report a home chain the service never sent. + expect(decodeComplete().blockchain).toBeNull() + }) + + /** The receive address a self-custody consumer needs must survive decoding. */ + it('carries the deposit address', () => { + expect(accountWith('depositAddress', '"0xabc"').depositAddress).toBe('0xabc') + // Absent until the provider mapping is complete — a state, not an error. + expect(decodeComplete().depositAddress).toBeNull() + }) + + it('carries business identity enrichment', () => { + const account = decodeComplete( + '"businessPii":{"address":{"city":"Boston","country":"US","line1":"1 Main St",' + + '"line2":"Apt 2","district":"MA","postalCode":"02101"},' + + '"businessName":"Acme Inc","businessUniqueIdentifier":"EIN-123",' + + '"identifierIssuingCountryCode":"US"}', + ) + + const pii = account.businessPii + expect(pii?.businessName).toBe('Acme Inc') + expect(pii?.businessUniqueIdentifier).toBe('EIN-123') + expect(pii?.identifierIssuingCountryCode).toBe('US') + expect(pii?.address?.city).toBe('Boston') + expect(pii?.address?.country).toBe('US') + expect(pii?.address?.district).toBe('MA') + expect(pii?.address?.line1).toBe('1 Main St') + expect(pii?.address?.line2).toBe('Apt 2') + expect(pii?.address?.postalCode).toBe('02101') + }) + + /** + * A partial one is ordinary, not malformed. The service populates these + * best-effort from customer records and omits what it does not have, so a + * business with no tax id on file must still yield a readable account. + */ + it('tolerates partial business identity enrichment', () => { + const pii = decodeComplete('"businessPii":{"businessName":"Acme Inc"}').businessPii + + expect(pii?.businessName).toBe('Acme Inc') + expect(pii?.businessUniqueIdentifier).toBeNull() + expect(pii?.identifierIssuingCountryCode).toBeNull() + expect(pii?.address).toBeNull() + }) +}) + +describe('redaction', () => { + const account = decodeComplete( + '"depositAddress":"0xSECRET","balances":[{"amount":"12345.67","currency":"USD"}],' + + '"businessPii":{"address":{"city":"Boston","line1":"1 Main St"},"businessName":"Acme Inc",' + + '"businessUniqueIdentifier":"EIN-123"}', + ) + const secrets = ['0xSECRET', '12345.67', 'Acme Inc', 'EIN-123', '1 Main St', 'Boston'] + + /** + * There is no `toString` hook that JavaScript's rendering paths all go through, + * so redaction is held by **absence**: every sensitive value is reached through a + * prototype accessor over a `#` private field rather than through an own + * property. `Object.keys`, `JSON.stringify`, spread, `for...in`, and the + * inspectors behind `console.log` all walk own enumerable properties, so none of + * them can reach one. + */ + it('keeps every sensitive value off the account object as an own property', () => { + expect(Object.getOwnPropertyNames(account).sort()).toEqual( + [ + 'accountId', + 'blockchain', + 'clientEntityId', + 'custodyType', + 'description', + 'entityId', + 'groupId', + 'purpose', + 'status', + 'type', + ].sort(), + ) + expect(Object.getOwnPropertyNames(account.balances[0] as Money)).toEqual(['currency']) + expect(Object.getOwnPropertyNames(account.businessPii ?? {})).toEqual([]) + expect(Object.getOwnPropertyNames(account.businessPii?.address ?? {})).toEqual([]) + }) + + it.each([ + ['JSON.stringify', (value: unknown): string => JSON.stringify(value) ?? ''], + ['util.inspect (what console.log renders)', (value: unknown): string => inspect(value)], + ['util.inspect at full depth', (value: unknown): string => inspect(value, { depth: null })], + ['String()', (value: unknown): string => String(value)], + ['template literal', (value: unknown): string => `${String(value)}`], + [ + 'spread into a plain object', + (value: unknown): string => JSON.stringify({ ...(value as object) }) ?? '', + ], + [ + 'for...in', + (value: unknown): string => { + let out = '' + for (const key in value as Record) { + out += `${key}=${String((value as Record)[key])};` + } + return out + }, + ], + ])('reveals no sensitive value through %s', (_name, render) => { + for (const rendered of [ + render(account), + render(account.balances), + render(account.balances[0]), + render(account.businessPii), + render(account.businessPii?.address), + ]) { + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + } + }) + + it('still renders the identifiers and states that make a log line useful', () => { + expect(String(account)).toContain('acct-1') + expect(String(account)).toContain('active') + expect(JSON.stringify(account)).toContain('acct-1') + expect(inspect(account)).toContain('acct-1') + }) + + /** The balance *count* is what stands in for the balances, as on the other SDKs. */ + it('renders a balance count in place of the balances', () => { + expect(String(account)).toContain('balances=1 entries') + expect(JSON.parse(JSON.stringify(account))).toMatchObject({ balances: '1 entries' }) + }) + + it('says the amount was withheld rather than omitting it silently', () => { + expect(String(account.balances[0])).toBe('Money(amount=, currency=USD)') + expect(JSON.parse(JSON.stringify(account.balances[0]))).toEqual({ + amount: '', + currency: 'USD', + }) + expect(JSON.parse(JSON.stringify(account.businessPii))).toBe('BusinessPii()') + expect(JSON.parse(JSON.stringify(account.businessPii?.address))).toBe('Address()') + }) + + /** + * **The honest limit, recorded rather than claimed away.** What is prevented is a + * value reaching a log by *accident* — the crash reporter, the + * `console.log(account)`, the `JSON.stringify` of a state tree. A consumer that + * reads `account.balances[0].amount` and logs it is doing so deliberately, and + * nothing in an SDK that has to expose the balance can stop that. + * + * Nor is it a control against an inspector that is *asked* to evaluate prototype + * accessors: `util.inspect(value, { showHidden: true, getters: true })` walks and + * calls them, and reveals every field. That combination is a debugger's opt-in, + * not something `console.log` or a crash reporter does, but the claim this SDK + * makes is "not in a default rendering" and not "unreachable". + */ + it('does not withhold from an inspector explicitly asked to evaluate accessors', () => { + const revealing = inspect(account, { showHidden: true, getters: true, depth: null }) + expect(revealing).toContain('12345.67') + expect(revealing).toContain('0xSECRET') + + // The ordinary route, and it is the public read the model exists to provide. + expect((account.balances[0] as Money).amount).toBe('12345.67') + }) +}) + +describe('immutability', () => { + const account = decodeComplete( + '"balances":[{"amount":"1","currency":"USD"},{"amount":"2","currency":"EUR"}]', + ) + + /** + * `readonly` is erased at compile time, so it is not what holds this. The + * instance and the balance array are frozen at construction, which is the + * runtime equivalent of the `unmodifiableList` the Kotlin model needs. + */ + it('freezes the account, its balances, and each balance', () => { + expect(Object.isFrozen(account)).toBe(true) + expect(Object.isFrozen(account.balances)).toBe(true) + expect(Object.isFrozen(account.balances[0])).toBe(true) + }) + + it('refuses a write through a cast', () => { + const mutable = account as unknown as Record + expect(() => { + mutable['accountId'] = 'acct-forged' + }).toThrow(TypeError) + expect(() => { + mutable['balances'] = [] + }).toThrow(TypeError) + expect(() => { + mutable['newField'] = 'x' + }).toThrow(TypeError) + expect(account.accountId).toBe('acct-1') + expect(account.balances).toHaveLength(2) + }) + + it('refuses a mutation of the returned balance array', () => { + const mutable = account.balances as Money[] + expect(() => mutable.push(mutable[0] as Money)).toThrow(TypeError) + expect(() => mutable.pop()).toThrow(TypeError) + expect(account.balances).toHaveLength(2) + }) +}) + +describe('consumer construction', () => { + /** + * The control is that no runtime constructor for a model reaches the public + * entry, and neither does the factory that builds one. A consumer resolving the + * package gets types and nothing to call. + */ + it('exposes no model constructor on the public entry', () => { + const runtime = sdk as unknown as Record + for (const name of [ + 'Account', + 'Money', + 'BusinessPii', + 'Address', + 'AccountsClient', + 'DaaUserClient', + 'createDaaUserClient', + 'toAccount', + 'decodeDataEnvelope', + ]) { + expect(runtime[name]).toBeUndefined() + } + }) + + /** + * And the type is nominal, not structural: the `#` private fields mean an object + * shaped like an account is not one, so a fabricated value cannot be passed to + * code that checks. TypeScript rejects the same literal at compile time for the + * same reason. + */ + it('does not accept a look-alike object as an account', () => { + const fabricated = { + accountId: 'acct-forged', + balances: [], + blockchain: null, + businessPii: null, + clientEntityId: null, + custodyType: { kind: 'self' }, + depositAddress: '0xattacker', + description: null, + entityId: 'e', + groupId: null, + purpose: { kind: 'custody' }, + status: { kind: 'active' }, + type: { kind: 'first_party' }, + } + + expect(fabricated instanceof Account).toBe(false) + expect(decodeComplete() instanceof Account).toBe(true) + }) +}) diff --git a/src/__test__/accountsClient.test.ts b/src/__test__/accountsClient.test.ts new file mode 100644 index 0000000..037fa34 --- /dev/null +++ b/src/__test__/accountsClient.test.ts @@ -0,0 +1,473 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { Money } from '../models/Money' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The account read, end to end through the client: request shape, envelope, + * decoding, and status mapping. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +/** A complete account: every field the service guarantees, plus the custody type. */ +const COMPLETE_ACCOUNT = + '{"accountId":"acct-1","balances":[],"entityId":"e","purpose":"custody",' + + '"status":"active","type":"first_party","custodyType":"self"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + accounts: ReturnType['accounts'] + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { accounts: createDaaUserClient(transport, 'production', NO_SIGNING).accounts, transport } +} + +function okClient(payload = COMPLETE_ACCOUNT) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + it('reads an account over the public accounts path', async () => { + const { accounts, transport } = okClient() + + const account = await accounts.get('acct-1') + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.method).toBe('GET') + expect(sent.path).toBe('/v1/accounts/acct-1') + expect(sent.query).toBeNull() + expect(sent.bodyBytes).toBeNull() + expect(sent.headers).toEqual({}) + expect(account.accountId).toBe('acct-1') + expect(account.custodyType).toEqual({ kind: 'self' }) + }) + + /** + * An `accountId` carrying a path separator would address a different operation + * rather than fail: `/v1/accounts/acct-1/transfers` is a real sibling route. An + * empty one addresses the collection instead of a member. + */ + it('rejects an accountId that would address a different route', async () => { + const { accounts, transport } = okClient() + + for (const bad of ['acct-1/transfers', 'acct-1/', '/acct-1', '', 'a/b/c']) { + const detail = await detailOf(accounts.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + // Rejecting only a literal `/` is not enough. The native SDKs get a second + // line of defence for free — their request type refuses anything outside the + // RFC 3986 unreserved set — but `DaaTransport` is a consumer-implemented + // interface, so nothing downstream here would catch an encoded separator. + it('rejects an accountId carrying an encoded separator or other unsafe character', async () => { + const { accounts, transport } = okClient() + + for (const bad of [ + 'acct-1%2Ftransfers', + 'acct%2f1', + 'acct-1?x=1', + 'acct-1#frag', + 'acct 1', + 'acct-1\u0000', + 'acct-1\r\nX-Injected: 1', + '.', + '..', + 'acct/../transfers', + ]) { + const detail = await detailOf(accounts.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts the unreserved characters a service-assigned id can use', async () => { + for (const good of ['acct-1', 'ACCT_1', 'a.b~c', '0123456789']) { + const { accounts, transport } = okClient() + await accounts.get(good) + expect(transport.sent[0]?.path).toBe(`/v1/accounts/${good}`) + } + }) +}) + +describe('the success path', () => { + it('accepts the documented 200 status', async () => { + const { accounts } = clientFor({ status: 200, bodyBytes: envelope(COMPLETE_ACCOUNT) }) + expect((await accounts.get('acct-1')).accountId).toBe('acct-1') + }) + + /** + * The payload sits under `data`. A body with it at the root — the shape the + * OpenAPI schema documents — is malformed, not a value-less account. + */ + it('rejects a body whose account sits at the root instead of the envelope', async () => { + const { accounts } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes(COMPLETE_ACCOUNT), + }) + + expect(await detailOf(accounts.get('acct-1'))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-2', + }) + }) + + /** A `response` wrapper is not this SDK's envelope. */ + it('rejects a body wrapped in a response key instead of data', async () => { + const { accounts } = clientFor({ + status: 200, + bodyBytes: bytes(`{"response":${COMPLETE_ACCOUNT}}`), + }) + + expect((await detailOf(accounts.get('acct-1'))).kind).toBe('contract_violation') + }) + + /** An envelope present but empty is malformed — the wrapper is not optional on a 2xx. */ + it('rejects an empty envelope, an empty body, and no body at all', async () => { + for (const bodyBytes of [bytes('{"data":null}'), bytes(''), null]) { + const { accounts } = clientFor({ status: 200, bodyBytes }) + expect((await detailOf(accounts.get('acct-1'))).kind).toBe('contract_violation') + } + }) + + /** + * The invalid byte sits in a field the payload does **not** read, on purpose. In + * a declared field, `JSON.parse` would reject the body on its own and the guard + * would be redundant, and the test would pass whether or not the guard exists. + * Lenient UTF-8 decoding replaces the bad sequence with U+FFFD, + * which is a legal JSON string character, so nothing downstream would notice. + */ + it('rejects a body with an invalid utf8 byte in a field it does not read', async () => { + const head = bytes('{"data":{"accountId":"acct-1","undeclared":"') + const tail = bytes( + `","balances":[],"entityId":"e","purpose":"custody","status":"active","type":"first_party"}}`, + ) + const body = new Uint8Array(head.length + 1 + tail.length) + body.set(head, 0) + body[head.length] = 0xff + body.set(tail, head.length + 1) + + // Sanity: the same body with a valid byte decodes, or the assertion is vacuous. + const valid = new Uint8Array(body) + valid[head.length] = 0x41 + expect( + (await clientFor({ status: 200, bodyBytes: valid }).accounts.get('acct-1')).accountId, + ).toBe('acct-1') + + const { accounts } = clientFor({ status: 200, bodyBytes: body }) + expect((await detailOf(accounts.get('acct-1'))).kind).toBe('contract_violation') + }) + + /** + * A `200` whose account is missing something the service guarantees must reach the + * caller as a broken contract, not as a successful account with holes in it. The + * correlation id has to survive, because it is the only thing that makes it + * diagnosable server-side. + */ + it('reports an account missing guaranteed fields as a broken contract with the correlation id', async () => { + const payloads = [ + '{}', + '{"accountId":"acct-1"}', + '{"accountId":"acct-1","balances":[],"entityId":"e","purpose":"custody"}', + // A guaranteed money amount the SDK cannot read is the same defect. + '{"accountId":"acct-1","balances":[{"amount":"nope","currency":"USD"}],' + + '"entityId":"e","purpose":"custody","status":"active","type":"first_party"}', + ] + + for (const payload of payloads) { + const { accounts } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-13' }, + bodyBytes: envelope(payload), + }) + expect(await detailOf(accounts.get('acct-1'))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-13', + }) + } + }) + + /** + * `status` arrives from a consumer-implemented transport, so its declared type + * is not a runtime guarantee. Both range comparisons are false for NaN, which + * without an integer check would read a broken response as a success. + */ + it('treats a non-integer status as a failure rather than a success', async () => { + for (const status of [Number.NaN, 200.5, Number.POSITIVE_INFINITY]) { + const { accounts } = clientFor({ + status: status as number, + bodyBytes: envelope(COMPLETE_ACCOUNT), + }) + + const detail = await detailOf(accounts.get('acct-1')) + expect(detail.kind).toBe('api') + } + }) + + /** + * The correlation id is a server-supplied header and it reaches + * `DaaError.message`, which a consuming app is likely to log verbatim. A + * header carrying CR/LF could otherwise forge log lines. + * + * Only the control characters go. The surrounding text stays, because the + * risk is a forged log *record*, not the words in one — and stripping more + * would mangle a legitimate id. An ordinary correlation id is printable, so + * this is a no-op on it, which the second case pins. + */ + it('strips control characters from the correlation id in the message', async () => { + const hostile = 'req-1\r\nWARN Injected log line' + const { accounts } = clientFor({ + status: 500, + headers: { 'X-Request-Id': hostile }, + bodyBytes: null, + }) + + try { + await accounts.get('acct-1') + throw new Error('expected the read to fail') + } catch (err) { + const message = (err as Error).message + expect(message).not.toContain('\n') + expect(message).not.toContain('\r') + expect(message).toContain('req-1') + expect(message).toContain('WARN Injected log line') + } + }) + + /** + * The other half: sanitising does not cost the value. A real correlation id + * survives byte for byte, so the message is where a caller gets the exact + * header — which is why the `api` detail does not need to carry a copy. + */ + it('leaves an ordinary correlation id untouched in the message', async () => { + const real = '8f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6b' + const { accounts } = clientFor({ + status: 500, + headers: { 'X-Request-Id': real }, + bodyBytes: null, + }) + + try { + await accounts.get('acct-1') + throw new Error('expected the read to fail') + } catch (err) { + expect((err as Error).message).toContain(`(requestId=${real})`) + } + }) + + /** No field name from the response reaches the error a consumer sees. */ + it('does not put a response field name in the error message', async () => { + const { accounts } = clientFor({ status: 200, bodyBytes: envelope('{"accountId":"acct-1"}') }) + + try { + await accounts.get('acct-1') + throw new Error('expected the read to fail') + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).not.toContain('entityId') + expect((err as Error).message).not.toContain('balances') + } + }) + + /** The receive address is the field a self-custody consumer opens the account for. */ + it('surfaces the deposit address and balances a self custody account carries', async () => { + const { accounts } = okClient( + '{"accountId":"acct-1","balances":[{"amount":"10.500000","currency":"USD"}],' + + '"entityId":"e","purpose":"custody","status":"active","type":"first_party",' + + '"custodyType":"self","blockchain":"ETH","depositAddress":"0xabc"}', + ) + + const account = await accounts.get('acct-1') + + expect(account.depositAddress).toBe('0xabc') + expect(account.blockchain).toBe('ETH') + expect(account.custodyType).toEqual({ kind: 'self' }) + expect((account.balances[0] as Money).amount).toBe('10.500000') + }) +}) + +describe('the failure path', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + for (const status of [201, 204, 299, 400, 401, 404, 409, 500, 503]) { + const { accounts } = clientFor({ + status, + headers: { 'X-Request-Id': `req-${status}` }, + bodyBytes: bytes(`{"status":{"code":${status * 10},"message":"nope"}}`), + }) + + const detail = await detailOf(accounts.get('acct-1')) + // Exactly the `api` variant and nothing more. The correlation id + // is deliberately absent: the error model puts it on `contract_violation` + // only, and it reaches the caller through the message. + expect(detail).toEqual({ + kind: 'api', + httpStatus: status, + daaStatusCode: status * 10, + retryable: status === 429 || status >= 500, + }) + } + }) + + /** + * A read is idempotent, so a `429` or `5xx` may be retried; a `4xx` will not + * become a success on a second attempt. The DAA status code is carried but never + * consulted — the error model's rule is that an unknown code stays observable and + * is never guessed retryable. + */ + it('marks only 429 and 5xx retryable', async () => { + for (const [status, retryable] of [ + [400, false], + [404, false], + [428, false], + [429, true], + [499, false], + [500, true], + [599, true], + ] as const) { + const { accounts } = clientFor({ status }) + expect(await detailOf(accounts.get('acct-1'))).toMatchObject({ kind: 'api', retryable }) + } + }) + + /** The error detail is best effort: losing the whole error because it did not parse would be worse. */ + it('reports the api error even when the body carries no readable status code', async () => { + for (const bodyBytes of [ + null, + bytes(''), + bytes('gateway timeout'), + bytes('{}'), + bytes('{"status":{}}'), + ]) { + const { accounts } = clientFor({ status: 502, bodyBytes }) + expect(await detailOf(accounts.get('acct-1'))).toEqual({ + kind: 'api', + httpStatus: 502, + retryable: true, + }) + } + }) + + it('carries a non-numeric DAA status code as the string the service sent', async () => { + const { accounts } = clientFor({ + status: 400, + bodyBytes: bytes('{"status":{"code":"BAD_REQUEST"}}'), + }) + expect(await detailOf(accounts.get('acct-1'))).toMatchObject({ daaStatusCode: 'BAD_REQUEST' }) + }) + + /** The correlation id is server-generated, so it is the one response value worth printing. */ + it('finds the correlation id whichever casing the transport uses', async () => { + for (const name of ['X-Request-Id', 'x-request-id', 'X-REQUEST-ID']) { + const { accounts } = clientFor({ status: 404, headers: { [name]: 'req-9' } }) + try { + await accounts.get('acct-1') + throw new Error('expected the read to fail') + } catch (err) { + expect((err as Error).message).toContain('req-9') + } + } + }) + + it('reports an absent correlation id as absent rather than as an empty string', async () => { + const { accounts } = clientFor({ status: 200, bodyBytes: bytes('{"data":null}') }) + expect(await detailOf(accounts.get('acct-1'))).toEqual({ kind: 'contract_violation' }) + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).accounts.get('acct-1'), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) + +describe('reachability', () => { + /** + * The client is reachable only through `DaaClient.forUser`, which takes a + * user context an `ACTIVE` Device Registration Complete produced. + * `createDaaUserClient` is the internal factory behind it and is not on the + * public entry, so a consumer cannot build the operations surface — or the + * signing material it requires — for itself. + */ + it('is reached only through the internal user-client factory', () => { + const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, + } + const user = createDaaUserClient(transport, 'production', NO_SIGNING) + expect(typeof user.accounts.get).toBe('function') + expect(Object.isFrozen(user)).toBe(true) + expect(Object.isFrozen(user.accounts)).toBe(true) + }) +}) diff --git a/src/__test__/accountsCreate.test.ts b/src/__test__/accountsCreate.test.ts new file mode 100644 index 0000000..4f13a31 --- /dev/null +++ b/src/__test__/accountsCreate.test.ts @@ -0,0 +1,407 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { sha256 } from '../crypto/sha256' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { CreateAccountRequest } from '../models/CreateAccountRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { registeredAuthKey, signingFor, unregisteredAuthKey } from './userClientSigning' + +/** + * The signed account create, end to end through the client. + * + * Every wire fact here is written as a literal — the path, the operation + * discriminator, the schema version, and the exact serialized body — rather + * than compared against the constant the production code reads. Comparing code + * to its own constant passes whatever the constant says: a wrong canonical + * path would pass, because the assertion would move with the defect. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const CLIENT_ENTITY_ID = '33333333-3333-4333-b333-333333333333' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' + +/** A complete account: every field the service guarantees, plus the custody type. */ +const CREATED_ACCOUNT = + '{"accountId":"acct-1","balances":[],"entityId":"e","purpose":"custody",' + + '"status":"pending","type":"first_party","custodyType":"self"}' + +const VALID_REQUEST: CreateAccountRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + blockchain: 'ARC', +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +async function createdClient(payload = CREATED_ACCOUNT) { + const transport = new RecordingTransport({ + status: 201, + headers: { 'X-Request-Id': 'req-create', Location: '/v1/accounts/acct-1' }, + bodyBytes: envelope(payload), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { accounts: createDaaUserClient(transport, 'production', signing).accounts, transport } +} + +function claimsOf(request: DaaHttpRequest): Record { + const compact = request.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('missing device authorization') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? ''))) +} + +function headerOf(request: DaaHttpRequest): Record { + const compact = request.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('missing device authorization') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(compact.split('.')[0] ?? ''))) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the signed request', () => { + it('posts the registry canonical path with the create_account discriminator', async () => { + const { accounts, transport } = await createdClient() + + await accounts.create(VALID_REQUEST) + + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + if (request === undefined) throw new Error('no request was sent') + expect(request.method).toBe('POST') + expect(request.path).toBe('/v1/accounts') + expect(request.query).toBeNull() + expect(request.headers['Content-Type']).toBe('application/json') + expect(claimsOf(request)).toMatchObject({ + canonical_path: '/v1/accounts', + method: 'POST', + discriminator: 'create_account', + schema_version: 1, + aud: 'circle-digital-asset-accounts', + idempotency_key: IDEMPOTENCY_KEY, + }) + expect(headerOf(request)).toMatchObject({ + alg: 'ES256', + kid: AUTH_KEY_ID, + typ: 'aw-device-authorization+jws', + }) + }) + + it('sends exactly the registry properties, in the registry order', async () => { + const { accounts, transport } = await createdClient() + + await accounts.create(VALID_REQUEST) + + const sent = transport.sent[0]?.bodyBytes + if (sent == null) throw new Error('no body was sent') + expect(new TextDecoder().decode(sent)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","clientEntityId":"${CLIENT_ENTITY_ID}",` + + '"custodyType":"self","type":"third_party","purpose":"custody",' + + '"description":"Primary","blockchain":"ARC"}', + ) + expect(Object.keys(JSON.parse(new TextDecoder().decode(sent)))).toEqual([ + 'idempotencyKey', + 'clientEntityId', + 'custodyType', + 'type', + 'purpose', + 'description', + 'blockchain', + ]) + }) + + it('sends every required property, including an empty description', async () => { + const { accounts, transport } = await createdClient() + + await accounts.create({ + idempotencyKey: IDEMPOTENCY_KEY, + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: '', + blockchain: 'ARC', + }) + + const sent = transport.sent[0]?.bodyBytes + if (sent == null) throw new Error('no body was sent') + expect(new TextDecoder().decode(sent)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","clientEntityId":"${CLIENT_ENTITY_ID}",` + + '"custodyType":"self","type":"third_party","purpose":"custody",' + + '"description":"","blockchain":"ARC"}', + ) + }) + + it('binds body_sha256 to the exact bytes it transmits', async () => { + const { accounts, transport } = await createdClient() + + await accounts.create(VALID_REQUEST) + + const request = transport.sent[0] + if (request?.bodyBytes == null) throw new Error('no body was sent') + // Hash what went on the wire, not what the client meant to send. If + // anything re-serialized the body between signing and transport, these + // differ — which is the failure this whole exact-byte discipline exists to + // make impossible. + expect(claimsOf(request).body_sha256).toBe(toBase64Url(sha256(request.bodyBytes))) + }) + + it('decodes the documented 201 into an account', async () => { + const { accounts } = await createdClient() + + const account = await accounts.create(VALID_REQUEST) + + expect(account.accountId).toBe('acct-1') + expect(account.status).toEqual({ kind: 'pending' }) + expect(account.custodyType).toEqual({ kind: 'self' }) + }) + + it('treats another 2xx as an API failure rather than a created account', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: { 'X-Request-Id': 'req-200' }, + bodyBytes: envelope(CREATED_ACCOUNT), + }) + const accounts = createDaaUserClient( + transport, + 'production', + signingFor(await registeredAuthKey(), AUTH_KEY_ID), + ).accounts + + expect(await detailOf(accounts.create(VALID_REQUEST))).toEqual({ + kind: 'api', + httpStatus: 200, + retryable: false, + }) + }) +}) + +describe('local rejection', () => { + async function rejectingClient() { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { + accounts: createDaaUserClient(transport, 'production', signing).accounts, + transport, + signing, + } + } + + it('refuses a property the registry schema does not name, without sending it', async () => { + const { accounts, transport, signing } = await rejectingClient() + + // `blockChain` is the realistic version of this: a near-miss of a real + // property. Dropping it silently would create the account on the default + // home chain while the caller believed it had chosen one. + const detail = await detailOf(accounts.create({ ...VALID_REQUEST, blockChain: 'ARC' } as never)) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + // Nothing was signed either: an Owner signature is not spent on bytes that + // cannot succeed. + expect(signing.resolutions()).toBe(0) + }) + + it('refuses each field the registry constrains, without sending anything', async () => { + const invalid: readonly CreateAccountRequest[] = [ + { ...VALID_REQUEST, idempotencyKey: 'not-a-uuid' }, + // A v1 UUID: syntactically a UUID, but the contract documents v4. + { ...VALID_REQUEST, idempotencyKey: '22222222-2222-1222-a222-222222222222' }, + { ...VALID_REQUEST, clientEntityId: 'not-a-uuid' }, + { ...VALID_REQUEST, custodyType: 'omnibus' } as never, + { ...VALID_REQUEST, type: 'fourth_party' } as never, + { ...VALID_REQUEST, purpose: 'trading' } as never, + { ...VALID_REQUEST, description: 7 } as never, + { ...VALID_REQUEST, blockchain: '' }, + // The clientEntityId-omission case gets its own test below, which + // checks the specific rejection reason rather than only `kind`. + 'not an object' as never, + [] as never, + ] + + for (const request of invalid) { + const { accounts, transport } = await rejectingClient() + expect((await detailOf(accounts.create(request))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + } + }) + + it('omits blockchain from the signed body when the caller does not supply it', async () => { + const { accounts, transport } = await createdClient() + + // `blockchain` is optional: DAA provisions on `ARC` when it is omitted. + // This SDK must not invent a stricter local rule than the service actually + // enforces. + await accounts.create({ + idempotencyKey: IDEMPOTENCY_KEY, + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + }) + + const sent = transport.sent[0]?.bodyBytes + if (sent == null) throw new Error('no body was sent') + expect(Object.keys(JSON.parse(new TextDecoder().decode(sent)))).toEqual([ + 'idempotencyKey', + 'clientEntityId', + 'custodyType', + 'type', + 'purpose', + 'description', + ]) + }) + + it('rejects an omitted clientEntityId, not just a malformed one', async () => { + const { accounts, transport, signing } = await rejectingClient() + + // A self-custody create requires `clientEntityId` outright; an omission is + // a distinct defect from the malformed-UUID case above, and the message + // names it as required, not merely as invalid. + const withoutClientEntityId = { + idempotencyKey: IDEMPOTENCY_KEY, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + blockchain: 'ARC', + } as never + + try { + await accounts.create(withoutClientEntityId) + throw new Error('expected the create to be rejected') + } catch (err) { + if (!isDaaError(err)) throw err + expect(err.detail.kind).toBe('contract_violation') + expect((err as Error).message).toMatch(/clientEntityId is required/) + } + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('rejects type=first_party, not just an unrecognized type', async () => { + const { accounts, transport, signing } = await rejectingClient() + + // `first_party` is a real value the registry's open string would admit. + // The contract narrows a self-custody create to `third_party` alone, so + // this is a distinct defect from the generic-sweep `fourth_party` case, + // which is merely a value neither side ever recognized. + const detail = await detailOf( + accounts.create({ ...VALID_REQUEST, type: 'first_party' } as never), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('rejects purpose=payments, not just an unrecognized purpose', async () => { + const { accounts, transport, signing } = await rejectingClient() + + // `payments` is a real value the registry's open string would admit. The + // contract narrows a self-custody create to `custody` alone, so this is a + // distinct defect from the generic-sweep `trading` case, which is merely + // a value neither side ever recognized. + const detail = await detailOf( + accounts.create({ ...VALID_REQUEST, purpose: 'payments' } as never), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('rejects a 256-character description, not just a non-string one', async () => { + const { accounts, transport, signing } = await rejectingClient() + + // The contract caps `description` at 255 characters (`maxLength: 255`) + // and the server enforces the same bound. One character over must fail + // locally, before a device-authorization ceremony and idempotency key are + // spent on a request the service would reject anyway. + const detail = await detailOf( + accounts.create({ ...VALID_REQUEST, description: 'a'.repeat(256) }), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('accepts a 255-character description', async () => { + const { accounts, transport } = await createdClient() + + await accounts.create({ ...VALID_REQUEST, description: 'a'.repeat(255) }) + + expect(transport.sent).toHaveLength(1) + }) + + it('fails closed while the AuthKey is not yet registered', async () => { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + // `created`, not `existing`: Device Registration Complete has not + // acknowledged this key, so it may sign the Complete call and nothing else. + const authKey = await unregisteredAuthKey() + expect(authKey.resolution()).toBe('created') + const accounts = createDaaUserClient( + transport, + 'production', + signingFor(authKey, AUTH_KEY_ID), + ).accounts + + expect(await detailOf(accounts.create(VALID_REQUEST))).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) +}) diff --git a/src/__test__/accountsPagination.test.ts b/src/__test__/accountsPagination.test.ts new file mode 100644 index 0000000..a38d7a2 --- /dev/null +++ b/src/__test__/accountsPagination.test.ts @@ -0,0 +1,340 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +const ORIGIN = 'https://api.circle.com' +const ACCOUNT = + '{"accountId":"acct-1","balances":[],"entityId":"entity-1","purpose":"custody",' + + '"status":"active","type":"first_party","custodyType":"self"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function pageBody(account = ACCOUNT): Uint8Array { + return bytes(`{"data":[${account}]}`) +} + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: readonly DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) throw new Error('unexpected request') + return response + } +} + +function response(headers: Readonly> = {}): DaaHttpResponse { + return { status: 200, headers, bodyBytes: pageBody() } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('accounts pagination', () => { + it('loads and freezes the first page over the public collection path', async () => { + const transport = new SequenceTransport([response()]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + + expect(transport.sent).toEqual([ + { method: 'GET', path: '/v1/accounts', query: null, headers: {}, bodyBytes: null }, + ]) + expect(page.items).toHaveLength(1) + expect(page.items[0]?.accountId).toBe('acct-1') + expect(Object.isFrozen(page)).toBe(true) + expect(Object.isFrozen(page.items)).toBe(true) + expect(Object.keys(page)).toEqual(['items']) + expect(JSON.stringify(page)).not.toContain('api.circle.com') + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + expect(transport.sent).toHaveLength(1) + }) + + it('serializes the documented account filters in one deterministic query', async () => { + const transport = new SequenceTransport([response()]) + const accounts = createDaaUserClient(transport, 'production', NO_SIGNING).accounts + + await accounts.list({ + custodyType: 'self', + clientEntityId: '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + type: 'third_party', + isAttributed: true, + purpose: 'custody', + status: ['active', 'pending'], + description: 'primary & reserve', + currencies: ['USD', 'EUR'], + groupId: '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + from: '2026-08-01T00:00:00Z', + to: '2026-08-18T00:00:00Z', + pageAfter: 'opaque/selector=1', + pageSize: 50, + }) + + expect(transport.sent[0]?.query).toBe( + 'custodyType=self&clientEntityId=3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' + + '&type=third_party&isAttributed=true&purpose=custody&status=active&status=pending' + + '&description=primary%20%26%20reserve¤cies=USD¤cies=EUR' + + '&groupId=4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' + + '&from=2026-08-01T00%3A00%3A00Z&to=2026-08-18T00%3A00%3A00Z' + + '&pageAfter=opaque%2Fselector%3D1&pageSize=50', + ) + }) + + it('round-trips opaque link queries without parsing, sorting, or re-encoding', async () => { + const nextQuery = 'z=last&pageAfter=a%2Fb%3D&repeat=1&repeat=2&reserved=%2B%26,still-opaque' + const previousQuery = 'pageBefore=before%2Fvalue&pageSize=2' + const transport = new SequenceTransport([ + response({ + link: + `<${ORIGIN}/v1/accounts?${nextQuery}>; rel="NeXt", ` + + `<${ORIGIN}/v1/accounts?${previousQuery}>; rel="prev"`, + }), + response(), + response(), + ]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + + await page.next() + await page.previous() + + expect(transport.sent[1]?.query).toBe(nextQuery) + expect(transport.sent[2]?.query).toBe(previousQuery) + for (const request of transport.sent) { + expect(request.path).toBe('/v1/accounts') + expect(request.method).toBe('GET') + expect(request.headers).toEqual({}) + expect(request.bodyBytes).toBeNull() + } + }) + + it('preserves the distinction between an absent and explicitly empty query', async () => { + for (const [target, expected] of [ + [`${ORIGIN}/v1/accounts`, null], + [`${ORIGIN}/v1/accounts?`, ''], + ] as const) { + const transport = new SequenceTransport([ + response({ Link: `<${target}>; rel="next"` }), + response(), + ]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + await page.next() + expect(transport.sent[1]?.query).toBe(expected) + } + }) + + it('compares origins by HTTPS host and effective port rather than textual casing', async () => { + const transport = new SequenceTransport([ + response({ Link: '; rel="next"' }), + response(), + ]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + await page.next() + + expect(transport.sent[1]?.query).toBe('pageAfter=x') + }) + + it('keeps the pagination trust decision independent of the host URL implementation', async () => { + const originalUrl = globalThis.URL + Object.defineProperty(globalThis, 'URL', { + configurable: true, + value: undefined, + writable: true, + }) + try { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts?pageAfter=x>; rel="next"` }), + response(), + ]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + + await expect(page.next()).resolves.not.toBeNull() + expect(transport.sent[1]?.query).toBe('pageAfter=x') + } finally { + Object.defineProperty(globalThis, 'URL', { + configurable: true, + value: originalUrl, + writable: true, + }) + } + }) + + it('uses the selected environment as the pagination trust anchor', async () => { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts?pageAfter=x>; rel="next"` }), + ]) + + const detail = await detailOf( + createDaaUserClient(transport, 'sandbox', NO_SIGNING).accounts.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it('uses publicApiOrigin, not the environment origin, as the trust anchor when set', async () => { + const override = 'https://api-test.circle.com' + const trusted = new SequenceTransport([ + response({ Link: `<${override}/v1/accounts?pageAfter=x>; rel="next"` }), + response(), + ]) + const page = await createDaaUserClient(trusted, 'sandbox', NO_SIGNING, override).accounts.list() + await page.next() + expect(trusted.sent[1]?.query).toBe('pageAfter=x') + + const untrusted = new SequenceTransport([ + response({ Link: '; rel="next"' }), + ]) + const detail = await detailOf( + createDaaUserClient(untrusted, 'sandbox', NO_SIGNING, override).accounts.list(), + ) + expect(detail.kind).toBe('contract_violation') + expect(untrusted.sent).toHaveLength(1) + }) + + it.each([ + 'http://api.circle.com/v1/accounts?pageAfter=x', + 'https://evil.example/v1/accounts?pageAfter=x', + 'https://api.circle.com.evil.example/v1/accounts?pageAfter=x', + 'https://api.circle.com:444/v1/accounts?pageAfter=x', + 'https://user@api.circle.com/v1/accounts?pageAfter=x', + 'https://api.circle.com/v1/accounts?pageAfter=x#fragment', + 'https://api.circle.com/v1/accounts/transfers?pageAfter=x', + 'https://api.circle.com/v10/accounts?pageAfter=x', + 'https://api.circle.com/v1/accounts/../withdrawals?pageAfter=x', + 'https://api.circle.com/v1//accounts?pageAfter=x', + 'https://api.circle.com/v1/%61ccounts?pageAfter=x', + 'https://api.circle.com/v1/accounts?pageAfter=%zz', + 'https://api.circle.com/v1/accounts?pageAfter=a b', + 'https://api.circle.com/v1/accounts?pageAfter="quoted"', + 'https://api.circle.com/v1/accounts?pageAfter=raw-\u{1f4a9}', + '/v1/accounts?pageAfter=x', + '//api.circle.com/v1/accounts?pageAfter=x', + ' https://api.circle.com/v1/accounts?pageAfter=x', + 'https://api.circle.com\\v1\\accounts?pageAfter=x', + ])('rejects an untrusted target without following it: %s', async (target) => { + const transport = new SequenceTransport([response({ Link: `<${target}>; rel="next"` })]) + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next", <${ORIGIN}/v1/accounts?pageAfter=2>; rel="NEXT"`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next"; rel="prev"`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next prev"`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel=next`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next"; title="unused"`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1; rel="next"`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel=""`, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next", `, + }, + { + Link: `<${ORIGIN}/v1/accounts?pageAfter=1>; rel="next"`, + link: `<${ORIGIN}/v1/accounts?pageAfter=2>; rel="prev"`, + }, + ])('rejects malformed, unsupported, or ambiguous Link metadata', async (headers) => { + const transport = new SequenceTransport([ + response({ ...headers, 'X-Request-Id': 'req-pagination' }), + ]) + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list(), + ) + + expect(detail).toEqual({ kind: 'contract_violation', correlationId: 'req-pagination' }) + expect(transport.sent).toHaveLength(1) + }) + + it('ignores unrelated link relations', async () => { + const transport = new SequenceTransport([ + response({ Link: `; rel="alternate"` }), + ]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).accounts.list() + + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + }) + + it.each([ + { pageAfter: 'one', pageBefore: 'two' }, + { pageSize: 0 }, + { pageSize: 1.5 }, + { clientEntityId: 'not-a-uuid' }, + { custodyType: 'unknown' }, + { status: ['unknown'] }, + { currencies: [''] }, + { from: '' }, + ])('rejects an invalid initial query without sending it: %o', async (query) => { + const transport = new SequenceTransport([]) + const accounts = createDaaUserClient(transport, 'production', NO_SIGNING).accounts + const detail = await detailOf(accounts.list(query as never)) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('maps malformed list bodies and unexpected success statuses through the shared response rules', async () => { + const malformed = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-list' }, bodyBytes: bytes('{"data":{}}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformed, 'production', NO_SIGNING).accounts.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-list' }) + + const wrongStatus = new SequenceTransport([{ status: 201, headers: {}, bodyBytes: pageBody() }]) + await expect( + detailOf(createDaaUserClient(wrongStatus, 'production', NO_SIGNING).accounts.list()), + ).resolves.toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) diff --git a/src/__test__/achFiatAccountsClient.test.ts b/src/__test__/achFiatAccountsClient.test.ts new file mode 100644 index 0000000..fa548b2 --- /dev/null +++ b/src/__test__/achFiatAccountsClient.test.ts @@ -0,0 +1,248 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { AchFiatAccountsClient } from '../api/AchFiatAccountsClient' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { NO_SIGNING } from './userClientSigning' + +/** + * The ACH fiat-account reads, mirroring `wireFiatAccountsClient.test.ts`. The + * one behavioral difference under test throughout: `clientEntityId` is + * **required** for `ach.list`, unlike `wires.list` — + * `AchFiatAccountListQuery` types it as a non-optional field, not `?`. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const FIAT_ACCOUNT_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = '11111111-1111-4111-8111-111111111111' + +const COMPLETE_ACH = + '{"id":"3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8","status":"complete",' + + '"description":"WELLS FARGO BANK, NA ****0010","trackingRef":"CIR1",' + + '"fingerprint":"eb170539-9e1c-4e92-bf4f-1d09534fdca2",' + + '"billingDetails":{"name":"Satoshi Nakamoto","city":"Boston","country":"US",' + + '"line1":"100 Money Street","postalCode":"01234"},' + + '"routingNumber":"121000248",' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z"}' + +const COMPLETE_INSTRUCTION = + '{"trackingRef":"CIR1","beneficiary":{"name":"CIRCLE INTERNET FINANCIAL INC"},' + + '"beneficiaryBank":{"routingNumber":"121000248","accountNumber":"****7427"}}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + ach: AchFiatAccountsClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { + ach: createDaaUserClient(transport, 'production', NO_SIGNING).fiatAccounts.ach, + transport, + } +} + +function okClient(payload: string) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('ach.list', () => { + it('requires clientEntityId and sends it as the exact query', async () => { + const { ach, transport } = okClient(`[${COMPLETE_ACH}]`) + + const result = await ach.list({ clientEntityId: CLIENT_ENTITY_ID }) + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/banks/ach', + query: `clientEntityId=${CLIENT_ENTITY_ID}`, + headers: {}, + bodyBytes: null, + }, + ]) + // The full ACH projection, not a leaner list-only summary. + expect(result[0]?.routingNumber).toBe('121000248') + }) + + it('rejects a call with no query object at all, without sending a request', async () => { + const { ach, transport } = okClient('[]') + + // @ts-expect-error — exercising the runtime guard for a caller that + // bypasses the compile-time requirement (plain JS, or an `any`). + expect((await detailOf(ach.list(undefined))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a query object missing clientEntityId, without sending a request', async () => { + const { ach, transport } = okClient('[]') + + // @ts-expect-error — same runtime guard, this time for an object missing + // the one required field. + expect((await detailOf(ach.list({}))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a non-UUID clientEntityId, without sending a request', async () => { + const { ach, transport } = okClient('[]') + + expect((await detailOf(ach.list({ clientEntityId: 'not-a-uuid' }))).kind).toBe( + 'contract_violation', + ) + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('ach.get', () => { + it('reads one ACH account over the public by-id path with an empty unsigned GET', async () => { + const { ach, transport } = okClient(COMPLETE_ACH) + + const account = await ach.get(FIAT_ACCOUNT_ID) + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: `/v1/banks/ach/${FIAT_ACCOUNT_ID}`, + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(account.id).toBe(FIAT_ACCOUNT_ID) + expect(account.status).toEqual({ kind: 'complete' }) + }) + + it('rejects a non-UUID fiatAccountId locally without sending a request', async () => { + const { ach, transport } = okClient(COMPLETE_ACH) + + for (const bad of ['', 'ach-1', `${FIAT_ACCOUNT_ID}/other`, `${FIAT_ACCOUNT_ID}%2Fother`]) { + expect((await detailOf(ach.get(bad))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts only the documented 200', async () => { + const { ach } = clientFor({ status: 201, bodyBytes: envelope(COMPLETE_ACH) }) + const detail = await detailOf(ach.get(FIAT_ACCOUNT_ID)) + expect(detail).toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) + +describe('ach.getInstructions', () => { + it('reads instructions over the public instructions path and accepts no query parameter', async () => { + const { ach, transport } = okClient(COMPLETE_INSTRUCTION) + + const instruction = await ach.getInstructions(FIAT_ACCOUNT_ID) + + // Unlike `wires.getInstructions`, the ACH route has no public `accountId` + // — the SDK method signature carries no query parameter at all. + expect(transport.sent).toEqual([ + { + method: 'GET', + path: `/v1/banks/ach/${FIAT_ACCOUNT_ID}/instructions`, + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(instruction.trackingRef).toBe('CIR1') + expect(instruction.beneficiaryBank?.routingNumber).toBe('121000248') + }) + + it('rejects a non-UUID fiatAccountId locally without sending a request', async () => { + const { ach, transport } = okClient(COMPLETE_INSTRUCTION) + expect((await detailOf(ach.getInstructions('not-a-uuid'))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('failure mapping', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + const { ach } = clientFor({ status: 404, bodyBytes: bytes('{"status":{"code":4004}}') }) + expect(await detailOf(ach.get(FIAT_ACCOUNT_ID))).toMatchObject({ + kind: 'api', + httpStatus: 404, + daaStatusCode: 4004, + }) + }) + + /** + * An environment may lack `GET /v1/banks/ach` entirely; see + * `AchFiatAccountsClient`'s class doc: this SDK does not distinguish that + * from any other `api` failure. + */ + it('surfaces a missing route as an ordinary api error, not a distinguished capability error', async () => { + const { ach } = clientFor({ status: 404, bodyBytes: bytes('{}') }) + const detail = await detailOf(ach.list({ clientEntityId: CLIENT_ENTITY_ID })) + expect(detail).toMatchObject({ kind: 'api', httpStatus: 404 }) + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).fiatAccounts.ach.get( + FIAT_ACCOUNT_ID, + ), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) diff --git a/src/__test__/achPayload.test.ts b/src/__test__/achPayload.test.ts new file mode 100644 index 0000000..db82d09 --- /dev/null +++ b/src/__test__/achPayload.test.ts @@ -0,0 +1,150 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' + +import { toAch, toAchInstruction, toAchList } from '../wire/achPayload' + +const COMPLETE_ACH = { + id: 'a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd', + type: 'ach', + status: 'complete', + description: 'WELLS FARGO BANK, NA ****0010', + trackingRef: 'CIR1A2B3C4', + fingerprint: 'eb170539-9e1c-4e92-bf4f-1d09534fdca2', + billingDetails: { + name: 'Satoshi Nakamoto', + city: 'Boston', + country: 'US', + line1: '100 Money Street', + postalCode: '01234', + }, + routingNumber: '121000248', + createDate: '2026-01-01T00:00:00Z', + updateDate: '2026-01-02T00:00:00Z', +} + +function decode(extra: Record = {}) { + return toAch({ ...COMPLETE_ACH, ...extra }) +} + +describe('ach payload', () => { + it('decodes the guaranteed core and defaults every absent enrichment', () => { + const ach = decode() + + expect(ach.id).toBe(COMPLETE_ACH.id) + expect(ach.status).toEqual({ kind: 'complete' }) + expect(ach.description).toBe(COMPLETE_ACH.description) + expect(ach.trackingRef).toBe(COMPLETE_ACH.trackingRef) + expect(ach.fingerprint).toBe(COMPLETE_ACH.fingerprint) + expect(ach.billingDetails.name).toBe('Satoshi Nakamoto') + expect(ach.routingNumber).toBe('121000248') + expect(ach.bankAddress).toBeNull() + }) + + it('rejects an ACH account missing a guaranteed field', () => { + const partial: Record = { ...COMPLETE_ACH } + delete partial.billingDetails + expect(() => toAch(partial)).toThrow() + }) + + it('defaults routingNumber to null when the service omits it', () => { + const partial: Record = { ...COMPLETE_ACH } + delete partial.routingNumber + expect(toAch(partial).routingNumber).toBeNull() + }) + + it('decodes the unpaginated collection array (the full ACH projection, not a summary)', () => { + const list = toAchList([COMPLETE_ACH, { ...COMPLETE_ACH, id: 'other-id' }]) + expect(list).toHaveLength(2) + expect(list[0]?.routingNumber).toBe('121000248') + expect(list[1]?.id).toBe('other-id') + }) + + it('rejects a collection body that is not an array', () => { + expect(() => toAchList(COMPLETE_ACH)).toThrow() + }) + + /** + * ACH `routingNumber` is restricted PII, alongside `billingDetails` and + * `bankAddress`. All three must never enter logs, + * traces, crash reports, or analytics. + */ + it('redacts billingDetails, bankAddress, and routingNumber from JSON and default inspection', () => { + const ach = decode({ bankAddress: { country: 'US' } }) + + const json = JSON.stringify(ach) + expect(json).not.toContain('Satoshi') + expect(json).not.toContain('121000248') + expect(ach.toString()).not.toContain('121000248') + expect(inspect(ach)).not.toContain('121000248') + expect(Object.keys(ach)).not.toContain('routingNumber') + expect(Object.keys(ach)).not.toContain('billingDetails') + }) + + it('renders a present routingNumber as redacted rather than null', () => { + const rendered = JSON.parse(JSON.stringify(decode())) as { routingNumber: string } + expect(rendered.routingNumber).toBe('') + }) +}) + +describe('ach instruction payload', () => { + const INSTRUCTION = { + trackingRef: 'CIR1A2B3C4', + beneficiary: { + name: 'CIRCLE INTERNET FINANCIAL INC', + address1: '99 HIGH STREET', + address2: 'BOSTON MA 02110', + }, + beneficiaryBank: { + name: 'WELLS FARGO BANK', + routingNumber: '121000248', + accountNumber: '****7427', + address: '4250 EXECUTIVE SQUARE SUITE 300', + city: 'LA JOLLA', + postalCode: '02110', + country: 'US', + }, + } + + it('decodes every field, including the Circle beneficiary identity unredacted', () => { + const instruction = toAchInstruction(INSTRUCTION) + + expect(instruction.trackingRef).toBe('CIR1A2B3C4') + expect(instruction.beneficiary).toEqual(INSTRUCTION.beneficiary) + expect(instruction.beneficiaryBank?.routingNumber).toBe('121000248') + }) + + it('defaults every field to null when the instruction is empty', () => { + const instruction = toAchInstruction({}) + expect(instruction.trackingRef).toBeNull() + expect(instruction.beneficiary).toBeNull() + expect(instruction.beneficiaryBank).toBeNull() + }) + + it('redacts beneficiaryBank (routingNumber, accountNumber) but not the Circle beneficiary', () => { + const instruction = toAchInstruction(INSTRUCTION) + + const json = JSON.stringify(instruction) + expect(json).not.toContain('121000248') + expect(json).not.toContain('7427') + expect(json).toContain('CIRCLE INTERNET FINANCIAL INC') + expect(instruction.toString()).not.toContain('121000248') + expect(inspect(instruction)).not.toContain('121000248') + }) +}) diff --git a/src/__test__/addressObjectPayload.test.ts b/src/__test__/addressObjectPayload.test.ts new file mode 100644 index 0000000..0f6dc30 --- /dev/null +++ b/src/__test__/addressObjectPayload.test.ts @@ -0,0 +1,286 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import * as sdk from '../index' +import { AddressObject } from '../models/AddressObject' +import { toAddressObject } from '../wire/addressObjectPayload' +import { MalformedPayloadError } from '../wire/payload' + +/** + * Decoding tests for the deposit-address model. + * + * These go through the real parse and mapping rather than constructing a + * payload object directly, because the wire spellings and the + * required/optional line are what is under test. + */ + +/** The fields every custody source guarantees on a by-id read. */ +const REQUIRED = '"id":"addr-1","address":"0xRECEIVE","chain":"ETH"' + +function decode(body: string): AddressObject { + return toAddressObject(JSON.parse(body) as unknown) +} + +function decodeComplete(extra = ''): AddressObject { + return decode(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) +} + +function addressWith(field: string, value: string): AddressObject { + return decodeComplete(`"${field}":${value}`) +} + +describe('required and optional fields', () => { + /** + * A response missing something every custody source guarantees is + * malformed, not an address with a hole in it. + */ + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + id: '"addr-1"', + address: '"0xRECEIVE"', + chain: '"ETH"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + // Sanity: the complete body decodes, or every assertion below is vacuous. + expect(decode(body(complete)).id).toBe('addr-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toAddressObject(null)).toThrow(MalformedPayloadError) + expect(() => toAddressObject([])).toThrow(MalformedPayloadError) + }) + + /** An explicit `null` on a guaranteed field is the same defect as omitting it. */ + it('rejects an explicit null on a guaranteed field', () => { + expect(() => decode('{"id":null,"address":"0xRECEIVE","chain":"ETH"}')).toThrow( + MalformedPayloadError, + ) + }) + + /** A present field in a shape the contract does not describe is malformed, not coerced. */ + it('rejects a field carried in the wrong shape', () => { + expect(() => addressWith('id', '{}')).toThrow(MalformedPayloadError) + expect(() => addressWith('id', 'true')).toThrow(MalformedPayloadError) + expect(() => addressWith('address', '7')).toThrow(MalformedPayloadError) + expect(() => addressWith('addressTag', '[]')).toThrow(MalformedPayloadError) + expect(() => addressWith('currency', '7')).toThrow(MalformedPayloadError) + expect(() => addressWith('accountId', '{}')).toThrow(MalformedPayloadError) + expect(() => addressWith('chain', '9')).toThrow(MalformedPayloadError) + }) + + /** + * `currency` is absent on segregated and self-custody by-id reads and + * present on `create`. A model that required it would fail to decode most + * segregated and self-custody address reads. + */ + it('tolerates an address with no currency', () => { + expect(decodeComplete().currency).toBeNull() + expect(addressWith('currency', '"USD"').currency).toBe('USD') + }) + + /** `accountId` is null when an omnibus address cannot be attributed to an account. */ + it('carries accountId including a null one for an unattributed omnibus address', () => { + expect(addressWith('accountId', '"acct-1"').accountId).toBe('acct-1') + expect(decodeComplete().accountId).toBeNull() + }) + + /** `addressTag` is present only on omnibus addresses; segregated and self-custody have none. */ + it('carries addressTag including a null one', () => { + expect(addressWith('addressTag', '"MEMO123"').addressTag).toBe('MEMO123') + expect(decodeComplete().addressTag).toBeNull() + }) +}) + +describe('chain and currency are plain strings, not closed unions', () => { + /** + * The service adds chains and currencies independently of an SDK release — + * the same reason `Account.blockchain` and `Money.currency` are plain + * strings. A chain or + * currency this version has never heard of must still decode. + */ + it('carries a chain this version has never heard of', () => { + expect(addressWith('chain', '"SOME_NEW_CHAIN"').chain).toBe('SOME_NEW_CHAIN') + }) + + it('carries a currency this version has never heard of', () => { + expect(addressWith('currency', '"SOME_NEW_CURRENCY"').currency).toBe('SOME_NEW_CURRENCY') + }) +}) + +describe('forward compatibility', () => { + /** + * Forward-compatible decoding: an unknown response field + * must not fail the read, matching the service's own tolerance for unknown + * fields. + */ + it('ignores an unknown response field wherever it appears', () => { + const address = decode( + '{"id":"addr-1","address":"0xRECEIVE","chain":"ETH","riskScore":7,"flags":null,' + + '"metadata":{"nested":true}}', + ) + + expect(address.id).toBe('addr-1') + expect(address.chain).toBe('ETH') + expect(Object.keys(address)).not.toContain('riskScore') + expect(Object.keys(address)).not.toContain('metadata') + }) +}) + +describe('redaction', () => { + const address = decodeComplete('"addressTag":"MEMO-SECRET","currency":"USD","accountId":"acct-1"') + const secrets = ['0xRECEIVE', 'MEMO-SECRET'] + + /** + * There is no `toString` hook every JavaScript rendering path goes through, + * so redaction is held by **absence**: `address` and `addressTag` are + * reached only through a prototype accessor over a `#` private field, never + * an own property, so `Object.keys`, `JSON.stringify`, spread, `for...in`, + * and the inspectors behind `console.log` cannot reach them. + */ + it('keeps the address and its tag off the object as an own property', () => { + expect(Object.getOwnPropertyNames(address).sort()).toEqual( + ['id', 'currency', 'chain', 'accountId'].sort(), + ) + }) + + it.each([ + ['JSON.stringify', (value: unknown): string => JSON.stringify(value) ?? ''], + ['util.inspect (what console.log renders)', (value: unknown): string => inspect(value)], + ['util.inspect at full depth', (value: unknown): string => inspect(value, { depth: null })], + ['String()', (value: unknown): string => String(value)], + ['template literal', (value: unknown): string => `${String(value)}`], + [ + 'spread into a plain object', + (value: unknown): string => JSON.stringify({ ...(value as object) }) ?? '', + ], + [ + 'for...in', + (value: unknown): string => { + let out = '' + for (const key in value as Record) { + out += `${key}=${String((value as Record)[key])};` + } + return out + }, + ], + ])('reveals no sensitive value through %s', (_name, render) => { + const rendered = render(address) + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + }) + + it('still renders the identifiers and states that make a log line useful', () => { + expect(String(address)).toContain('addr-1') + expect(String(address)).toContain('ETH') + expect(JSON.stringify(address)).toContain('addr-1') + expect(inspect(address)).toContain('addr-1') + }) + + it('says the address and its tag were withheld rather than omitting them silently', () => { + expect(String(address)).toContain('address=') + expect(String(address)).toContain('addressTag=') + expect(JSON.parse(JSON.stringify(address))).toMatchObject({ + address: '', + addressTag: '', + }) + }) + + /** There is nothing to redact from an address with no tag, so it renders `null`, not a marker. */ + it('renders a null addressTag as null rather than a redaction marker', () => { + const noTag = decodeComplete() + expect(JSON.parse(JSON.stringify(noTag))).toMatchObject({ addressTag: null }) + expect(String(noTag)).toContain('addressTag=null') + }) + + /** + * **The honest limit, recorded rather than claimed away.** What is prevented + * is a value reaching a log by *accident*. `util.inspect(value, { showHidden: + * true, getters: true })` walks and calls prototype accessors deliberately, + * and reveals every field — the same limit `accountPayload.test.ts` pins for + * `Account`. + */ + it('does not withhold from an inspector explicitly asked to evaluate accessors', () => { + const revealing = inspect(address, { showHidden: true, getters: true, depth: null }) + expect(revealing).toContain('0xRECEIVE') + expect(revealing).toContain('MEMO-SECRET') + + // The ordinary route, and it is the public read the model exists to provide. + expect(address.address).toBe('0xRECEIVE') + expect(address.addressTag).toBe('MEMO-SECRET') + }) +}) + +describe('immutability', () => { + const address = decodeComplete() + + /** `readonly` is erased at compile time; freezing at construction is what actually holds this. */ + it('freezes the address object', () => { + expect(Object.isFrozen(address)).toBe(true) + }) + + it('refuses a write through a cast', () => { + const mutable = address as unknown as Record + expect(() => { + mutable['id'] = 'addr-forged' + }).toThrow(TypeError) + expect(() => { + mutable['newField'] = 'x' + }).toThrow(TypeError) + expect(address.id).toBe('addr-1') + }) +}) + +describe('consumer construction', () => { + /** + * No runtime constructor for this model reaches the public entry. The model is + * exported as a type only, matching the guarantee for `Account`. + */ + it('exposes no model constructor on the public entry', () => { + const runtime = sdk as unknown as Record + expect(runtime['AddressObject']).toBeUndefined() + }) + + /** + * The `#` private fields mean an object shaped like an address is not one, + * so a fabricated value cannot be passed to code that checks. + */ + it('does not accept a look-alike object as an address object', () => { + const fabricated = { + id: 'addr-forged', + address: '0xattacker', + addressTag: null, + currency: null, + chain: 'ETH', + accountId: null, + } + + expect(fabricated instanceof AddressObject).toBe(false) + expect(decodeComplete() instanceof AddressObject).toBe(true) + }) +}) diff --git a/src/__test__/alias.test.ts b/src/__test__/alias.test.ts new file mode 100644 index 0000000..7d09eba --- /dev/null +++ b/src/__test__/alias.test.ts @@ -0,0 +1,319 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { deriveKeyScope, parseSecureKeyAlias, secureKeyAlias } from '../securekey/alias' + +// Any UUID; `isUuid` does not require a version nibble. +const CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000001' +const OTHER_CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000002' + +// A pinned worked example: SHA-256 over the UTF-8 bytes of +// `acme` + NUL + `sandbox` + NUL + `00000000-0000-4000-8000-000000000001`, +// truncated to the first 16 bytes and re-encoded as unpadded Base64URL. +// Recomputing this by hand is the fastest way to confirm `deriveKeyScope` +// hasn't silently changed its preimage or truncation. +const ACME_SANDBOX_OWNER_1_SCOPE = 'lS_9Ek7W1iNw6422KoRTwA' + +describe('deriveKeyScope', () => { + it('matches a pinned worked example', () => { + expect( + deriveKeyScope({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toBe(ACME_SANDBOX_OWNER_1_SCOPE) + }) + + it('is exactly 22 unpadded-Base64URL characters (128-bit digest)', () => { + const scope = deriveKeyScope({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(scope).toMatch(/^[A-Za-z0-9_-]{22}$/) + }) + + it('is stable for the same identity', () => { + const identity = { + appId: 'acme', + environment: 'sandbox' as const, + clientEntityId: CLIENT_ENTITY_ID, + } + expect(deriveKeyScope(identity)).toBe(deriveKeyScope({ ...identity })) + }) + + it('differs for two different clientEntityIds on the same appId/environment', () => { + const scopeA = deriveKeyScope({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const scopeB = deriveKeyScope({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: OTHER_CLIENT_ENTITY_ID, + }) + expect(scopeA).not.toBe(scopeB) + }) + + it('never contains the raw clientEntityId', () => { + const scope = deriveKeyScope({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(scope).not.toContain(CLIENT_ENTITY_ID) + // Nor any hyphen-delimited fragment a UUID would leave if it were + // simply concatenated rather than hashed. + expect(scope).not.toMatch(/-/) + }) + + it('differs across appId and across environment for the same clientEntityId', () => { + const base = { + appId: 'acme', + environment: 'sandbox' as const, + clientEntityId: CLIENT_ENTITY_ID, + } + const differentApp = deriveKeyScope({ ...base, appId: 'other-app' }) + const differentEnv = deriveKeyScope({ ...base, environment: 'production' }) + const scope = deriveKeyScope(base) + expect(differentApp).not.toBe(scope) + expect(differentEnv).not.toBe(scope) + }) +}) + +describe('secureKeyAlias', () => { + it('builds {appId}.{keyScope}.{environment} for valid input', () => { + expect( + secureKeyAlias({ appId: 'acme', environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }), + ).toBe(`acme.${ACME_SANDBOX_OWNER_1_SCOPE}.sandbox`) + }) + + it('rejects an empty or over-long appId', () => { + expect(() => + secureKeyAlias({ appId: '', environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }), + ).toThrow(/appId must match/) + expect(() => + secureKeyAlias({ + appId: 'a'.repeat(65), + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toThrow(/appId must match/) + }) + + it('rejects a disallowed character in appId', () => { + expect(() => + secureKeyAlias({ + appId: 'acme/evil', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toThrow(/appId must match/) + }) + + it('rejects an environment outside the allow-list', () => { + expect(() => + secureKeyAlias({ + appId: 'acme', + environment: 'Production' as never, + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toThrow(/unknown environment/) + }) + + it('rejects a clientEntityId that is not a UUID', () => { + expect(() => + secureKeyAlias({ appId: 'acme', environment: 'sandbox', clientEntityId: 'not-a-uuid' }), + ).toThrow(/clientEntityId must be a UUID/) + }) + + // Two different Owners on one installation resolve to different AuthKeys: + // user A registers, signs out, user B signs in, and B's registration must + // not reuse A's key. + it('produces different aliases for different clientEntityIds on the same appId/environment', () => { + const aliasA = secureKeyAlias({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const aliasB = secureKeyAlias({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: OTHER_CLIENT_ENTITY_ID, + }) + expect(aliasA).not.toBe(aliasB) + }) + + // A returning clientEntityId resolves to the SAME alias (and therefore, via + // the store's alias-keyed cache/native tag, the SAME AuthKey) it did before. + it('produces the same alias for a returning clientEntityId', () => { + const identity = { + appId: 'acme', + environment: 'sandbox' as const, + clientEntityId: CLIENT_ENTITY_ID, + } + expect(secureKeyAlias(identity)).toBe(secureKeyAlias({ ...identity })) + }) + + // The raw clientEntityId appears nowhere in the alias (and so nowhere in the + // native keychain tag the alias's appId slot feeds). + it('never contains the raw clientEntityId', () => { + const alias = secureKeyAlias({ + appId: 'acme', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(alias).not.toContain(CLIENT_ENTITY_ID) + }) + + it('keeps appId/environment injective', () => { + // Without environment validation, {"acme.staging","production"} and + // {"acme","staging.production"} would both yield "acme.staging.production". + // Validating `environment` makes the second impossible, with the per-Owner + // keyScope segment in the alias as well. + expect( + secureKeyAlias({ + appId: 'acme.staging', + environment: 'production', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toBe( + `acme.staging.${deriveKeyScope({ appId: 'acme.staging', environment: 'production', clientEntityId: CLIENT_ENTITY_ID })}.production`, + ) + expect(() => + secureKeyAlias({ + appId: 'acme', + environment: 'staging.production' as never, + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toThrow(/unknown environment/) + }) + + // Combined appId + digest over 64 characters fails closed with a contract + // violation. The digest is a fixed 22 characters plus a 1-character + // separator, so the appId budget is exactly 41. + it('accepts an appId at exactly the 41-character budget', () => { + const appId = 'a'.repeat(41) + expect(() => + secureKeyAlias({ appId, environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }), + ).not.toThrow() + }) + + it('fails closed with a contract violation one character over the appId budget', () => { + const appId = 'a'.repeat(42) + expect(() => + secureKeyAlias({ appId, environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }), + ).toThrow(/at most 41 characters/) + }) + + // The 42-64 band must be rejected at the door by the same check that reports + // the consumer-facing limit, not accepted here and refused later during key + // resolution. Reverse-DNS bundle identifiers land squarely in this band. + it('rejects the 42-64 band with the consumer-facing limit, not native 64', () => { + expect(() => + secureKeyAlias({ + appId: 'com.example.digitalassetaccounts.wallet.debug', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).toThrow(/at most 41 characters/) + }) + + it('does not echo the full appId into the budget error message', () => { + const appId = 'x'.repeat(60) + expect.assertions(1) + try { + secureKeyAlias({ appId, environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }) + } catch (e) { + expect((e as Error).message).not.toContain(appId) + } + }) + + it('does not echo the full appId into the pattern error message', () => { + const long = 'x'.repeat(200) + expect.assertions(1) + try { + secureKeyAlias({ appId: long, environment: 'sandbox', clientEntityId: CLIENT_ENTITY_ID }) + } catch (e) { + expect((e as Error).message).not.toContain(long) + } + }) +}) + +describe('parseSecureKeyAlias', () => { + // NOT a full inverse of secureKeyAlias: deriveKeyScope is one-way, + // so parsing an alias built from a real identity cannot recover + // clientEntityId, and what it returns for "appId" is the composed + // `{appId}.{keyScope}` native saw — not the consumer's original `appId`. + it('recovers environment and the composed native appId, not the original identity', () => { + const identity = { + appId: 'acme.staging', + environment: 'production' as const, + clientEntityId: CLIENT_ENTITY_ID, + } + const alias = secureKeyAlias(identity) + const scope = deriveKeyScope(identity) + expect(parseSecureKeyAlias(alias)).toEqual({ + appId: `acme.staging.${scope}`, + environment: 'production', + }) + }) + + // The composed value routinely exceeds the 41-character consumer budget (a + // 23-char appId composes to 46), so this path must be validated against + // native's 64, NOT against MAX_APP_ID_LENGTH. Enforcing the consumer cap + // here would reject almost every real alias and break key resolution for + // every existing Owner. + it('accepts a composed appId longer than the consumer budget', () => { + const identity = { + appId: 'com.example.wallet.demo', + environment: 'sandbox' as const, + clientEntityId: CLIENT_ENTITY_ID, + } + const composed = `${identity.appId}.${deriveKeyScope(identity)}` + expect(composed.length).toBe(46) + expect(parseSecureKeyAlias(secureKeyAlias(identity))).toEqual({ + appId: composed, + environment: 'sandbox', + }) + }) + + it('splits from the right so the last segment is the environment', () => { + expect(parseSecureKeyAlias('acme.staging.production')).toEqual({ + appId: 'acme.staging', + environment: 'production', + }) + }) + + it('rejects a value whose last segment is not an allowed environment', () => { + expect(() => parseSecureKeyAlias('acme.sandbox.evil')).toThrow(/unknown environment/) + expect(() => parseSecureKeyAlias('acme')).toThrow(/must be \{appId\}\.\{environment\}/) + }) + + it('does not echo the alias into the error message', () => { + const long = `x${'y'.repeat(200)}.not-an-env` + expect.assertions(1) + try { + parseSecureKeyAlias(long) + } catch (e) { + expect((e as Error).message).not.toContain(long) + } + }) +}) diff --git a/src/__test__/authClient.test.ts b/src/__test__/authClient.test.ts new file mode 100644 index 0000000..c538f18 --- /dev/null +++ b/src/__test__/authClient.test.ts @@ -0,0 +1,817 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { AuthClient } from '../api/AuthClient' +import { requireDaaRegistrationNative } from '../auth/daaRegistrationNative' +import { registrationCodeChallengeS256 } from '../auth/registrationCodeVerifier' +import { DEVICE_KEY_POLICY } from '../config' +import { fromBase64Url } from '../crypto/base64url' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { DaaClient } from '../DaaClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import { PreparedSocialLogin } from '../models/PreparedSocialLogin' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { isUuidV4 } from '../validation/uuid' +import { + generateReceiptSigningKey, + receiptClaims, + signReceipt, + trustAnchorFor, + type ReceiptSigningKey, +} from './prepareReceiptSigning' + +/** + * `AuthClient.prepareSocialLogin`, end to end through the client. + * + * The load-bearing assertions are two contract requirements, and both are + * pinned literally rather than by regex: + * + * - the path is `/v1/accounts/auth/loginRequests` with no `/social/` segment + * (camelCase; contract `prepareSocialLogin`); + * - the body's key set is what the service accepts (no + * `registrationCodeChallengeMethod`). + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const LOGIN_REQUEST_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const NONCE = 'n'.repeat(48) +const STATE = 's'.repeat(48) +const RECEIPT = `eyJhbGciOiJFUzI1NiJ9.${'p'.repeat(64)}.c2ln` +const EXPIRES_AT = '2026-08-26T12:00:00Z' + +const PREPARED = `{"loginRequestId":"${LOGIN_REQUEST_ID}","oidcNonce":"${NONCE}","oidcState":"${STATE}","expiresAt":"${EXPIRES_AT}"}` + +function envelope(payload: string): Uint8Array { + return new TextEncoder().encode(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + client: AuthClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 201, + headers: response.headers ?? { 'X-Request-Id': 'req-1' }, + bodyBytes: response.bodyBytes ?? envelope(PREPARED), + }) + return { client: new AuthClient({ transport }), transport } +} + +function sentBody(transport: RecordingTransport): Record { + const request = transport.sent[0] + if (request === undefined || request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + return JSON.parse(new TextDecoder().decode(request.bodyBytes)) as Record +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + it('posts to the contract path, with no /social/ segment', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + expect(transport.sent).toHaveLength(1) + expect(transport.sent[0]?.method).toBe('POST') + expect(transport.sent[0]?.path).toBe('/v1/accounts/auth/loginRequests') + expect(transport.sent[0]?.path).not.toMatch(/social/) + expect(transport.sent[0]?.query).toBeNull() + expect(transport.sent[0]?.headers).toEqual({ 'Content-Type': 'application/json' }) + }) + + it('sends exactly the PrepareSocialLoginRequest fields', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'APPLE' }) + + expect(Object.keys(sentBody(transport)).sort()).toEqual([ + 'idempotencyKey', + 'provider', + 'registrationCodeChallenge', + 'registrationFlowPublicKey', + ]) + }) + + it('sends no AuthKey material of any kind', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const body = sentBody(transport) + for (const forbidden of [ + 'authKeyPublicKey', + 'authKeyId', + 'authKeyThumbprint', + 'publicKey', + 'thumbprint', + 'jkt', + 'kid', + 'installationId', + 'profileId', + ]) { + expect(body[forbidden]).toBeUndefined() + } + const request = transport.sent[0] + if (request === undefined || request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + // Belt and braces: nothing anywhere in the raw bytes names an AuthKey, and no + // device-authorization header rides along. + expect(new TextDecoder().decode(request.bodyBytes)).not.toMatch(/authKey/i) + expect(Object.keys(request.headers)).not.toContain('X-Device-Authorization') + }) + + it('sends an S256 challenge and the flow public key in the pinned wire forms', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const body = sentBody(transport) + expect(body.provider).toBe('GOOGLE') + expect(body.registrationCodeChallenge).toMatch(/^[A-Za-z0-9_-]{43}$/) + expect(body.registrationFlowPublicKey).toMatch(/^[A-Za-z0-9_-]{122}$/) + expect(fromBase64Url(body.registrationFlowPublicKey as string)).toHaveLength(91) + expect(isUuidV4(body.idempotencyKey as string)).toBe(true) + }) + + it('does not send the verifier — only its digest goes out at Prepare', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const body = sentBody(transport) + const challenge = body.registrationCodeChallenge as string + // The verifier is unreachable by construction, so this asserts the negative + // that is checkable: the challenge is a digest, so it cannot itself be the + // preimage the server later matches it against. + expect(registrationCodeChallengeS256(challenge)).not.toBe(challenge) + expect(Object.keys(body)).not.toContain('registrationCodeVerifier') + // No other value on the body hashes to the challenge either, so the verifier + // did not ride along under a different field name. + for (const value of Object.values(body)) { + if (typeof value === 'string' && value !== challenge) { + expect(registrationCodeChallengeS256(value)).not.toBe(challenge) + } + } + }) + + it('mints fresh attempt material per call', async () => { + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new AuthClient({ transport }) + + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const bodies = transport.sent.map((request) => { + if (request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + return JSON.parse(new TextDecoder().decode(request.bodyBytes)) as Record + }) + expect(bodies[0]?.idempotencyKey).not.toBe(bodies[1]?.idempotencyKey) + expect(bodies[0]?.registrationCodeChallenge).not.toBe(bodies[1]?.registrationCodeChallenge) + expect(bodies[0]?.registrationFlowPublicKey).not.toBe(bodies[1]?.registrationFlowPublicKey) + }) + + it('serializes the body once and sends that same slice', async () => { + const { client, transport } = clientFor({}) + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const request = transport.sent[0] + if (request === undefined || request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + const text = new TextDecoder().decode(request.bodyBytes) + // Key order is the contract's declaration order, and it is whatever + // `serializeBody` emitted — nothing re-serializes or canonicalizes it. + expect(text.indexOf('"idempotencyKey"')).toBeLessThan(text.indexOf('"provider"')) + expect(text.indexOf('"provider"')).toBeLessThan(text.indexOf('"registrationCodeChallenge"')) + expect(text.indexOf('"registrationCodeChallenge"')).toBeLessThan( + text.indexOf('"registrationFlowPublicKey"'), + ) + }) + + it('rejects a provider that is not an uppercase registry key, before sending anything', async () => { + for (const provider of ['google', 'Google', '', 'GOOGLE-X', 'G'.repeat(65), '1GOOGLE']) { + const { client, transport } = clientFor({}) + expect(await detailOf(client.prepareSocialLogin({ provider }))).toEqual({ + kind: 'contract_violation', + }) + expect(transport.sent).toHaveLength(0) + } + }) + + it('rejects a non-object input', async () => { + const { client } = clientFor({}) + for (const input of [null, undefined, 'GOOGLE', ['GOOGLE']]) { + expect( + await detailOf(client.prepareSocialLogin(input as unknown as { provider: string })), + ).toEqual({ kind: 'contract_violation' }) + } + }) +}) + +describe('the response', () => { + it('returns the PreparedSocialLogin fields and nothing about an AuthKey', async () => { + const { client } = clientFor({}) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + expect(prepared).toBeInstanceOf(PreparedSocialLogin) + expect(Object.keys(prepared).sort()).toEqual([ + 'expiresAt', + 'loginRequestId', + 'oidcNonce', + 'oidcState', + 'prepareReceiptJws', + ]) + expect(prepared.loginRequestId).toBe(LOGIN_REQUEST_ID) + expect(prepared.oidcNonce).toBe(NONCE) + expect(prepared.oidcState).toBe(STATE) + expect(prepared.prepareReceiptJws).toBeNull() + expect(prepared.expiresAt).toBe(EXPIRES_AT) + expect(Object.isFrozen(prepared)).toBe(true) + }) + + it('returns a usable PreparedSocialLogin from the body the service sends', async () => { + // The `201` body below is a captured response to this client's own + // Prepare request. It differs from the contract in two ways — + // `expiresAt` is a JSON number of epoch milliseconds, and there is no + // `prepareReceiptJws` — so this is the end-to-end case, not just the decoder's. + const { client } = clientFor({ + bodyBytes: new TextEncoder().encode( + '{"data":{"loginRequestId":"9f6ead8b-ff88-43fc-af00-7016eef7f4b3",' + + '"oidcNonce":"V3dQJq2pX2-t70oIlt0EX7I6oZLo_id94-43ywbCAL8",' + + '"oidcState":"VVOX5X68MHIBzK2K8eVOtad3pQAFGs2vDxY43QosYAA",' + + '"expiresAt":1788290024580}}', + ), + }) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + expect(prepared).toBeInstanceOf(PreparedSocialLogin) + expect(prepared.loginRequestId).toBe('9f6ead8b-ff88-43fc-af00-7016eef7f4b3') + expect(prepared.prepareReceiptJws).toBeNull() + // Normalised at the decode boundary: the public field is the ISO-8601 string + // whichever form arrived, so a consumer never branches on the wire's type. + expect(prepared.expiresAt).toBe('2026-09-01T19:13:44.580Z') + }) + + it('ignores a receipt when no trust anchor is pinned, and login proceeds as if none arrived', async () => { + // Anything in the receipt member — a well-formed JWS, a malformed string, a + // value of the wrong type — is ignored alike, and none reaches the application. + for (const receiptMember of [`"${RECEIPT}"`, '"not-a-jws"', '42', '{"alg":"none"}']) { + const { client } = clientFor({ + bodyBytes: envelope( + `{"loginRequestId":"${LOGIN_REQUEST_ID}","oidcNonce":"${NONCE}","oidcState":"${STATE}","expiresAt":"${EXPIRES_AT}","prepareReceiptJws":${receiptMember}}`, + ), + }) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + expect(prepared).toBeInstanceOf(PreparedSocialLogin) + expect(prepared.loginRequestId).toBe(LOGIN_REQUEST_ID) + expect(prepared.oidcNonce).toBe(NONCE) + expect(prepared.prepareReceiptJws).toBeNull() + } + }) + + it('holds the attempt secret privately: the verifier is on no enumerable surface', async () => { + const { client, transport } = clientFor({}) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const challenge = sentBody(transport).registrationCodeChallenge as string + + const serialized = JSON.stringify(prepared) + expect(serialized).not.toMatch(/verifier/i) + // Whatever the verifier is, its digest is the challenge. If the verifier had + // leaked onto an enumerable field, hashing every string on the object would + // reproduce the challenge. + for (const value of Object.values(prepared as unknown as Record)) { + if (typeof value === 'string') { + expect(registrationCodeChallengeS256(value)).not.toBe(challenge) + } + } + }) + + it('does not put the idToken into the error when Social Session fails', async () => { + const { client } = clientFor({}) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + // This transport only knows Prepare's 201; Session is a different call. + const detail = await detailOf( + prepared.completeSocialSession({ + idToken: 'ID_TOKEN_MARKER', + clientEntityId: CLIENT_ENTITY_ID, + }), + ) + expect(detail.kind).toBe('api') + await prepared + .completeSocialSession({ idToken: 'ID_TOKEN_MARKER', clientEntityId: CLIENT_ENTITY_ID }) + .catch((err: unknown) => { + expect((err as Error).message).not.toMatch(/ID_TOKEN_MARKER/) + }) + }) + + it('releases the flow key when completeSocialSession fails closed', async () => { + let releaseCalls = 0 + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new AuthClient({ + transport, + registrationFlowKeys: { + async generate() { + return { + async publicKeySpkiBase64Url() { + return 'I'.repeat(122) + }, + async signExactBytes() { + throw new Error('flow-key sign unused in this test') + }, + async release() { + releaseCalls += 1 + }, + } + }, + }, + }) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + expect(releaseCalls).toBe(0) + + await expect( + prepared.completeSocialSession({ idToken: 'token', clientEntityId: CLIENT_ENTITY_ID }), + ).rejects.toBeDefined() + expect(releaseCalls).toBe(1) + }) + + it('releases the flow key when the application abandons a successful Prepare', async () => { + let releaseCalls = 0 + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new AuthClient({ + transport, + registrationFlowKeys: { + async generate() { + return { + async publicKeySpkiBase64Url() { + return 'I'.repeat(122) + }, + async signExactBytes() { + throw new Error('flow-key sign unused in this test') + }, + async release() { + releaseCalls += 1 + }, + } + }, + }, + }) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + expect(releaseCalls).toBe(0) + + await prepared.abandon() + expect(releaseCalls).toBe(1) + await prepared.abandon() + expect(releaseCalls).toBe(2) + }) + + it('maps 410 to login_request_expired', async () => { + const { client } = clientFor({ status: 410, bodyBytes: null }) + expect(await detailOf(client.prepareSocialLogin({ provider: 'GOOGLE' }))).toEqual({ + kind: 'login_request_expired', + }) + }) + + it('maps 409 with IDEMPOTENCY_KEY_REUSED to idempotency_conflict, carrying the key the SDK minted', async () => { + const { client, transport } = clientFor({ + status: 409, + bodyBytes: new TextEncoder().encode('{"code":420034,"message":"m","externalMessage":"e"}'), + }) + const detail = await detailOf(client.prepareSocialLogin({ provider: 'GOOGLE' })) + + expect(detail.kind).toBe('idempotency_conflict') + if (detail.kind === 'idempotency_conflict') { + expect(detail.idempotencyKey).toBe(sentBody(transport).idempotencyKey) + } + }) + + it('treats any other status, including another 2xx, as an api failure', async () => { + for (const status of [200, 202, 401, 429, 503]) { + const { client } = clientFor({ status, bodyBytes: envelope(PREPARED) }) + const detail = await detailOf(client.prepareSocialLogin({ provider: 'GOOGLE' })) + expect(detail.kind).toBe('api') + if (detail.kind === 'api') { + expect(detail.httpStatus).toBe(status) + expect(detail.retryable).toBe(status === 429 || status >= 500) + } + } + }) + + it('reports a response it cannot read as a contract violation with the correlation id', async () => { + const { client } = clientFor({ + headers: { 'X-Request-Id': 'req-7' }, + bodyBytes: envelope('{"loginRequestId":"not-a-uuid"}'), + }) + expect(await detailOf(client.prepareSocialLogin({ provider: 'GOOGLE' }))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-7', + }) + }) + + it('rethrows whatever the consumer transport threw, unchanged', async () => { + const failure = new Error('offline') + const client = new AuthClient({ + transport: { + async send() { + throw failure + }, + }, + }) + await expect(client.prepareSocialLogin({ provider: 'GOOGLE' })).rejects.toBe(failure) + }) + + it('sends the injected provider key verbatim, not the native default', async () => { + // Pins the `registrationFlowKeys` seam's contract. Production defaults to + // native DaaRegistration; this is the only test that substitutes the + // provider, so without it the swap's only contract would be untested. + const injected = 'I'.repeat(122) + let generateCalls = 0 + let releaseCalls = 0 + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new AuthClient({ + transport, + registrationFlowKeys: { + async generate() { + generateCalls += 1 + return { + async publicKeySpkiBase64Url() { + return injected + }, + async signExactBytes() { + throw new Error('flow-key sign unused in this test') + }, + async release() { + releaseCalls += 1 + }, + } + }, + }, + }) + + await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + expect(generateCalls).toBe(1) + expect(releaseCalls).toBe(0) + // Verbatim: the client must not re-encode or normalize what the provider + // returned. A native provider hands back the platform's own SPKI encoding. + expect(sentBody(transport).registrationFlowPublicKey).toBe(injected) + }) + + it('releases the flow key when Prepare fails after minting it', async () => { + let releaseCalls = 0 + const client = new AuthClient({ + transport: { + async send() { + throw new Error('offline') + }, + }, + registrationFlowKeys: { + async generate() { + return { + async publicKeySpkiBase64Url() { + return 'I'.repeat(122) + }, + async signExactBytes() { + throw new Error('flow-key sign unused in this test') + }, + async release() { + releaseCalls += 1 + }, + } + }, + }, + }) + + await expect(client.prepareSocialLogin({ provider: 'GOOGLE' })).rejects.toThrow('offline') + expect(releaseCalls).toBe(1) + }) + + it('does not let a throwing release replace the transport error', async () => { + const failure = new Error('offline') + const client = new AuthClient({ + transport: { + async send() { + throw failure + }, + }, + registrationFlowKeys: { + async generate() { + return { + async publicKeySpkiBase64Url() { + return 'I'.repeat(122) + }, + async signExactBytes() { + throw new Error('flow-key sign unused in this test') + }, + async release() { + throw new Error('release blew up') + }, + } + }, + }, + }) + + await expect(client.prepareSocialLogin({ provider: 'GOOGLE' })).rejects.toBe(failure) + }) +}) + +/** + * A transport standing in for DAA with a receipt signer configured: it reads + * the challenge and flow key the SDK sent and signs a receipt over them, the + * way the service's Prepare does. `tamper` models a relay rewriting the + * response on the way back. + */ +class ReceiptIssuingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor( + private readonly key: ReceiptSigningKey, + private readonly tamper: ( + claims: Record, + data: Record, + ) => void = () => {}, + ) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const body = JSON.parse(new TextDecoder().decode(request.bodyBytes!)) as Record + const now = Math.floor(Date.now() / 1000) + const claims = receiptClaims( + { + loginRequestId: LOGIN_REQUEST_ID, + nonce: NONCE, + provider: body['provider']!, + environment: 'sandbox', + registrationCodeChallenge: body['registrationCodeChallenge']!, + registrationFlowKeyThumbprint: p256JwkThumbprint( + fromBase64Url(body['registrationFlowPublicKey']!), + ), + }, + now, + ) + const data: Record = { + loginRequestId: LOGIN_REQUEST_ID, + oidcNonce: NONCE, + oidcState: STATE, + expiresAt: EXPIRES_AT, + } + this.tamper(claims, data) + if (!('prepareReceiptJws' in data)) { + data['prepareReceiptJws'] = await signReceipt(this.key, claims) + } + return { + status: 201, + headers: {}, + bodyBytes: new TextEncoder().encode(JSON.stringify({ data })), + } + } +} + +describe('the Prepare receipt with a trust anchor pinned', () => { + let key: ReceiptSigningKey + + beforeAll(async () => { + key = await generateReceiptSigningKey('sandbox-receipt-1') + }) + + function anchoredClient(transport: DaaTransport): AuthClient { + return new AuthClient({ + transport, + environment: 'sandbox', + prepareReceiptTrustAnchor: trustAnchorFor([key]), + }) + } + + it('returns the PreparedSocialLogin when the receipt binds this attempt', async () => { + const transport = new ReceiptIssuingTransport(key) + const prepared = await anchoredClient(transport).prepareSocialLogin({ provider: 'GOOGLE' }) + expect(prepared.loginRequestId).toBe(LOGIN_REQUEST_ID) + expect(prepared.oidcNonce).toBe(NONCE) + expect(prepared.prepareReceiptJws).not.toBeNull() + }) + + it.each([ + [ + 'a missing receipt', + (_c: Record, d: Record) => { + d['prepareReceiptJws'] = null + }, + ], + [ + 'a malformed receipt', + (_c: Record, d: Record) => { + d['prepareReceiptJws'] = 'not-a-jws' + }, + ], + [ + 'a receipt that is not a string', + (_c: Record, d: Record) => { + d['prepareReceiptJws'] = 42 + }, + ], + [ + 'a relay-substituted challenge', + (c: Record) => { + c['registrationCodeChallenge'] = registrationCodeChallengeS256( + 'another-attempt-verifier-'.repeat(2), + ) + }, + ], + [ + 'a relay-substituted flow key', + (c: Record) => { + c['registrationFlowKeyThumbprint'] = 'xx0BcA-wMohw8atYDJOe6peGModklG2wRHBlXHMvl0M' + }, + ], + [ + "another attempt's nonce in the response", + (_c: Record, d: Record) => { + d['oidcNonce'] = 'z'.repeat(48) + }, + ], + [ + "another attempt's loginRequestId in the response", + (_c: Record, d: Record) => { + d['loginRequestId'] = CLIENT_ENTITY_ID + }, + ], + [ + 'another environment', + (c: Record) => { + c['environment'] = 'production' + }, + ], + [ + 'an expired receipt', + (c: Record) => { + c['iat'] = 1_700_000_000 + c['exp'] = 1_700_000_600 + }, + ], + ])('fails closed on %s, before anything reaches the application', async (_name, tamper) => { + const release = jest.spyOn(requireDaaRegistrationNative(), 'releaseRegistrationFlowKey') + try { + const transport = new ReceiptIssuingTransport(key, tamper) + expect( + await detailOf(anchoredClient(transport).prepareSocialLogin({ provider: 'GOOGLE' })), + ).toEqual({ kind: 'prepare_receipt_invalid' }) + expect(release).toHaveBeenCalledTimes(1) + } finally { + release.mockRestore() + } + }) + + it('fails closed on a receipt signed by a key the anchor does not pin', async () => { + const stranger = await generateReceiptSigningKey(key.kid) + const transport = new ReceiptIssuingTransport(stranger) + expect( + await detailOf(anchoredClient(transport).prepareSocialLogin({ provider: 'GOOGLE' })), + ).toEqual({ kind: 'prepare_receipt_invalid' }) + }) + + it('checks the requested provider, not one the relay reports', async () => { + const transport = new ReceiptIssuingTransport(key, (c) => { + c['provider'] = 'APPLE' + }) + expect( + await detailOf(anchoredClient(transport).prepareSocialLogin({ provider: 'GOOGLE' })), + ).toEqual({ kind: 'prepare_receipt_invalid' }) + }) +}) + +describe('DaaClient wiring', () => { + it('exposes one frozen AuthClient over the configured transport', async () => { + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + + expect(client.auth).toBe(client.auth) + expect(Object.isFrozen(client.auth)).toBe(true) + await client.auth.prepareSocialLogin({ provider: 'GOOGLE' }) + expect(transport.sent[0]?.path).toBe('/v1/accounts/auth/loginRequests') + }) + + it('needs no secure-key store to prepare: forUser still fails closed', () => { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + + expect(() => client.auth).not.toThrow() + expect(() => client.forUser({} as never)).toThrow(/ACTIVE DaaUserContext/) + }) + + it('exposes no resolveAuthKey on the public client.auth surface', () => { + // TypeScript's `private` is erased at build time, so this must be a + // runtime assertion, not a type-only one: it has to fail even against the + // compiled JS a consumer actually runs. `client.auth` is the public entry + // point (`DaaClient.auth`), and `resolveAuthKey` must not be a callable + // member reachable from it — that would hand any JavaScript in the host + // process a live handle to the enclave-held Owner AuthKey. + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + + expect((client.auth as unknown as Record).resolveAuthKey).toBeUndefined() + expect(Object.getOwnPropertyNames(Object.getPrototypeOf(client.auth) as object)).not.toContain( + 'resolveAuthKey', + ) + }) + + it('constructs when DaaRegistration is absent; prepare fails closed', async () => { + const requireNative = jest.mocked(requireOptionalNativeModule) + const previous = requireNative.getMockImplementation() + requireNative.mockImplementation(() => null) + try { + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: envelope(PREPARED), + }) + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + expect(client.auth).toBeDefined() + await expect(client.auth.prepareSocialLogin({ provider: 'GOOGLE' })).rejects.toThrow( + /native DaaRegistration module is not available/, + ) + } finally { + requireNative.mockReset() + if (previous !== undefined) { + requireNative.mockImplementation(previous) + } + } + }) +}) diff --git a/src/__test__/authKeyBinding.test.ts b/src/__test__/authKeyBinding.test.ts new file mode 100644 index 0000000..27cb21a --- /dev/null +++ b/src/__test__/authKeyBinding.test.ts @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { assertAuthKeyMatchesContext, bindAuthKeyToContext } from '../models/DaaUserContext' +import { toDeviceRegistrationResult } from '../wire/deviceRegistrationResultPayload' +import { InMemorySecureKeyStore } from '../testing' + +const CLIENT_ENTITY_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const OWNER_BINDING_ID = '11111111-2222-4333-8444-555555555555' +const AUTH_KEY_ID = '99999999-8888-4777-8666-555555555555' + +function activeContext() { + const result = toDeviceRegistrationResult( + { + deviceCredentialStatus: 'active', + ownerBindingId: OWNER_BINDING_ID, + authKeyId: AUTH_KEY_ID, + resolvedAt: '2026-08-26T12:00:00Z', + }, + CLIENT_ENTITY_ID, + ) + if (result.status !== 'ACTIVE') throw new Error('expected an ACTIVE context') + return result.context +} + +describe('DaaUserContext AuthKey binding', () => { + it('accepts the AuthKey paired at registration completion', async () => { + const authKey = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const context = bindAuthKeyToContext(activeContext(), await authKey.thumbprint()) + + await expect(assertAuthKeyMatchesContext(context, authKey)).resolves.toBeUndefined() + }) + + it('rejects a different local key before it can use the server-assigned kid', async () => { + const expected = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const replacement = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: 'bbbbbbbb-cccc-4ddd-8eee-ffffffffffff', + }) + const context = bindAuthKeyToContext(activeContext(), await expected.thumbprint()) + + await expect(assertAuthKeyMatchesContext(context, replacement)).rejects.toThrow( + 'does not match the ACTIVE DaaUserContext', + ) + }) + + it('rejects an unbound decoded context rather than trusting its authKeyId', async () => { + const authKey = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + + await expect(assertAuthKeyMatchesContext(activeContext(), authKey)).rejects.toThrow( + 'has no local AuthKey binding', + ) + }) +}) diff --git a/src/__test__/authKeyWireFixture.test.ts b/src/__test__/authKeyWireFixture.test.ts new file mode 100644 index 0000000..d7743f9 --- /dev/null +++ b/src/__test__/authKeyWireFixture.test.ts @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { bytesToHex, hexToBytes } from './authKeyWireFixture' + +describe('hexToBytes', () => { + it('decodes lower-case hex and round-trips through bytesToHex', () => { + expect(Array.from(hexToBytes('00ff10'))).toEqual([0x00, 0xff, 0x10]) + expect(bytesToHex(hexToBytes('0a1b2c'))).toBe('0a1b2c') + }) + + it('rejects a non-hex character in the second nibble', () => { + // `Number.parseInt` stops at the first invalid character rather than + // failing, so `Number.parseInt('1z', 16)` is 1. A per-byte NaN check would + // decode this as 0x01 and report nothing. + expect(Number.isNaN(Number.parseInt('1z', 16))).toBe(false) + expect(() => hexToBytes('1z')).toThrow(/non-hex character/) + }) + + it('rejects a non-hex character in the first nibble', () => { + expect(() => hexToBytes('z1')).toThrow(/non-hex character/) + }) + + it('rejects upper-case hex, which the fixture never uses', () => { + expect(() => hexToBytes('AB')).toThrow(/non-hex character/) + }) + + it('rejects an odd-length string before decoding', () => { + expect(() => hexToBytes('abc')).toThrow(/odd length/) + }) + + it('decodes the empty string', () => { + expect(Array.from(hexToBytes(''))).toEqual([]) + }) +}) diff --git a/src/__test__/authKeyWireFixture.ts b/src/__test__/authKeyWireFixture.ts new file mode 100644 index 0000000..e0aab5c --- /dev/null +++ b/src/__test__/authKeyWireFixture.ts @@ -0,0 +1,166 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Test-only loader for the canonical cross-language AuthKey wire fixture +// (`daa-authkey-wire-v1`). +// +// `daa-ios-sdk` owns the artifact at `Conformance/AuthKeyWireV1.json`, and the +// AuthKey wire contract requires every DAA SDK to consume that same +// artifact — a locally generated substitute does not satisfy cross-platform +// conformance. `fixtures/AuthKeyWireV1.json` is therefore a byte-for-byte copy +// (never reformatted; see `.prettierignore`), and this loader pins its SHA-256 +// so a local edit fails the suite instead of silently diverging from iOS and +// Android. `daa-android-sdk` guards its copy the same way in +// `AuthKeyWireFixture.kt`. +// +// This file is not a test (`testMatch` is `**/__test__/**/*.test.ts`) and never +// ships: `tsconfig.build.json` and `package.json#files` both exclude `__test__`. + +import { readFileSync } from 'node:fs' + +import { sha256 } from '../crypto/sha256' + +/** SHA-256 of the canonical `AuthKeyWireV1.json`, as published by `daa-ios-sdk`. */ +export const AUTH_KEY_WIRE_V1_SHA256 = + 'fc1d3f78b19269872aa75433a3ea14932a947a99af4c76329aca15bc867bf6ff' + +const EXPECTED_PROFILE = 'daa-authkey-wire-v1' +const EXPECTED_CONTRACT = 'docs/authkey-wire-contract.md' + +export type AuthKeyWireNamedHex = Readonly<{ + name: string + hex: string +}> + +export type AuthKeyWireFixture = Readonly<{ + profile: string + contract: string + p256PublicKey: Readonly<{ + x963Hex: string + spkiBase64Url: string + jwkThumbprint: string + }> + signedMessage: Readonly<{ + name: string + messageHex: string + publicKeyX963Hex: string + derHex: string + rawHex: string + }> + ecdsaSignatures: readonly Readonly<{ + name: string + derHex: string + rawHex: string + }>[] + rejected: Readonly<{ + ecdsaDer: readonly AuthKeyWireNamedHex[] + ecdsaRaw: readonly AuthKeyWireNamedHex[] + x963PublicKeys: readonly AuthKeyWireNamedHex[] + subjectPublicKeyInfo: readonly AuthKeyWireNamedHex[] + }> +}> + +/** Lower-case hex, for comparing against the fixture's hex-encoded vectors. */ +export function bytesToHex(bytes: Uint8Array): string { + let out = '' + for (let i = 0; i < bytes.length; i++) { + out += bytes[i]!.toString(16).padStart(2, '0') + } + return out +} + +/** Decode one of the fixture's lower-case hex vectors. */ +export function hexToBytes(hex: string): Uint8Array { + if (hex.length % 2 !== 0) { + throw new Error(`AuthKeyWireV1: hex vector has an odd length: ${hex.length}`) + } + // Asserted over the whole string rather than per byte: `Number.parseInt` + // stops at the first invalid character instead of failing, so + // `Number.parseInt('1z', 16)` is 1 — a bad second nibble would decode as the + // first nibble's value and never reach a NaN check. + if (!/^[0-9a-f]*$/.test(hex)) { + throw new Error('AuthKeyWireV1: hex vector has a non-hex character') + } + const out = new Uint8Array(hex.length / 2) + for (let i = 0; i < out.length; i++) { + out[i] = Number.parseInt(hex.slice(i * 2, i * 2 + 2), 16) + } + return out +} + +/** + * The vendored fixture's raw bytes, read without the digest guard so a caller + * can assert the digest itself. + */ +export function readAuthKeyWireFixtureBytes(): Uint8Array { + return new Uint8Array(readFileSync(`${__dirname}/fixtures/AuthKeyWireV1.json`)) +} + +/** + * Load the canonical fixture, failing if the vendored copy has drifted. + * + * The digest is computed with this SDK's own vendored `sha256` rather than a + * Node dependency (`crypto` is not available to production React Native code, + * and this SDK adds no Node dependency). That is only self-referential in + * appearance: `sha256.test.ts` pins the same implementation against the FIPS + * 180-4 vectors and, exhaustively through two blocks, against WebCrypto — so a + * broken digest cannot quietly ratify a broken fixture. + */ +export function loadAuthKeyWireFixture(): AuthKeyWireFixture { + const bytes = readAuthKeyWireFixtureBytes() + const digest = bytesToHex(sha256(bytes)) + if (digest !== AUTH_KEY_WIRE_V1_SHA256) { + throw new Error( + `AuthKeyWireV1.json is not the canonical artifact: expected SHA-256 ` + + `${AUTH_KEY_WIRE_V1_SHA256}, got ${digest}. Re-copy it byte-for-byte from ` + + `daa-ios-sdk/Conformance/AuthKeyWireV1.json; do not re-serialize it.`, + ) + } + + const fixture = JSON.parse(new TextDecoder().decode(bytes)) as AuthKeyWireFixture + + // Metadata and vector counts are checked the same way the Android loader + // checks them, so a future fixture revision that keeps the shape but drops a + // vector cannot silently shrink this suite's coverage. + if (fixture.profile !== EXPECTED_PROFILE || fixture.contract !== EXPECTED_CONTRACT) { + throw new Error(`AuthKeyWireV1.json metadata drifted: ${fixture.profile} / ${fixture.contract}`) + } + const counts: readonly [string, number, number][] = [ + ['ecdsaSignatures', fixture.ecdsaSignatures.length, 3], + ['rejected.ecdsaDer', fixture.rejected.ecdsaDer.length, 3], + ['rejected.ecdsaRaw', fixture.rejected.ecdsaRaw.length, 6], + ['rejected.x963PublicKeys', fixture.rejected.x963PublicKeys.length, 3], + ['rejected.subjectPublicKeyInfo', fixture.rejected.subjectPublicKeyInfo.length, 4], + ] + for (const [name, actual, expected] of counts) { + if (actual !== expected) { + throw new Error(`AuthKeyWireV1.json ${name}: expected ${expected} vectors, got ${actual}`) + } + } + + return fixture +} + +/** Look up a named vector, so a test names the case it is asserting. */ +export function namedHex(vectors: readonly AuthKeyWireNamedHex[], name: string): Uint8Array { + const vector = vectors.find((candidate) => candidate.name === name) + if (!vector) { + throw new Error(`AuthKeyWireV1.json is missing the "${name}" vector`) + } + return hexToBytes(vector.hex) +} diff --git a/src/__test__/base64url.test.ts b/src/__test__/base64url.test.ts new file mode 100644 index 0000000..2bdfd7a --- /dev/null +++ b/src/__test__/base64url.test.ts @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { bytesToHex, hexToBytes, loadAuthKeyWireFixture } from './authKeyWireFixture' + +describe('base64url', () => { + it('encodes without padding and using the URL-safe alphabet', () => { + // 0xFF 0xFE 0xFD -> standard "//79", URL-safe "__79" + expect(toBase64Url(new Uint8Array([0xff, 0xfe, 0xfd]))).toBe('__79') + }) + + it('encodes the empty array as the empty string', () => { + expect(toBase64Url(new Uint8Array([]))).toBe('') + }) + + it('round-trips arbitrary byte lengths', () => { + for (let len = 0; len < 40; len++) { + const bytes = new Uint8Array(len) + for (let i = 0; i < len; i++) bytes[i] = (i * 37 + 11) & 0xff + expect(Array.from(fromBase64Url(toBase64Url(bytes)))).toEqual(Array.from(bytes)) + } + }) + + it('rejects invalid input', () => { + expect(() => fromBase64Url('****')).toThrow(/invalid Base64URL/) + }) + + it('rejects an impossible length (len % 4 === 1)', () => { + expect(() => fromBase64Url('A')).toThrow(/invalid Base64URL length/) + }) + + it('rejects a non-canonical encoding with non-zero trailing bits', () => { + expect(() => fromBase64Url('AB')).toThrow(/non-canonical/) + }) +}) + +// The only Base64URL value the canonical fixture publishes is the P-256 SPKI, so +// this is the shared wire-encoding vector the three SDKs have in common. +describe('base64url against the canonical AuthKeyWireV1 vectors', () => { + const fixture = loadAuthKeyWireFixture() + const { spkiBase64Url, x963Hex } = fixture.p256PublicKey + + it('decodes the canonical SPKI to 91 bytes ending in the canonical point', () => { + const spki = fromBase64Url(spkiBase64Url) + expect(spki.length).toBe(91) + expect(bytesToHex(spki.subarray(26))).toBe(x963Hex) + }) + + it('re-encodes the canonical SPKI to the exact published string', () => { + // Encoding is the direction that reaches the wire, so this pins the + // unpadded URL-safe alphabet against a value iOS and Android also produce. + expect(toBase64Url(fromBase64Url(spkiBase64Url))).toBe(spkiBase64Url) + expect(spkiBase64Url).not.toContain('=') + }) + + it('round-trips every hex-encoded vector in the fixture', () => { + const vectors = [ + x963Hex, + fixture.signedMessage.messageHex, + fixture.signedMessage.derHex, + fixture.signedMessage.rawHex, + ...fixture.ecdsaSignatures.flatMap((signature) => [signature.derHex, signature.rawHex]), + ...fixture.rejected.ecdsaDer.map((vector) => vector.hex), + ...fixture.rejected.ecdsaRaw.map((vector) => vector.hex), + ] + for (const hex of vectors) { + const bytes = hexToBytes(hex) + expect(bytesToHex(fromBase64Url(toBase64Url(bytes)))).toBe(hex) + } + }) +}) diff --git a/src/__test__/client.test.ts b/src/__test__/client.test.ts new file mode 100644 index 0000000..cc84da2 --- /dev/null +++ b/src/__test__/client.test.ts @@ -0,0 +1,473 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import * as sdk from '../index' +import * as testing from '../testing' +import { createDaaUserClient } from '../api/DaaUserClient' +import { DEVICE_KEY_POLICY, publicApiOriginFor } from '../config' +import { DaaClient } from '../DaaClient' +import { isDaaError } from '../errors' +import type { + Account, + AccountListQuery, + AccountsClient, + AddressObject, + AddressObjectRendering, + CreateAccountRequest, + CreateTransferAmount, + CreateTransferDestination, + CreateTransferRequest, + CreateTransferRiskSignals, + CreateTransferSource, + DaaUserClient, + Deposit, + DepositAddressChain, + DepositAddressListQuery, + DepositAccountLocation, + DepositAddressesClient, + DepositRendering, + DepositRiskEvaluation, + DepositsClient, + DepositSourceLocation, + DepositStatus, + DepositType, + Fee, + GenerateAddressRequest, + Page, + Transaction, + TransactionAccountLocation, + TransactionBlockchainLocation, + TransactionBlockchainLocationRendering, + TransactionFiatLocation, + TransactionListQuery, + TransactionLocation, + TransactionRendering, + TransactionStatus, + TransactionsClient, + TransactionType, + Transfer, + TransferListQuery, + TransferDestinationAccountLocation, + TransferDestinationAccountLocationRendering, + TransferDestinationBlockchainLocation, + TransferDestinationBlockchainLocationRendering, + TransferDestinationLocation, + TransferErrorCode, + TransferPolicyEvaluation, + TransferRendering, + TransfersClient, + TransferSourceLocation, + TransferStatus, + WithdrawalAdjustments, + WithdrawalDestination, + WithdrawalDestinationType, + WithdrawalDetail, + WithdrawalDetailRendering, + WithdrawalErrorCode, + WithdrawalPolicyEvaluation, + WithdrawalReturn, + WithdrawalRiskEvaluation, + WithdrawalsClient, + WithdrawalStatus, + WithdrawalSubAccountSweep, + WithdrawalSweepStatus, + WithdrawalToAmount, +} from '../index' +import type { DaaTransport } from '../transport/DaaTransport' +import { NO_SIGNING } from './userClientSigning' + +type IntegratedPublicModels = readonly [ + Account, + AccountListQuery, + Page, + AddressObject, + AddressObjectRendering, + CreateAccountRequest, + CreateTransferAmount, + CreateTransferDestination, + CreateTransferRequest, + CreateTransferRiskSignals, + CreateTransferSource, + DepositAddressChain, + DepositAddressListQuery, + Deposit, + DepositAccountLocation, + DepositRendering, + DepositRiskEvaluation, + DepositSourceLocation, + DepositStatus, + DepositType, + Fee, + GenerateAddressRequest, + Transaction, + TransactionAccountLocation, + TransactionBlockchainLocation, + TransactionBlockchainLocationRendering, + TransactionFiatLocation, + TransactionListQuery, + TransactionLocation, + TransactionRendering, + TransactionStatus, + TransactionType, + Transfer, + TransferListQuery, + TransferDestinationAccountLocation, + TransferDestinationAccountLocationRendering, + TransferDestinationBlockchainLocation, + TransferDestinationBlockchainLocationRendering, + TransferDestinationLocation, + TransferErrorCode, + TransferPolicyEvaluation, + TransferRendering, + TransferSourceLocation, + TransferStatus, + WithdrawalAdjustments, + WithdrawalDestination, + WithdrawalDestinationType, + WithdrawalDetail, + WithdrawalDetailRendering, + WithdrawalErrorCode, + WithdrawalPolicyEvaluation, + WithdrawalReturn, + WithdrawalRiskEvaluation, + WithdrawalStatus, + WithdrawalSubAccountSweep, + WithdrawalSweepStatus, + WithdrawalToAmount, +] + +const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, +} + +describe('DaaClient', () => { + it('rejects a missing appId', () => { + expect( + () => + new DaaClient({ + appId: '', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }), + ).toThrow(/appId is required/) + }) + + // The rules themselves are pinned in alias.test.ts; this pins that the + // constructor applies them, rather than the first AuthKey resolution, which + // runs only after Social Session has bound the end user. + it.each([ + ['one character over the 41-character budget', 'a'.repeat(42)], + ['a character outside the key-namespace charset', 'app/123'], + ])('rejects an appId with %s at construction', (_label, appId) => { + let thrown: unknown + try { + new DaaClient({ appId, environment: 'sandbox', transport, keyPolicy: DEVICE_KEY_POLICY }) + } catch (err) { + thrown = err + } + + expect(isDaaError(thrown) && thrown.detail.kind).toBe('contract_violation') + }) + + it('rejects an unknown environment (runtime allow-list)', () => { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: 'prod' as never, + transport, + keyPolicy: DEVICE_KEY_POLICY, + }), + ).toThrow(/unknown environment/) + }) + + it('exposes config accessors', () => { + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + expect(client.appId).toBe('app-123') + expect(client.environment).toBe('sandbox') + expect(client.transport).toBe(transport) + expect(client.keyPolicy).toBe(DEVICE_KEY_POLICY) + }) + + it('derives the pagination trust anchor from the environment', () => { + expect( + Object.freeze({ + sandbox: publicApiOriginFor('sandbox'), + production: publicApiOriginFor('production'), + }), + ).toEqual({ + sandbox: 'https://api-sandbox.circle.com', + production: 'https://api.circle.com', + }) + }) + + it('offers only the public environments', () => { + expect(sdk.DAA_ENVIRONMENTS).toEqual(['sandbox', 'production']) + for (const environment of ['development', 'Production']) { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: environment as never, + transport, + keyPolicy: DEVICE_KEY_POLICY, + }), + ).toThrow(/unknown environment/) + } + }) + + it.each([ + 'https://api-test.circle.com', + 'https://circle.com', + 'https://a-1.b2.circle.com', + 'https://xn--bcher-kva.circle.com', + `https://${'a'.repeat(63)}.circle.com`, + `https://aa.${'a.'.repeat(120)}circle.com`, + ])('accepts publicApiOrigin %s with sandbox', (publicApiOrigin) => { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + publicApiOrigin, + }), + ).not.toThrow() + }) + + it.each(['https://api-test.circle.com', 'https://api.circle.com', 'http://x', ''])( + 'refuses publicApiOrigin %p with production, even a valid origin', + (publicApiOrigin) => { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: 'production', + transport, + keyPolicy: DEVICE_KEY_POLICY, + publicApiOrigin, + }), + ).toThrow('DAA: publicApiOrigin cannot be set for production') + }, + ) + + it.each([ + '', + 'http://api-test.circle.com', + 'HTTPS://api-test.circle.com', + 'https://API-TEST.circle.com', + 'https://evil.example', + 'https://circle.com.evil.example', + 'https://evilcircle.com', + 'https://api-test.circle.com/', + 'https://api-test.circle.com/v1', + 'https://api-test.circle.com:443', + 'https://api-test.circle.com:8443', + 'https://api-test.circle.com?x=1', + 'https://api-test.circle.com#x', + 'https://user@api-test.circle.com', + 'https://api-test.circle.com.', + 'https://.circle.com', + 'https://a..circle.com', + 'https://-api.circle.com', + 'https://api-.circle.com', + 'https://api_test.circle.com', + `https://${'a'.repeat(64)}.circle.com`, + `https://${'a.'.repeat(122)}circle.com`, + ' https://api-test.circle.com', + 'https://daa-scä.circle.com', + 'https://api-test.circle.com\n', + 'https://api-test\t.circle.com', + 'https://circle.com\u0000', + null, + 42, + ])('refuses publicApiOrigin %p as not a bare https circle.com origin', (publicApiOrigin) => { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + publicApiOrigin: publicApiOrigin as never, + }), + ).toThrow( + 'DAA: publicApiOrigin must be a bare, lowercase https origin on circle.com or a subdomain', + ) + }) + + it('exposes auth but keeps the authenticated operations surface fail-closed', () => { + const client = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + // Prepare is reachable (the login's first call); see `authClient.test.ts`. + expect(typeof client.auth.prepareSocialLogin).toBe('function') + // `forUser` needs a `DaaUserContext`, which only an ACTIVE Device Registration + // Complete produces. + expect(() => client.forUser({} as never)).toThrow(/ACTIVE DaaUserContext/) + }) +}) + +describe('DaaUserClient integration', () => { + it('builds every resource client over the same transport and freezes the surface', async () => { + const failure = new Error('shared transport') + const sharedTransport: DaaTransport = { + async send() { + throw failure + }, + } + const user: DaaUserClient = createDaaUserClient(sharedTransport, 'production', NO_SIGNING) + const clients: readonly [ + AccountsClient, + DepositAddressesClient, + DepositsClient, + TransactionsClient, + TransfersClient, + WithdrawalsClient, + ] = [ + user.accounts, + user.depositAddresses, + user.deposits, + user.transactions, + user.transfers, + user.withdrawals, + ] + const publicModelsCompile: IntegratedPublicModels | null = null + + expect(Object.isFrozen(user)).toBe(true) + expect(publicModelsCompile).toBeNull() + for (const client of clients) { + expect(Object.isFrozen(client)).toBe(true) + } + + // Each client reached the one shared transport: its throw comes back as a + // transport error with that same throw as the cause. + const sharedFailure = { detail: { kind: 'transport', retryable: true }, cause: failure } + await expect(user.accounts.get('acct-1')).rejects.toMatchObject(sharedFailure) + await expect( + user.depositAddresses.get('3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8'), + ).rejects.toMatchObject(sharedFailure) + await expect(user.deposits.get('3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8')).rejects.toMatchObject( + sharedFailure, + ) + await expect(user.transactions.list()).rejects.toMatchObject(sharedFailure) + await expect(user.transfers.get('3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8')).rejects.toMatchObject( + sharedFailure, + ) + await expect( + user.withdrawals.get('3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8'), + ).rejects.toMatchObject(sharedFailure) + }) +}) + +describe('public surface', () => { + it('exposes only the approved runtime exports (no signing entry points)', () => { + const keys = Object.keys(sdk) + .filter((k) => k !== '__esModule') + .sort() + expect(keys).toEqual( + [ + 'DAA_ENVIRONMENTS', + 'DEVICE_KEY_POLICY', + 'DaaClient', + 'DaaError', + // Passkey SCA: the factory and its error type. No ceremony or signing + // primitive is exported; the factory only reaches the DaaSca native module. + 'ScaError', + 'createScaClient', + 'fromBase64Url', + 'isDaaError', + 'isScaError', + 'serializeBody', + 'serializeEmptyBody', + 'toBase64Url', + ].sort(), + ) + }) + + it('does not runtime-export integrated clients or server-attributed model constructors', () => { + const runtime = sdk as Record + for (const name of [ + 'AccountsClient', + 'AuthClient', + 'AuthKeyResolution', + 'OwnerAuthKey', + 'PreparedSocialLogin', + 'DepositAddressesClient', + 'DepositAddressListQuery', + 'DepositsClient', + 'TransactionsClient', + 'TransactionListQuery', + 'Transaction', + 'TransactionBlockchainLocation', + 'TransfersClient', + 'WithdrawalsClient', + 'DaaUserClient', + 'AddressObject', + 'CreateAccountRequest', + 'CreateTransferRequest', + 'GenerateAddressRequest', + 'Deposit', + 'Transfer', + 'TransferListQuery', + 'TransferDestinationAccountLocation', + 'TransferDestinationBlockchainLocation', + 'WithdrawalDetail', + 'WithdrawalToAmount', + 'Page', + ]) { + expect(runtime[name]).toBeUndefined() + } + }) + + // A surface lock, not an inventory: `./testing` is the one entry allowed to + // hand out real runtime capability, so anything appearing here should be a + // deliberate decision rather than a re-export that drifted in. Adding a name + // means justifying it. + it('the ./testing entry exposes only the sanctioned test doubles', () => { + const keys = Object.keys(testing) + .filter((k) => k !== '__esModule') + .sort() + expect(keys).toEqual([ + // WebCrypto-backed Owner key. Fails closed in a production build. + 'InMemorySecureKeyStore', + ]) + }) + + it('the ./testing entry pulls in neither React nor React Native', () => { + // A transitive React import here would make this entry unusable from the + // node environment most backend-adjacent test suites run in. + for (const name of ['react', 'react-native']) { + expect(Object.keys(require.cache).some((f) => f.includes(`/node_modules/${name}/`))).toBe( + false, + ) + } + }) +}) diff --git a/src/__test__/daaStatusCodes.test.ts b/src/__test__/daaStatusCodes.test.ts new file mode 100644 index 0000000..64b7799 --- /dev/null +++ b/src/__test__/daaStatusCodes.test.ts @@ -0,0 +1,523 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { loginStepFailure } from '../api/loginFailure' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { CreateAccountRequest } from '../models/CreateAccountRequest' +import type { CreateTransferRequest } from '../models/CreateTransferRequest' +import type { CreateWithdrawalRequest } from '../models/CreateWithdrawalRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { DAA_STATUS_CODES, isDaaStatus, type DaaStatusName } from '../wire/daaStatusCodes' +import { readDaaStatusCode } from '../wire/errorEnvelope' +import { registeredAuthKey, signingFor } from './userClientSigning' + +/** + * DAA's real error bodies, through the real clients. + * + * DAA sends `{"code":,"message":…,"externalMessage":…}` — a flat error + * object with the code at the root, never a name string. The SDK classifies on + * that number only, so a name string in a fixture would test the `api` + * fallback, not the mapping. Every code here is a literal, not + * a read of `DAA_STATUS_CODES`, so a wrong number in the table fails these + * tests instead of moving with them. + */ + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const next = this.responses.shift() + if (next === undefined) { + throw new Error('transport has no more responses') + } + return next + } +} + +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const CLIENT_ENTITY_ID = '33333333-3333-4333-b333-333333333333' +const DESTINATION_ID = '55555555-5555-4555-8555-555555555555' +const REQUEST_ID = 'req-daa-1' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +/** The error body DAA actually sends. */ +function daaError(code: number): Uint8Array { + return bytes( + `{"code":${code},"message":"internal detail","externalMessage":"The request was rejected"}`, + ) +} + +function failure(status: number, code: number): DaaHttpResponse { + return { status, headers: { 'X-Request-Id': REQUEST_ID }, bodyBytes: daaError(code) } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +const ACCOUNT_REQUEST: CreateAccountRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + blockchain: 'ARC', +} + +const TRANSFER_REQUEST: CreateTransferRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'account', id: 'acct-dst' }, + amount: { amount: '10.25', currency: 'USD' }, +} + +const WITHDRAWAL_REQUEST: CreateWithdrawalRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'wire', id: DESTINATION_ID }, + amount: { amount: '10.25', currency: 'USD' }, +} + +type SignedCall = (responses: DaaHttpResponse[]) => Promise<{ + transport: SequenceTransport + call: Promise +}> + +async function userClient(responses: DaaHttpResponse[]) { + const transport = new SequenceTransport(responses) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { transport, user: createDaaUserClient(transport, 'production', signing) } +} + +const SIGNED_WRITES: ReadonlyArray<[string, SignedCall]> = [ + [ + 'accounts.create', + async (responses) => { + const { transport, user } = await userClient(responses) + return { transport, call: user.accounts.create(ACCOUNT_REQUEST) } + }, + ], + [ + 'transfers.create', + async (responses) => { + const { transport, user } = await userClient(responses) + return { transport, call: user.transfers.create(TRANSFER_REQUEST) } + }, + ], + [ + 'withdrawals.create', + async (responses) => { + const { transport, user } = await userClient(responses) + return { transport, call: user.withdrawals.create(WITHDRAWAL_REQUEST) } + }, + ], +] + +const REFRESH_CONTEXT: SignedCall = async (responses) => { + const { transport, user } = await userClient(responses) + return { transport, call: user.refreshContext() } +} + +const SIGNED_CALLS: ReadonlyArray<[string, SignedCall]> = [ + ...SIGNED_WRITES, + ['refreshContext', REFRESH_CONTEXT], +] + +/** + * Name strings, which classify as `api`. Every non-numeric string takes the + * same path, so two cover it: the name of a row that has a numeric code, and + * the name of a condition that has no code. + */ +const NAME_STRINGS = ['IDEMPOTENCY_KEY_REUSED', 'DEVICE_AUTHORIZATION_EXPIRED'] as const + +function failureBody(status: number, body: string): DaaHttpResponse { + return { status, headers: { 'X-Request-Id': REQUEST_ID }, bodyBytes: bytes(body) } +} + +describe('readDaaStatusCode', () => { + it('reads the root code of the flat body DAA sends', () => { + expect(readDaaStatusCode(daaError(420034))).toBe(420034) + }) + + it('reads status.code when the root code is absent', () => { + expect(readDaaStatusCode(bytes('{"status":{"code":420034}}'))).toBe(420034) + expect(readDaaStatusCode(bytes('{"status":{"code":"IDEMPOTENCY_KEY_REUSED"}}'))).toBe( + 'IDEMPOTENCY_KEY_REUSED', + ) + // A JSON null is not a present root code. + expect(readDaaStatusCode(bytes('{"code":null,"status":{"code":420034}}'))).toBe(420034) + }) + + it('reads only the root code when both shapes are present', () => { + expect(readDaaStatusCode(bytes('{"code":420031,"status":{"code":420034}}'))).toBe(420031) + expect(readDaaStatusCode(bytes('{"code":499999,"status":{"code":420031}}'))).toBe(499999) + expect( + readDaaStatusCode(bytes('{"code":"DEVICE_AUTHORIZATION_EXPIRED","status":{"code":420031}}')), + ).toBe('DEVICE_AUTHORIZATION_EXPIRED') + }) + + it('does not fall back to status.code when a present root code is unreadable', () => { + for (const root of ['{"nested":1}', '[420031]', '""', 'true', 'false', '1e999']) { + expect(readDaaStatusCode(bytes(`{"code":${root},"status":{"code":420031}}`))).toBeNull() + } + }) + + it('hands a quoted numeric code back as the number', () => { + expect(readDaaStatusCode(bytes('{"code":"420034"}'))).toBe(420034) + }) + + it('is null for a body with no readable code', () => { + expect(readDaaStatusCode(bytes('{"message":"no code"}'))).toBeNull() + expect(readDaaStatusCode(bytes('{"code":[420034]}'))).toBeNull() + expect(readDaaStatusCode(bytes('{"code":""}'))).toBeNull() + expect(readDaaStatusCode(bytes('bad gateway'))).toBeNull() + expect(readDaaStatusCode(null)).toBeNull() + }) +}) + +describe('the status-code table', () => { + it('carries the numbers DAA sends', () => { + expect(DAA_STATUS_CODES).toEqual({ + DEVICE_AUTHORIZATION_INVALID: 420031, + IDEMPOTENCY_KEY_REUSED: 420034, + DEVICE_AUTHORIZATION_REQUEST_MISMATCH: 420036, + AUTH_KEY_BINDING_CONFLICT: 420038, + LOGIN_REQUEST_CONSUMED: 420039, + DEVICE_AUTHORIZATION_REPLAYED: 420043, + }) + expect(Object.isFrozen(DAA_STATUS_CODES)).toBe(true) + }) + + it('matches the numeric code only', () => { + expect(isDaaStatus(420034, 'IDEMPOTENCY_KEY_REUSED')).toBe(true) + expect(isDaaStatus('IDEMPOTENCY_KEY_REUSED', 'IDEMPOTENCY_KEY_REUSED')).toBe(false) + expect(isDaaStatus(420035, 'IDEMPOTENCY_KEY_REUSED')).toBe(false) + // A decimal string is turned into the number by readDaaStatusCode, not here. + expect(isDaaStatus('420034', 'IDEMPOTENCY_KEY_REUSED')).toBe(false) + expect(isDaaStatus(null, 'IDEMPOTENCY_KEY_REUSED')).toBe(false) + }) + + it('matches no table row from any name string, including the row’s own name', () => { + for (const code of NAME_STRINGS) { + for (const name of Object.keys(DAA_STATUS_CODES) as DaaStatusName[]) { + expect(isDaaStatus(code, name)).toBe(false) + } + } + }) +}) + +describe.each(SIGNED_WRITES)('%s with a real DAA error body', (_name, signedCall) => { + it('maps 409 / 420034 to idempotency_conflict with the request’s own key', async () => { + const { transport, call } = await signedCall([failure(409, 420034)]) + + expect(await detailOf(call)).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: IDEMPOTENCY_KEY, + correlationId: REQUEST_ID, + }) + expect(transport.sent).toHaveLength(1) + }) + + it('keeps 400 / 420034 an api failure: idempotency_conflict needs the documented 409', async () => { + // What DAA's transfer and withdrawal create routes send. + const { transport, call } = await signedCall([failure(400, 420034)]) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 420034, + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }) + + it('maps 409 / 420043 (replayed) to contract_violation without retrying', async () => { + const { transport, call } = await signedCall([failure(409, 420043)]) + + expect(await detailOf(call)).toEqual({ kind: 'contract_violation', correlationId: REQUEST_ID }) + expect(transport.sent).toHaveLength(1) + }) +}) + +describe.each(SIGNED_CALLS)('%s device-authorization failures', (_name, signedCall) => { + it.each([ + [401, 420031], + [400, 420031], + [403, 420036], + ])('maps %i / %i to contract_violation without retrying', async (status, code) => { + const { transport, call } = await signedCall([failure(status, code)]) + + expect(await detailOf(call)).toEqual({ kind: 'contract_violation', correlationId: REQUEST_ID }) + expect(transport.sent).toHaveLength(1) + }) + + it('keeps a code the signed mapping does not classify observable as api', async () => { + // LOGIN_REQUEST_CONSUMED: a real DAA code that only the login calls map. + const { transport, call } = await signedCall([failure(409, 420039)]) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 420039, + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }) +}) + +describe('refreshContext with a real DAA error body', () => { + it('has no key to recover from a bodyless GET, so 409 / 420034 stays an api failure', async () => { + const { call } = await REFRESH_CONTEXT([failure(409, 420034)]) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 420034, + retryable: false, + }) + }) +}) + +describe('an unsigned call with a real DAA error body', () => { + const DEPOSIT_KEY = '44444444-4444-4444-8444-444444444444' + + async function createDepositAddress(response: DaaHttpResponse): Promise { + const transport = new SequenceTransport([response]) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return detailOf( + createDaaUserClient(transport, 'production', signing).depositAddresses.create({ + idempotencyKey: DEPOSIT_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + }), + ) + } + + it('maps 409 + IDEMPOTENCY_KEY_REUSED on deposit-address create to idempotency_conflict with the request key', async () => { + expect(await createDepositAddress(failure(409, 420034))).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: DEPOSIT_KEY, + correlationId: REQUEST_ID, + }) + }) + + it('reads the decimal-string and status.code forms of 420034 on deposit-address create', async () => { + for (const body of ['{"code":"420034"}', '{"status":{"code":420034}}']) { + expect(await createDepositAddress(failureBody(409, body))).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: DEPOSIT_KEY, + correlationId: REQUEST_ID, + }) + } + }) + + it('keeps 420034 on another status as an api failure carrying the numeric code', async () => { + expect(await createDepositAddress(failure(400, 420034))).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 420034, + retryable: false, + }) + }) + + it('keeps another 409 on deposit-address create as an api failure', async () => { + expect(await createDepositAddress(failure(409, 2))).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 2, + retryable: false, + }) + expect( + await createDepositAddress(failureBody(409, '{"code":"IDEMPOTENCY_KEY_REUSED"}')), + ).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 'IDEMPOTENCY_KEY_REUSED', + retryable: false, + }) + expect( + await createDepositAddress(failureBody(409, '{"code":499999,"status":{"code":420034}}')), + ).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 499999, + retryable: false, + }) + }) +}) + +describe.each(SIGNED_CALLS)('%s: the numeric-code matching rule', (_name, call) => { + it.each([ + ['a decimal string', '{"code":"420031"}'], + ['status.code when the root code is absent', '{"status":{"code":420031}}'], + ['status.code when the root code is null', '{"code":null,"status":{"code":420031}}'], + ])('classifies %s for 420031 as contract_violation', async (_label, body) => { + const { transport, call: pending } = await call([failureBody(400, body)]) + + expect(await detailOf(pending)).toEqual({ + kind: 'contract_violation', + correlationId: REQUEST_ID, + }) + expect(transport.sent).toHaveLength(1) + }) + + it.each(NAME_STRINGS)('classifies the name string %s as api and sends once', async (name) => { + const { transport, call: pending } = await call([ + failureBody(400, `{"code":"${name}"}`), + failureBody(400, `{"code":"${name}"}`), + ]) + + expect(await detailOf(pending)).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: name, + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }) + + it('classifies a code that is not in the table as api', async () => { + const { call: pending } = await call([failure(400, 499999)]) + + expect(await detailOf(pending)).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 499999, + retryable: false, + }) + }) + + it.each([ + ['an unknown numeric', '499999', 499999], + ['an uncoded name as', '"DEVICE_AUTHORIZATION_EXPIRED"', 'DEVICE_AUTHORIZATION_EXPIRED'], + ['a coded name as', '"DEVICE_AUTHORIZATION_INVALID"', 'DEVICE_AUTHORIZATION_INVALID'], + ])( + 'classifies %s root code as api even when status.code is 420031', + async (_label, root, daaStatusCode) => { + const { call: pending } = await call([ + failureBody(400, `{"code":${root},"status":{"code":420031}}`), + ]) + + expect(await detailOf(pending)).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode, + retryable: false, + }) + }, + ) + + it.each(['""', 'true', '{"nested":1}'])( + 'classifies a present but unreadable root code %s as api even when status.code is 420031', + async (root) => { + const { call: pending } = await call([ + failureBody(400, `{"code":${root},"status":{"code":420031}}`), + ]) + + expect(await detailOf(pending)).toEqual({ kind: 'api', httpStatus: 400, retryable: false }) + }, + ) +}) + +describe.each(SIGNED_WRITES)('%s: 420034 in each accepted shape', (_name, signedCall) => { + it.each([ + ['a decimal string', '{"code":"420034"}'], + ['status.code', '{"status":{"code":420034}}'], + ])('maps 409 with %s to idempotency_conflict', async (_label, body) => { + const { call } = await signedCall([failureBody(409, body)]) + + expect(await detailOf(call)).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: IDEMPOTENCY_KEY, + correlationId: REQUEST_ID, + }) + }) + + it.each([ + ['at the root', '{"code":"IDEMPOTENCY_KEY_REUSED"}'], + ['at status.code', '{"status":{"code":"IDEMPOTENCY_KEY_REUSED"}}'], + ])( + 'keeps 409 with the name string IDEMPOTENCY_KEY_REUSED %s an api failure and sends once', + async (_label, body) => { + const { transport, call } = await signedCall([failureBody(409, body), failureBody(409, body)]) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 'IDEMPOTENCY_KEY_REUSED', + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }, + ) +}) + +describe('the login mapping under the numeric-code matching rule', () => { + const LOGIN_KEY = '66666666-6666-4666-8666-666666666666' + + it.each([ + ['a decimal string', '{"code":"420034"}'], + ['status.code', '{"status":{"code":420034}}'], + ])('maps 409 with %s for 420034 to idempotency_conflict', (_label, body) => { + expect(loginStepFailure(failureBody(409, body), LOGIN_KEY)?.detail).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: LOGIN_KEY, + correlationId: REQUEST_ID, + }) + }) + + it.each([ + ['a decimal string', '{"code":"420039"}'], + ['status.code', '{"status":{"code":420039}}'], + ])('maps %s for 420039 to contract_violation', (_label, body) => { + expect(loginStepFailure(failureBody(409, body), LOGIN_KEY)?.detail).toEqual({ + kind: 'contract_violation', + correlationId: REQUEST_ID, + }) + }) + + it.each(NAME_STRINGS)('leaves 409 with the name string %s to the api fallback', (name) => { + expect(loginStepFailure(failureBody(409, `{"code":"${name}"}`), LOGIN_KEY)).toBeNull() + expect( + loginStepFailure(failureBody(409, `{"status":{"code":"${name}"}}`), LOGIN_KEY), + ).toBeNull() + }) + + it('leaves an unknown root code to the api fallback even when status.code is 420034', () => { + expect( + loginStepFailure(failureBody(409, '{"code":499999,"status":{"code":420034}}'), LOGIN_KEY), + ).toBeNull() + }) +}) diff --git a/src/__test__/daaUserClientLifecycle.test.ts b/src/__test__/daaUserClientLifecycle.test.ts new file mode 100644 index 0000000..1b8d4b0 --- /dev/null +++ b/src/__test__/daaUserClientLifecycle.test.ts @@ -0,0 +1,258 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { fromBase64Url } from '../crypto/base64url' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { CreateAccountRequest } from '../models/CreateAccountRequest' +import type { CreateTransferRequest } from '../models/CreateTransferRequest' +import type { CreateWithdrawalRequest } from '../models/CreateWithdrawalRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { registeredAuthKey, signingFor, unregisteredAuthKey } from './userClientSigning' + +/** + * `DaaUserClient.refreshContext` and `.close()` — the two lifecycle methods. + * Mirrors `withdrawalsCreate.test.ts`'s + * discipline: literal wire facts, not a comparison against the constant the + * production code reads. + */ + +const CONTEXT_PATH = '/v1/accounts/auth/context' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const OWNER_BINDING_ID = '22222222-2222-4222-a222-222222222222' +const RESOLVED_AT = '2026-01-01T00:00:00Z' + +/** A complete `DeviceContext`: every field the service guarantees. */ +const DEVICE_CONTEXT_PAYLOAD = + '{"deviceCredentialStatus":"active",' + + `"ownerBindingId":"${OWNER_BINDING_ID}",` + + `"authKeyId":"${AUTH_KEY_ID}",` + + `"resolvedAt":"${RESOLVED_AT}"}` + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function claimsOf(request: DaaHttpRequest): Record { + const compact = request.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('missing device authorization') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? ''))) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +async function refreshableClient(payload = DEVICE_CONTEXT_PAYLOAD, status = 200) { + const transport = new RecordingTransport({ + status, + headers: { 'X-Request-Id': 'req-context' }, + bodyBytes: envelope(payload), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { + user: createDaaUserClient(transport, 'production', signing), + transport, + signing, + } +} + +describe('refreshContext', () => { + it('signs a bodyless GET to the registry canonical path and decodes the DeviceContext', async () => { + const { user, transport } = await refreshableClient() + + const context = await user.refreshContext() + + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + if (request === undefined) throw new Error('no request was sent') + expect(request.method).toBe('GET') + expect(request.path).toBe(CONTEXT_PATH) + expect(request.query).toBeNull() + expect(request.bodyBytes).toBeNull() + expect(claimsOf(request)).toMatchObject({ + canonical_path: CONTEXT_PATH, + method: 'GET', + discriminator: 'get_device_context', + schema_version: 1, + aud: 'circle-digital-asset-accounts', + }) + expect(claimsOf(request)).not.toHaveProperty('idempotency_key') + + expect(context).toEqual({ + deviceCredentialStatus: 'active', + ownerBindingId: OWNER_BINDING_ID, + authKeyId: AUTH_KEY_ID, + resolvedAt: RESOLVED_AT, + }) + }) + + it('fails closed while the AuthKey is not yet registered, before sending anything', async () => { + const transport = new RecordingTransport({ status: 200, headers: {}, bodyBytes: null }) + const authKey = await unregisteredAuthKey() + expect(authKey.resolution()).toBe('created') + const user = createDaaUserClient(transport, 'production', signingFor(authKey, AUTH_KEY_ID)) + + expect(await detailOf(user.refreshContext())).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) + + it('accepts only the documented 200', async () => { + for (const status of [201, 204, 299]) { + const { user } = await refreshableClient(DEVICE_CONTEXT_PAYLOAD, status) + const detail = await detailOf(user.refreshContext()) + expect(detail.kind).toBe('api') + if (detail.kind === 'api') expect(detail.httpStatus).toBe(status) + } + }) + + it('maps a malformed data envelope to a contract violation', async () => { + const { user } = await refreshableClient('{}') + expect((await detailOf(user.refreshContext())).kind).toBe('contract_violation') + }) +}) + +describe('close', () => { + it('closes further refreshContext calls without resolving the AuthKey or touching the transport', async () => { + const { user, transport, signing } = await refreshableClient() + + user.close() + + expect(await detailOf(user.refreshContext())).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('closes signed writes on accounts, transfers, and withdrawals', async () => { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + const user = createDaaUserClient(transport, 'production', signing) + + const accountRequest: CreateAccountRequest = { + idempotencyKey: '33333333-3333-4333-a333-333333333333', + clientEntityId: '77777777-7777-4777-8777-777777777777', + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'test account', + blockchain: 'ARC', + } + const transferRequest: CreateTransferRequest = { + idempotencyKey: '44444444-4444-4444-8444-444444444444', + destination: { type: 'account', id: 'acct-dst' }, + amount: { amount: '10.00', currency: 'USD' }, + } + const withdrawalRequest: CreateWithdrawalRequest = { + idempotencyKey: '55555555-5555-4555-8555-555555555555', + destination: { type: 'wire', id: '66666666-6666-4666-8666-666666666666' }, + amount: { amount: '10.00', currency: 'USD' }, + } + + user.close() + + expect(await detailOf(user.accounts.create(accountRequest))).toEqual({ + kind: 'contract_violation', + }) + expect(await detailOf(user.transfers.create(transferRequest))).toEqual({ + kind: 'contract_violation', + }) + expect(await detailOf(user.withdrawals.create(withdrawalRequest))).toEqual({ + kind: 'contract_violation', + }) + expect(transport.sent).toHaveLength(0) + expect(signing.resolutions()).toBe(0) + }) + + it('does not sign with an AuthKey that was resolved before close', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: {}, + bodyBytes: envelope(DEVICE_CONTEXT_PAYLOAD), + }) + const authKey = await registeredAuthKey() + let close: () => void = () => {} + const user = createDaaUserClient(transport, 'production', { + authKeyId: AUTH_KEY_ID, + resolveAuthKey: async () => { + close() + return authKey + }, + }) + close = () => user.close() + + expect(await detailOf(user.refreshContext())).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) + + it('gates unsigned reads after close', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: {}, + bodyBytes: envelope( + '{"accountId":"acct-1","balances":[{"amount":"0.00","currency":"USD"}],' + + '"entityId":"entity-1","purpose":"custody","status":"active","type":"first_party"}', + ), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + const user = createDaaUserClient(transport, 'production', signing) + + user.close() + + expect(await detailOf(user.accounts.get('acct-1'))).toEqual({ + kind: 'contract_violation', + }) + expect(transport.sent).toHaveLength(0) + }) + + it('is idempotent', async () => { + const { user, transport } = await refreshableClient() + + user.close() + user.close() + + expect(await detailOf(user.refreshContext())).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) +}) diff --git a/src/__test__/depositAddressesClient.test.ts b/src/__test__/depositAddressesClient.test.ts new file mode 100644 index 0000000..f05ffd5 --- /dev/null +++ b/src/__test__/depositAddressesClient.test.ts @@ -0,0 +1,744 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import type { DepositAddressesClient } from '../api/DepositAddressesClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import { DEPOSIT_ADDRESS_CHAINS } from '../models/GenerateAddressRequest' +import type { DepositAddressChain, GenerateAddressRequest } from '../models/GenerateAddressRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The deposit-address read, end to end through the client: request shape, + * envelope, decoding, and status mapping. Mirrors `accountsClient.test.ts`'s + * structure for the sibling read. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const VALID_ID = '8f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6b' +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' + +/** A complete address: every field every custody source guarantees on a by-id read. */ +const COMPLETE_ADDRESS = `{"id":"${VALID_ID}","address":"0xRECEIVE","chain":"ETH"}` +const NEXT_ID = '9f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6b' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + client: DepositAddressesClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { + client: createDaaUserClient(transport, 'production', NO_SIGNING).depositAddresses, + transport, + } +} + +function okClient(payload = COMPLETE_ADDRESS) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + it('lists addresses over the public collection path and serializes documented filters', async () => { + const { client, transport } = clientFor({ bodyBytes: envelope(`[${COMPLETE_ADDRESS}]`) }) + + const page = await client.list({ + custodyType: 'omnibus', + accountId: '1000662322', + chain: 'ETH', + currency: 'USD', + from: '2026-01-01T00:00:00Z', + to: '2026-01-31T23:59:59Z', + pageAfter: VALID_ID, + pageSize: 50, + }) + + expect(transport.sent).toHaveLength(1) + expect(transport.sent[0]).toMatchObject({ + method: 'GET', + path: '/v1/accounts/addresses/deposit', + query: + 'custodyType=omnibus&accountId=1000662322&chain=ETH¤cy=USD&from=2026-01-01T00%3A00%3A00Z&to=2026-01-31T23%3A59%3A59Z&pageAfter=' + + `${VALID_ID}&pageSize=50`, + headers: {}, + bodyBytes: null, + }) + expect(page.items).toHaveLength(1) + expect(page.items[0]?.address).toBe('0xRECEIVE') + expect(Object.isFrozen(page.items)).toBe(true) + }) + + it('replays the API pagination query byte-for-byte on the same deposit-address collection', async () => { + const first = envelope(`[${COMPLETE_ADDRESS}]`) + const second = envelope('[]') + const transport: DaaTransport & { readonly sent: DaaHttpRequest[] } = { + sent: [], + async send(request) { + this.sent.push(request) + return this.sent.length === 1 + ? { + status: 200, + headers: { + Link: `; rel="next"`, + }, + bodyBytes: first, + } + : { status: 200, headers: {}, bodyBytes: second } + }, + } + const client = createDaaUserClient(transport, 'production', NO_SIGNING).depositAddresses + + const page = await client.list() + await page.next() + + expect(transport.sent).toHaveLength(2) + expect(transport.sent[1]).toMatchObject({ + method: 'GET', + path: '/v1/accounts/addresses/deposit', + query: `pageAfter=${NEXT_ID}%2Bopaque&filter=a%2Fb`, + }) + }) + + it('closes the unsigned write and retained Page navigation after the user closes', async () => { + const transport: DaaTransport & { readonly sent: DaaHttpRequest[] } = { + sent: [], + async send(request) { + this.sent.push(request) + return { + status: 200, + headers: { + Link: `; rel="next"`, + }, + bodyBytes: envelope(`[${COMPLETE_ADDRESS}]`), + } + }, + } + const user = createDaaUserClient(transport, 'production', NO_SIGNING) + const page = await user.depositAddresses.list() + + user.close() + + const request: GenerateAddressRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'acct-1', + currency: 'USD', + } + expect(await detailOf(user.depositAddresses.create(request))).toEqual({ + kind: 'contract_violation', + }) + expect(await detailOf(page.next())).toEqual({ + kind: 'contract_violation', + }) + expect(transport.sent).toHaveLength(1) + }) + + it('rejects invalid collection queries before sending a request', async () => { + const { client, transport } = okClient() + + for (const query of [ + null, + [], + { custodyType: 'wrong' }, + { accountId: '' }, + { pageAfter: VALID_ID, pageBefore: NEXT_ID }, + { pageAfter: 'not-a-uuid' }, + { pageSize: 0 }, + ]) { + expect((await detailOf(client.list(query as never))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('treats a non-array collection data value as a broken contract', async () => { + const { client } = clientFor({ bodyBytes: envelope(COMPLETE_ADDRESS) }) + + expect((await detailOf(client.list())).kind).toBe('contract_violation') + }) + + it('mirrors the canonical public Accounts Chain values exhaustively', () => { + expect(DEPOSIT_ADDRESS_CHAINS).toEqual([ + 'ALGO', + 'APTOS', + 'ARB', + 'AVAX', + 'BASE', + 'BTC', + 'CELO', + 'CODEX', + 'ETH', + 'HBAR', + 'HYPEREVM', + 'INK', + 'LINEA', + 'NEAR', + 'NOBLE', + 'OP', + 'PAH', + 'PLUME', + 'POLY', + 'SEI', + 'SOL', + 'SONIC', + 'SUI', + 'UNI', + 'WORLDCHAIN', + 'XDC', + 'XLM', + 'XRP', + 'ZKS', + 'ZKSYNC', + ]) + expect(Object.isFrozen(DEPOSIT_ADDRESS_CHAINS)).toBe(true) + }) + + it('reads a deposit address over the public path', async () => { + const { client, transport } = okClient() + + const address = await client.get(VALID_ID) + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.method).toBe('GET') + // The public spelling. + expect(sent.path).toBe(`/v1/accounts/addresses/deposit/${VALID_ID}`) + expect(sent.query).toBeNull() + expect(sent.bodyBytes).toBeNull() + expect(sent.headers).toEqual({}) + expect(address.id).toBe(VALID_ID) + expect(address.chain).toBe('ETH') + }) + + /** + * The service types `depositId` as a required UUID, so any other + * shape cannot resolve to an address — reject it locally + * rather than spend a round trip finding out. A UUID-formatted identifier also + * contains no path separator or control character, so this doubles as the + * route-confusion defence `AccountsClient.get`'s character-class check + * exists for. + */ + it('rejects a depositId that is not UUID-formatted', async () => { + const { client, transport } = okClient() + + for (const bad of [ + '', + 'not-a-uuid', + `${VALID_ID}/transfers`, + `${VALID_ID}%2f`, + `${VALID_ID}\r\nX-Injected: 1`, + VALID_ID.replace(/-/g, ''), // no separators + VALID_ID.slice(0, -1), // one char short + `${VALID_ID}0`, // one char long + '.', + '..', + ]) { + const detail = await detailOf(client.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts an uppercase UUID', async () => { + const { client, transport } = okClient() + const upper = VALID_ID.toUpperCase() + await client.get(upper) + expect(transport.sent[0]?.path).toBe(`/v1/accounts/addresses/deposit/${upper}`) + }) + + it('creates over the public path with the exact documented body bytes', async () => { + const { client, transport } = clientFor({ + status: 201, + headers: { + Location: `/v1/accounts/addresses/deposit/${VALID_ID}`, + 'X-Request-Id': 'req-create', + }, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + const request: GenerateAddressRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + } + + const address = await client.create(request) + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent).toMatchObject({ + method: 'POST', + path: '/v1/accounts/addresses/deposit', + query: null, + headers: { 'Content-Type': 'application/json' }, + }) + expect(new TextDecoder().decode(sent.bodyBytes as Uint8Array)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","accountId":"account-1","currency":"USD","chain":"ETH"}`, + ) + expect(address.id).toBe(VALID_ID) + expect(address.address).toBe('0xRECEIVE') + expect(Object.isFrozen(address)).toBe(true) + expect(Object.keys(address)).not.toContain('address') + expect(JSON.stringify(address)).not.toContain('0xRECEIVE') + }) + + it('omits custodyType so DAA derives the authoritative selector from accountId', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + + await client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'EUR', + chain: 'SOL', + }) + + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.query).toBeNull() + expect(new TextDecoder().decode(sent.bodyBytes as Uint8Array)).not.toContain('custodyType') + }) + + it('snapshots each field once and drops properties outside the wire contract', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + const reads = { idempotencyKey: 0, accountId: 0, currency: 0, chain: 0 } + const request = { + get idempotencyKey() { + reads.idempotencyKey += 1 + return IDEMPOTENCY_KEY + }, + get accountId() { + reads.accountId += 1 + return 'account-1' + }, + get currency() { + reads.currency += 1 + return 'USD' as const + }, + get chain() { + reads.chain += 1 + return 'ETH' as const + }, + custodyType: 'self', + ignored: 'not-on-the-wire', + } + + await client.create(request) + + expect(reads).toEqual({ idempotencyKey: 1, accountId: 1, currency: 1, chain: 1 }) + const body = new TextDecoder().decode(transport.sent[0]?.bodyBytes as Uint8Array) + expect(body).not.toContain('custodyType') + expect(body).not.toContain('ignored') + }) + + it('rejects invalid create input before transport', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + const valid = { + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + } as const + const invalid: unknown[] = [ + null, + [], + 'request', + { ...valid, idempotencyKey: 'not-a-uuid' }, + { ...valid, idempotencyKey: '22222222-2222-1222-a222-222222222222' }, + { ...valid, idempotencyKey: '22222222-2222-4222-7222-222222222222' }, + { ...valid, accountId: '' }, + { ...valid, accountId: null }, + { ...valid, accountId: undefined }, + { idempotencyKey: valid.idempotencyKey, currency: valid.currency, chain: valid.chain }, + { ...valid, currency: 'USDC' }, + { ...valid, chain: '' }, + { ...valid, chain: null }, + ] + + for (const request of invalid) { + expect((await detailOf(client.create(request as GenerateAddressRequest))).kind).toBe( + 'contract_violation', + ) + } + expect(transport.sent).toHaveLength(0) + }) + + /** + * The broader public Accounts API permits omitting `accountId` to select + * the caller's omnibus master account, but this SDK's typed client only + * supports account-scoped resolution — see `GenerateAddressRequest`'s class + * doc. A caller who omits `accountId` is rejected locally rather than + * silently routed to the master account. + */ + it('rejects create() without accountId rather than falling back to the omnibus master account', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + + const result = await detailOf( + client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + currency: 'USD', + chain: 'ETH', + } as GenerateAddressRequest), + ) + + expect(result.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + /** + * `chain` is optional: the service resolves an omitted `chain` to the + * account's immutable home blockchain for segregated/self-custody accounts + * — the only accounts this SDK's typed client reaches (see + * `GenerateAddressRequest`'s class doc). + */ + it('creates with chain omitted, letting the service resolve the account home chain', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + + await client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + }) + + expect(new TextDecoder().decode(transport.sent[0]?.bodyBytes as Uint8Array)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","accountId":"account-1","currency":"USD"}`, + ) + }) + + /** + * A `chain` value outside the author-time `DEPOSIT_ADDRESS_CHAINS` union is + * a growable-catalog value, not a contract violation — see that constant's + * doc in `models/GenerateAddressRequest.ts`. The server remains the + * authority and 400s on a genuinely unsupported chain. + */ + it('does not reject a chain outside the locally known catalog', async () => { + const { client, transport } = clientFor({ + status: 201, + bodyBytes: envelope(COMPLETE_ADDRESS), + }) + + await client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'BRAND_NEW_CHAIN' as DepositAddressChain, + }) + + expect(new TextDecoder().decode(transport.sent[0]?.bodyBytes as Uint8Array)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","accountId":"account-1","currency":"USD","chain":"BRAND_NEW_CHAIN"}`, + ) + }) +}) + +describe('the success path', () => { + it('accepts the documented 200 status', async () => { + const { client } = clientFor({ status: 200, bodyBytes: envelope(COMPLETE_ADDRESS) }) + expect((await client.get(VALID_ID)).id).toBe(VALID_ID) + }) + + /** The payload sits under `data`; a body with it at the root is malformed. */ + it('rejects a body whose address sits at the root instead of the envelope', async () => { + const { client } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes(COMPLETE_ADDRESS), + }) + + expect(await detailOf(client.get(VALID_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-2', + }) + }) + + /** An envelope present but empty is malformed — the wrapper is not optional on a 2xx. */ + it('rejects an empty envelope, an empty body, and no body at all', async () => { + for (const bodyBytes of [bytes('{"data":null}'), bytes(''), null]) { + const { client } = clientFor({ status: 200, bodyBytes }) + expect((await detailOf(client.get(VALID_ID))).kind).toBe('contract_violation') + } + }) + + /** + * A `200` whose address is missing something every source guarantees must + * reach the caller as a broken contract, not a successful address with a + * hole in it. The correlation id has to survive. + */ + it('reports an address missing guaranteed fields as a broken contract with the correlation id', async () => { + const payloads = ['{}', `{"id":"${VALID_ID}"}`, `{"id":"${VALID_ID}","address":"0xRECEIVE"}`] + + for (const payload of payloads) { + const { client } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-13' }, + bodyBytes: envelope(payload), + }) + expect(await detailOf(client.get(VALID_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-13', + }) + } + }) + + /** The fields a segregated/self-custody read may leave null must still surface as null, not fail the read. */ + it('surfaces a segregated/self-custody read that omits currency and addressTag', async () => { + const { client } = okClient( + `{"id":"${VALID_ID}","address":"0xabc","chain":"ETH","addressTag":null,"currency":null,` + + '"accountId":"acct-1"}', + ) + + const address = await client.get(VALID_ID) + + expect(address.address).toBe('0xabc') + expect(address.currency).toBeNull() + expect(address.addressTag).toBeNull() + expect(address.accountId).toBe('acct-1') + }) + + it('requires exactly 201 and a data envelope for create', async () => { + for (const status of [200, 202, 204, 299]) { + const { client } = clientFor({ status, bodyBytes: envelope(COMPLETE_ADDRESS) }) + expect( + ( + await detailOf( + client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + }), + ) + ).kind, + ).toBe('api') + } + + for (const bodyBytes of [bytes(COMPLETE_ADDRESS), bytes('{"data":null}'), bytes(''), null]) { + const { client } = clientFor({ + status: 201, + headers: { 'x-request-id': 'req-create-bad' }, + bodyBytes, + }) + expect( + await detailOf( + client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + }), + ), + ).toEqual({ kind: 'contract_violation', correlationId: 'req-create-bad' }) + } + }) +}) + +describe('the failure path', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + for (const status of [201, 204, 299, 400, 401, 404, 409, 500, 503]) { + const { client } = clientFor({ + status, + headers: { 'X-Request-Id': `req-${status}` }, + bodyBytes: bytes(`{"status":{"code":${status * 10},"message":"nope"}}`), + }) + + const detail = await detailOf(client.get(VALID_ID)) + expect(detail).toEqual({ + kind: 'api', + httpStatus: status, + daaStatusCode: status * 10, + retryable: status === 429 || status >= 500, + }) + } + }) + + it('marks only 429 and 5xx retryable', async () => { + for (const [status, retryable] of [ + [400, false], + [404, false], + [429, true], + [500, true], + [599, true], + ] as const) { + const { client } = clientFor({ status }) + expect(await detailOf(client.get(VALID_ID))).toMatchObject({ kind: 'api', retryable }) + } + }) + + /** No field name from the response reaches the error a consumer sees. */ + it('does not put a response field name in the error message', async () => { + const { client } = clientFor({ status: 200, bodyBytes: envelope(`{"id":"${VALID_ID}"}`) }) + + try { + await client.get(VALID_ID) + throw new Error('expected the read to fail') + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).not.toContain('address') + expect((err as Error).message).not.toContain('chain') + } + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).depositAddresses.get(VALID_ID), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) + + it('maps a create reusing a key for a different account to idempotency_conflict with that key', async () => { + const { client, transport } = clientFor({ + status: 409, + headers: { 'X-Request-Id': 'req-reused' }, + bodyBytes: bytes( + '{"code":420034,"message":"The idempotency key was reused with a different request"}', + ), + }) + + const call = client.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: '1000662322', + currency: 'USD', + chain: 'ETH', + }) + + await expect(call).rejects.toMatchObject({ + detail: { kind: 'idempotency_conflict', idempotencyKey: IDEMPOTENCY_KEY }, + }) + await expect(call).rejects.not.toHaveProperty( + 'message', + expect.stringContaining(IDEMPOTENCY_KEY), + ) + expect(transport.sent).toHaveLength(1) + }) + + it('preserves authoritative and unknown create API failures and transport failures', async () => { + const { client } = clientFor({ + status: 400, + headers: { 'x-request-id': 'req-conflict' }, + bodyBytes: bytes('{"status":{"code":420034}}'), + }) + const request: GenerateAddressRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + accountId: 'account-1', + currency: 'USD', + chain: 'ETH', + } + + expect(await detailOf(client.create(request))).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 420034, + retryable: false, + }) + + const { client: unknownConflict } = clientFor({ + status: 409, + bodyBytes: bytes('{"status":{"code":"SOME_NEW_CONFLICT"}}'), + }) + expect(await detailOf(unknownConflict.create(request))).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 'SOME_NEW_CONFLICT', + retryable: false, + }) + + const failure = new Error('relay unavailable') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).depositAddresses.create(request), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true, idempotencyKey: IDEMPOTENCY_KEY }, + cause: failure, + }) + }) +}) + +describe('construction', () => { + it('freezes the client', () => { + const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, + } + expect( + Object.isFrozen(createDaaUserClient(transport, 'production', NO_SIGNING).depositAddresses), + ).toBe(true) + }) +}) diff --git a/src/__test__/depositPayload.test.ts b/src/__test__/depositPayload.test.ts new file mode 100644 index 0000000..43db6b7 --- /dev/null +++ b/src/__test__/depositPayload.test.ts @@ -0,0 +1,481 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import { Deposit } from '../models/Deposit' +import { DepositSummary } from '../models/DepositSummary' +import type { Money } from '../models/Money' +import { MalformedPayloadError } from '../wire/payload' +import { toDeposit, toDepositSummaries, toDepositSummary } from '../wire/depositPayload' + +/** + * Decoding tests for the deposit model. These go through the real parse and + * mapping rather than constructing a payload object directly, because the wire + * spellings, the number handling, and the required/optional line are the things + * under test — see the class note on `Deposit` for why that line does not follow + * the OpenAPI schema's required marking. + */ + +const REQUIRED = + '"id":"dep-1","amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"' + +function decode(body: string): Deposit { + return toDeposit(JSON.parse(body) as unknown) +} + +function decodeComplete(extra = ''): Deposit { + return decode(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) +} + +function depositWith(field: string, value: string): Deposit { + return decodeComplete(`"${field}":${value}`) +} + +describe('required and optional fields', () => { + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + id: '"dep-1"', + amount: '{"amount":"10.00","currency":"USD"}', + status: '"pending"', + createDate: '"2026-01-01T00:00:00Z"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + // Sanity: the complete body decodes, or every assertion below is vacuous. + expect(decode(body(complete)).id).toBe('dep-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toDeposit(null)).toThrow(MalformedPayloadError) + expect(() => toDeposit([])).toThrow(MalformedPayloadError) + }) + + it('rejects an explicit null on a guaranteed field', () => { + expect(() => + decode( + '{"id":null,"amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}', + ), + ).toThrow(MalformedPayloadError) + }) + + it('rejects a field carried in the wrong shape', () => { + expect(() => depositWith('id', '{}')).toThrow(MalformedPayloadError) + expect(() => depositWith('id', 'true')).toThrow(MalformedPayloadError) + expect(() => depositWith('amount', '"nope"')).toThrow(MalformedPayloadError) + expect(() => depositWith('createDate', '7')).toThrow(MalformedPayloadError) + }) + + /** + * `destination` is marked required in the schema, but the service reports a + * `null` destination whenever the ledger leg is not a wallet location — a + * real code path. Absence must decode cleanly, not throw. + */ + it('tolerates an absent destination despite the schema marking it required', () => { + expect(decodeComplete().destination).toBeNull() + }) + + it('tolerates an absent update date', () => { + expect(decodeComplete().updateDate).toBeNull() + }) + + it('reports every other absent optional field as absent', () => { + const deposit = decodeComplete() + expect(deposit.sourceAccountId).toBeNull() + expect(deposit.fee).toBeNull() + expect(deposit.fees).toBeNull() + expect(deposit.fromAmount).toBeNull() + expect(deposit.errorCode).toBeNull() + expect(deposit.externalRef).toBeNull() + expect(deposit.customerExternalRef).toBeNull() + expect(deposit.riskEvaluation).toBeNull() + expect(deposit.source).toBeNull() + expect(deposit.trackingRef).toBeNull() + }) + + it('rejects an optional money field carried in the wrong shape', () => { + expect(() => depositWith('fee', '"nope"')).toThrow(MalformedPayloadError) + expect(() => depositWith('fee', '{"amount":"nope","currency":"USD"}')).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects a destination missing its guaranteed id or type', () => { + expect(() => depositWith('destination', '{"type":"account"}')).toThrow(MalformedPayloadError) + expect(() => depositWith('destination', '{"id":"acct-1"}')).toThrow(MalformedPayloadError) + }) + + it('rejects a source missing its guaranteed id or type', () => { + expect(() => depositWith('source', '{"type":"wire"}')).toThrow(MalformedPayloadError) + expect(() => depositWith('source', '{"id":"fiat-1"}')).toThrow(MalformedPayloadError) + }) +}) + +describe('closed-set fields', () => { + it('maps every known status and falls back for the rest', () => { + expect(depositWith('status', '"pending"').status).toEqual({ kind: 'pending' }) + expect(depositWith('status', '"complete"').status).toEqual({ kind: 'complete' }) + expect(depositWith('status', '"failed"').status).toEqual({ kind: 'failed' }) + expect(depositWith('status', '"settling"').status).toEqual({ + kind: 'unrecognized', + rawValue: 'settling', + }) + }) + + it('treats a value spelled like an Object.prototype member as unrecognized', () => { + for (const hostile of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) { + expect(depositWith('status', `"${hostile}"`).status).toEqual({ + kind: 'unrecognized', + rawValue: hostile, + }) + } + }) + + it('maps every known destination type and falls back for the rest', () => { + expect(depositWith('destination', '{"type":"account","id":"acct-1"}').destination).toEqual({ + kind: 'account', + accountId: 'acct-1', + }) + expect(depositWith('destination', '{"type":"blockchain","id":"acct-1"}').destination).toEqual({ + kind: 'unrecognized', + rawValue: 'blockchain', + }) + }) + + it('maps every known source rail and falls back for the rest', () => { + const wire = depositWith('source', '{"type":"wire","id":"fiat-1","name":"Checking"}').source + expect(wire).toEqual({ type: { kind: 'wire' }, id: 'fiat-1', name: 'Checking' }) + + const unknownRail = depositWith('source', '{"type":"venmo","id":"fiat-1"}').source + expect(unknownRail).toEqual({ + type: { kind: 'unrecognized', rawValue: 'venmo' }, + id: 'fiat-1', + name: null, + }) + }) +}) + +describe('money fields', () => { + it('preserves an amount that a JavaScript number would round', () => { + const deposit = depositWith('amount', '{"amount":"1234567890123456.78","currency":"USD"}') + expect((deposit.amount as Money).amount).toBe('1234567890123456.78') + expect((deposit.amount as Money).currency).toBe('USD') + }) + + it('rejects an amount sent as a JSON number rather than coercing it', () => { + expect(() => depositWith('amount', '{"amount":10.5,"currency":"USD"}')).toThrow( + MalformedPayloadError, + ) + }) + + it('decodes the optional money fields when present', () => { + const deposit = decodeComplete( + '"fee":{"amount":"1.00","currency":"USD"},' + + '"fees":{"amount":"1.50","currency":"USD"},' + + '"fromAmount":{"amount":"9.00","currency":"EUR"}', + ) + expect((deposit.fee as Money).amount).toBe('1.00') + expect((deposit.fees as Money).amount).toBe('1.50') + expect((deposit.fromAmount as Money).amount).toBe('9.00') + expect((deposit.fromAmount as Money).currency).toBe('EUR') + }) +}) + +describe('risk evaluation', () => { + it('carries a risk decision when present', () => { + const deposit = decodeComplete('"riskEvaluation":{"decision":"denied","reason":"velocity"}') + expect(deposit.riskEvaluation).toEqual({ decision: 'denied', reason: 'velocity' }) + }) + + it('tolerates a risk decision with no reason', () => { + const deposit = decodeComplete('"riskEvaluation":{"decision":"denied"}') + expect(deposit.riskEvaluation).toEqual({ decision: 'denied', reason: null }) + }) + + it('tolerates a reason-only risk evaluation the service can produce', () => { + const deposit = decodeComplete('"riskEvaluation":{"reason":"velocity"}') + expect(deposit.riskEvaluation).toEqual({ decision: null, reason: 'velocity' }) + }) + + it('rejects a risk evaluation field carried in the wrong shape', () => { + expect(() => decodeComplete('"riskEvaluation":{"decision":7}')).toThrow(MalformedPayloadError) + }) +}) + +describe('forward compatibility', () => { + it('ignores an unknown response field wherever it appears', () => { + const deposit = decode( + `{${REQUIRED},"settlementTier":"gold","riskScore":7,"flags":null,` + + `"destination":{"type":"account","id":"acct-1","extra":"nope"}}`, + ) + expect(deposit.id).toBe('dep-1') + expect(deposit.destination).toEqual({ kind: 'account', accountId: 'acct-1' }) + expect(Object.keys(deposit)).not.toContain('settlementTier') + expect(Object.keys(deposit)).not.toContain('riskScore') + }) + + it('decodes a response carrying an unknown field and an unknown value at once', () => { + const deposit = decode(`{${REQUIRED},"status":"settling","tierMetadata":{"a":1}}`) + expect(deposit.id).toBe('dep-1') + expect(deposit.status).toEqual({ kind: 'unrecognized', rawValue: 'settling' }) + }) +}) + +describe('redaction', () => { + const deposit = decodeComplete( + '"fee":{"amount":"5.25","currency":"USD"},' + + '"destination":{"type":"account","id":"acct-1"},' + + '"externalRef":"bank-ref-123","customerExternalRef":"customer memo 456"', + ) + const secrets = ['10.00', '5.25', 'bank-ref-123', 'customer memo 456'] + + it('keeps sensitive fields off the deposit object as own properties', () => { + expect(Object.getOwnPropertyNames(deposit)).not.toContain('amount') + expect(Object.getOwnPropertyNames(deposit)).not.toContain('fee') + expect(Object.getOwnPropertyNames(deposit)).not.toContain('fees') + expect(Object.getOwnPropertyNames(deposit)).not.toContain('fromAmount') + expect(Object.getOwnPropertyNames(deposit)).not.toContain('externalRef') + expect(Object.getOwnPropertyNames(deposit)).not.toContain('customerExternalRef') + }) + + it('keeps sensitive values available through explicit accessors', () => { + expect(deposit.externalRef).toBe('bank-ref-123') + expect(deposit.customerExternalRef).toBe('customer memo 456') + }) + + it.each([ + ['JSON.stringify', (value: unknown): string => JSON.stringify(value) ?? ''], + ['util.inspect (what console.log renders)', (value: unknown): string => inspect(value)], + ['String()', (value: unknown): string => String(value)], + [ + 'spread into a plain object', + (value: unknown): string => JSON.stringify({ ...(value as object) }) ?? '', + ], + [ + 'for...in', + (value: unknown): string => { + let out = '' + for (const key in value as Record) { + out += `${key}=${String((value as Record)[key])};` + } + return out + }, + ], + ])('reveals no sensitive value through %s', (_name, render) => { + for (const rendered of [render(deposit), render(deposit.amount), render(deposit.fee)]) { + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + } + }) + + it('still renders the identifiers and states that make a log line useful', () => { + expect(String(deposit)).toContain('dep-1') + expect(String(deposit)).toContain('pending') + expect(JSON.stringify(deposit)).toContain('dep-1') + }) +}) + +describe('immutability', () => { + const deposit = decodeComplete() + + it('freezes the deposit', () => { + expect(Object.isFrozen(deposit)).toBe(true) + }) + + /** + * Freezing the deposit alone is not enough: the nested values it hands out are + * ordinary objects, so a consumer reaching one could edit an account id, a + * rail, or a risk decision on a deposit the SDK already returned. The + * guarantee is only worth stating if it reaches the whole graph. + */ + it('freezes every nested value it decoded, not only the deposit', () => { + const full = decodeComplete( + '"destination":{"type":"account","id":"acct-1"},' + + '"source":{"type":"wire","id":"fiat-1","name":"Checking"},' + + '"riskEvaluation":{"decision":"denied","reason":"velocity"}', + ) + + expect(Object.isFrozen(full.destination)).toBe(true) + expect(Object.isFrozen(full.source)).toBe(true) + expect(Object.isFrozen(full.source?.type)).toBe(true) + expect(Object.isFrozen(full.riskEvaluation)).toBe(true) + expect(Object.isFrozen(full.status)).toBe(true) + + // An unrecognized arm is decoded rather than looked up, so it is the one + // most likely to be missed. + const unknown = decodeComplete('"destination":{"type":"blockchain","id":"acct-1"}') + expect(Object.isFrozen(unknown.destination)).toBe(true) + }) + + it('refuses a write to a nested value through a cast', () => { + const full = decodeComplete('"destination":{"type":"account","id":"acct-1"}') + const mutable = full.destination as unknown as Record + + expect(() => { + mutable['accountId'] = 'acct-forged' + }).toThrow(TypeError) + expect(full.destination).toEqual({ kind: 'account', accountId: 'acct-1' }) + }) + + it('refuses a write through a cast', () => { + const mutable = deposit as unknown as Record + expect(() => { + mutable['id'] = 'dep-forged' + }).toThrow(TypeError) + expect(deposit.id).toBe('dep-1') + }) +}) + +describe('consumer construction', () => { + it('does not accept a look-alike object as a deposit', () => { + const fabricated = { + id: 'dep-forged', + status: { kind: 'pending' }, + } + expect(fabricated instanceof Deposit).toBe(false) + expect(decodeComplete() instanceof Deposit).toBe(true) + }) +}) + +/** + * `toDepositSummary` decoding — the compact list-endpoint projection. + * + * Same required/optional line as `toDeposit` (both wire records + * carry the same guaranteed fields), but the summary's own wire record has no + * `source`, `fees`, `fromAmount`, or `trackingRef` property at all, so there is + * nothing to assert absent for those — see `models/DepositSummary.ts`'s class + * note. + */ +describe('DepositSummary decoding', () => { + function decodeSummary(body: string): DepositSummary { + return toDepositSummary(JSON.parse(body) as unknown) + } + + function decodeSummaryComplete(extra = ''): DepositSummary { + return decodeSummary(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) + } + + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + id: '"dep-1"', + amount: '{"amount":"10.00","currency":"USD"}', + status: '"pending"', + createDate: '"2026-01-01T00:00:00Z"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + expect(decodeSummary(body(complete)).id).toBe('dep-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decodeSummary(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => toDepositSummary(null)).toThrow(MalformedPayloadError) + expect(() => toDepositSummary([])).toThrow(MalformedPayloadError) + }) + + it('tolerates an absent destination and an absent update date', () => { + const summary = decodeSummaryComplete() + expect(summary.destination).toBeNull() + expect(summary.updateDate).toBeNull() + }) + + it('reports every other absent optional field as absent', () => { + const summary = decodeSummaryComplete() + expect(summary.sourceAccountId).toBeNull() + expect(summary.fee).toBeNull() + expect(summary.errorCode).toBeNull() + expect(summary.externalRef).toBeNull() + expect(summary.customerExternalRef).toBeNull() + expect(summary.riskEvaluation).toBeNull() + }) + + it('maps every known status and falls back for the rest', () => { + expect(decodeSummary(`{${REQUIRED.replace('"pending"', '"complete"')}}`).status).toEqual({ + kind: 'complete', + }) + expect(decodeSummary(`{${REQUIRED.replace('"pending"', '"settling"')}}`).status).toEqual({ + kind: 'unrecognized', + rawValue: 'settling', + }) + }) + + it('decodes destination and the single fee field when present', () => { + const summary = decodeSummaryComplete( + '"destination":{"type":"account","id":"acct-1"},"fee":{"amount":"1.00","currency":"USD"}', + ) + expect(summary.destination).toEqual({ kind: 'account', accountId: 'acct-1' }) + expect((summary.fee as Money).amount).toBe('1.00') + }) + + it('has no source, fees, fromAmount, or trackingRef fields at all', () => { + const summary = decodeSummaryComplete() + expect(Object.getOwnPropertyNames(summary)).not.toContain('source') + expect(Object.getOwnPropertyNames(summary)).not.toContain('fees') + expect(Object.getOwnPropertyNames(summary)).not.toContain('fromAmount') + expect(Object.getOwnPropertyNames(summary)).not.toContain('trackingRef') + }) + + it('withholds amounts and references from default renderings', () => { + const summary = decodeSummaryComplete( + '"fee":{"amount":"5.25","currency":"USD"},"externalRef":"bank-ref-123",' + + '"customerExternalRef":"customer memo 456"', + ) + const rendered = JSON.stringify(summary) + for (const secret of ['10.00', '5.25', 'bank-ref-123', 'customer memo 456']) { + expect(rendered).not.toContain(secret) + } + expect(summary.externalRef).toBe('bank-ref-123') + expect(summary.customerExternalRef).toBe('customer memo 456') + }) + + it('freezes the summary', () => { + expect(Object.isFrozen(decodeSummaryComplete())).toBe(true) + }) + + it('does not accept a look-alike object as a DepositSummary', () => { + const fabricated = { id: 'dep-forged', status: { kind: 'pending' } } + expect(fabricated instanceof DepositSummary).toBe(false) + expect(decodeSummaryComplete() instanceof DepositSummary).toBe(true) + }) + + it('decodes a page of summaries and rejects a non-array collection', () => { + const items = toDepositSummaries(JSON.parse(`[{${REQUIRED}}]`) as unknown) + expect(items).toHaveLength(1) + expect(items[0]?.id).toBe('dep-1') + expect(Object.isFrozen(items)).toBe(true) + expect(() => toDepositSummaries(JSON.parse(`{${REQUIRED}}`) as unknown)).toThrow( + MalformedPayloadError, + ) + }) +}) diff --git a/src/__test__/depositsClient.test.ts b/src/__test__/depositsClient.test.ts new file mode 100644 index 0000000..5bd0613 --- /dev/null +++ b/src/__test__/depositsClient.test.ts @@ -0,0 +1,368 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { DEPOSIT_TYPES } from '../api/DepositsClient' +import type { DepositsClient } from '../api/DepositsClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { Money } from '../models/Money' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The deposit read, end to end through the client: request shape, envelope, + * decoding, and status mapping. Mirrors `accountsClient.test.ts`. + * The client is reached through the internal user-client factory, the same + * path `DaaClient.forUser` uses. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +/** The service types this path parameter as a UUID, so every read uses one. */ +const DEPOSIT_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' + +/** A complete deposit: every field the service guarantees. */ +const COMPLETE_DEPOSIT = + '{"id":"dep-1","amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + deposits: DepositsClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { deposits: createDaaUserClient(transport, 'production', NO_SIGNING).deposits, transport } +} + +function okClient(payload = COMPLETE_DEPOSIT) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + /** + * Author-time autocomplete/typo-protection union, mirrored from the + * API's deposit `type` values — not a runtime allowlist. See + * `DepositsClient.ts`'s `DEPOSIT_TYPES` doc for why the `type` query filter + * accepts any non-empty string at runtime instead. + */ + it('mirrors the server DepositType rails exhaustively', () => { + expect(DEPOSIT_TYPES).toEqual([ + 'wire', + 'ach', + 'cbit', + 'rtgs', + 'rtp', + 'xpay', + 'signet', + 'sepa', + 'sepa_instant', + 'sen', + 'pix', + 'cubix', + 'book_transfer', + 'fed_now', + ]) + expect(Object.isFrozen(DEPOSIT_TYPES)).toBe(true) + }) + + it('reads a deposit over the public deposits path', async () => { + const { deposits, transport } = okClient() + + const deposit = await deposits.get(DEPOSIT_ID) + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.method).toBe('GET') + // The public spelling. + expect(sent.path).toBe(`/v1/accounts/deposits/${DEPOSIT_ID}`) + expect(sent.query).toBeNull() + expect(sent.bodyBytes).toBeNull() + expect(sent.headers).toEqual({}) + expect(deposit.id).toBe('dep-1') + expect(deposit.status).toEqual({ kind: 'pending' }) + }) + + it('rejects a depositId that would address a different route', async () => { + const { deposits, transport } = okClient() + + for (const bad of [ + `${DEPOSIT_ID}/transfers`, + `${DEPOSIT_ID}/`, + `/${DEPOSIT_ID}`, + '', + 'a/b/c', + ]) { + const detail = await detailOf(deposits.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a depositId carrying an encoded separator or other unsafe character', async () => { + const { deposits, transport } = okClient() + + for (const bad of [ + `${DEPOSIT_ID}%2Ftransfers`, + 'dep%2f1', + `${DEPOSIT_ID}?x=1`, + `${DEPOSIT_ID}#frag`, + `${DEPOSIT_ID} `, + ` ${DEPOSIT_ID}`, + `${DEPOSIT_ID}\r\nX-Injected: 1`, + '.', + '..', + 'dep/../transfers', + ]) { + const detail = await detailOf(deposits.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts a UUID-formatted identifier in either case', async () => { + for (const good of [DEPOSIT_ID, DEPOSIT_ID.toUpperCase()]) { + const { deposits, transport } = okClient() + await deposits.get(good) + expect(transport.sent[0]?.path).toBe(`/v1/accounts/deposits/${good}`) + } + }) + + /** + * The SDK contract types this parameter `depositId: UUID`, unlike + * `accounts.get`, whose id is a `string` because public account ids may be + * numeric. An id that would pass a generic path-segment guard is still + * rejected here: it cannot resolve to a deposit, so sending it would only + * turn a caller's mistake into a round trip and a 400. + */ + it('rejects an id that is well-formed as a path segment but is not a UUID', async () => { + const { deposits, transport } = okClient() + + for (const bad of [ + 'dep-1', + 'DEP_1', + 'a.b~c', + '0123456789', + '3f1a2b4c5d6e4f708192a3b4c5d6e7f8', + '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f', + '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f89', + '3g1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + ]) { + expect((await detailOf(deposits.get(bad))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('the success path', () => { + it('rejects undocumented 2xx statuses as API failures', async () => { + for (const status of [201, 204, 299]) { + const { deposits } = clientFor({ + status, + bodyBytes: envelope(COMPLETE_DEPOSIT), + }) + expect(await detailOf(deposits.get(DEPOSIT_ID))).toMatchObject({ + kind: 'api', + httpStatus: status, + }) + } + }) + + it('rejects a body whose deposit sits at the root instead of the envelope', async () => { + const { deposits } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes(COMPLETE_DEPOSIT), + }) + + expect(await detailOf(deposits.get(DEPOSIT_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-2', + }) + }) + + it('rejects a body wrapped in a response key instead of data', async () => { + const { deposits } = clientFor({ + status: 200, + bodyBytes: bytes(`{"response":${COMPLETE_DEPOSIT}}`), + }) + + expect((await detailOf(deposits.get(DEPOSIT_ID))).kind).toBe('contract_violation') + }) + + it('rejects an empty envelope, an empty body, and no body at all', async () => { + for (const bodyBytes of [bytes('{"data":null}'), bytes(''), null]) { + const { deposits } = clientFor({ status: 200, bodyBytes }) + expect((await detailOf(deposits.get(DEPOSIT_ID))).kind).toBe('contract_violation') + } + }) + + it('reports a deposit missing guaranteed fields as a broken contract with the correlation id', async () => { + const payloads = [ + '{}', + '{"id":"dep-1"}', + '{"id":"dep-1","amount":{"amount":"10.00","currency":"USD"}}', + '{"id":"dep-1","amount":{"amount":"nope","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}', + ] + + for (const payload of payloads) { + const { deposits } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-13' }, + bodyBytes: envelope(payload), + }) + expect(await detailOf(deposits.get(DEPOSIT_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-13', + }) + } + }) + + it('treats a non-integer status as a failure rather than a success', async () => { + for (const status of [Number.NaN, 200.5, Number.POSITIVE_INFINITY]) { + const { deposits } = clientFor({ + status: status as number, + bodyBytes: envelope(COMPLETE_DEPOSIT), + }) + + const detail = await detailOf(deposits.get(DEPOSIT_ID)) + expect(detail.kind).toBe('api') + } + }) + + /** + * `destination` can legitimately be absent even on a `200` — see the `Deposit` + * class note — but when present it must decode. + */ + it('surfaces a destination when the service includes one', async () => { + const { deposits } = okClient( + '{"id":"dep-1","amount":{"amount":"10.00","currency":"USD"},"status":"complete",' + + '"createDate":"2026-01-01T00:00:00Z","destination":{"type":"account","id":"acct-9"}}', + ) + + const deposit = await deposits.get(DEPOSIT_ID) + expect(deposit.destination).toEqual({ kind: 'account', accountId: 'acct-9' }) + expect((deposit.amount as Money).amount).toBe('10.00') + }) +}) + +describe('the failure path', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + for (const status of [400, 401, 404, 409, 500, 503]) { + const { deposits } = clientFor({ + status, + headers: { 'X-Request-Id': `req-${status}` }, + bodyBytes: bytes(`{"status":{"code":${status * 10},"message":"nope"}}`), + }) + + const detail = await detailOf(deposits.get(DEPOSIT_ID)) + expect(detail).toEqual({ + kind: 'api', + httpStatus: status, + daaStatusCode: status * 10, + retryable: status === 429 || status >= 500, + }) + } + }) + + it('marks only 429 and 5xx retryable', async () => { + for (const [status, retryable] of [ + [400, false], + [404, false], + [428, false], + [429, true], + [499, false], + [500, true], + [599, true], + ] as const) { + const { deposits } = clientFor({ status }) + expect(await detailOf(deposits.get(DEPOSIT_ID))).toMatchObject({ kind: 'api', retryable }) + } + }) + + it('reports the api error even when the body carries no readable status code', async () => { + for (const bodyBytes of [ + null, + bytes(''), + bytes('gateway timeout'), + bytes('{}'), + bytes('{"status":{}}'), + ]) { + const { deposits } = clientFor({ status: 502, bodyBytes }) + expect(await detailOf(deposits.get(DEPOSIT_ID))).toEqual({ + kind: 'api', + httpStatus: 502, + retryable: true, + }) + } + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).deposits.get(DEPOSIT_ID), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) diff --git a/src/__test__/depositsPagination.test.ts b/src/__test__/depositsPagination.test.ts new file mode 100644 index 0000000..92ffc89 --- /dev/null +++ b/src/__test__/depositsPagination.test.ts @@ -0,0 +1,242 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +const ORIGIN = 'https://api.circle.com' +const CURSOR_AFTER = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CURSOR_BEFORE = '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const DEPOSIT_SUMMARY = + '{"id":"dep-1","amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function pageBody(deposit = DEPOSIT_SUMMARY): Uint8Array { + return bytes(`{"data":[${deposit}]}`) +} + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: readonly DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) throw new Error('unexpected request') + return response + } +} + +function response(headers: Readonly> = {}): DaaHttpResponse { + return { status: 200, headers, bodyBytes: pageBody() } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('deposits pagination', () => { + it('loads and freezes deposit summaries over the exact public collection path', async () => { + const transport = new SequenceTransport([response()]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).deposits.list() + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/accounts/deposits', + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(page.items[0]?.id).toBe('dep-1') + expect(page.items[0]?.status).toEqual({ kind: 'pending' }) + expect(Object.isFrozen(page)).toBe(true) + expect(Object.isFrozen(page.items)).toBe(true) + expect(Object.isFrozen(page.items[0])).toBe(true) + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + }) + + it('serializes the documented deposit filters in deterministic order', async () => { + const transport = new SequenceTransport([response()]) + const deposits = createDaaUserClient(transport, 'production', NO_SIGNING).deposits + + await deposits.list({ + custodyType: 'omnibus', + accountId: '1000662322', + type: 'wire', + status: ['pending', 'complete'], + from: '2026-08-01T00:00:00Z', + to: '2026-08-18T00:00:00Z', + pageAfter: CURSOR_AFTER, + pageSize: 50, + }) + + expect(transport.sent[0]?.query).toBe( + 'custodyType=omnibus&accountId=1000662322&type=wire&status=pending&status=complete' + + '&from=2026-08-01T00%3A00%3A00Z&to=2026-08-18T00%3A00%3A00Z' + + `&pageAfter=${CURSOR_AFTER}&pageSize=50`, + ) + }) + + /** + * `type` is a server-owned, externally-growing rail catalog (see + * `DepositsClient.ts`'s `DEPOSIT_TYPES` doc) — a rail Circle onboards after + * this SDK last shipped must still be usable as a filter rather than + * rejected locally with `contract_violation`. + */ + it('passes through a deposit rail type outside the locally known catalog', async () => { + const transport = new SequenceTransport([response()]) + const deposits = createDaaUserClient(transport, 'production', NO_SIGNING).deposits + + await deposits.list({ type: 'a_brand_new_rail' as never }) + + expect(transport.sent[0]?.query).toBe('type=a_brand_new_rail') + }) + + it('follows only the same deposit collection and preserves its opaque query', async () => { + const nextQuery = 'z=last&pageAfter=backing%2Fcursor%3D&repeat=1&repeat=2&reserved=%2B%26' + const previousQuery = 'pageBefore=opaque-value&pageSize=2' + const transport = new SequenceTransport([ + response({ + Link: + `<${ORIGIN}/v1/accounts/deposits?${nextQuery}>; rel="next", ` + + `<${ORIGIN}/v1/accounts/deposits?${previousQuery}>; rel="prev"`, + }), + response(), + response(), + ]) + + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).deposits.list() + await page.next() + await page.previous() + + expect(transport.sent[1]?.query).toBe(nextQuery) + expect(transport.sent[2]?.query).toBe(previousQuery) + for (const request of transport.sent) { + expect(request.path).toBe('/v1/accounts/deposits') + expect(request.method).toBe('GET') + expect(request.bodyBytes).toBeNull() + } + }) + + it('refuses the list and retained Page navigation after the user closes', async () => { + const transport = new SequenceTransport([ + response({ + Link: + `<${ORIGIN}/v1/accounts/deposits?pageAfter=${CURSOR_AFTER}>; rel="next", ` + + `<${ORIGIN}/v1/accounts/deposits?pageBefore=${CURSOR_BEFORE}>; rel="prev"`, + }), + ]) + const user = createDaaUserClient(transport, 'production', NO_SIGNING) + const page = await user.deposits.list() + + user.close() + + expect(await detailOf(page.next())).toEqual({ kind: 'contract_violation' }) + expect(await detailOf(page.previous())).toEqual({ kind: 'contract_violation' }) + expect(await detailOf(user.deposits.list())).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + `${ORIGIN}/v1/accounts?pageAfter=${CURSOR_AFTER}`, + `${ORIGIN}/v1/accounts/transfers?pageAfter=${CURSOR_AFTER}`, + `https://evil.example/v1/accounts/deposits?pageAfter=${CURSOR_AFTER}`, + ])('rejects navigation outside the trusted deposit collection: %s', async (target) => { + const transport = new SequenceTransport([response({ Link: `<${target}>; rel="next"` })]) + + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).deposits.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it('uses the configured environment as the pagination trust anchor', async () => { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts/deposits?pageAfter=x>; rel="next"` }), + ]) + + const detail = await detailOf( + createDaaUserClient(transport, 'sandbox', NO_SIGNING).deposits.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + null, + [], + { pageAfter: CURSOR_AFTER, pageBefore: CURSOR_BEFORE }, + { pageAfter: 'not-a-uuid' }, + { pageBefore: 'not-a-uuid' }, + { custodyType: 'unknown' }, + { type: '' }, + { status: ['settling'] }, + { accountId: '' }, + { from: '' }, + { to: '' }, + { pageSize: 0 }, + { pageSize: 1.5 }, + ])('rejects an invalid initial query without sending it: %o', async (query) => { + const transport = new SequenceTransport([]) + const deposits = createDaaUserClient(transport, 'production', NO_SIGNING).deposits + + expect((await detailOf(deposits.list(query as never))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('maps malformed list bodies and undocumented success statuses through shared rules', async () => { + const malformed = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-list' }, bodyBytes: bytes('{"data":{}}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformed, 'production', NO_SIGNING).deposits.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-list' }) + + const malformedItem = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-item' }, bodyBytes: bytes('{"data":[{}]}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformedItem, 'production', NO_SIGNING).deposits.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-item' }) + + const wrongStatus = new SequenceTransport([{ status: 201, headers: {}, bodyBytes: pageBody() }]) + await expect( + detailOf(createDaaUserClient(wrongStatus, 'production', NO_SIGNING).deposits.list()), + ).resolves.toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) diff --git a/src/__test__/deviceAuthorization.test.ts b/src/__test__/deviceAuthorization.test.ts new file mode 100644 index 0000000..a770a73 --- /dev/null +++ b/src/__test__/deviceAuthorization.test.ts @@ -0,0 +1,402 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { authorizeExactRequest, deviceAuthorizationProfile } from '../auth/deviceAuthorization' +import type { + DeviceAuthorizationClock, + DeviceAuthorizationOperation, +} from '../auth/deviceAuthorization' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { serializeBody, serializeEmptyBody } from '../crypto/serialization' +import { sha256 } from '../crypto/sha256' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { InMemorySecureKeyStore } from '../testing' + +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const JTI = '33333333-3333-4333-8333-333333333333' +const NOW = 1_785_990_000 +const EMPTY_BODY_SHA256 = '47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU' + +const PAYLOAD_WITH_IDEMPOTENCY = [ + 'aud', + 'body_sha256', + 'canonical_path', + 'discriminator', + 'exp', + 'iat', + 'idempotency_key', + 'jti', + 'method', + 'schema_version', +] + +const PAYLOAD_WITHOUT_IDEMPOTENCY = PAYLOAD_WITH_IDEMPOTENCY.filter( + (key) => key !== 'idempotency_key', +) + +const clock: DeviceAuthorizationClock = { + nowEpochSeconds: () => NOW, + jti: () => JTI, +} + +const REGISTRY: ReadonlyArray<{ + operation: DeviceAuthorizationOperation + method: 'GET' | 'POST' + canonicalPath: string +}> = [ + { operation: 'create_account', method: 'POST', canonicalPath: '/v1/accounts' }, + { operation: 'transfer', method: 'POST', canonicalPath: '/v1/accounts/transfers' }, + { operation: 'withdrawal', method: 'POST', canonicalPath: '/v1/accounts/withdrawals' }, + { + operation: 'complete_social_login', + method: 'POST', + canonicalPath: '/v1/accounts/auth/sessions', + }, + { operation: 'get_device_context', method: 'GET', canonicalPath: '/v1/accounts/auth/context' }, + { + operation: 'register_device_key', + method: 'POST', + canonicalPath: '/v1/accounts/auth/deviceKeyRegistration', + }, +] + +async function registeredKey(): Promise { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: '00000000-0000-4000-8000-000000000001', + }) + await key.acknowledgeRegistration() + return key +} + +async function compactJws( + authKey: OwnerAuthKey, + args: { + operation?: DeviceAuthorizationOperation + bodyBytes?: Uint8Array + authKeyId?: string + clock?: DeviceAuthorizationClock + } = {}, +): Promise { + const bodyBytes = + args.bodyBytes ?? serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + return authorizeExactRequest( + { + authKey, + authKeyId: args.authKeyId ?? AUTH_KEY_ID, + operation: args.operation ?? 'transfer', + bodyBytes, + }, + args.clock ?? clock, + ) +} + +function splitCompact(compact: string): { header: string; payload: string; signature: string } { + const parts = compact.split('.') + if ( + parts.length !== 3 || + parts[0] === undefined || + parts[1] === undefined || + parts[2] === undefined + ) { + throw new Error('expected compact JWS') + } + return { header: parts[0], payload: parts[1], signature: parts[2] } +} + +function jsonOf(segment: string): unknown { + return JSON.parse(new TextDecoder().decode(fromBase64Url(segment))) +} + +function claimKeys(claims: unknown): string[] { + if (typeof claims !== 'object' || claims === null) { + throw new Error('expected claims object') + } + return Object.keys(claims).sort() +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('authorizeExactRequest', () => { + it('binds body_sha256 to the exact serialized bytes that will be sent', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + const compact = await compactJws(authKey, { bodyBytes }) + const claims = jsonOf(splitCompact(compact).payload) + + expect(claims).toEqual({ + body_sha256: toBase64Url(sha256(bodyBytes)), + idempotency_key: IDEMPOTENCY_KEY, + canonical_path: '/v1/accounts/transfers', + method: 'POST', + aud: 'circle-digital-asset-accounts', + discriminator: 'transfer', + schema_version: 1, + jti: JTI, + iat: NOW, + exp: NOW + 300, + }) + expect(claimKeys(claims)).toEqual(PAYLOAD_WITH_IDEMPOTENCY) + }) + + it('uses the published JWS header profile and the DeviceContext authKeyId as kid', async () => { + const compact = await compactJws(await registeredKey()) + expect(jsonOf(splitCompact(compact).header)).toEqual({ + alg: 'ES256', + kid: AUTH_KEY_ID, + typ: 'aw-device-authorization+jws', + }) + }) + + it('hashes the empty byte array and omits idempotency_key for a bodyless request', async () => { + const compact = await compactJws(await registeredKey(), { + operation: 'get_device_context', + bodyBytes: serializeEmptyBody(), + }) + const claims = jsonOf(splitCompact(compact).payload) + expect(claims).toEqual({ + body_sha256: EMPTY_BODY_SHA256, + canonical_path: '/v1/accounts/auth/context', + method: 'GET', + aud: 'circle-digital-asset-accounts', + discriminator: 'get_device_context', + schema_version: 1, + jti: JTI, + iat: NOW, + exp: NOW + 300, + }) + expect(claimKeys(claims)).toEqual(PAYLOAD_WITHOUT_IDEMPOTENCY) + }) + + it('omits idempotency_key when the JSON body has none', async () => { + const compact = await compactJws(await registeredKey(), { + bodyBytes: serializeBody({ amount: '1.00' }), + }) + const claims = jsonOf(splitCompact(compact).payload) + expect(claims).not.toHaveProperty('idempotency_key') + expect(claimKeys(claims)).toEqual(PAYLOAD_WITHOUT_IDEMPOTENCY) + }) + + it('does not read idempotencyKey from Object.prototype', async () => { + const previous = Object.getOwnPropertyDescriptor(Object.prototype, 'idempotencyKey') + Object.defineProperty(Object.prototype, 'idempotencyKey', { + configurable: true, + value: IDEMPOTENCY_KEY, + }) + + try { + const compact = await compactJws(await registeredKey(), { + bodyBytes: serializeBody({ amount: '1.00' }), + }) + const claims = jsonOf(splitCompact(compact).payload) + expect(claims).not.toHaveProperty('idempotency_key') + } finally { + if (previous === undefined) { + Reflect.deleteProperty(Object.prototype, 'idempotencyKey') + } else { + Object.defineProperty(Object.prototype, 'idempotencyKey', previous) + } + } + }) + + it('pins schema_version as the JSON integer 1, not the string v1', async () => { + const claims = jsonOf(splitCompact(await compactJws(await registeredKey())).payload) + expect(claims).toMatchObject({ schema_version: 1 }) + if (typeof claims !== 'object' || claims === null || !('schema_version' in claims)) { + throw new Error('expected schema_version') + } + expect(typeof claims.schema_version).toBe('number') + }) + + it('produces a different digest when JSON whitespace changes', async () => { + const authKey = await registeredKey() + const compactBody = serializeBody({ a: 1 }) + const spacedBody = new TextEncoder().encode('{"a": 1}') + const compactDigest = jsonOf( + splitCompact(await compactJws(authKey, { bodyBytes: compactBody })).payload, + ) + const spacedDigest = jsonOf( + splitCompact(await compactJws(authKey, { bodyBytes: spacedBody })).payload, + ) + expect(compactDigest).toMatchObject({ body_sha256: toBase64Url(sha256(compactBody)) }) + expect(spacedDigest).toMatchObject({ body_sha256: toBase64Url(sha256(spacedBody)) }) + expect(toBase64Url(sha256(compactBody))).not.toBe(toBase64Url(sha256(spacedBody))) + }) + + it('binds each closed registry operation to its method, path, and discriminator', async () => { + const authKey = await registeredKey() + for (const entry of REGISTRY) { + expect(deviceAuthorizationProfile(entry.operation)).toEqual({ + discriminator: entry.operation, + schemaVersion: 1, + method: entry.method, + canonicalPath: entry.canonicalPath, + }) + const bodyBytes = + entry.method === 'GET' + ? serializeEmptyBody() + : serializeBody({ idempotencyKey: IDEMPOTENCY_KEY }) + const claims = jsonOf( + splitCompact(await compactJws(authKey, { operation: entry.operation, bodyBytes })).payload, + ) + expect(claims).toMatchObject({ + discriminator: entry.operation, + schema_version: 1, + method: entry.method, + canonical_path: entry.canonicalPath, + }) + } + }) + + it('keeps exp - iat at the 300s verifier maximum', async () => { + const claims = jsonOf(splitCompact(await compactJws(await registeredKey())).payload) + expect(claims).toMatchObject({ iat: NOW, exp: NOW + 300 }) + }) + + it('verifies as compact ES256 over the exact signing input', async () => { + const authKey = await registeredKey() + const compact = await compactJws(authKey) + const { header, payload, signature } = splitCompact(compact) + const signingInput = new TextEncoder().encode(`${header}.${payload}`) + const sig = fromBase64Url(signature) + expect(sig.length).toBe(64) + + const spki = fromBase64Url(await authKey.publicKeySpkiBase64Url()) + const verifyKey = await globalThis.crypto.subtle.importKey( + 'spki', + toArrayBuffer(spki), + { name: 'ECDSA', namedCurve: 'P-256' }, + false, + ['verify'], + ) + const ok = await globalThis.crypto.subtle.verify( + { name: 'ECDSA', hash: 'SHA-256' }, + verifyKey, + toArrayBuffer(sig), + toArrayBuffer(signingInput), + ) + expect(ok).toBe(true) + }) + + it('rejects an unregistered AuthKey for post-activation operations', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: '00000000-0000-4000-8000-000000000001', + }) + expect(await detailOf(compactJws(key))).toEqual({ kind: 'contract_violation' }) + }) + + it('allows register_device_key while the AuthKey is still created', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: '00000000-0000-4000-8000-000000000001', + }) + const compact = await compactJws(key, { + operation: 'register_device_key', + bodyBytes: serializeBody({ + idempotencyKey: IDEMPOTENCY_KEY, + registrationHandle: 'h'.repeat(32), + authKeyPublicKey: 'I'.repeat(122), + }), + }) + expect(jsonOf(splitCompact(compact).header)).toMatchObject({ + typ: 'aw-device-authorization+jws', + kid: AUTH_KEY_ID, + }) + expect(jsonOf(splitCompact(compact).payload)).toMatchObject({ + discriminator: 'register_device_key', + }) + }) + + it('signs post-activation operations through signExactBytes, never signRegistrationDeviceAuthorization', async () => { + let exactBytesCalls = 0 + let registrationCalls = 0 + const real = await registeredKey() + const authKey: OwnerAuthKey = { + publicKeySpkiBase64Url: () => real.publicKeySpkiBase64Url(), + thumbprint: () => real.thumbprint(), + resolution: () => real.resolution(), + acknowledgeRegistration: () => real.acknowledgeRegistration(), + signExactBytes: async (message) => { + exactBytesCalls += 1 + return real.signExactBytes(message) + }, + signRegistrationDeviceAuthorization: async (message) => { + registrationCalls += 1 + return real.signExactBytes(message) + }, + } + await compactJws(authKey) + + expect(exactBytesCalls).toBe(1) + expect(registrationCalls).toBe(0) + }) + + it('rejects a non-UUID authKeyId', async () => { + expect(await detailOf(compactJws(await registeredKey(), { authKeyId: 'not-a-uuid' }))).toEqual({ + kind: 'contract_violation', + }) + }) + + it('rejects a body whose idempotencyKey is not a UUID', async () => { + expect( + await detailOf( + compactJws(await registeredKey(), { bodyBytes: serializeBody({ idempotencyKey: 'k' }) }), + ), + ).toEqual({ kind: 'contract_violation' }) + }) + + it('does not put a compact JWS in error messages', async () => { + const authKey: OwnerAuthKey = { + publicKeySpkiBase64Url: async () => 'x', + thumbprint: async () => 'x', + resolution: () => 'existing', + acknowledgeRegistration: async () => undefined, + signExactBytes: async () => new Uint8Array(63), + signRegistrationDeviceAuthorization: async () => { + throw new Error('not exercised by post-activation deviceAuthorization tests') + }, + } + try { + await compactJws(authKey) + throw new Error('expected failure') + } catch (err) { + expect(isDaaError(err)).toBe(true) + if (!isDaaError(err)) return + expect(err.message).not.toMatch(/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/) + expect(err.message).not.toMatch(/eyJ/) + } + }) +}) diff --git a/src/__test__/deviceContextPayload.test.ts b/src/__test__/deviceContextPayload.test.ts new file mode 100644 index 0000000..6e909cb --- /dev/null +++ b/src/__test__/deviceContextPayload.test.ts @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { toDeviceContext } from '../wire/deviceContextPayload' +import { MalformedPayloadError } from '../wire/payload' + +const UUID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const OTHER_UUID = '11111111-1111-4111-8111-111111111111' +const RESOLVED_AT = '2026-08-26T12:00:00Z' + +/** + * The epoch-millisecond form the service sends some timestamps in, and the + * exact instant it has to normalise to. Mirrors `loginPayload.test.ts`'s + * constant: `DeviceContext` is one of the three login-flow responses that use + * that form, per `wire/instant.ts`. + */ +const EPOCH_MILLIS = 1788290024580 +const EPOCH_MILLIS_ISO = '2026-09-01T19:13:44.580Z' + +const BAD_EPOCHS = [ + 1788290024580.5, // fractional + -1788290024580, // negative + 0, // the epoch itself is a dropped field, not a timestamp + Number.NaN, + Number.POSITIVE_INFINITY, +] + +const BAD_DATE_TEXT = ['1788290024580', '2026-08-26 12:00:00Z', '2026-08-26', '', 'not-a-date'] + +const COMPLETE = Object.freeze({ + deviceCredentialStatus: 'active', + ownerBindingId: UUID, + authKeyId: OTHER_UUID, + resolvedAt: RESOLVED_AT, +}) + +function decode(overrides: Record = {}) { + return toDeviceContext({ ...COMPLETE, ...overrides }) +} + +describe('toDeviceContext', () => { + it('decodes the exact GET /v1/accounts/auth/context shape', () => { + expect(decode()).toEqual({ + deviceCredentialStatus: 'active', + ownerBindingId: UUID, + authKeyId: OTHER_UUID, + resolvedAt: RESOLVED_AT, + }) + }) + + it('ignores an extra response field rather than failing the response', () => { + expect(decode({ clientEntityId: UUID })).toEqual({ + deviceCredentialStatus: 'active', + ownerBindingId: UUID, + authKeyId: OTHER_UUID, + resolvedAt: RESOLVED_AT, + }) + }) + + it('rejects a deviceCredentialStatus other than the one defined value', () => { + for (const bad of ['inactive', 'ACTIVE', '', null, 1]) { + expect(() => decode({ deviceCredentialStatus: bad })).toThrow(MalformedPayloadError) + } + }) + + it('rejects a non-UUID ownerBindingId or authKeyId', () => { + for (const bad of ['', 'not-a-uuid', OTHER_UUID + 'x']) { + expect(() => decode({ ownerBindingId: bad })).toThrow(MalformedPayloadError) + expect(() => decode({ authKeyId: bad })).toThrow(MalformedPayloadError) + } + }) + + it('accepts a UUID in either case', () => { + expect(decode({ authKeyId: OTHER_UUID.toUpperCase() }).authKeyId).toBe(OTHER_UUID.toUpperCase()) + }) + + it('takes either wire form for resolvedAt and hands on one normalised instant', () => { + // Pinned to the instant, not to an ISO *shape*: a seconds-vs-milliseconds + // misreading, or an off-by-one, still produces a well-formed timestamp. + expect(decode({ resolvedAt: EPOCH_MILLIS }).resolvedAt).toBe(EPOCH_MILLIS_ISO) + expect(decode({ resolvedAt: 1 }).resolvedAt).toBe('1970-01-01T00:00:00.001Z') + // The string form is passed through untouched. + expect(decode({ resolvedAt: RESOLVED_AT }).resolvedAt).toBe(RESOLVED_AT) + }) + + it('rejects a resolvedAt that is neither wire form', () => { + for (const resolvedAt of [...BAD_EPOCHS, ...BAD_DATE_TEXT]) { + expect(() => decode({ resolvedAt })).toThrow(MalformedPayloadError) + } + }) + + it('rejects a value that is not an object', () => { + for (const bad of [null, undefined, 'text', 1, [], true]) { + expect(() => toDeviceContext(bad)).toThrow(MalformedPayloadError) + } + }) + + it('rejects a payload missing a guaranteed field', () => { + for (const key of ['deviceCredentialStatus', 'ownerBindingId', 'authKeyId', 'resolvedAt']) { + const rest: Record = { ...COMPLETE } + delete rest[key] + expect(() => toDeviceContext(rest)).toThrow(MalformedPayloadError) + } + }) +}) diff --git a/src/__test__/deviceRegistrationResultPayload.test.ts b/src/__test__/deviceRegistrationResultPayload.test.ts new file mode 100644 index 0000000..3110aef --- /dev/null +++ b/src/__test__/deviceRegistrationResultPayload.test.ts @@ -0,0 +1,73 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { toDeviceRegistrationResult } from '../wire/deviceRegistrationResultPayload' +import { MalformedPayloadError } from '../wire/payload' + +const CLIENT_ENTITY_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const OWNER_BINDING_ID = '11111111-2222-4333-8444-555555555555' +const AUTH_KEY_ID = '99999999-8888-4777-8666-555555555555' +const RESOLVED_AT = '2026-08-26T12:00:00Z' + +function flatPayload(extra: Record): Record { + return { + deviceCredentialStatus: 'active', + ownerBindingId: OWNER_BINDING_ID, + authKeyId: AUTH_KEY_ID, + resolvedAt: RESOLVED_AT, + ...extra, + } +} + +describe('toDeviceRegistrationResult — RECOVERY_PENDING-signal rejection on the flat shape', () => { + it('names the offending recoveryReference field, not status', () => { + const payload = flatPayload({ recoveryReference: 'r'.repeat(16) }) + + let thrown: unknown + try { + toDeviceRegistrationResult(payload, CLIENT_ENTITY_ID) + } catch (err) { + thrown = err + } + + expect(thrown).toBeInstanceOf(MalformedPayloadError) + // `status` is absent on this payload, not malformed — the field that + // actually made the payload ambiguous is `recoveryReference`. + expect((thrown as MalformedPayloadError).fieldName).toBe('recoveryReference') + }) + + it('names the offending expiresAt field, not status', () => { + const payload = flatPayload({ expiresAt: RESOLVED_AT }) + + let thrown: unknown + try { + toDeviceRegistrationResult(payload, CLIENT_ENTITY_ID) + } catch (err) { + thrown = err + } + + expect(thrown).toBeInstanceOf(MalformedPayloadError) + expect((thrown as MalformedPayloadError).fieldName).toBe('expiresAt') + }) + + it('still decodes the flat shape when neither RECOVERY_PENDING field is present', () => { + const payload = flatPayload({}) + const result = toDeviceRegistrationResult(payload, CLIENT_ENTITY_ID) + expect(result.status).toBe('ACTIVE') + }) +}) diff --git a/src/__test__/errors.test.ts b/src/__test__/errors.test.ts new file mode 100644 index 0000000..1c14fcb --- /dev/null +++ b/src/__test__/errors.test.ts @@ -0,0 +1,152 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + contractViolation, + idempotencyConflict, + isDaaError, + loginRequestExpired, + mapNativeError, + prepareReceiptInvalid, + withRequestId, +} from '../errors' + +describe('the login-attempt errors', () => { + it('models an expired login request without inventing a retry hint', () => { + const err = loginRequestExpired(null) + expect(err.detail).toEqual({ kind: 'login_request_expired' }) + // The recovery is a new prepare, not a retry, so there is no `retryable` flag + // for a caller to misread. + expect(err.detail).not.toHaveProperty('retryable') + }) + + it('models an invalid Prepare receipt as its own kind, keeping the cause off the detail', () => { + const cause = new Error('native detail') + const err = prepareReceiptInvalid('the Prepare receipt has expired', cause) + expect(err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + // The recovery is a new prepare, not a retry of this one. + expect(err.detail).not.toHaveProperty('retryable') + expect(err.message).toBe('DAA: the Prepare receipt has expired') + expect(err.cause).toBe(cause) + }) + + it('can attach a correlation id to a contract violation without interpolating a JWS', () => { + const err = contractViolation('the device authorization was replayed', 'req-1') + expect(err.detail).toEqual({ kind: 'contract_violation', correlationId: 'req-1' }) + expect(err.message).toMatch(/requestId=req-1/) + expect(err.message).not.toMatch(/eyJ/) + }) + + it('carries the conflicting idempotency key on the detail but not in the message', () => { + const err = idempotencyConflict('22222222-2222-4222-a222-222222222222', null) + expect(err.detail).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: '22222222-2222-4222-a222-222222222222', + }) + expect(err.message).not.toMatch(/22222222/) + }) +}) + +describe('a request id with control characters', () => { + // The id comes from a response header and reaches `message`, which an app + // logs; CR/LF there could forge a log line. + const HOSTILE = 'abc\r\ndef\u0007' + + it.each([ + ['loginRequestExpired', () => loginRequestExpired(HOSTILE)], + [ + 'idempotencyConflict', + () => idempotencyConflict('22222222-2222-4222-a222-222222222222', HOSTILE), + ], + [ + 'withRequestId', + () => withRequestId(prepareReceiptInvalid('the Prepare receipt has expired'), HOSTILE), + ], + ])('%s keeps only printable ASCII in the message', (_name, build) => { + const err = build() + expect(err.message.endsWith(' (requestId=abcdef)')).toBe(true) + expect(err.message).not.toMatch(/[^\x20-\x7e]/) + }) + + it('keeps the exact id on the idempotency_conflict detail', () => { + const err = idempotencyConflict('22222222-2222-4222-a222-222222222222', HOSTILE) + expect(err.detail).toHaveProperty('correlationId', HOSTILE) + }) +}) + +describe('withRequestId', () => { + it('names the id in the message and keeps the kind, the cause and the stack', () => { + const cause = new Error('verifier detail') + const original = prepareReceiptInvalid('the Prepare receipt has expired', cause) + const err = withRequestId(original, 'req-1') + expect(err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + expect(err.message).toBe('DAA: the Prepare receipt has expired (requestId=req-1)') + expect(err.cause).toBe(cause) + // The frames are the original throw site's, not this wrapper's. + const frames = (stack: string | undefined) => (stack ?? '').split('\n').slice(1) + expect(frames(err.stack)).toEqual(frames(original.stack)) + expect(err.stack?.split('\n')[0]).toContain('(requestId=req-1)') + }) + + it('puts a request id holding replace patterns into the stack literally', () => { + const original = prepareReceiptInvalid('the Prepare receipt has expired') + const err = withRequestId(original, "a$'b$&c$$d") + expect(err.message).toBe("DAA: the Prepare receipt has expired (requestId=a$'b$&c$$d)") + expect(err.stack?.split('\n')[0]).toBe(`DaaError: ${err.message}`) + }) +}) + +describe('mapNativeError', () => { + it('maps the two custody codes to their kinds and keeps native text out of message', () => { + const auth = mapNativeError( + Object.assign(new Error('SecItemCopyMatching OSStatus -25293'), { + code: 'USER_AUTH_REQUIRED', + }), + ) + expect(auth.detail.kind).toBe('local_user_authentication_required') + expect(auth.message).not.toMatch(/OSStatus/) + + const init = mapNativeError( + Object.assign(new Error('keystore uninitialized'), { code: 'NOT_INITIALIZED' }), + ) + expect(init.detail.kind).toBe('device_not_initialized') + + expect(mapNativeError(new Error('anything else')).detail.kind).toBe('contract_violation') + expect(mapNativeError(undefined).detail.kind).toBe('contract_violation') + }) + + it('passes an already-structured DaaError through unchanged', () => { + const original = contractViolation('already mapped') + expect(mapNativeError(original)).toBe(original) + }) + + it('retains the cause but does not export it through serialization', () => { + const native = Object.assign( + new Error('AndroidKeyStore: KM_ERROR_KEY_USER_NOT_AUTHENTICATED'), + { + code: 'X', + nativeStackAndroid: ['at com.example.Keystore.sign'], + }, + ) + const err = mapNativeError(native) + expect(isDaaError(err)).toBe(true) + expect(err.cause).toBe(native) // available to a host that deliberately inspects + // The raw native internals must not reach a serialized/exported form. + expect(JSON.stringify(err)).not.toMatch(/KM_ERROR|nativeStackAndroid/) + }) +}) diff --git a/src/__test__/es256Jws.test.ts b/src/__test__/es256Jws.test.ts new file mode 100644 index 0000000..220d0f0 --- /dev/null +++ b/src/__test__/es256Jws.test.ts @@ -0,0 +1,487 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { + nativeVerifyPrepareReceiptSignature, + requireDaaRegistrationNative, + type DaaRegistrationNativeModule, +} from '../auth/daaRegistrationNative' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { + SUPPORTED_JWS_ALGORITHMS, + verifyCompactEs256, + type PinnedEs256Key, +} from '../crypto/es256Jws' +import { isDaaError } from '../errors' +import { hexToBytes, loadAuthKeyWireFixture, namedHex } from './authKeyWireFixture' +import { + encodeJsonSegment, + generateReceiptSigningKey, + signCompactJws, + type ReceiptSigningKey, +} from './prepareReceiptSigning' + +/** + * Compact ES256 JWS verification. + * + * Signature math is the platform's. In Jest the platform is `jest.setup.js`'s + * WebCrypto stand-in for the `DaaRegistration` module, so the known-answer and + * negative vectors below exercise the stand-in and the TypeScript around it — + * the same arrangement as `crypto/random.ts`. What this file proves about + * TypeScript is the structural rules: allowlisted `alg`, expected `typ`, `kid` + * lookup in a pinned set, no key from the token, 64-byte signatures, and + * payload parsing only after verification. + */ + +const TYP = 'test+jws' +const CLAIMS = { iss: 'https://example.invalid', sub: 'receipt', n: 1 } +const requireNative = requireOptionalNativeModule as jest.Mock +const defaultNativeImpl = requireNative.getMockImplementation() + +afterEach(() => { + requireNative.mockReset() + if (defaultNativeImpl !== undefined) { + requireNative.mockImplementation(defaultNativeImpl) + } +}) + +function pinned(...keys: ReceiptSigningKey[]): PinnedEs256Key[] { + return keys.map((key) => ({ kid: key.kid, publicKeyX963: key.x963 })) +} + +function header( + key: ReceiptSigningKey, + extra: Record = {}, +): Record { + return { alg: 'ES256', typ: TYP, kid: key.kid, ...extra } +} + +async function verify(jws: string, keys: PinnedEs256Key[]) { + return verifyCompactEs256(jws, { keys, expectedTyp: TYP }) +} + +describe('verifyCompactEs256', () => { + it('verifies a real ES256 JWS and returns its header and claims', async () => { + const key = await generateReceiptSigningKey('k1') + const result = await verify(await signCompactJws(key, header(key), CLAIMS), pinned(key)) + expect(result.verified).toBe(true) + if (!result.verified) { + throw new Error('unreachable') + } + expect(result.protectedHeader).toMatchObject({ alg: 'ES256', kid: 'k1', typ: TYP }) + expect(result.payload).toEqual(CLAIMS) + }) + + it('selects the pinned key by kid, so a rotation overlap verifies under either', async () => { + const [retiring, current] = await Promise.all([ + generateReceiptSigningKey('retiring'), + generateReceiptSigningKey('current'), + ]) + for (const key of [retiring, current]) { + const jws = await signCompactJws(key, header(key), CLAIMS) + expect((await verify(jws, pinned(retiring, current))).verified).toBe(true) + } + }) + + it('rejects a kid that names a different pinned key', async () => { + const [signer, other] = await Promise.all([ + generateReceiptSigningKey('signer'), + generateReceiptSigningKey('other'), + ]) + const jws = await signCompactJws(signer, header(signer, { kid: 'other' }), CLAIMS) + expect(await verify(jws, pinned(signer, other))).toEqual({ + verified: false, + reason: 'signature_mismatch', + }) + }) + + it('rejects an unknown or missing kid without trying any key', async () => { + const key = await generateReceiptSigningKey('k1') + expect( + await verify(await signCompactJws(key, header(key, { kid: 'k2' }), CLAIMS), pinned(key)), + ).toEqual({ + verified: false, + reason: 'unknown_key_id', + }) + for (const kid of [undefined, '', 7, null]) { + const jws = await signCompactJws( + key, + { alg: 'ES256', typ: TYP, ...(kid === undefined ? {} : { kid }) }, + CLAIMS, + ) + expect(await verify(jws, pinned(key))).toEqual({ verified: false, reason: 'missing_key_id' }) + } + }) + + it('rejects a signature from a key that is not pinned under that kid', async () => { + const [signer, pinnedKey] = await Promise.all([ + generateReceiptSigningKey('k1'), + generateReceiptSigningKey('k1'), + ]) + const jws = await signCompactJws(signer, header(signer), CLAIMS) + expect(await verify(jws, pinned(pinnedKey))).toEqual({ + verified: false, + reason: 'signature_mismatch', + }) + }) + + it('rejects a tampered payload or header while the signature is left alone', async () => { + const key = await generateReceiptSigningKey('k1') + const jws = await signCompactJws(key, header(key), CLAIMS) + const [encodedHeader, encodedPayload, signature] = jws.split('.') as [string, string, string] + const swappedPayload = `${encodedHeader}.${encodeJsonSegment({ ...CLAIMS, sub: 'x' })}.${signature}` + const swappedHeader = `${encodeJsonSegment(header(key, { extra: 1 }))}.${encodedPayload}.${signature}` + for (const tampered of [swappedPayload, swappedHeader]) { + expect(await verify(tampered, pinned(key))).toEqual({ + verified: false, + reason: 'signature_mismatch', + }) + } + }) + + it('rejects every single-bit flip of a valid signature', async () => { + const key = await generateReceiptSigningKey('k1') + const jws = await signCompactJws(key, header(key), CLAIMS) + const [h, p, s] = jws.split('.') as [string, string, string] + const signature = fromBase64Url(s) + for (let bit = 0; bit < 512; bit += 37) { + const flipped = Uint8Array.from(signature) + flipped[bit >> 3]! ^= 1 << (bit & 7) + expect((await verify(`${h}.${p}.${toBase64Url(flipped)}`, pinned(key))).verified).toBe(false) + } + }) +}) + +describe('verifyCompactEs256 header rules', () => { + it('allows exactly one algorithm', () => { + expect(SUPPORTED_JWS_ALGORITHMS).toEqual(['ES256']) + expect(Object.isFrozen(SUPPORTED_JWS_ALGORITHMS)).toBe(true) + }) + + it('rejects every other alg, including on a genuinely ES256-signed token', async () => { + const key = await generateReceiptSigningKey('k1') + for (const alg of [ + 'none', + 'ES256K', + 'HS256', + 'RS256', + 'ES384', + 'es256', + '', + 256, + null, + ['ES256'], + ]) { + const jws = await signCompactJws(key, header(key, { alg }), CLAIMS) + expect(await verify(jws, pinned(key))).toEqual({ + verified: false, + reason: 'unsupported_algorithm', + }) + } + const noAlg = await signCompactJws(key, { typ: TYP, kid: key.kid }, CLAIMS) + expect(await verify(noAlg, pinned(key))).toEqual({ + verified: false, + reason: 'unsupported_algorithm', + }) + }) + + it('rejects a typ other than the expected one, or none', async () => { + const key = await generateReceiptSigningKey('k1') + for (const typ of ['JWT', 'daa-device-authorization+jws', '', undefined]) { + const jws = await signCompactJws( + key, + typ === undefined ? { alg: 'ES256', kid: key.kid } : header(key, { typ }), + CLAIMS, + ) + expect(await verify(jws, pinned(key))).toEqual({ verified: false, reason: 'unexpected_type' }) + } + }) + + it('rejects a header that carries or locates a key, even when it verifies', async () => { + const key = await generateReceiptSigningKey('k1') + for (const extra of [ + { jwk: { kty: 'EC', crv: 'P-256', x: key.jwk.x, y: key.jwk.y } }, + { jku: 'https://attacker.invalid/jwks.json' }, + { x5u: 'https://attacker.invalid/chain.pem' }, + { x5c: ['MIIB'] }, + ]) { + const jws = await signCompactJws(key, header(key, extra), CLAIMS) + expect(await verify(jws, pinned(key))).toEqual({ + verified: false, + reason: 'header_sources_a_key', + }) + } + }) + + it('rejects any crit', async () => { + const key = await generateReceiptSigningKey('k1') + const jws = await signCompactJws(key, header(key, { crit: ['exp'], exp: 1 }), CLAIMS) + expect(await verify(jws, pinned(key))).toEqual({ + verified: false, + reason: 'unsupported_critical_header', + }) + }) + + it('does not read inherited members as header members', async () => { + const key = await generateReceiptSigningKey('k1') + const polluted = Object.prototype as Record + polluted['alg'] = 'ES256' + try { + const jws = await signCompactJws(key, { typ: TYP, kid: key.kid }, CLAIMS) + expect(await verify(jws, pinned(key))).toEqual({ + verified: false, + reason: 'unsupported_algorithm', + }) + } finally { + delete polluted['alg'] + } + }) +}) + +describe('verifyCompactEs256 malformed input', () => { + let key: ReceiptSigningKey + let jws: string + + beforeAll(async () => { + key = await generateReceiptSigningKey('k1') + jws = await signCompactJws(key, header(key), CLAIMS) + }) + + it('rejects anything that is not three non-empty segments', async () => { + const [h, p, s] = jws.split('.') as [string, string, string] + for (const value of [ + '', + h, + `${h}.${p}`, + `${jws}.extra`, + `.${p}.${s}`, + `${h}..${s}`, + `${h}.${p}.`, + ]) { + expect(await verify(value, pinned(key))).toEqual({ + verified: false, + reason: 'malformed_compact_serialization', + }) + } + }) + + it('rejects a header that is not Base64URL JSON of an object', async () => { + const [, p, s] = jws.split('.') as [string, string, string] + for (const encoded of [ + '****', + toBase64Url(new TextEncoder().encode('not json')), + encodeJsonSegment(['ES256']), + encodeJsonSegment(null), + ]) { + expect(await verify(`${encoded}.${p}.${s}`, pinned(key))).toEqual({ + verified: false, + reason: 'malformed_protected_header', + }) + } + }) + + it('rejects a signature that is not exactly 64 decoded bytes before calling the platform', async () => { + const [h, p] = jws.split('.') as [string, string] + const native = requireDaaRegistrationNative() + const spy = jest.spyOn(native, 'verifyPrepareReceiptSignature') + try { + for (const signature of [ + '****', + toBase64Url(new Uint8Array(63)), + toBase64Url(new Uint8Array(65)), + toBase64Url(new Uint8Array(72)), + ]) { + expect(await verify(`${h}.${p}.${signature}`, pinned(key))).toEqual({ + verified: false, + reason: 'malformed_signature', + }) + } + expect(spy).not.toHaveBeenCalled() + } finally { + spy.mockRestore() + } + }) + + it('parses the payload only after the signature verifies', async () => { + const [h, , s] = jws.split('.') as [string, string, string] + const garbage = toBase64Url(new TextEncoder().encode('{not json')) + expect(await verify(`${h}.${garbage}.${s}`, pinned(key))).toEqual({ + verified: false, + reason: 'signature_mismatch', + }) + for (const payload of [['a'], 'text', 42, null]) { + const signed = await signCompactJws(key, header(key), payload) + expect(await verify(signed, pinned(key))).toEqual({ + verified: false, + reason: 'malformed_payload', + }) + } + }) + + it('refuses a malformed pinned key set as a configuration error', async () => { + const bad: PinnedEs256Key[][] = [ + [], + [{ kid: '', publicKeyX963: key.x963 }], + [ + { kid: 'k1', publicKeyX963: key.x963 }, + { kid: 'k1', publicKeyX963: key.x963 }, + ], + [{ kid: 'k1', publicKeyX963: key.x963.subarray(0, 33) }], + ] + for (const keys of bad) { + await expect(verify(jws, keys)).rejects.toMatchObject({ + detail: { kind: 'contract_violation' }, + }) + } + }) +}) + +describe('platform signature verification', () => { + const fixture = loadAuthKeyWireFixture() + const native = (): DaaRegistrationNativeModule => requireDaaRegistrationNative() + + async function platformVerify( + publicKeyX963: Uint8Array, + message: Uint8Array, + signature: Uint8Array, + ) { + return nativeVerifyPrepareReceiptSignature(native(), { + publicKeyX963, + signingInput: message, + signature, + }) + } + + /** RFC 6979 §A.2.5 key U, uncompressed. */ + const RFC6979_KEY = hexToBytes( + '0460fed4ba255a9d31c961eb74c6356d68c049b8923b61fa6ce669622e60f29fb6' + + '7903fe1008b8bc99a41ae9e95628bc64f2f1b20c2d7e9f5177a3c294d4462299', + ) + const RFC6979_VECTORS = [ + { + message: 'sample', + rs: + 'efd48b2aacb6a8fd1140dd9cd45e81d69d2c877b56aaf991c34d0ea84eaf3716' + + 'f7cb1c942d657c41d436c7a1b6e29f65f3e900dbb9aff4064dc4ab2f843acda8', + }, + { + message: 'test', + rs: + 'f1abb023518351cd71d881567b1ea663ed3efcf6c5132b354f28d3b0b7d38367' + + '019f4113742a2b14bd25926b49c649155f267e60d3814b4c0cc84250e46f0083', + }, + ] + + it('accepts the RFC 6979 P-256/SHA-256 vectors and rejects them crossed', async () => { + const utf8 = (text: string) => new TextEncoder().encode(text) + for (const vector of RFC6979_VECTORS) { + expect(await platformVerify(RFC6979_KEY, utf8(vector.message), hexToBytes(vector.rs))).toBe( + true, + ) + } + expect( + await platformVerify(RFC6979_KEY, utf8('sample'), hexToBytes(RFC6979_VECTORS[1]!.rs)), + ).toBe(false) + }) + + it('accepts the canonical wire fixture signature and rejects its tampered forms', async () => { + const key = hexToBytes(fixture.signedMessage.publicKeyX963Hex) + const message = hexToBytes(fixture.signedMessage.messageHex) + const signature = hexToBytes(fixture.signedMessage.rawHex) + expect(await platformVerify(key, message, signature)).toBe(true) + + const tampered = Uint8Array.from(message) + tampered[0]! ^= 1 + expect(await platformVerify(key, tampered, signature)).toBe(false) + expect( + await platformVerify(hexToBytes(fixture.p256PublicKey.x963Hex), message, signature), + ).toBe(false) + }) + + it('rejects every scalar-boundary signature the fixture publishes', async () => { + const key = hexToBytes(fixture.signedMessage.publicKeyX963Hex) + const message = hexToBytes(fixture.signedMessage.messageHex) + expect(fixture.rejected.ecdsaRaw.length).toBeGreaterThan(0) + for (const vector of fixture.rejected.ecdsaRaw) { + expect(await platformVerify(key, message, hexToBytes(vector.hex))).toBe(false) + } + }) + + it('rejects a 63- or 65-byte signature', async () => { + const key = hexToBytes(fixture.signedMessage.publicKeyX963Hex) + const message = hexToBytes(fixture.signedMessage.messageHex) + const signature = hexToBytes(fixture.signedMessage.rawHex) + expect(await platformVerify(key, message, signature.subarray(0, 63))).toBe(false) + const long = new Uint8Array(65) + long.set(signature) + expect(await platformVerify(key, message, long)).toBe(false) + }) + + it('fails closed on an off-curve or malformed key', async () => { + const message = hexToBytes(fixture.signedMessage.messageHex) + const signature = hexToBytes(fixture.signedMessage.rawHex) + for (const name of ['off-curve', 'invalid-marker', 'compressed']) { + const point = namedHex(fixture.rejected.x963PublicKeys, name) + await expect(platformVerify(point, message, signature)).rejects.toMatchObject({ + detail: { kind: 'contract_violation' }, + }) + } + }) + + it('counts only a literal true as verified', async () => { + for (const value of ['true', 1, {}, null, undefined]) { + const fake = { + ...native(), + verifyPrepareReceiptSignature: jest.fn(async () => value as unknown as boolean), + } + expect( + await nativeVerifyPrepareReceiptSignature(fake, { + publicKeyX963: RFC6979_KEY, + signingInput: new Uint8Array(1), + signature: new Uint8Array(64), + }), + ).toBe(false) + } + }) + + it('fails closed on a host whose native module predates the verify function', async () => { + const withoutVerify: Partial = { ...native() } + delete withoutVerify.verifyPrepareReceiptSignature + requireNative.mockImplementation(() => withoutVerify) + const key = await generateReceiptSigningKey('k1') + const jws = await signCompactJws(key, header(key), CLAIMS) + await expect(verify(jws, pinned(key))).rejects.toThrow( + /verifyPrepareReceiptSignature is required/, + ) + }) + + it('fails closed on a React Native host with no DaaRegistration module', async () => { + const key = await generateReceiptSigningKey('k1') + const jws = await signCompactJws(key, header(key), CLAIMS) + requireNative.mockImplementation(() => null) + try { + await verify(jws, pinned(key)) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/DaaRegistration module is not available/) + return + } + throw new Error('expected verification to fail closed without the native module') + }) +}) diff --git a/src/__test__/fixtures/AuthKeyWireV1.json b/src/__test__/fixtures/AuthKeyWireV1.json new file mode 100644 index 0000000..2aaf138 --- /dev/null +++ b/src/__test__/fixtures/AuthKeyWireV1.json @@ -0,0 +1,107 @@ +{ + "profile": "daa-authkey-wire-v1", + "contract": "docs/authkey-wire-contract.md", + "p256PublicKey": { + "x963Hex": "046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5", + "spkiBase64Url": "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEaxfR8uEsQkf4vOblY6RA8ncDfYEt6zOg9KE5RdiYwpZP40Li_hp_m47n60p8D54WK84zV2sxXs7LtkBoN79R9Q", + "jwkThumbprint": "xx0BcA-wMohw8atYDJOe6peGModklG2wRHBlXHMvl0M" + }, + "signedMessage": { + "name": "openssl-p256-sha256", + "messageHex": "44414120417574684b657920776972652076310a", + "publicKeyX963Hex": "04125d0d94cac0b7a78ecb8d35fc2b87620e43a45bdc207fc2ed4f606d48525b60a63cc04bcc5decd5c9607e66a521bdb585057f90e8bc0306137b81af1f02fbea", + "derHex": "30460221009ec14e469a98645531586220060989e6972c10b6670095e52a805d642cd925eb022100ed20b2ce70a9142be0e5971acc0c1d4d677a46e1d6601206777049b043649989", + "rawHex": "9ec14e469a98645531586220060989e6972c10b6670095e52a805d642cd925ebed20b2ce70a9142be0e5971acc0c1d4d677a46e1d6601206777049b043649989" + }, + "ecdsaSignatures": [ + { + "name": "r-high-bit-s-short", + "derHex": "30440221008000000000000000000000000000000000000000000000000000000000000000021f01000000000000000000000000000000000000000000000000000000000000", + "rawHex": "80000000000000000000000000000000000000000000000000000000000000000001000000000000000000000000000000000000000000000000000000000000" + }, + { + "name": "r-short-s-high-bit", + "derHex": "3044021f010000000000000000000000000000000000000000000000000000000000000221008000000000000000000000000000000000000000000000000000000000000000", + "rawHex": "00010000000000000000000000000000000000000000000000000000000000008000000000000000000000000000000000000000000000000000000000000000" + }, + { + "name": "r-group-order-minus-one", + "derHex": "3026022100ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632550020101", + "rawHex": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc6325500000000000000000000000000000000000000000000000000000000000000001" + } + ], + "rejected": { + "ecdsaDer": [ + { + "name": "empty-sequence", + "hex": "3000" + }, + { + "name": "zero-r", + "hex": "3006020100020101" + }, + { + "name": "r-equals-group-order", + "hex": "3026022100ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551020101" + } + ], + "ecdsaRaw": [ + { + "name": "zero-r", + "hex": "00000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000001" + }, + { + "name": "zero-s", + "hex": "00000000000000000000000000000000000000000000000000000000000000010000000000000000000000000000000000000000000000000000000000000000" + }, + { + "name": "r-equals-group-order", + "hex": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc6325510000000000000000000000000000000000000000000000000000000000000001" + }, + { + "name": "s-equals-group-order", + "hex": "0000000000000000000000000000000000000000000000000000000000000001ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551" + }, + { + "name": "r-greater-than-group-order", + "hex": "ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff0000000000000000000000000000000000000000000000000000000000000001" + }, + { + "name": "s-greater-than-group-order", + "hex": "0000000000000000000000000000000000000000000000000000000000000001ffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff" + } + ], + "x963PublicKeys": [ + { + "name": "compressed", + "hex": "026b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296" + }, + { + "name": "invalid-marker", + "hex": "036b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" + }, + { + "name": "off-curve", + "hex": "0400000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000" + } + ], + "subjectPublicKeyInfo": [ + { + "name": "invalid-sequence-tag", + "hex": "3159301306072a8648ce3d020106082a8648ce3d030107034200046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" + }, + { + "name": "truncated", + "hex": "3059301306072a8648ce3d020106082a8648ce3d030107034200046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51" + }, + { + "name": "overlong", + "hex": "3059301306072a8648ce3d020106082a8648ce3d030107034200046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f500" + }, + { + "name": "wrong-curve-oid", + "hex": "3059301306072a8648ce3d020106082a8648ce3d030108034200046b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c2964fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" + } + ] + } +} diff --git a/src/__test__/jwkThumbprint.test.ts b/src/__test__/jwkThumbprint.test.ts new file mode 100644 index 0000000..253b38b --- /dev/null +++ b/src/__test__/jwkThumbprint.test.ts @@ -0,0 +1,85 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { bytesToHex, loadAuthKeyWireFixture, namedHex } from './authKeyWireFixture' + +describe('p256JwkThumbprint', () => { + it('rejects anything that is not a 91-byte P-256 SPKI', () => { + expect(() => p256JwkThumbprint(new Uint8Array(65))).toThrow(/91-byte P-256 SPKI/) + }) + + it('matches a WebCrypto-derived RFC 7638 thumbprint', async () => { + const kp = (await globalThis.crypto.subtle.generateKey( + { name: 'ECDSA', namedCurve: 'P-256' }, + true, + ['sign', 'verify'], + )) as CryptoKeyPair + const spki = new Uint8Array(await globalThis.crypto.subtle.exportKey('spki', kp.publicKey)) + const jwk = (await globalThis.crypto.subtle.exportKey('jwk', kp.publicKey)) as JsonWebKey + const canonical = `{"crv":"${jwk.crv}","kty":"${jwk.kty}","x":"${jwk.x}","y":"${jwk.y}"}` + const reference = toBase64Url( + new Uint8Array( + await globalThis.crypto.subtle.digest( + 'SHA-256', + toArrayBuffer(new TextEncoder().encode(canonical)), + ), + ), + ) + // Validates both the SPKI x/y slicing and the vendored SHA-256 end-to-end. + expect(p256JwkThumbprint(spki)).toBe(reference) + }) +}) + +// The generated-key test above proves this implementation agrees with itself and +// with WebCrypto. These pin it to the canonical cross-language vectors instead, +// so the TypeScript `jkt` cannot drift from the iOS and Android SDKs. +describe('p256JwkThumbprint against the canonical AuthKeyWireV1 vectors', () => { + const fixture = loadAuthKeyWireFixture() + const spki = fromBase64Url(fixture.p256PublicKey.spkiBase64Url) + + it('derives the canonical RFC 7638 thumbprint from the canonical SPKI', () => { + expect(spki.length).toBe(91) + expect(p256JwkThumbprint(spki)).toBe(fixture.p256PublicKey.jwkThumbprint) + }) + + it('slices x and y from the offset the canonical X9.63 point occupies', () => { + // Pins the hard-coded offset 26: everything from there must be the 65-byte + // uncompressed point the fixture publishes separately as `x963Hex`. + expect(bytesToHex(spki.subarray(26))).toBe(fixture.p256PublicKey.x963Hex) + }) + + it('rejects the canonical malformed SPKI encodings it can detect', () => { + for (const name of ['truncated', 'overlong']) { + const vector = namedHex(fixture.rejected.subjectPublicKeyInfo, name) + expect(() => p256JwkThumbprint(vector)).toThrow(/91-byte P-256 SPKI/) + } + }) + + it('rejects a bare X9.63 point, which is not a SubjectPublicKeyInfo', () => { + // `compressed` is caught by the point marker as well as the length; the + // other two are only ever caught by the length check, because this function + // accepts an SPKI and never a bare point. + for (const name of ['compressed', 'invalid-marker', 'off-curve']) { + const vector = namedHex(fixture.rejected.x963PublicKeys, name) + expect(() => p256JwkThumbprint(vector)).toThrow(/91-byte P-256 SPKI/) + } + }) +}) diff --git a/src/__test__/keyPolicy.test.ts b/src/__test__/keyPolicy.test.ts new file mode 100644 index 0000000..728f159 --- /dev/null +++ b/src/__test__/keyPolicy.test.ts @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { readFileSync } from 'node:fs' + +import { requireOptionalNativeModule } from 'expo-modules-core' + +import { DaaClient } from '../DaaClient' +import { assertDeviceKeyPolicy, DEVICE_KEY_POLICY, isRequiredDeviceKeyPolicy } from '../config' +import { isDaaError } from '../errors' +import { resolveNativeBridge } from '../securekey/resolveNativeBridge' +import type { DaaTransport } from '../transport/DaaTransport' + +const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, +} + +const weakerPolicy = Object.freeze({ + hardwareBacked: false, + userVerification: 'REQUIRED_FOR_EACH_SIGNATURE', +}) + +function sdkConfig() { + return { + appId: 'app-123', + environment: 'sandbox' as const, + transport, + keyPolicy: DEVICE_KEY_POLICY, + } +} + +function readUtf8(relativeFromTest: string): string { + return new TextDecoder().decode(readFileSync(`${__dirname}/${relativeFromTest}`)) +} + +describe('DeviceKeyPolicy closed set', () => { + it('accepts only the required singleton policy', () => { + expect(assertDeviceKeyPolicy(DEVICE_KEY_POLICY)).toBe(DEVICE_KEY_POLICY) + expect(isRequiredDeviceKeyPolicy(DEVICE_KEY_POLICY)).toBe(true) + expect(assertDeviceKeyPolicy({ ...DEVICE_KEY_POLICY, extra: 1 })).toBe(DEVICE_KEY_POLICY) + }) + + it('rejects a missing or weaker policy', () => { + expect(() => assertDeviceKeyPolicy(undefined)).toThrow(/keyPolicy is required/) + expect(() => assertDeviceKeyPolicy(null)).toThrow(/keyPolicy is required/) + expect(() => assertDeviceKeyPolicy(weakerPolicy)).toThrow(/hardware-backed/) + expect(() => + assertDeviceKeyPolicy({ + hardwareBacked: true, + userVerification: 'OPTIONAL', + }), + ).toThrow(/REQUIRED_FOR_EACH_SIGNATURE/) + expect(isRequiredDeviceKeyPolicy(weakerPolicy)).toBe(false) + }) +}) + +describe('DaaClient keyPolicy', () => { + it('rejects construction without the closed-set policy', () => { + expect( + () => + new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + } as never), + ).toThrow(/keyPolicy is required/) + }) + + it('rejects a weaker policy at construction', () => { + expect( + () => + new DaaClient({ + ...sdkConfig(), + keyPolicy: weakerPolicy as never, + }), + ).toThrow(/hardware-backed/) + }) + + it('stores the canonical frozen policy', () => { + const client = new DaaClient(sdkConfig()) + expect(client.keyPolicy).toBe(DEVICE_KEY_POLICY) + expect(Object.isFrozen(client.keyPolicy)).toBe(true) + }) +}) + +describe('native declaredKeyPolicy', () => { + const requireNative = jest.mocked(requireOptionalNativeModule) + const originalNative = requireNative.getMockImplementation() + + afterEach(() => { + requireNative.mockReset() + if (originalNative !== undefined) { + requireNative.mockImplementation(originalNative) + } + }) + + function mockSecureKey(declared: unknown) { + requireNative.mockImplementation((name) => { + if (name !== 'DaaSecureKey') { + return null + } + return { + declaredKeyPolicy: typeof declared === 'function' ? declared : () => declared, + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + } + }) + } + + it('constructs when the native module declares the configured policy', () => { + mockSecureKey(DEVICE_KEY_POLICY) + const client = new DaaClient(sdkConfig()) + expect(client.keyPolicy).toBe(DEVICE_KEY_POLICY) + expect(() => resolveNativeBridge()).not.toThrow() + }) + + it('fails closed when the native module declares a weaker policy', () => { + mockSecureKey(weakerPolicy) + const err = (() => { + try { + new DaaClient(sdkConfig()) + return undefined + } catch (caught: unknown) { + return caught + } + })() + expect(isDaaError(err) && err.detail.kind === 'contract_violation').toBe(true) + expect(String(err)).toMatch(/does not match the configured DeviceKeyPolicy/) + + expect(() => resolveNativeBridge()).toThrow(/does not match the configured DeviceKeyPolicy/) + }) + + it('fails closed when the native module omits the capability query', () => { + requireNative.mockImplementation((name) => { + if (name !== 'DaaSecureKey') { + return null + } + return { + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + } + }) + expect(() => new DaaClient(sdkConfig())).toThrow(/did not declare a DeviceKeyPolicy/) + expect(() => resolveNativeBridge()).toThrow(/did not declare a DeviceKeyPolicy/) + }) +}) + +// Reads the native source as text and greps for literal substrings, rather +// than compiling Swift/Kotlin (this suite is Node-only). Intentionally +// brittle to the exact strings below: a Swift/Kotlin formatter reflowing +// these lines without changing their meaning would break this test, and +// that is an acceptable, expected failure mode for a check whose entire job +// is pinning the literal source, not a bug to work around. +describe('native source pin', () => { + it('Expo DaaSecureKey modules declare the required DeviceKeyPolicy', () => { + const swift = readUtf8('../../ios/DaaSecureKeyModule.swift') + const kotlin = readUtf8( + '../../android/src/main/java/com/circle/daa/reactnative/DaaSecureKeyModule.kt', + ) + for (const source of [swift, kotlin]) { + expect(source).toContain('declaredKeyPolicy') + expect(source).toContain('REQUIRED_FOR_EACH_SIGNATURE') + } + expect(swift).toContain('"hardwareBacked": true') + expect(kotlin).toContain('"hardwareBacked" to true') + }) +}) diff --git a/src/__test__/loginCeremony.test.ts b/src/__test__/loginCeremony.test.ts new file mode 100644 index 0000000..55a6205 --- /dev/null +++ b/src/__test__/loginCeremony.test.ts @@ -0,0 +1,884 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { AuthClient } from '../api/AuthClient' +import { webCryptoRegistrationFlowKeyProvider } from '../auth/RegistrationFlowKey' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { + DEVICE_REGISTRATION_COMPLETE_PATH, + REGISTRATION_DEVICE_AUTHORIZATION_HEADER, + REGISTRATION_FLOW_AUTHORIZATION_HEADER, +} from '../auth/registrationAuthorization' +import { registrationCodeChallengeS256 } from '../auth/registrationCodeVerifier' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { p256JwkThumbprint, p256PublicJwkFromSpki } from '../crypto/jwkThumbprint' +import { sha256 } from '../crypto/sha256' +import { DEVICE_KEY_POLICY } from '../config' +import { DaaClient } from '../DaaClient' +import { isDaaError } from '../errors' +import { SOCIAL_SESSION_PATH } from '../models/PreparedSocialLogin' +import { InMemorySecureKeyStore } from '../securekey/InMemorySecureKey' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { isUuidV4 } from '../validation/uuid' + +/** + * Social Session, AuthKey selection, Device Registration Complete, and + * `DaaClient.forUser` — the rest of the login ceremony after Prepare. + */ + +class ScriptedTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) { + throw new Error(`unexpected request ${request.method} ${request.path}`) + } + return response + } +} + +const LOGIN_REQUEST_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const OWNER_BINDING_ID = '11111111-2222-4333-8444-555555555555' +const AUTH_KEY_ID = '99999999-8888-4777-8666-555555555555' +const NONCE = 'n'.repeat(48) +const STATE = 's'.repeat(48) +const EXPIRES_AT = '2026-08-26T12:00:00Z' +const HANDLE = 'h'.repeat(32) +const ID_TOKEN = 'ID_TOKEN_MARKER' + +const PREPARED = `{"loginRequestId":"${LOGIN_REQUEST_ID}","oidcNonce":"${NONCE}","oidcState":"${STATE}","expiresAt":"${EXPIRES_AT}"}` +const SESSION = `{"registrationHandle":"${HANDLE}","clientEntityId":"${CLIENT_ENTITY_ID}","expiresAt":"${EXPIRES_AT}"}` +const ACTIVE = `{"deviceCredentialStatus":"active","ownerBindingId":"${OWNER_BINDING_ID}","authKeyId":"${AUTH_KEY_ID}","resolvedAt":"${EXPIRES_AT}"}` +const RECOVERY = `{"status":"RECOVERY_PENDING","recoveryReference":"${'r'.repeat(16)}","expiresAt":"${EXPIRES_AT}"}` +// No `status` member (the flat shape), but a `recoveryReference` +// alongside it — a payload that cannot honestly be resolved toward ACTIVE. +const ACTIVE_WITH_RECOVERY_FIELD = `{"deviceCredentialStatus":"active","ownerBindingId":"${OWNER_BINDING_ID}","authKeyId":"${AUTH_KEY_ID}","resolvedAt":"${EXPIRES_AT}","recoveryReference":"${'r'.repeat(16)}"}` +// Same ambiguity, the other `RECOVERY_PENDING` field: no `status`, but an +// `expiresAt` alongside the flat shape. +const ACTIVE_WITH_EXPIRES_AT_FIELD = `{"deviceCredentialStatus":"active","ownerBindingId":"${OWNER_BINDING_ID}","authKeyId":"${AUTH_KEY_ID}","resolvedAt":"${EXPIRES_AT}","expiresAt":"${EXPIRES_AT}"}` + +function envelope(payload: string): Uint8Array { + return new TextEncoder().encode(`{"data":${payload}}`) +} + +function jsonResponse(status: number, payload: string): DaaHttpResponse { + return { status, headers: { 'X-Request-Id': 'req-1' }, bodyBytes: envelope(payload) } +} + +function compactJwt(payload: object, header: object = { alg: 'ES256' }): string { + const encodedHeader = toBase64Url(new TextEncoder().encode(JSON.stringify(header))) + const body = toBase64Url(new TextEncoder().encode(JSON.stringify(payload))) + return `${encodedHeader}.${body}.c2ln` +} + +function decodeJwsPayload(jws: string): Record { + const payload = jws.split('.')[1] + if (payload === undefined) { + throw new Error('expected a compact JWS') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(payload))) as Record +} + +function decodeJwsHeader(jws: string): Record { + const header = jws.split('.')[0] + if (header === undefined) { + throw new Error('expected a compact JWS') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(header))) as Record +} + +function sentJson(request: DaaHttpRequest): Record { + if (request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + return JSON.parse(new TextDecoder().decode(request.bodyBytes)) as Record +} + +function ceremonyClient(responses: DaaHttpResponse[]): { + client: AuthClient + transport: ScriptedTransport + store: InMemorySecureKeyStore +} { + const transport = new ScriptedTransport(responses) + const store = new InMemorySecureKeyStore() + const client = new AuthClient({ + transport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + secureKeys: store, + identity: { appId: 'app-123', environment: 'sandbox' }, + }) + return { client, transport, store } +} + +describe('Social Session', () => { + it('posts loginRequestId, idToken, and clientEntityId to the contract path, then selects an AuthKey', async () => { + const { client, transport, store } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + + expect(transport.sent).toHaveLength(2) + const session = transport.sent[1] + if (session === undefined || session.bodyBytes === null) { + throw new Error('expected a Session request') + } + expect(session.method).toBe('POST') + expect(session.path).toBe(SOCIAL_SESSION_PATH) + expect(session.query).toBeNull() + expect(session.headers).toEqual({ 'Content-Type': 'application/json' }) + expect(Object.keys(session.headers)).not.toContain('X-Device-Authorization') + + const body = sentJson(session) + expect(Object.keys(body).sort()).toEqual([ + 'clientEntityId', + 'idToken', + 'idempotencyKey', + 'loginRequestId', + ]) + expect(body.loginRequestId).toBe(LOGIN_REQUEST_ID) + expect(body.idToken).toBe(ID_TOKEN) + expect(body.clientEntityId).toBe(CLIENT_ENTITY_ID) + expect(new TextDecoder().decode(session.bodyBytes)).toBe( + JSON.stringify({ + idempotencyKey: body.idempotencyKey, + loginRequestId: LOGIN_REQUEST_ID, + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }), + ) + + expect(pending.registrationHandle).toBe(HANDLE) + expect(pending.clientEntityId).toBe(CLIENT_ENTITY_ID) + expect(pending.expiresAt).toBe(EXPIRES_AT) + const authKey = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(authKey.resolution()).toBe('created') + }) + + // The service declares `clientEntityId` required with no resolve-or-create + // fallback, so a bad one is a 400 rather than a login. Reject it locally, + // before the attempt is spent, rather than spending it on a doomed request. + it.each<[string, unknown]>([ + ['missing', undefined], + ['null', null], + ['not a UUID', 'not-a-uuid'], + ['a UUID with surrounding text', ` ${CLIENT_ENTITY_ID} `], + ['not a string', 42], + ])('rejects a clientEntityId that is %s', async (_label, clientEntityId) => { + const { client, transport } = ceremonyClient([jsonResponse(201, PREPARED)]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + + const error: unknown = await prepared + .completeSocialSession({ idToken: ID_TOKEN, clientEntityId } as { + idToken: string + clientEntityId: string + }) + .catch((err: unknown) => err) + + expect(isDaaError(error)).toBe(true) + if (isDaaError(error)) { + expect(error.detail.kind).toBe('contract_violation') + } + // Prepare and nothing else: the Session request was never sent. + expect(transport.sent).toHaveLength(1) + }) + + it('fails closed when an Owner grant is missing registrationFlowKeyThumbprint', async () => { + const grant = compactJwt({ sub: 'GRANT_MARKER', aud: 'circle-digital-asset-accounts' }) + const { client } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse( + 200, + `{"registrationHandle":"${HANDLE}","clientEntityId":"${CLIENT_ENTITY_ID}","expiresAt":"${EXPIRES_AT}","ownerGrant":"${grant}"}`, + ), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + try { + await prepared.completeSocialSession({ idToken: ID_TOKEN, clientEntityId: CLIENT_ENTITY_ID }) + } catch (err) { + expect(isDaaError(err)).toBe(true) + if (isDaaError(err)) { + expect(err.detail.kind).toBe('contract_violation') + } + expect((err as Error).message).not.toMatch(/GRANT_MARKER/) + expect((err as Error).message).not.toMatch(/ID_TOKEN_MARKER/) + expect(JSON.stringify(err)).not.toMatch(/GRANT_MARKER/) + return + } + throw new Error('expected missing grant thumbprint to fail closed') + }) + + it('accepts an Owner grant only when registrationFlowKeyThumbprint matches the flow key', async () => { + const transport: DaaTransport & { sent: DaaHttpRequest[] } = { + sent: [], + async send(request) { + transport.sent.push(request) + if (transport.sent.length === 1) { + return jsonResponse(201, PREPARED) + } + const prepare = transport.sent[0] + if (prepare === undefined) { + throw new Error('expected Prepare to be sent first') + } + const flowSpki = fromBase64Url(sentJson(prepare).registrationFlowPublicKey as string) + const grant = compactJwt({ + registrationFlowKeyThumbprint: p256JwkThumbprint(flowSpki), + }) + return jsonResponse( + 200, + `{"registrationHandle":"${HANDLE}","clientEntityId":"${CLIENT_ENTITY_ID}","expiresAt":"${EXPIRES_AT}","ownerGrant":"${grant}"}`, + ) + }, + } + const client = new AuthClient({ + transport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + secureKeys: new InMemorySecureKeyStore(), + identity: { appId: 'app-123', environment: 'sandbox' }, + }) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(pending.registrationHandle).toBe(HANDLE) + }) +}) + +describe('production AuthKey store reuse', () => { + const requireNative = jest.mocked(requireOptionalNativeModule) + + it('reuses one NativeSecureKeyStore so concurrent Session completions share resolveOrCreate', async () => { + let resolveCalls = 0 + const previous = requireNative.getMockImplementation() + requireNative.mockImplementation((name: string) => { + if (name === 'DaaSecureKey') { + return { + declaredKeyPolicy: () => DEVICE_KEY_POLICY, + resolveOrCreate: async () => { + resolveCalls += 1 + return 'created' + }, + publicKeySpkiBase64Url: async () => 'I'.repeat(122), + acknowledgeRegistration: async () => undefined, + } + } + return previous?.(name) ?? null + }) + + try { + const transport = new ScriptedTransport([ + jsonResponse(201, PREPARED), + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, SESSION), + ]) + const client = new AuthClient({ + transport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + identity: { appId: 'app-123', environment: 'sandbox' }, + }) + const first = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const second = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + await Promise.all([ + first.completeSocialSession({ idToken: ID_TOKEN, clientEntityId: CLIENT_ENTITY_ID }), + second.completeSocialSession({ idToken: ID_TOKEN, clientEntityId: CLIENT_ENTITY_ID }), + ]) + + expect(resolveCalls).toBe(1) + } finally { + requireNative.mockImplementation(previous ?? (() => null)) + } + }) +}) + +describe('Device Registration Complete', () => { + it('signs and sends both registration proofs under their two headers: the flow proof with all 14 claims, the device proof with only the 10 request claims', async () => { + const { client, transport, store } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + + expect(result.status).toBe('ACTIVE') + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + expect(result.context.clientEntityId).toBe(CLIENT_ENTITY_ID) + expect(result.context.deviceContext.authKeyId).toBe(AUTH_KEY_ID) + expect(result.context.deviceContext.deviceCredentialStatus).toBe('active') + + const complete = transport.sent[2] + if (complete === undefined || complete.bodyBytes === null) { + throw new Error('expected a Complete request') + } + expect(complete.method).toBe('POST') + expect(DEVICE_REGISTRATION_COMPLETE_PATH).toBe('/v1/accounts/auth/deviceKeyRegistration') + expect(complete.path).toBe('/v1/accounts/auth/deviceKeyRegistration') + expect(complete.query).toBeNull() + expect(Object.keys(complete.headers).sort()).toEqual( + [ + 'Content-Type', + REGISTRATION_DEVICE_AUTHORIZATION_HEADER, + REGISTRATION_FLOW_AUTHORIZATION_HEADER, + ].sort(), + ) + expect(complete.headers['Content-Type']).toBe('application/json') + expect(REGISTRATION_DEVICE_AUTHORIZATION_HEADER).toBe('X-Device-Authorization') + expect(REGISTRATION_FLOW_AUTHORIZATION_HEADER).toBe('X-Registration-Flow-Authorization') + + const body = sentJson(complete) + expect(Object.keys(body).sort()).toEqual([ + 'authKeyPublicKey', + 'idempotencyKey', + 'registrationCodeVerifier', + 'registrationHandle', + ]) + expect(body.registrationHandle).toBe(HANDLE) + // profile_id (the bound clientEntityId) travels only in the two JWS claim + // sets, never in the HTTP body itself. + expect(body).not.toHaveProperty('profileId') + expect(body).not.toHaveProperty('existingDeviceApprovalJws') + expect(new TextDecoder().decode(complete.bodyBytes)).toBe(JSON.stringify(body)) + + // The verifier redeemed here must be the one minted before Prepare, not a + // fresh one — that round-trip is the whole point of the challenge/verifier + // exchange. + const prepare = transport.sent[0] + if (prepare === undefined || prepare.bodyBytes === null) { + throw new Error('expected a Prepare request') + } + const prepareChallenge = sentJson(prepare).registrationCodeChallenge as string + const prepareFlowPublicKey = sentJson(prepare).registrationFlowPublicKey as string + expect(registrationCodeChallengeS256(body.registrationCodeVerifier as string)).toBe( + prepareChallenge, + ) + + const deviceJws = complete.headers[REGISTRATION_DEVICE_AUTHORIZATION_HEADER] + const flowJws = complete.headers[REGISTRATION_FLOW_AUTHORIZATION_HEADER] + if (deviceJws === undefined || flowJws === undefined) { + throw new Error('expected both X-Device-Authorization and X-Registration-Flow-Authorization') + } + + // Both headers embed the signer's own P-256 public JWK, bound to the key + // that actually holds each role: the proposed AuthKey for the device proof, + // and the ephemeral flow key minted (and sent to Prepare) for the flow proof. + const deviceHeader = decodeJwsHeader(deviceJws) + expect(deviceHeader.alg).toBe('ES256') + expect(deviceHeader.typ).toBe('daa-device-authorization+jws') + expect(deviceHeader.kid).toBeUndefined() + expect(deviceHeader.jwk).toEqual( + p256PublicJwkFromSpki(fromBase64Url(body.authKeyPublicKey as string)), + ) + + const flowHeader = decodeJwsHeader(flowJws) + expect(flowHeader.alg).toBe('ES256') + expect(flowHeader.typ).toBe('daa-registration-flow-authorization+jws') + expect(flowHeader.kid).toBeUndefined() + expect(flowHeader.jwk).toEqual(p256PublicJwkFromSpki(fromBase64Url(prepareFlowPublicKey))) + + // Every claim DAA checks on Complete, with the right names and values. The flow proof carries all 14. + const digest = toBase64Url(sha256(complete.bodyBytes)) + const devicePayload = decodeJwsPayload(deviceJws) + const flowPayload = decodeJwsPayload(flowJws) + expect(flowPayload.discriminator).toBe('device_key_registration.v1') + expect(flowPayload.schema_version).toBe(1) + expect(flowPayload.body_sha256).toBe(digest) + expect(flowPayload.idempotency_key).toBe(body.idempotencyKey) + expect(flowPayload.canonical_path).toBe('/v1/accounts/auth/deviceKeyRegistration') + expect(flowPayload.method).toBe('POST') + expect(flowPayload.aud).toBe('circle-digital-asset-accounts') + expect(flowPayload.registration_handle_sha256).toBe( + toBase64Url(sha256(new TextEncoder().encode(HANDLE))), + ) + expect(flowPayload.profile_id).toBe(CLIENT_ENTITY_ID) + expect(flowPayload.auth_key_thumbprint).toBe( + p256JwkThumbprint(fromBase64Url(body.authKeyPublicKey as string)), + ) + expect(flowPayload.code_verifier_sha256).toBe( + registrationCodeChallengeS256(body.registrationCodeVerifier as string), + ) + expect(flowPayload.code_verifier_sha256).toBe(prepareChallenge) + expect(isUuidV4(flowPayload.jti as string)).toBe(true) + expect(typeof flowPayload.iat).toBe('number') + expect(flowPayload.exp).toBe((flowPayload.iat as number) + 300) + expect(Object.keys(flowPayload).sort()).toEqual([ + 'aud', + 'auth_key_thumbprint', + 'body_sha256', + 'canonical_path', + 'code_verifier_sha256', + 'discriminator', + 'exp', + 'iat', + 'idempotency_key', + 'jti', + 'method', + 'profile_id', + 'registration_handle_sha256', + 'schema_version', + ]) + + // The device proof carries only the 10 request claims — DAA + // decodes it strictly and rejects any binding claim — with the same + // values as the flow proof, bar jti. + const flowJti = flowPayload.jti + const flowRequestClaims = Object.fromEntries( + Object.entries(flowPayload).filter(([name]) => name in devicePayload && name !== 'jti'), + ) + const { jti: deviceJti, ...deviceRequestClaims } = devicePayload + expect(deviceRequestClaims).toEqual(flowRequestClaims) + expect(Object.keys(devicePayload).sort()).toEqual([ + 'aud', + 'body_sha256', + 'canonical_path', + 'discriminator', + 'exp', + 'iat', + 'idempotency_key', + 'jti', + 'method', + 'schema_version', + ]) + expect(isUuidV4(deviceJti as string)).toBe(true) + expect(isUuidV4(flowJti as string)).toBe(true) + expect(flowJti).not.toBe(deviceJti) + + const authKey = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(authKey.resolution()).toBe('existing') + }) + + it('does not put JWS, verifier, or idToken into Complete errors', async () => { + const { client, transport } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + { status: 400, headers: { 'X-Request-Id': 'req-1' }, bodyBytes: null }, + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + try { + await pending.complete() + } catch (err) { + const complete = transport.sent[2] + const deviceJws = complete?.headers[REGISTRATION_DEVICE_AUTHORIZATION_HEADER] + const flowJws = complete?.headers[REGISTRATION_FLOW_AUTHORIZATION_HEADER] + const message = (err as Error).message + expect(message).not.toMatch(/ID_TOKEN_MARKER/) + if (deviceJws !== undefined) { + expect(message).not.toContain(deviceJws) + } + if (flowJws !== undefined) { + expect(message).not.toContain(flowJws) + } + expect(JSON.stringify(err)).not.toMatch(/ID_TOKEN_MARKER/) + return + } + throw new Error('expected Complete to fail') + }) + + it('returns RECOVERY_PENDING without acknowledging the AuthKey', async () => { + const { client, store } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, RECOVERY), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + expect(result.status).toBe('RECOVERY_PENDING') + const authKey = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(authKey.resolution()).toBe('created') + }) + + it('fails closed rather than acknowledging the AuthKey when status is absent but a recoveryReference is present', async () => { + const { client, store } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE_WITH_RECOVERY_FIELD), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + + await expect(pending.complete()).rejects.toThrow() + + const authKey = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(authKey.resolution()).toBe('created') + }) + + it('fails closed rather than acknowledging the AuthKey when status is absent but an expiresAt is present', async () => { + const { client, store } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE_WITH_EXPIRES_AT_FIELD), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + + await expect(pending.complete()).rejects.toThrow() + + const authKey = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(authKey.resolution()).toBe('created') + }) + + // Complete spends a single-use registration handle, so the same pending + // registration is never sent twice, even after a successful first call. + it('is one-shot: a second complete() is rejected without another request', async () => { + const { client, transport } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + expect(result.status).toBe('ACTIVE') + expect(transport.sent).toHaveLength(3) + + const retry: unknown = await pending.complete().catch((err: unknown) => err) + expect(isDaaError(retry)).toBe(true) + if (isDaaError(retry)) { + expect(retry.detail.kind).toBe('contract_violation') + } + expect((retry as Error).message).toMatch(/already been consumed/) + expect(transport.sent).toHaveLength(3) + }) +}) + +describe('DaaClient.forUser', () => { + it('opens the operations surface only for an ACTIVE context', async () => { + const { client } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + + const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, + } + const daa = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + const user = daa.forUser(result.context) + expect(user.accounts).toBeDefined() + expect(() => daa.forUser({} as never)).toThrow(/ACTIVE DaaUserContext/) + }) + + it('carries publicApiOrigin into the surface as the pagination trust anchor', async () => { + const { client } = ceremonyClient([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE), + ]) + const prepared = await client.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + + const publicApiOrigin = 'https://api-test.circle.com' + const page = new TextEncoder().encode('{"data":[]}') + const transport = new ScriptedTransport([ + { + status: 200, + headers: { Link: `<${publicApiOrigin}/v1/accounts?pageAfter=x>; rel="next"` }, + bodyBytes: page, + }, + { status: 200, headers: {}, bodyBytes: page }, + ]) + const daa = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + publicApiOrigin, + }) + const first = await daa.forUser(result.context).accounts.list() + await first.next() + expect(transport.sent[1]?.query).toBe('pageAfter=x') + }) + + /** + * End to end on the production path: hand an ACTIVE context to `forUser`, + * and perform an authorized write signed by the real native AuthKey store. + * It is written against the native `DaaSecureKey` module rather than an + * injected store because what it pins is the wiring — if `forUser` validated + * the context and then built the operations surface without it, every write + * would have no credential to sign with and none of the read tests could + * notice. + * + * The native `DaaSecureKey` mock is used by both registration completion and + * the later DaaClient, so the context's local thumbprint binding is the same + * one the signed operation resolves. The registration-flow key remains + * WebCrypto here because the test does not exercise the native flow-key + * provider. + */ + it('signs a create with the context authKeyId and the AuthKey that login resolved', async () => { + const requireNative = jest.mocked(requireOptionalNativeModule) + const previous = requireNative.getMockImplementation() + const keyPair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [ + 'sign', + 'verify', + ]) + let resolveCalls = 0 + const signWithKey = async (signingInputBase64Url: string): Promise => + toBase64Url( + new Uint8Array( + await crypto.subtle.sign( + { name: 'ECDSA', hash: 'SHA-256' }, + keyPair.privateKey, + toArrayBuffer(fromBase64Url(signingInputBase64Url)), + ), + ), + ) + requireNative.mockImplementation((name: string) => { + if (name === 'DaaSecureKey') { + return { + declaredKeyPolicy: () => DEVICE_KEY_POLICY, + resolveOrCreate: async () => { + resolveCalls += 1 + return 'existing' + }, + publicKeySpkiBase64Url: async () => + toBase64Url(new Uint8Array(await crypto.subtle.exportKey('spki', keyPair.publicKey))), + acknowledgeRegistration: async () => undefined, + signDeviceAuthorization: async ( + _appId: string, + _environment: string, + signingInputBase64Url: string, + ) => signWithKey(signingInputBase64Url), + signRegistrationDeviceAuthorization: async ( + _appId: string, + _environment: string, + signingInputBase64Url: string, + ) => signWithKey(signingInputBase64Url), + } + } + return previous?.(name) ?? null + }) + + try { + const authTransport = new ScriptedTransport([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + jsonResponse(200, ACTIVE), + ]) + const authClient = new AuthClient({ + transport: authTransport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + identity: { appId: 'app-123', environment: 'sandbox' }, + }) + const prepared = await authClient.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const result = await pending.complete() + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + + const transport = new ScriptedTransport([ + jsonResponse( + 201, + '{"accountId":"acct-1","balances":[],"entityId":"e","purpose":"custody",' + + '"status":"pending","type":"first_party","custodyType":"self"}', + ), + ]) + const daa = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + + const account = await daa.forUser(result.context).accounts.create({ + idempotencyKey: '22222222-2222-4222-a222-222222222222', + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + blockchain: 'ARC', + }) + + expect(account.accountId).toBe('acct-1') + const create = transport.sent[0] + if (create === undefined) { + throw new Error('expected a create request') + } + expect(create.method).toBe('POST') + expect(create.path).toBe('/v1/accounts') + const compact = create.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('expected a device authorization on the create') + } + const header: unknown = JSON.parse( + new TextDecoder().decode(fromBase64Url(compact.split('.')[0] ?? '')), + ) + const claims: unknown = JSON.parse( + new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? '')), + ) + // The `kid` is the service-assigned id from the ACTIVE DeviceContext, not + // a fresh one the SDK made up — that is the value being carried through. + expect(header).toMatchObject({ kid: AUTH_KEY_ID }) + expect(claims).toMatchObject({ + canonical_path: '/v1/accounts', + discriminator: 'create_account', + }) + // AuthClient and DaaClient each have a JS resolver, but both resolve the + // same native key identity; the thumbprint check is what ties the context + // and the later JWS kid together across those two handles. + expect(resolveCalls).toBe(2) + } finally { + requireNative.mockImplementation(previous ?? (() => null)) + } + }) + + /** + * A real `DaaClient`'s registration-flow key comes from the native + * `DaaRegistration` module by default. That module's flow-key + * `signRegistrationAuthorization` is bridged on both platforms (see + * `RegistrationFlowKey.ts`), but this suite's `jest.setup.js` fake does not + * implement it, so Complete on the production path still fails closed here + * rather than silently succeeding without the flow-key proof — pinning that + * a missing native sign method is caught, not silently swallowed. + */ + it('fails closed at Complete when the native registration-flow key cannot sign', async () => { + // Just enough native DaaSecureKey to get through AuthKey selection at + // Social Session; the point of this test is the flow-key sign step in + // Complete, not AuthKey behavior. + const requireNative = jest.mocked(requireOptionalNativeModule) + const previous = requireNative.getMockImplementation() + const keyPair = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [ + 'sign', + 'verify', + ]) + requireNative.mockImplementation((name: string) => { + if (name === 'DaaSecureKey') { + return { + declaredKeyPolicy: () => DEVICE_KEY_POLICY, + resolveOrCreate: async () => 'created', + publicKeySpkiBase64Url: async () => + toBase64Url(new Uint8Array(await crypto.subtle.exportKey('spki', keyPair.publicKey))), + acknowledgeRegistration: async () => undefined, + signDeviceAuthorization: async () => { + throw new Error('signDeviceAuthorization should not be reached in this test') + }, + } + } + return previous?.(name) ?? null + }) + + try { + const transport = new ScriptedTransport([ + jsonResponse(201, PREPARED), + jsonResponse(200, SESSION), + ]) + const daa = new DaaClient({ + appId: 'app-123', + environment: 'sandbox', + transport, + keyPolicy: DEVICE_KEY_POLICY, + }) + const prepared = await daa.auth.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + const error: unknown = await pending.complete().catch((err: unknown) => err) + + expect(isDaaError(error)).toBe(true) + if (isDaaError(error)) { + expect(error.detail.kind).toBe('contract_violation') + } + expect((error as Error).message).toMatch(/signRegistrationAuthorization is required/) + } finally { + requireNative.mockImplementation(previous ?? (() => null)) + } + }) +}) diff --git a/src/__test__/loginFailure.test.ts b/src/__test__/loginFailure.test.ts new file mode 100644 index 0000000..79e3c44 --- /dev/null +++ b/src/__test__/loginFailure.test.ts @@ -0,0 +1,228 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AuthClient } from '../api/AuthClient' +import { webCryptoRegistrationFlowKeyProvider } from '../auth/RegistrationFlowKey' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import { InMemorySecureKeyStore } from '../securekey/InMemorySecureKey' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The login calls' failure mapping, with DAA's real error body. + * + * DAA returns `409` for three different codes on the login path: + * `IDEMPOTENCY_KEY_REUSED` (`420034`), `LOGIN_REQUEST_CONSUMED` (`420039`) and + * `AUTH_KEY_BINDING_CONFLICT` (`420038`). Only the first is + * `idempotency_conflict`. Each code is a literal here, so a wrong number in + * the table fails these tests. + */ + +class ScriptedTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) { + throw new Error(`unexpected request ${request.method} ${request.path}`) + } + return response + } +} + +const LOGIN_REQUEST_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' +const NONCE = 'n'.repeat(48) +const STATE = 's'.repeat(48) +const EXPIRES_AT = '2026-08-26T12:00:00Z' +const HANDLE = 'h'.repeat(32) +const REQUEST_ID = 'req-login-1' + +const PREPARED = `{"loginRequestId":"${LOGIN_REQUEST_ID}","oidcNonce":"${NONCE}","oidcState":"${STATE}","expiresAt":"${EXPIRES_AT}"}` +const SESSION = `{"registrationHandle":"${HANDLE}","clientEntityId":"${CLIENT_ENTITY_ID}","expiresAt":"${EXPIRES_AT}"}` + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function ok(status: number, payload: string): DaaHttpResponse { + return { status, headers: { 'X-Request-Id': 'req-ok' }, bodyBytes: bytes(`{"data":${payload}}`) } +} + +/** The error body DAA actually sends. */ +function failure(status: number, code: number | string): DaaHttpResponse { + return { + status, + headers: { 'X-Request-Id': REQUEST_ID }, + bodyBytes: bytes( + `{"code":${JSON.stringify(code)},"message":"internal detail","externalMessage":"The request was rejected"}`, + ), + } +} + +function client(responses: DaaHttpResponse[]): { auth: AuthClient; transport: ScriptedTransport } { + const transport = new ScriptedTransport(responses) + const auth = new AuthClient({ + transport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + secureKeys: new InMemorySecureKeyStore(), + identity: { appId: 'app-123', environment: 'sandbox' }, + }) + return { auth, transport } +} + +function sentKey(transport: ScriptedTransport, index: number): unknown { + const request = transport.sent[index] + if (request === undefined || request.bodyBytes === null) { + throw new Error('expected a request with a body') + } + return (JSON.parse(new TextDecoder().decode(request.bodyBytes)) as { idempotencyKey: unknown }) + .idempotencyKey +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +type Step = Readonly<{ + name: string + index: number + run: ( + failed: DaaHttpResponse, + ) => Promise<{ call: Promise; transport: ScriptedTransport }> +}> + +const STEPS: readonly Step[] = [ + { + name: 'Prepare', + index: 0, + run: async (failed) => { + const { auth, transport } = client([failed]) + return { call: auth.prepareSocialLogin({ provider: 'GOOGLE' }), transport } + }, + }, + { + name: 'Social Session', + index: 1, + run: async (failed) => { + const { auth, transport } = client([ok(201, PREPARED), failed]) + const prepared = await auth.prepareSocialLogin({ provider: 'GOOGLE' }) + return { + call: prepared.completeSocialSession({ + idToken: 'ID_TOKEN_MARKER', + clientEntityId: CLIENT_ENTITY_ID, + }), + transport, + } + }, + }, + { + name: 'Device Registration Complete', + index: 2, + run: async (failed) => { + const { auth, transport } = client([ok(201, PREPARED), ok(200, SESSION), failed]) + const prepared = await auth.prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: 'ID_TOKEN_MARKER', + clientEntityId: CLIENT_ENTITY_ID, + }) + return { call: pending.complete(), transport } + }, + }, +] + +describe.each(STEPS)('$name failure mapping', ({ index, run }) => { + it('maps 409 with IDEMPOTENCY_KEY_REUSED (420034) to idempotency_conflict with the key it sent', async () => { + const { call, transport } = await run(failure(409, 420034)) + const detail = await detailOf(call) + + expect(detail).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: sentKey(transport, index), + correlationId: REQUEST_ID, + }) + expect(transport.sent).toHaveLength(index + 1) + }) + + it.each(['IDEMPOTENCY_KEY_REUSED', 'LOGIN_REQUEST_CONSUMED'])( + 'keeps 409 with the name string %s a non-retryable api failure', + async (name) => { + const { call, transport } = await run(failure(409, name)) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: name, + retryable: false, + }) + expect(transport.sent).toHaveLength(index + 1) + }, + ) + + it('maps 409 with LOGIN_REQUEST_CONSUMED (420039) to contract_violation with the correlation id', async () => { + const { call, transport } = await run(failure(409, 420039)) + + expect(await detailOf(call)).toEqual({ kind: 'contract_violation', correlationId: REQUEST_ID }) + expect(transport.sent).toHaveLength(index + 1) + }) + + it('maps 409 with AUTH_KEY_BINDING_CONFLICT (420038) to a non-retryable api failure', async () => { + const { call } = await run(failure(409, 420038)) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 420038, + retryable: false, + }) + }) + + it('does not treat a 409 without a classified code as idempotency_conflict', async () => { + const { call } = await run({ status: 409, headers: {}, bodyBytes: null }) + + expect(await detailOf(call)).toEqual({ kind: 'api', httpStatus: 409, retryable: false }) + }) + + it('does not treat 420034 on another status as idempotency_conflict', async () => { + const { call } = await run(failure(400, 420034)) + + expect(await detailOf(call)).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 420034, + retryable: false, + }) + }) + + it('maps 410 to login_request_expired', async () => { + const { call } = await run(failure(410, 420035)) + + expect(await detailOf(call)).toEqual({ kind: 'login_request_expired' }) + }) +}) diff --git a/src/__test__/loginPayload.test.ts b/src/__test__/loginPayload.test.ts new file mode 100644 index 0000000..3253057 --- /dev/null +++ b/src/__test__/loginPayload.test.ts @@ -0,0 +1,347 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOwnerGrantFlowKeyThumbprint } from '../auth/ownerGrant' +import { toBase64Url } from '../crypto/base64url' +import { isDaaError } from '../errors' +import { MalformedPayloadError } from '../wire/payload' +import { toPendingRegistration } from '../wire/pendingRegistrationPayload' +import { toDeviceRegistrationResult } from '../wire/deviceRegistrationResultPayload' + +const HANDLE = 'h'.repeat(32) +const EXPIRES_AT = '2026-08-26T12:00:00Z' +const UUID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' + +/** + * The epoch-millisecond form the service sends some timestamps in, and the + * exact instant it has to normalise to. + * + * The number is a Prepare `expiresAt` value in the service's wire form. + * `SocialSession` and `DeviceContext` are the same kind of field, serialised + * the same way; these cases assert the decoder's tolerance, not the service's + * behaviour. + */ +const EPOCH_MILLIS = 1788290024580 +const EPOCH_MILLIS_ISO = '2026-09-01T19:13:44.580Z' + +/** Numbers that are not a plausible count of epoch milliseconds. */ +const BAD_EPOCHS = [ + 1788290024580.5, // fractional + -1788290024580, // negative + 0, // the epoch itself is a dropped field, not a timestamp + 8.64e15 + 1, // past the largest instant `Date` represents + 1e15, // renders a year the ISO-8601 grammar cannot spell + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER, +] + +/** + * Text that is not the ISO-8601 form. The first is the epoch *as a string*: the + * tolerance is for a JSON number, so quoting it does not buy it a pass. + */ +const BAD_DATE_TEXT = ['1788290024580', '2026-08-26 12:00:00Z', '2026-08-26', '', 'not-a-date'] + +function session(overrides: Record = {}): Record { + return { + registrationHandle: HANDLE, + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + ...overrides, + } +} + +function compactJwt(payload: object): string { + const header = toBase64Url(new TextEncoder().encode('{"alg":"ES256"}')) + const body = toBase64Url(new TextEncoder().encode(JSON.stringify(payload))) + return `${header}.${body}.c2ln` +} + +describe('toPendingRegistration', () => { + it('reads the SocialSession fields', () => { + expect( + toPendingRegistration({ + registrationHandle: HANDLE, + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + }), + ).toEqual({ + registrationHandle: HANDLE, + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + ownerGrant: null, + }) + }) + + it('captures ownerGrant when present without treating it as verified', () => { + const grant = compactJwt({ registrationFlowKeyThumbprint: 'a'.repeat(43) }) + expect( + toPendingRegistration({ + registrationHandle: HANDLE, + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + ownerGrant: grant, + }).ownerGrant, + ).toBe(grant) + }) + + it('takes either wire form for expiresAt and hands on one normalised instant', () => { + // Pinned to the instant, not to an ISO *shape*: a seconds-vs-milliseconds + // misreading, or an off-by-one, still produces a well-formed timestamp. + expect(toPendingRegistration(session({ expiresAt: EPOCH_MILLIS })).expiresAt).toBe( + EPOCH_MILLIS_ISO, + ) + expect(toPendingRegistration(session({ expiresAt: 1 })).expiresAt).toBe( + '1970-01-01T00:00:00.001Z', + ) + // The string form, which the contract declares, is passed through untouched; + // only the number form is normalised. + expect(toPendingRegistration(session({ expiresAt: EXPIRES_AT })).expiresAt).toBe(EXPIRES_AT) + }) + + it('rejects an expiresAt that is neither wire form', () => { + for (const expiresAt of [...BAD_EPOCHS, ...BAD_DATE_TEXT]) { + expect(() => toPendingRegistration(session({ expiresAt }))).toThrow(MalformedPayloadError) + } + }) + + it('rejects a handle outside the contract bounds or a non-UUID clientEntityId', () => { + expect(() => + toPendingRegistration({ + registrationHandle: '', + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + }), + ).toThrow(MalformedPayloadError) + expect(() => + toPendingRegistration({ + registrationHandle: 'h'.repeat(201), + clientEntityId: UUID, + expiresAt: EXPIRES_AT, + }), + ).toThrow(MalformedPayloadError) + expect(() => + toPendingRegistration({ + registrationHandle: HANDLE, + clientEntityId: 'not-a-uuid', + expiresAt: EXPIRES_AT, + }), + ).toThrow(MalformedPayloadError) + }) +}) + +describe('requireOwnerGrantFlowKeyThumbprint', () => { + const thumbprint = 'b'.repeat(43) + + it('fails closed when the claim is missing and never interpolates the grant', () => { + const grant = compactJwt({ sub: 'GRANT_SECRET' }) + try { + requireOwnerGrantFlowKeyThumbprint(grant, thumbprint, null) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/registrationFlowKeyThumbprint/) + expect((err as Error).message).not.toMatch(/GRANT_SECRET/) + return + } + throw new Error('expected fail-closed') + }) + + it('fails closed when the thumbprint does not match the flow key', () => { + const grant = compactJwt({ registrationFlowKeyThumbprint: 'c'.repeat(43) }) + expect(() => requireOwnerGrantFlowKeyThumbprint(grant, thumbprint, null)).toThrow( + /does not match/, + ) + }) + + it('accepts an exact matching thumbprint', () => { + const grant = compactJwt({ registrationFlowKeyThumbprint: thumbprint }) + expect(() => requireOwnerGrantFlowKeyThumbprint(grant, thumbprint, null)).not.toThrow() + }) +}) + +describe('toDeviceRegistrationResult', () => { + const deviceContext = { + deviceCredentialStatus: 'active', + ownerBindingId: UUID, + authKeyId: UUID, + resolvedAt: EXPIRES_AT, + } + + function resolvedAtOf(payload: Record): string { + const result = toDeviceRegistrationResult(payload, UUID) + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + return result.context.deviceContext.resolvedAt + } + + function recoveryPending(expiresAt: unknown): Record { + return { status: 'RECOVERY_PENDING', recoveryReference: 'r'.repeat(16), expiresAt } + } + + function recoveryExpiresAt(expiresAt: unknown): string { + const result = toDeviceRegistrationResult(recoveryPending(expiresAt), UUID) + if (result.status !== 'RECOVERY_PENDING') { + throw new Error('expected RECOVERY_PENDING') + } + return result.expiresAt + } + + it('decodes a flat DeviceContext as ACTIVE', () => { + const result = toDeviceRegistrationResult(deviceContext, UUID) + expect(result.status).toBe('ACTIVE') + if (result.status === 'ACTIVE') { + expect(result.context.clientEntityId).toBe(UUID) + expect(result.context.deviceContext.deviceCredentialStatus).toBe('active') + } + }) + + it('takes either wire form for resolvedAt and hands on one normalised instant', () => { + // Pinned to the instant, not to an ISO *shape*: a seconds-vs-milliseconds + // misreading, or an off-by-one, still produces a well-formed timestamp. + expect(resolvedAtOf({ ...deviceContext, resolvedAt: EPOCH_MILLIS })).toBe(EPOCH_MILLIS_ISO) + expect(resolvedAtOf({ ...deviceContext, resolvedAt: 1 })).toBe('1970-01-01T00:00:00.001Z') + // The string form is passed through untouched. + expect(resolvedAtOf(deviceContext)).toBe(EXPIRES_AT) + }) + + it('rejects a resolvedAt that is neither wire form', () => { + for (const resolvedAt of [...BAD_EPOCHS, ...BAD_DATE_TEXT]) { + expect(() => toDeviceRegistrationResult({ ...deviceContext, resolvedAt }, UUID)).toThrow( + MalformedPayloadError, + ) + } + }) + + it('ignores extra response fields on a flat DeviceContext', () => { + const result = toDeviceRegistrationResult({ ...deviceContext, extra: 1 }, UUID) + expect(result.status).toBe('ACTIVE') + }) + + it('decodes a wrapped ACTIVE into a nominal DaaUserContext', () => { + const result = toDeviceRegistrationResult( + { + status: 'ACTIVE', + context: { + clientEntityId: UUID, + deviceContext, + }, + }, + UUID, + ) + expect(result.status).toBe('ACTIVE') + if (result.status === 'ACTIVE') { + expect(result.context.clientEntityId).toBe(UUID) + expect(result.context.deviceContext.deviceCredentialStatus).toBe('active') + } + }) + + it('rejects a context minted via ctx.constructor for a different Owner', () => { + // `isActiveDaaUserContext`'s `instanceof` + `#active` check stops a + // consumer-fabricated object literal, but that alone does not stop the + // class itself: anything holding one real ACTIVE context can reach + // `DaaUserContext` through `ctx.constructor`, with no import of this + // module at all. The constructor is brand-gated, so calling it that way + // throws instead of minting a second ACTIVE context for a different Owner. + const result = toDeviceRegistrationResult( + { + status: 'ACTIVE', + context: { clientEntityId: UUID, deviceContext }, + }, + UUID, + ) + if (result.status !== 'ACTIVE') { + throw new Error('expected ACTIVE') + } + const forgedOwnerId = 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee' + const Ctor = result.context.constructor as new (...args: unknown[]) => unknown + + let thrown: unknown + try { + new Ctor({ + clientEntityId: forgedOwnerId, + deviceContext: { ...deviceContext, ownerBindingId: forgedOwnerId }, + }) + } catch (err) { + thrown = err + } + + expect(isDaaError(thrown)).toBe(true) + }) + + it('rejects a wrapped ACTIVE whose clientEntityId diverges from Social Session', () => { + expect(() => + toDeviceRegistrationResult( + { + status: 'ACTIVE', + context: { + clientEntityId: 'aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee', + deviceContext, + }, + }, + UUID, + ), + ).toThrow(MalformedPayloadError) + }) + + it('decodes RECOVERY_PENDING without a context', () => { + const result = toDeviceRegistrationResult( + { + status: 'RECOVERY_PENDING', + recoveryReference: 'r'.repeat(16), + expiresAt: EXPIRES_AT, + }, + UUID, + ) + expect(result.status).toBe('RECOVERY_PENDING') + }) + + it('takes either wire form for a RECOVERY_PENDING expiresAt', () => { + expect(recoveryExpiresAt(EPOCH_MILLIS)).toBe(EPOCH_MILLIS_ISO) + expect(recoveryExpiresAt(1)).toBe('1970-01-01T00:00:00.001Z') + expect(recoveryExpiresAt(EXPIRES_AT)).toBe(EXPIRES_AT) + }) + + it('rejects a RECOVERY_PENDING expiresAt that is neither wire form', () => { + for (const expiresAt of [...BAD_EPOCHS, ...BAD_DATE_TEXT]) { + expect(() => toDeviceRegistrationResult(recoveryPending(expiresAt), UUID)).toThrow( + MalformedPayloadError, + ) + } + }) + + it('rejects an unknown status rather than degrading', () => { + expect(() => toDeviceRegistrationResult({ status: 'PENDING' }, UUID)).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects RECOVERY_PENDING that also carries a context', () => { + expect(() => + toDeviceRegistrationResult( + { + status: 'RECOVERY_PENDING', + recoveryReference: 'r'.repeat(16), + expiresAt: EXPIRES_AT, + context: { clientEntityId: UUID }, + }, + UUID, + ), + ).toThrow(MalformedPayloadError) + }) +}) diff --git a/src/__test__/moneyPayload.test.ts b/src/__test__/moneyPayload.test.ts new file mode 100644 index 0000000..cfa7840 --- /dev/null +++ b/src/__test__/moneyPayload.test.ts @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import { optionalMoney, requiredMoney, toMoney } from '../wire/moneyPayload' +import { MalformedPayloadError } from '../wire/payload' + +describe('money payload primitives', () => { + it('preserves the exact decimal string and currency', () => { + const money = toMoney({ amount: '12345678901234567890.00100', currency: 'USD' }, 'amount') + + expect(money.amount).toBe('12345678901234567890.00100') + expect(money.currency).toBe('USD') + }) + + it('rejects absent, malformed, and JSON-number amounts with the caller label', () => { + for (const value of [ + null, + {}, + { amount: 1, currency: 'USD' }, + { amount: 'nope', currency: 'USD' }, + ]) { + expect(() => toMoney(value, 'fee')).toThrow(MalformedPayloadError) + try { + toMoney(value, 'fee') + } catch (error) { + expect((error as MalformedPayloadError).fieldName).toMatch(/^fee(?:\.amount)?$/) + } + } + }) + + it('distinguishes required money from an absent optional field', () => { + expect(optionalMoney({}, 'fee')).toBeNull() + expect(optionalMoney({ fee: null }, 'fee')).toBeNull() + expect(requiredMoney({ amount: { amount: '1.00', currency: 'EUR' } }, 'amount').amount).toBe( + '1.00', + ) + expect(() => requiredMoney({}, 'amount')).toThrow(MalformedPayloadError) + }) + + it('inherits Money redaction rather than exposing the amount in default renderings', () => { + const validMoney = toMoney({ amount: '98765.4321', currency: 'USD' }, 'amount') + + for (const rendered of [JSON.stringify(validMoney), inspect(validMoney), String(validMoney)]) { + expect(rendered).not.toContain('98765.4321') + } + }) +}) diff --git a/src/__test__/nativeSecureKey.test.ts b/src/__test__/nativeSecureKey.test.ts new file mode 100644 index 0000000..8d2057d --- /dev/null +++ b/src/__test__/nativeSecureKey.test.ts @@ -0,0 +1,689 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { DEVICE_KEY_POLICY } from '../config' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { DaaError, isDaaError } from '../errors' +import type { NativeSecureKeyBridge } from '../securekey/NativeSecureKeyBridge' +import { NativeSecureKeyStore } from '../securekey/NativeSecureKey' +import { resolveNativeBridge } from '../securekey/resolveNativeBridge' + +// `expo-modules-core` is mocked globally in jest.setup.js (returns null, so the +// native module is always absent in Node). The import above picks up that mock; +// `jest.mocked()` below re-points it per test. + +// A WebCrypto-backed stand-in for the platform native module. It exercises the +// exact bridge contract (Base64URL in/out, one non-exportable P-256 key per +// alias) without device hardware, so it validates NativeSecureKeyStore's +// delegation and byte transport end-to-end. The thumbprint is derived in TS, so +// the bridge does not implement it. +class FakeNativeBridge implements NativeSecureKeyBridge { + private readonly keys = new Map() + private readonly acknowledged = new Set() + public resolveCalls = 0 + + private subtle(): SubtleCrypto { + return globalThis.crypto.subtle + } + + private pair(alias: string): CryptoKeyPair { + const kp = this.keys.get(alias) + if (!kp) throw new Error(`no key for ${alias}`) + return kp + } + + async resolveOrCreate(alias: string): Promise<'created' | 'existing'> { + this.resolveCalls += 1 + if (!this.keys.has(alias)) { + const kp = (await this.subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [ + 'sign', + 'verify', + ])) as CryptoKeyPair + this.keys.set(alias, kp) + return 'created' + } + // A key that exists but was never acknowledged still resolves 'created' — + // this mirrors the native SDK contract, where only a durable + // acknowledgement yields 'existing'. + return this.acknowledged.has(alias) ? 'existing' : 'created' + } + + async acknowledgeRegistration(alias: string): Promise { + this.pair(alias) // native rejects an ack for a key that was never resolved + this.acknowledged.add(alias) + } + + async publicKeySpkiBase64Url(alias: string): Promise { + const spki = await this.subtle().exportKey('spki', this.pair(alias).publicKey) + return toBase64Url(new Uint8Array(spki)) + } + + async sign(alias: string, messageBase64Url: string): Promise { + const signature = await this.subtle().sign( + { name: 'ECDSA', hash: 'SHA-256' }, + this.pair(alias).privateKey, + toArrayBuffer(fromBase64Url(messageBase64Url)), + ) + return toBase64Url(new Uint8Array(signature)) + } + + registrationSignCalls = 0 + + async signRegistrationDeviceAuthorization( + alias: string, + messageBase64Url: string, + ): Promise { + // A distinct bridge method from `sign`, tracked separately so a test can + // assert which one a caller actually reached, even though this fake signs + // with the same underlying key either way. + this.registrationSignCalls += 1 + return this.sign(alias, messageBase64Url) + } +} + +const CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000001' + +const identity = { + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, +} as const + +describe('NativeSecureKeyStore', () => { + it('returns the same installation key for the same identity', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + const a = await store.resolveOrCreate(identity) + const b = await store.resolveOrCreate(identity) + expect(a).toBe(b) + }) + + it('reports created until acknowledgement, then existing, and still signs while created', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + const key = await store.resolveOrCreate(identity) + expect(key.resolution()).toBe('created') + const sig = await key.signExactBytes(new Uint8Array([1, 2, 3])) + expect(sig.length).toBe(64) + + await key.acknowledgeRegistration() + expect(key.resolution()).toBe('existing') + await key.acknowledgeRegistration() + expect(key.resolution()).toBe('existing') + }) + + it('reports created again for an unacknowledged key resolved by a fresh store', async () => { + // The durable state lives in the bridge (native), not in the store's + // in-process handle cache. A second store over the same bridge is what a + // relaunch looks like: an existing-but-unacknowledged key must NOT be + // reported as 'existing'. + const bridge = new FakeNativeBridge() + const first = await new NativeSecureKeyStore(bridge).resolveOrCreate(identity) + expect(first.resolution()).toBe('created') + + const afterRelaunch = await new NativeSecureKeyStore(bridge).resolveOrCreate(identity) + expect(afterRelaunch.resolution()).toBe('created') + + await afterRelaunch.acknowledgeRegistration() + const afterAck = await new NativeSecureKeyStore(bridge).resolveOrCreate(identity) + expect(afterAck.resolution()).toBe('existing') + }) + + it('does not re-enter native acknowledgement once the handle is existing', async () => { + let acks = 0 + const counting: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'created' + }, + async acknowledgeRegistration() { + acks += 1 + }, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(counting).resolveOrCreate(identity) + await key.acknowledgeRegistration() + await key.acknowledgeRegistration() + await key.acknowledgeRegistration() + expect(acks).toBe(1) + expect(key.resolution()).toBe('existing') + }) + + it('de-duplicates concurrent acknowledgement to a single native call', async () => { + let acks = 0 + let release: (() => void) | undefined + const gate = new Promise((resolve) => { + release = resolve + }) + const slow: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'created' + }, + async acknowledgeRegistration() { + acks += 1 + await gate // hold the call open so both callers overlap + }, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(slow).resolveOrCreate(identity) + const both = Promise.all([key.acknowledgeRegistration(), key.acknowledgeRegistration()]) + release?.() + await both + expect(acks).toBe(1) + expect(key.resolution()).toBe('existing') + }) + + it('retries acknowledgement after a failure rather than memoizing it', async () => { + let calls = 0 + const flakyAck: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'created' + }, + async acknowledgeRegistration() { + calls += 1 + if (calls === 1) throw new Error('kSecUseAuthenticationUI -25293') + }, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(flakyAck).resolveOrCreate(identity) + await expect(key.acknowledgeRegistration()).rejects.toBeInstanceOf(DaaError) + expect(key.resolution()).toBe('created') + // The failed attempt is not memoized: a retry reaches native and succeeds. + await expect(key.acknowledgeRegistration()).resolves.toBeUndefined() + expect(calls).toBe(2) + expect(key.resolution()).toBe('existing') + }) + + it('keeps the handle created when native acknowledgement fails, and maps the error', async () => { + const failing: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'created' + }, + async acknowledgeRegistration() { + throw new Error('SecItemUpdate OSStatus -25300') + }, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(failing).resolveOrCreate(identity) + const err = await key.acknowledgeRegistration().catch((e: unknown) => e) + expect(err).toBeInstanceOf(DaaError) + expect((err as DaaError).detail.kind).toBe('contract_violation') + expect((err as DaaError).message).not.toMatch(/OSStatus/) // raw native text suppressed + // Fail closed: a failed ack must not present the key as registered. + expect(key.resolution()).toBe('created') + }) + + it('rejects a native resolution other than created or existing', async () => { + const bad: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'maybe' as never + }, + async acknowledgeRegistration() {}, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + await expect(new NativeSecureKeyStore(bad).resolveOrCreate(identity)).rejects.toThrow( + /created or existing/, + ) + }) + + it('delegates signing across the bridge and yields a verifiable ES256 R||S', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + const key = await store.resolveOrCreate(identity) + const message = new TextEncoder().encode('{"idempotencyKey":"k"}') + const sig = await key.signExactBytes(message) + expect(sig.length).toBe(64) + + const spki = fromBase64Url(await key.publicKeySpkiBase64Url()) + const verifyKey = await globalThis.crypto.subtle.importKey( + 'spki', + toArrayBuffer(spki), + { name: 'ECDSA', namedCurve: 'P-256' }, + false, + ['verify'], + ) + const ok = await globalThis.crypto.subtle.verify( + { name: 'ECDSA', hash: 'SHA-256' }, + verifyKey, + toArrayBuffer(sig), + toArrayBuffer(message), + ) + expect(ok).toBe(true) + }) + + it('routes signRegistrationDeviceAuthorization through a distinct bridge call from signExactBytes', async () => { + const bridge = new FakeNativeBridge() + const store = new NativeSecureKeyStore(bridge) + const key = await store.resolveOrCreate(identity) + const message = new TextEncoder().encode('{"idempotencyKey":"k"}') + + const sig = await key.signRegistrationDeviceAuthorization(message) + expect(sig.length).toBe(64) + expect(bridge.registrationSignCalls).toBe(1) + + // The two AuthKey methods are not interchangeable: signExactBytes must not + // have reached the registration bridge call, and vice versa. + await key.signExactBytes(message) + expect(bridge.registrationSignCalls).toBe(1) + }) + + it('derives distinct thumbprints per environment namespace', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + const sandbox = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const production = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'production', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(await sandbox.thumbprint()).not.toBe(await production.thumbprint()) + }) + + it('derives distinct thumbprints per Owner namespace', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + const ownerA = await store.resolveOrCreate(identity) + const ownerB = await store.resolveOrCreate({ + ...identity, + clientEntityId: '00000000-0000-4000-8000-000000000002', + }) + expect(await ownerA.thumbprint()).not.toBe(await ownerB.thumbprint()) + }) + + it('maps a native failure to a DaaError without leaking its text, and evicts it', async () => { + let calls = 0 + const flaky: NativeSecureKeyBridge = { + async resolveOrCreate() { + calls += 1 + if (calls === 1) throw new Error('SecItemCopyMatching OSStatus -25300') + return 'existing' + }, + async acknowledgeRegistration() {}, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const store = new NativeSecureKeyStore(flaky) + const err = await store.resolveOrCreate(identity).catch((e: unknown) => e) + expect(err).toBeInstanceOf(DaaError) + expect((err as DaaError).detail.kind).toBe('contract_violation') + expect((err as DaaError).message).not.toMatch(/OSStatus/) // raw native text suppressed + // Not memoized: a second call succeeds. + await expect(store.resolveOrCreate(identity)).resolves.toBeDefined() + expect(calls).toBe(2) + }) + + it('de-duplicates concurrent resolution to a single native call', async () => { + const bridge = new FakeNativeBridge() + const store = new NativeSecureKeyStore(bridge) + const [a, b] = await Promise.all([ + store.resolveOrCreate(identity), + store.resolveOrCreate(identity), + ]) + expect(a).toBe(b) + expect(bridge.resolveCalls).toBe(1) + }) + + it('rejects a native signature that is not 64-byte R||S', async () => { + const derLike: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'existing' + }, + async acknowledgeRegistration() {}, + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + // 70 bytes — what a native module returns if it forgets DER -> R||S. + async sign() { + return toBase64Url(new Uint8Array(70)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(derLike).resolveOrCreate(identity) + await expect(key.signExactBytes(new Uint8Array([1, 2, 3]))).rejects.toThrow(/64 bytes/) + }) + + it('rejects a public key that is not a 91-byte P-256 SPKI', async () => { + const rawPoint: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'existing' + }, + async acknowledgeRegistration() {}, + // 65-byte uncompressed point instead of the 91-byte SPKI. + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(65)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(rawPoint).resolveOrCreate(identity) + await expect(key.publicKeySpkiBase64Url()).rejects.toThrow(/91 bytes/) + }) + + it('rejects a 91-byte public key that is not an uncompressed-point SPKI (thumbprint path)', async () => { + const notSpki: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'existing' + }, + async acknowledgeRegistration() {}, + // Right length, but byte 26 !== 0x04 — passes decodeExact, fails jkt. + async publicKeySpkiBase64Url() { + return toBase64Url(new Uint8Array(91)) + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(notSpki).resolveOrCreate(identity) + const err = await key.thumbprint().catch((e: unknown) => e) + expect(err).toBeInstanceOf(DaaError) + expect((err as DaaError).detail.kind).toBe('contract_violation') + }) + + it('rejects a native value that is not valid Base64URL', async () => { + const bad: NativeSecureKeyBridge = { + async resolveOrCreate() { + return 'existing' + }, + async acknowledgeRegistration() {}, + async publicKeySpkiBase64Url() { + return 'A' // length % 4 === 1 — impossible for Base64URL + }, + async sign() { + return toBase64Url(new Uint8Array(64)) + }, + async signRegistrationDeviceAuthorization() { + return toBase64Url(new Uint8Array(64)) + }, + } + const key = await new NativeSecureKeyStore(bad).resolveOrCreate(identity) + await expect(key.publicKeySpkiBase64Url()).rejects.toThrow(/not valid Base64URL/) + }) + + it('rejects an appId that is not a valid key namespace', async () => { + const store = new NativeSecureKeyStore(new FakeNativeBridge()) + await expect( + store.resolveOrCreate({ + appId: '', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }), + ).rejects.toThrow(/appId must match/) + }) +}) + +describe('resolveNativeBridge', () => { + const requireNative = jest.mocked(requireOptionalNativeModule) + + function nativeModule( + overrides: { + declaredKeyPolicy?: () => unknown + resolveOrCreate?: jest.Mock + publicKeySpkiBase64Url?: jest.Mock + acknowledgeRegistration?: jest.Mock + signDeviceAuthorization?: jest.Mock + signRegistrationDeviceAuthorization?: jest.Mock + } = {}, + ) { + return { + declaredKeyPolicy: () => DEVICE_KEY_POLICY, + resolveOrCreate: jest.fn(async () => 'created'), + publicKeySpkiBase64Url: jest.fn(async () => toBase64Url(new Uint8Array(91))), + acknowledgeRegistration: jest.fn(async () => undefined), + ...overrides, + } + } + + afterEach(() => { + requireNative.mockReset() + requireNative.mockImplementation(() => null) + }) + + it('fails closed when the native module is absent', () => { + requireNative.mockReturnValue(null) + expect(() => resolveNativeBridge()).toThrow(/not available/) + }) + + it('parses a dotted appId from the right and delegates resolve and SPKI', async () => { + const native = nativeModule() + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.resolveOrCreate('acme.staging.sandbox')).resolves.toBe('created') + expect(native.resolveOrCreate).toHaveBeenCalledWith('acme.staging', 'sandbox') + + await expect(bridge.publicKeySpkiBase64Url('acme.staging.sandbox')).resolves.toBe( + toBase64Url(new Uint8Array(91)), + ) + expect(native.publicKeySpkiBase64Url).toHaveBeenCalledWith('acme.staging', 'sandbox') + }) + + it('delegates acknowledgement to the native module as structured identity', async () => { + const native = nativeModule() + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.acknowledgeRegistration('acme.staging.sandbox')).resolves.toBeUndefined() + // The alias is split from the right, exactly as resolve and SPKI do, and + // reaches the acknowledgeRegistration(appId, environment) the Expo module + // exposes on both platforms. + expect(native.acknowledgeRegistration).toHaveBeenCalledWith('acme.staging', 'sandbox') + }) + + it('rejects acknowledgement for a malformed alias before calling native', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.acknowledgeRegistration('acme.mainnet')).rejects.toThrow( + /unknown environment/, + ) + expect(native.acknowledgeRegistration).not.toHaveBeenCalled() + }) + + it('surfaces a native acknowledgement rejection to the caller', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(async () => { + throw new Error('NOT_INITIALIZED') + }), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + // The bridge does not swallow it; NativeSecureKeyStore's guardNative maps it. + await expect(bridge.acknowledgeRegistration('acme.sandbox')).rejects.toThrow(/NOT_INITIALIZED/) + }) + + it('delegates sign to native signDeviceAuthorization with structured identity', async () => { + const signature = toBase64Url(new Uint8Array(64)) + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + signDeviceAuthorization: jest.fn(async () => signature), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.sign('acme.staging.sandbox', 'AAAA')).resolves.toBe(signature) + // Exactly three arguments: the native SDK sets all of the biometric prompt + // text from the validated operation, so the bridge passes none. + expect(native.signDeviceAuthorization).toHaveBeenCalledWith('acme.staging', 'sandbox', 'AAAA') + expect(native).not.toHaveProperty('sign') + }) + + it('rejects sign for a malformed alias before calling native', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + signDeviceAuthorization: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.sign('acme.mainnet', 'AAAA')).rejects.toThrow(/unknown environment/) + expect(native.signDeviceAuthorization).not.toHaveBeenCalled() + }) + + it('fail-closes sign when native signDeviceAuthorization is absent', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + const err = await bridge.sign('acme.sandbox', 'AAAA').catch((e: unknown) => e) + expect(isDaaError(err) && err.detail.kind === 'contract_violation').toBe(true) + expect(native).not.toHaveProperty('sign') + expect(native).not.toHaveProperty('signDeviceAuthorization') + }) + + it('fail-closes when native resolveOrCreate returns an unknown resolution', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(async () => 'rotated'), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect(bridge.resolveOrCreate('acme.sandbox')).rejects.toThrow(/unknown resolution/) + }) + + it('delegates registration signing to native signRegistrationDeviceAuthorization, a DIFFERENT native function from sign', async () => { + const signature = toBase64Url(new Uint8Array(64)) + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + signDeviceAuthorization: jest.fn(async () => { + throw new Error('signDeviceAuthorization should not be reached for registration') + }), + signRegistrationDeviceAuthorization: jest.fn(async () => signature), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect( + bridge.signRegistrationDeviceAuthorization('acme.staging.sandbox', 'AAAA'), + ).resolves.toBe(signature) + // No prompt text here either; see the signDeviceAuthorization case above. + expect(native.signRegistrationDeviceAuthorization).toHaveBeenCalledWith( + 'acme.staging', + 'sandbox', + 'AAAA', + ) + expect(native.signDeviceAuthorization).not.toHaveBeenCalled() + }) + + it('rejects registration signing for a malformed alias before calling native', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + signRegistrationDeviceAuthorization: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + await expect( + bridge.signRegistrationDeviceAuthorization('acme.mainnet', 'AAAA'), + ).rejects.toThrow(/unknown environment/) + expect(native.signRegistrationDeviceAuthorization).not.toHaveBeenCalled() + }) + + it('fail-closes registration signing when native signRegistrationDeviceAuthorization is absent', async () => { + const native = nativeModule({ + resolveOrCreate: jest.fn(), + publicKeySpkiBase64Url: jest.fn(), + acknowledgeRegistration: jest.fn(), + }) + requireNative.mockReturnValue(native) + + const bridge = resolveNativeBridge() + const err = await bridge + .signRegistrationDeviceAuthorization('acme.sandbox', 'AAAA') + .catch((e: unknown) => e) + expect(isDaaError(err) && err.detail.kind === 'contract_violation').toBe(true) + expect(native).not.toHaveProperty('signRegistrationDeviceAuthorization') + }) +}) diff --git a/src/__test__/node.d.ts b/src/__test__/node.d.ts new file mode 100644 index 0000000..59530df --- /dev/null +++ b/src/__test__/node.d.ts @@ -0,0 +1,62 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Minimal ambient declarations for the Node built-ins the tests need, and +// nothing else. Each is declared narrower than the real API so +// no test can reach past what it uses. The callers: +// +// - the conformance fixture loader, which reads a file off disk +// (`__dirname` + `node:fs`) +// - the redaction tests, which assert against what `console.log` prints +// (`node:util`) +// +// The repo has no declared `@types/node` and `tsconfig.json` limits `types` to +// `["jest"]` on purpose: production and native code must not be able to reach a +// Node API. Widening the global type set — or taking a dependency to get these few functions — would weaken +// that. +// These declarations are ambient, so despite living here they are visible to +// every file `tsconfig.json` includes — all of `src`, not just `src/__test__/`. +// `tsconfig.build.json` and `package.json#files` exclude `src/__test__/`, which +// keeps them out of a consumer's build but does not stop production code +// type-checking against them. The `no-restricted-imports` rule in +// `eslint.config.js` is what actually holds the invariant, at the lint step. + +declare const __dirname: string + +declare module 'node:fs' { + export function readFileSync(path: string): Uint8Array +} + +// `util.inspect` is what Node's `console.log` renders an object with, so the +// redaction tests assert against it rather than only against `JSON.stringify`. +declare module 'node:util' { + export function inspect( + value: unknown, + options?: { depth?: number | null; showHidden?: boolean; getters?: boolean }, + ): string +} + +// `require.cache` keys are the absolute paths of every module loaded so far. +// One test-only caller: the `./testing` entry asserts that importing it does not +// transitively pull in React, which is what keeps the test doubles usable from a +// plain node test environment. Declared as the narrowest thing that answers "was +// this loaded?" — a set of paths — rather than the real +// `Record`, so nothing can reach a loaded module through it. +declare const require: { + cache: Record +} diff --git a/src/__test__/payload.test.ts b/src/__test__/payload.test.ts new file mode 100644 index 0000000..54d1b85 --- /dev/null +++ b/src/__test__/payload.test.ts @@ -0,0 +1,94 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + asObject, + MalformedPayloadError, + optionalNonNegativeInteger, + optionalNonNegativeNumber, + optionalObject, + optionalString, + requiredNonNegativeInteger, + requiredString, + unrecognized, +} from '../wire/payload' + +describe('payload primitives', () => { + it('rejects non-object payloads', () => { + for (const value of [null, [], 'text', 1]) { + expect(() => asObject(value, 'payload')).toThrow(MalformedPayloadError) + } + }) + + it('reads optional strings and treats omitted or null fields as absent', () => { + expect(optionalString({}, 'value')).toBeNull() + expect(optionalString({ value: null }, 'value')).toBeNull() + expect(optionalString({ value: 'ok' }, 'value')).toBe('ok') + expect(() => optionalString({ value: 1 }, 'value', 'label')).toThrow('label') + }) + + it('reads optional objects and treats omitted or null fields as absent', () => { + expect(optionalObject({}, 'value')).toBeNull() + expect(optionalObject({ value: null }, 'value')).toBeNull() + expect(optionalObject({ value: { nested: true } }, 'value')).toEqual({ nested: true }) + expect(() => optionalObject({ value: [] }, 'value')).toThrow(MalformedPayloadError) + expect(() => optionalObject({ value: 'nope' }, 'value')).toThrow('value') + }) + + it('requires a string field', () => { + expect(requiredString({ value: 'ok' }, 'value')).toBe('ok') + expect(() => requiredString({}, 'value')).toThrow(MalformedPayloadError) + expect(() => requiredString({ value: null }, 'value')).toThrow(MalformedPayloadError) + }) + + it('creates a frozen unrecognized arm that preserves the raw value', () => { + const value = unrecognized('__proto__') + expect(value).toEqual({ kind: 'unrecognized', rawValue: '__proto__' }) + expect(Object.isFrozen(value)).toBe(true) + }) + + it('requires a non-negative integer field, sent as a JSON number', () => { + expect(requiredNonNegativeInteger({ value: 0 }, 'value')).toBe(0) + expect(requiredNonNegativeInteger({ value: 5000000 }, 'value')).toBe(5000000) + expect(() => requiredNonNegativeInteger({}, 'value')).toThrow(MalformedPayloadError) + expect(() => requiredNonNegativeInteger({ value: null }, 'value')).toThrow( + MalformedPayloadError, + ) + expect(() => requiredNonNegativeInteger({ value: -1 }, 'value')).toThrow(MalformedPayloadError) + expect(() => requiredNonNegativeInteger({ value: 1.5 }, 'value')).toThrow(MalformedPayloadError) + expect(() => requiredNonNegativeInteger({ value: '5' }, 'value', 'label')).toThrow('label') + }) + + it('reads an optional non-negative integer field and treats omitted or null as absent', () => { + expect(optionalNonNegativeInteger({}, 'value')).toBeNull() + expect(optionalNonNegativeInteger({ value: null }, 'value')).toBeNull() + expect(optionalNonNegativeInteger({ value: 7 }, 'value')).toBe(7) + expect(() => optionalNonNegativeInteger({ value: -1 }, 'value')).toThrow(MalformedPayloadError) + }) + + it('reads an optional non-negative decimal field and treats omitted or null as absent', () => { + expect(optionalNonNegativeNumber({}, 'value')).toBeNull() + expect(optionalNonNegativeNumber({ value: null }, 'value')).toBeNull() + expect(optionalNonNegativeNumber({ value: 24.69 }, 'value')).toBe(24.69) + expect(optionalNonNegativeNumber({ value: 0 }, 'value')).toBe(0) + expect(() => optionalNonNegativeNumber({ value: -0.01 }, 'value')).toThrow( + MalformedPayloadError, + ) + expect(() => optionalNonNegativeNumber({ value: '1' }, 'value', 'label')).toThrow('label') + }) +}) diff --git a/src/__test__/prepareReceipt.test.ts b/src/__test__/prepareReceipt.test.ts new file mode 100644 index 0000000..33b851e --- /dev/null +++ b/src/__test__/prepareReceipt.test.ts @@ -0,0 +1,545 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { + PARENT_ENTITY_ID_DIGEST_DOMAIN, + PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS, + PREPARE_RECEIPT_MAX_LENGTH, + PREPARE_RECEIPT_MIN_LENGTH, + PREPARE_RECEIPT_TYP, + checkPrepareReceipt, + isPrepareReceiptShape, + parentEntityIdDigest, + pinnedPrepareReceiptTrustAnchor, + requirePrepareReceiptTenantScope, + verifyPrepareReceipt, + type PrepareReceiptExpectation, + type PrepareReceiptTrustAnchor, +} from '../auth/prepareReceipt' +import { DAA_ENVIRONMENTS } from '../config' +import { fromBase64Url } from '../crypto/base64url' +import { + requireDaaRegistrationNative, + type DaaRegistrationNativeModule, +} from '../auth/daaRegistrationNative' +import { isDaaError } from '../errors' +import { + generateReceiptSigningKey, + receiptClaims, + signReceipt, + trustAnchorFor, + type ReceiptSigningKey, +} from './prepareReceiptSigning' + +/** + * The Prepare receipt: shape, the anchor/receipt decision table, and claim + * binding against the claim set DAA signs. Signatures go through the platform + * verifier, which in Jest is `jest.setup.js`'s WebCrypto stand-in. + */ + +const NOW = 1_790_000_000 +const clock = { nowEpochSeconds: () => NOW } + +const EXPECTED: PrepareReceiptExpectation = { + loginRequestId: '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + nonce: 'V3dQJq2pX2-t70oIlt0EX7I6oZLo_id94-43ywbCAL8', + provider: 'GOOGLE', + environment: 'sandbox', + registrationCodeChallenge: 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM', + registrationFlowKeyThumbprint: 'xx0BcA-wMohw8atYDJOe6peGModklG2wRHBlXHMvl0M', +} + +let key: ReceiptSigningKey +let anchor: PrepareReceiptTrustAnchor + +beforeAll(async () => { + key = await generateReceiptSigningKey('prepare-receipt-sandbox-1') + anchor = trustAnchorFor([key]) +}) + +async function receipt( + overrides: Record = {}, + header: Record = {}, +) { + return signReceipt(key, receiptClaims(EXPECTED, NOW, overrides), header) +} + +/** + * The message of the expected rejection. A rejected receipt is + * `prepare_receipt_invalid`; a fault in the SDK's own anchor, expectation, or + * clock is `contract_violation`. Any other outcome fails the test. + */ +async function rejection( + operation: Promise, + kind: 'prepare_receipt_invalid' | 'contract_violation' = 'prepare_receipt_invalid', +): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err) && err.detail.kind === kind) { + expect(err.detail).toEqual({ kind }) + return err.message + } + throw err + } + throw new Error('expected the receipt to be rejected') +} + +function jws(payloadLength: number): string { + return `eyJhbGciOiJFUzI1NiJ9.${'a'.repeat(payloadLength)}.c2ln` +} + +const VALID = jws(64) + +describe('isPrepareReceiptShape', () => { + it('accepts a compact JWS inside the contract length bounds', () => { + expect(VALID.length).toBeGreaterThanOrEqual(PREPARE_RECEIPT_MIN_LENGTH) + expect(isPrepareReceiptShape(VALID)).toBe(true) + }) + + it('rejects a value shorter than the contract minimum', () => { + const short = jws(1) + expect(short.length).toBeLessThan(PREPARE_RECEIPT_MIN_LENGTH) + expect(isPrepareReceiptShape(short)).toBe(false) + }) + + it('rejects a value longer than the contract maximum', () => { + expect(isPrepareReceiptShape(jws(PREPARE_RECEIPT_MAX_LENGTH))).toBe(false) + }) + + it('rejects anything that is not three Base64URL segments', () => { + for (const value of [ + '', // empty + `${'a'.repeat(80)}`, // no separators + `${'a'.repeat(40)}.${'b'.repeat(40)}`, // two segments (unsecured JWS shape) + `${'a'.repeat(30)}.${'b'.repeat(30)}.${'c'.repeat(30)}.${'d'.repeat(30)}`, // four (JWE) + `${'a'.repeat(30)}..${'c'.repeat(40)}`, // empty middle segment + `${'a'.repeat(30)}.${'b+/'.repeat(20)}.${'c'.repeat(30)}`, // standard Base64, not URL + `${'a'.repeat(30)}.${'b'.repeat(30)}.${'c'.repeat(30)}=`, // padded + ]) { + expect(isPrepareReceiptShape(value)).toBe(false) + } + }) +}) + +describe('pinnedPrepareReceiptTrustAnchor', () => { + it('is unset for every environment', () => { + for (const environment of DAA_ENVIRONMENTS) { + expect(pinnedPrepareReceiptTrustAnchor(environment)).toBeNull() + } + }) +}) + +describe('checkPrepareReceipt', () => { + const noExpectation = (): never => { + throw new Error('no expectation is computed without an anchor') + } + + it('anchor unset, no receipt: nothing to verify, and nothing is computed', async () => { + await expect(checkPrepareReceipt(null, null, noExpectation)).resolves.toBeNull() + }) + + it('anchor unset, receipt present: ignored without being read, and login proceeds', async () => { + // A valid receipt, a malformed one, and values of the wrong type all come + // back as no receipt: with no anchor, nothing about the receipt is examined. + for (const present of [await receipt(), 'not-a-jws', '', 42, { alg: 'none' }]) { + await expect(checkPrepareReceipt(present, null, noExpectation)).resolves.toBeNull() + } + }) + + it('anchor set, no receipt: fails closed, because the receipt is required', async () => { + const message = await rejection(checkPrepareReceipt(null, anchor, () => EXPECTED, clock)) + expect(message).toMatch(/requires one/) + }) + + it('anchor set, receipt present: verifies it', async () => { + const verified = await checkPrepareReceipt(await receipt(), anchor, () => EXPECTED, clock) + expect(verified).toMatchObject({ + loginRequestId: EXPECTED.loginRequestId, + nonce: EXPECTED.nonce, + expiresAtEpochSeconds: NOW + 600, + }) + }) + + it('anchor set, receipt present but wrong: fails closed', async () => { + const wrong = await receipt({ registrationCodeChallenge: 'x'.repeat(43) }) + await rejection(checkPrepareReceipt(wrong, anchor, () => EXPECTED, clock)) + }) + + it('anchor set, receipt present but not a string: fails closed', async () => { + for (const notAString of [42, { alg: 'none' }, ['a', 'b', 'c']]) { + expect( + await rejection(checkPrepareReceipt(notAString, anchor, () => EXPECTED, clock)), + ).toMatch(/not a compact JWS/) + } + }) +}) + +describe('verifyPrepareReceipt claim binding', () => { + it('accepts the full claim set DAA signs, under its header', async () => { + const jws = await receipt() + const [encodedHeader] = jws.split('.') as [string] + expect(JSON.parse(new TextDecoder().decode(fromBase64Url(encodedHeader)))).toEqual({ + typ: PREPARE_RECEIPT_TYP, + kid: key.kid, + alg: 'ES256', + }) + const verified = await verifyPrepareReceipt(jws, anchor, EXPECTED, clock) + expect(verified.tenantScope).toEqual({ + customerAppId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + parentEntityIdDigest: 'RWVw0KJgIFpk0F50hV4BAIdY983ge-AkxlZeWxSShMs', + }) + }) + + it.each([ + ['registrationCodeChallenge', 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cN'], + ['registrationFlowKeyThumbprint', 'xx0BcA-wMohw8atYDJOe6peGModklG2wRHBlXHMvl0N'], + ['loginRequestId', '9f6ead8b-ff88-43fc-af00-7016eef7f4b3'], + ['nonce', 'another-attempts-nonce-another-attempts-non'], + ['provider', 'APPLE'], + ['environment', 'production'], + ['iss', 'https://elsewhere.invalid'], + ['aud', 'another-audience'], + ])('rejects a receipt that binds a different %s', async (name, value) => { + const message = await rejection( + verifyPrepareReceipt(await receipt({ [name]: value }), anchor, EXPECTED, clock), + ) + expect(message).toMatch(new RegExp(`expected ${name}$`)) + }) + + it.each([ + 'registrationCodeChallenge', + 'registrationFlowKeyThumbprint', + 'loginRequestId', + 'nonce', + 'provider', + 'environment', + 'iss', + 'aud', + 'jti', + ])('rejects a receipt with no %s', async (name) => { + const message = await rejection( + verifyPrepareReceipt(await receipt({ [name]: undefined }), anchor, EXPECTED, clock), + ) + expect(message).toMatch(new RegExp(name)) + }) + + it('reads nonce, not oidcNonce: other claim names do not verify', async () => { + const placeholder = await receipt({ + nonce: undefined, + oidcNonce: EXPECTED.nonce, + oidcState: 'state', + }) + const message = await rejection(verifyPrepareReceipt(placeholder, anchor, EXPECTED, clock)) + expect(message).toMatch(/expected nonce$/) + }) + + it('does not require a state claim, because DAA signs none', async () => { + const claims = receiptClaims(EXPECTED, NOW) + expect(Object.keys(claims).some((name) => /state/i.test(name))).toBe(false) + await expect( + verifyPrepareReceipt(await receipt(), anchor, EXPECTED, clock), + ).resolves.toBeDefined() + }) + + it('accepts aud as an array that contains the anchor audience', async () => { + const jws = await receipt({ aud: ['other', anchor.audience] }) + await expect(verifyPrepareReceipt(jws, anchor, EXPECTED, clock)).resolves.toBeDefined() + }) + + it('does not read a claim inherited from Object.prototype', async () => { + const polluted = Object.prototype as Record + polluted['nonce'] = EXPECTED.nonce + try { + const message = await rejection( + verifyPrepareReceipt(await receipt({ nonce: undefined }), anchor, EXPECTED, clock), + ) + expect(message).toMatch(/expected nonce$/) + } finally { + delete polluted['nonce'] + } + }) + + it('rejects a receipt signed by a key the anchor does not pin', async () => { + const stranger = await generateReceiptSigningKey(key.kid) + const jws = await signReceipt(stranger, receiptClaims(EXPECTED, NOW)) + expect(await rejection(verifyPrepareReceipt(jws, anchor, EXPECTED, clock))).toMatch( + /signature_mismatch/, + ) + }) + + it('rejects a receipt with another typ or alg', async () => { + expect( + await rejection( + verifyPrepareReceipt(await receipt({}, { typ: 'JWT' }), anchor, EXPECTED, clock), + ), + ).toMatch(/unexpected_type/) + expect( + await rejection( + verifyPrepareReceipt(await receipt({}, { alg: 'none' }), anchor, EXPECTED, clock), + ), + ).toMatch(/unsupported_algorithm/) + }) + + it('never puts the receipt into the error a consumer would log', async () => { + const jws = await receipt({ nonce: 'SECRETRECEIPTMARKER'.repeat(3) }) + try { + await verifyPrepareReceipt(jws, anchor, EXPECTED, clock) + } catch (err) { + expect((err as Error).message).not.toMatch(/SECRETRECEIPTMARKER/) + expect(JSON.stringify(err)).not.toMatch(/SECRETRECEIPTMARKER/) + expect((err as Error).message).not.toContain(jws.split('.')[1]!) + return + } + throw new Error('expected the receipt to be rejected') + }) +}) + +describe('verifyPrepareReceipt time claims', () => { + const skew = 60 + + it('accepts a receipt expiring within the clock allowance', async () => { + const jws = await receipt({ iat: NOW - 700, exp: NOW - skew }) + await expect(verifyPrepareReceipt(jws, anchor, EXPECTED, clock)).resolves.toBeDefined() + }) + + it('rejects a receipt expired beyond the allowance', async () => { + const jws = await receipt({ iat: NOW - 700, exp: NOW - skew - 1 }) + expect(await rejection(verifyPrepareReceipt(jws, anchor, EXPECTED, clock))).toMatch(/expired/) + }) + + it('rejects an iat or nbf in the future beyond the allowance', async () => { + expect( + await rejection( + verifyPrepareReceipt(await receipt({ iat: NOW + skew + 1 }), anchor, EXPECTED, clock), + ), + ).toMatch(/iat is in the future/) + expect( + await rejection( + verifyPrepareReceipt(await receipt({ nbf: NOW + skew + 1 }), anchor, EXPECTED, clock), + ), + ).toMatch(/nbf is in the future/) + await expect( + verifyPrepareReceipt(await receipt({ iat: NOW + skew }), anchor, EXPECTED, clock), + ).resolves.toBeDefined() + }) + + it('rejects a receipt that expires before it was issued', async () => { + const jws = await receipt({ iat: NOW, exp: NOW - 1 }) + expect(await rejection(verifyPrepareReceipt(jws, anchor, EXPECTED, clock))).toMatch( + /before it was issued/, + ) + }) + + it('requires exp and iat as integer seconds, and rejects milliseconds', async () => { + for (const [name, value] of [ + ['exp', undefined], + ['iat', undefined], + ['exp', (NOW + 600) * 1000], + ['exp', 'soon'], + ['iat', NOW + 0.5], + ['exp', 0], + ] as const) { + const message = await rejection( + verifyPrepareReceipt(await receipt({ [name]: value }), anchor, EXPECTED, clock), + ) + expect(message).toMatch(new RegExp(name)) + } + }) +}) + +describe('verifyPrepareReceipt configuration faults', () => { + it('refuses a malformed anchor', async () => { + const jws = await receipt() + for (const bad of [ + { ...anchor, issuer: '' }, + { ...anchor, audience: '' }, + { ...anchor, verificationKeys: [] }, + { ...anchor, maxClockSkewSeconds: PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS + 1 }, + { ...anchor, maxClockSkewSeconds: -1 }, + { ...anchor, verificationKeys: [{ kid: key.kid, jwk: { ...key.jwk, crv: 'P-384' } }] }, + { + ...anchor, + verificationKeys: [{ kid: key.kid, jwk: { ...key.jwk, x: key.jwk.x.slice(1) } }], + }, + ] as PrepareReceiptTrustAnchor[]) { + expect( + await rejection(verifyPrepareReceipt(jws, bad, EXPECTED, clock), 'contract_violation'), + ).toMatch(/trust anchor|verification key|pinned/) + } + }) + + it('refuses an incomplete expectation', async () => { + const jws = await receipt() + for (const name of Object.keys(EXPECTED) as (keyof PrepareReceiptExpectation)[]) { + const expected = { ...EXPECTED, [name]: '' } + expect( + await rejection(verifyPrepareReceipt(jws, anchor, expected, clock), 'contract_violation'), + ).toMatch(new RegExp(`requires the expected ${name}`)) + } + }) + + it('refuses an anchor whose keys lack distinct, non-empty kids', async () => { + const jws = await receipt() + const pinnedKey = anchor.verificationKeys[0]! + for (const verificationKeys of [ + [{ ...pinnedKey, kid: '' }], + [pinnedKey, pinnedKey], + ] as PrepareReceiptTrustAnchor['verificationKeys'][]) { + expect( + await rejection( + verifyPrepareReceipt(jws, { ...anchor, verificationKeys }, EXPECTED, clock), + 'contract_violation', + ), + ).toMatch(/kid/) + } + }) + + it('refuses a clock that is not a positive Unix timestamp', async () => { + const jws = await receipt() + for (const now of [0, -1, 1.5, Number.NaN]) { + expect( + await rejection( + verifyPrepareReceipt(jws, anchor, EXPECTED, { nowEpochSeconds: () => now }), + 'contract_violation', + ), + ).toMatch(/positive Unix timestamp/) + } + }) + + it('refuses a receipt outside the contract bounds before touching the signature', async () => { + expect(await rejection(verifyPrepareReceipt('a.b.c', anchor, EXPECTED, clock))).toMatch( + /length bounds/, + ) + }) +}) + +describe('verifyPrepareReceipt without a working platform verifier', () => { + const requireNative = requireOptionalNativeModule as jest.Mock + const defaultNativeImpl = requireNative.getMockImplementation() + + afterEach(() => { + requireNative.mockReset() + if (defaultNativeImpl !== undefined) { + requireNative.mockImplementation(defaultNativeImpl) + } + }) + + function withNative(native: Partial | null): void { + requireNative.mockImplementation(() => native) + } + + it('is prepare_receipt_invalid with no DaaRegistration module', async () => { + const jws = await receipt() + withNative(null) + expect(await rejection(verifyPrepareReceipt(jws, anchor, EXPECTED, clock))).toMatch( + /DaaRegistration module is not available/, + ) + }) + + it('is prepare_receipt_invalid on a module that predates the verify function', async () => { + const jws = await receipt() + const withoutVerify: Partial = { + ...requireDaaRegistrationNative(), + } + delete withoutVerify.verifyPrepareReceiptSignature + withNative(withoutVerify) + expect(await rejection(verifyPrepareReceipt(jws, anchor, EXPECTED, clock))).toMatch( + /verifyPrepareReceiptSignature is required/, + ) + }) + + it('is prepare_receipt_invalid when the platform verifier rejects, keeping the cause', async () => { + const jws = await receipt() + const nativeFailure = new Error('native verifier failed') + withNative({ + ...requireDaaRegistrationNative(), + verifyPrepareReceiptSignature: jest.fn(async () => { + throw nativeFailure + }), + }) + try { + await verifyPrepareReceipt(jws, anchor, EXPECTED, clock) + } catch (err) { + expect(isDaaError(err) && err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + expect((err as Error).message).toMatch(/signature verification failed/) + expect((err as Error).message).not.toContain('native verifier failed') + expect(isDaaError((err as { cause?: unknown }).cause)).toBe(true) + return + } + throw new Error('expected the receipt to be rejected') + }) +}) + +describe('tenant scope', () => { + it('pins parentEntityIdDigest to the golden vector DAA publishes', () => { + expect(PARENT_ENTITY_ID_DIGEST_DOMAIN).toBe('daa-prepare-receipt-parent-entity-digest-v1\u0000') + expect(parentEntityIdDigest('3fa85f64-5717-4562-b3fc-2c963f66afa6')).toBe( + 'RWVw0KJgIFpk0F50hV4BAIdY983ge-AkxlZeWxSShMs', + ) + }) + + it('refuses a parent entity id that is not a canonical lower-case UUID', () => { + for (const value of [ + '3FA85F64-5717-4562-B3FC-2C963F66AFA6', + '3fa85f6457174562b3fc2c963f66afa6', + '', + ]) { + expect(() => parentEntityIdDigest(value)).toThrow(/canonical lower-case UUID/) + } + }) + + it('compares both tenant claims when a caller supplies the expected scope', async () => { + const verified = await verifyPrepareReceipt(await receipt(), anchor, EXPECTED, clock) + const scope = { + customerAppId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + parentEntityId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + } + expect(() => requirePrepareReceiptTenantScope(verified, scope)).not.toThrow() + expect(() => + requirePrepareReceiptTenantScope(verified, { ...scope, customerAppId: 'another-app' }), + ).toThrow(/expected customerAppId/) + try { + requirePrepareReceiptTenantScope(verified, { ...scope, customerAppId: 'another-app' }) + } catch (err) { + expect(isDaaError(err) && err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + } + expect(() => + requirePrepareReceiptTenantScope(verified, { + ...scope, + parentEntityId: '00000000-0000-4000-8000-000000000001', + }), + ).toThrow(/expected parentEntityIdDigest/) + }) + + it('rejects a receipt missing either tenant claim when the comparison is used', async () => { + const verified = await verifyPrepareReceipt( + await receipt({ parentEntityIdDigest: undefined }), + anchor, + EXPECTED, + clock, + ) + expect(() => + requirePrepareReceiptTenantScope(verified, { + customerAppId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + parentEntityId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + }), + ).toThrow(/expected parentEntityIdDigest/) + }) +}) diff --git a/src/__test__/prepareReceiptSigning.ts b/src/__test__/prepareReceiptSigning.ts new file mode 100644 index 0000000..9660e08 --- /dev/null +++ b/src/__test__/prepareReceiptSigning.ts @@ -0,0 +1,134 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Receipt-signing material for tests: a WebCrypto P-256 key standing in for +// DAA's receipt-signing key, and a compact-JWS signer that emits the receipt +// DAA signs. +// +// Not a test file — Jest's `testMatch` is `**/__test__/**/*.test.ts`, so this +// module is only ever imported, never collected. + +import { + PREPARE_RECEIPT_TYP, + type PrepareReceiptExpectation, + type PrepareReceiptTrustAnchor, +} from '../auth/prepareReceipt' +import { toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import type { P256PublicJwk } from '../crypto/jwkThumbprint' + +export type ReceiptSigningKey = Readonly<{ + kid: string + privateKey: CryptoKey + jwk: P256PublicJwk + x963: Uint8Array +}> + +export async function generateReceiptSigningKey(kid = 'receipt-key-1'): Promise { + const pair = (await globalThis.crypto.subtle.generateKey( + { name: 'ECDSA', namedCurve: 'P-256' }, + true, + ['sign', 'verify'], + )) as CryptoKeyPair + const x963 = new Uint8Array(await globalThis.crypto.subtle.exportKey('raw', pair.publicKey)) + return { + kid, + privateKey: pair.privateKey, + jwk: { + kty: 'EC', + crv: 'P-256', + x: toBase64Url(x963.subarray(1, 33)), + y: toBase64Url(x963.subarray(33, 65)), + }, + x963, + } +} + +export function encodeJsonSegment(value: unknown): string { + return toBase64Url(new TextEncoder().encode(JSON.stringify(value))) +} + +/** Sign an arbitrary header/payload pair into a compact JWS. */ +export async function signCompactJws( + key: ReceiptSigningKey, + header: Record, + payload: unknown, +): Promise { + const signingInput = `${encodeJsonSegment(header)}.${encodeJsonSegment(payload)}` + const signature = new Uint8Array( + await globalThis.crypto.subtle.sign( + { name: 'ECDSA', hash: 'SHA-256' }, + key.privateKey, + toArrayBuffer(new TextEncoder().encode(signingInput)), + ), + ) + return `${signingInput}.${toBase64Url(signature)}` +} + +export const RECEIPT_ISSUER = 'https://daa.example.invalid' +export const RECEIPT_AUDIENCE = 'daa-sdk.example.invalid' + +export function trustAnchorFor( + keys: readonly ReceiptSigningKey[], + overrides: Partial = {}, +): PrepareReceiptTrustAnchor { + return { + issuer: RECEIPT_ISSUER, + audience: RECEIPT_AUDIENCE, + verificationKeys: keys.map((key) => ({ kid: key.kid, jwk: key.jwk })), + maxClockSkewSeconds: 60, + ...overrides, + } +} + +/** Every claim DAA's signer sets, bound to `expected`. */ +export function receiptClaims( + expected: PrepareReceiptExpectation, + nowEpochSeconds: number, + overrides: Record = {}, +): Record { + return { + iss: RECEIPT_ISSUER, + aud: RECEIPT_AUDIENCE, + jti: '6f1c2d3e-4b5a-4c6d-8e7f-0a1b2c3d4e5f', + environment: expected.environment, + customerAppId: '3fa85f64-5717-4562-b3fc-2c963f66afa6', + parentEntityIdDigest: 'RWVw0KJgIFpk0F50hV4BAIdY983ge-AkxlZeWxSShMs', + provider: expected.provider, + loginRequestId: expected.loginRequestId, + nonce: expected.nonce, + registrationCodeChallenge: expected.registrationCodeChallenge, + registrationFlowKeyThumbprint: expected.registrationFlowKeyThumbprint, + iat: nowEpochSeconds, + exp: nowEpochSeconds + 600, + ...overrides, + } +} + +/** A receipt with DAA's header: `typ`, `kid`, `alg`. */ +export async function signReceipt( + key: ReceiptSigningKey, + claims: Record, + header: Record = {}, +): Promise { + return signCompactJws( + key, + { typ: PREPARE_RECEIPT_TYP, kid: key.kid, alg: 'ES256', ...header }, + claims, + ) +} diff --git a/src/__test__/random.test.ts b/src/__test__/random.test.ts new file mode 100644 index 0000000..0a2b0a7 --- /dev/null +++ b/src/__test__/random.test.ts @@ -0,0 +1,214 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { toBase64Url } from '../crypto/base64url' +import { + randomBytes, + randomUuidV4, + webCryptoRandomBytes, + webCryptoRandomUuidV4, +} from '../crypto/random' +import { isDaaError } from '../errors' +import { isUuidV4 } from '../validation/uuid' +import type { DaaRegistrationNativeModule } from '../auth/daaRegistrationNative' + +/** + * The randomness source. + * + * Production `randomBytes` / `randomUuidV4` require the Expo module. Jest + * injects a fake in `jest.setup.js`. Host WebCrypto is covered only through + * the explicit `webCryptoRandom*` helpers. + */ + +const requireNative = jest.mocked(requireOptionalNativeModule) +const defaultNativeImpl = requireNative.getMockImplementation() + +afterEach(() => { + requireNative.mockReset() + if (defaultNativeImpl !== undefined) { + requireNative.mockImplementation(defaultNativeImpl) + } +}) + +function withHostCrypto(replacement: Partial | undefined, operation: () => T): T { + const host = globalThis as { crypto: Crypto | undefined } + const original = host.crypto + host.crypto = replacement as Crypto | undefined + try { + return operation() + } finally { + host.crypto = original + } +} + +function fakeRegistrationNative( + overrides: Partial = {}, +): DaaRegistrationNativeModule { + return { + randomBytes: jest.fn((count: number) => toBase64Url(new Uint8Array(count).fill(7))), + randomUuidV4: jest.fn(() => '0192d5c8-8f1a-4b2e-9c7d-3a5e2f6b1c04'), + generateRegistrationFlowKey: jest.fn(() => 'flow-key-id'), + registrationFlowPublicKeySpkiBase64Url: jest.fn(() => toBase64Url(new Uint8Array(91))), + releaseRegistrationFlowKey: jest.fn(), + signRegistrationAuthorization: jest.fn(() => toBase64Url(new Uint8Array(64))), + verifyPrepareReceiptSignature: jest.fn(async () => false), + ...overrides, + } +} + +describe('randomBytes', () => { + it('fills the requested length from the native module', () => { + expect(randomBytes(1)).toHaveLength(1) + expect(randomBytes(32)).toHaveLength(32) + }) + + it('rejects a length that is not a positive integer', () => { + for (const length of [0, -1, 1.5, Number.NaN]) { + expect(() => randomBytes(length)).toThrow(/positive integer/) + } + }) + + it('uses native DaaSecureRandom and does not call getRandomValues', () => { + const native = fakeRegistrationNative() + requireNative.mockImplementation((name: string) => (name === 'DaaRegistration' ? native : null)) + const getRandomValues = jest.fn() + withHostCrypto({ getRandomValues }, () => { + const bytes = randomBytes(32) + expect(bytes).toHaveLength(32) + expect(Array.from(bytes)).toEqual(Array(32).fill(7)) + expect(native.randomBytes).toHaveBeenCalledWith(32) + }) + expect(getRandomValues).not.toHaveBeenCalled() + }) + + it('fails closed when the Expo module is absent, rather than using WebCrypto', () => { + requireNative.mockImplementation(() => null) + const getRandomValues = jest.fn() + try { + withHostCrypto({ getRandomValues }, () => randomBytes(32)) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/native DaaRegistration module is not available/) + expect(getRandomValues).not.toHaveBeenCalled() + return + } + throw new Error('expected randomBytes to fail closed without native module') + }) +}) + +describe('webCryptoRandomBytes', () => { + it('fails closed with no getRandomValues, rather than falling back to Math.random', () => { + for (const replacement of [undefined, {}, { getRandomValues: 'nope' as unknown as never }]) { + try { + withHostCrypto(replacement, () => webCryptoRandomBytes(32)) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/^DAA: crypto\.getRandomValues is required/) + continue + } + throw new Error('expected webCryptoRandomBytes to fail closed') + } + }) +}) + +describe('randomUuidV4', () => { + it('passes the SDK guard the prepare idempotencyKey has to pass', () => { + for (let i = 0; i < 64; i++) { + expect(isUuidV4(randomUuidV4())).toBe(true) + } + }) + + it('is fresh per call', () => { + const uuids = new Set() + for (let i = 0; i < 64; i++) { + uuids.add(randomUuidV4()) + } + expect(uuids.size).toBe(64) + }) + + it('uses the native module UUID, not crypto.randomUUID', () => { + const native = fakeRegistrationNative() + requireNative.mockImplementation((name: string) => (name === 'DaaRegistration' ? native : null)) + const randomUUID = jest.fn( + () => + '00000000-0000-4000-8000-000000000000' as `${string}-${string}-${string}-${string}-${string}`, + ) + const uuid = withHostCrypto({ randomUUID }, () => randomUuidV4()) + expect(uuid).toBe('0192d5c8-8f1a-4b2e-9c7d-3a5e2f6b1c04') + expect(randomUUID).not.toHaveBeenCalled() + }) + + it('fails closed when the Expo module is absent', () => { + requireNative.mockImplementation(() => null) + try { + randomUuidV4() + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/native DaaRegistration module is not available/) + return + } + throw new Error('expected randomUuidV4 to fail closed without native module') + }) +}) + +describe('webCryptoRandomUuidV4', () => { + it('delegates to crypto.randomUUID instead of assembling a UUID here', () => { + const canned = '0192d5c8-8f1a-4b2e-9c7d-3a5e2f6b1c04' + const randomUUID = jest.fn(() => canned as `${string}-${string}-${string}-${string}-${string}`) + + const uuid = withHostCrypto({ randomUUID }, () => webCryptoRandomUuidV4()) + + expect(randomUUID).toHaveBeenCalledTimes(1) + expect(uuid).toBe(canned) + }) + + it('fails closed when the host provides no randomUUID', () => { + for (const replacement of [undefined, {}, { randomUUID: 'nope' as unknown as never }]) { + try { + withHostCrypto(replacement, () => webCryptoRandomUuidV4()) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/^DAA: crypto\.randomUUID is required/) + continue + } + throw new Error('expected webCryptoRandomUuidV4 to fail closed') + } + }) + + it('fails closed when a polyfill returns a malformed or non-v4 value', () => { + const bad = [ + '', + 'not-a-uuid', + '0192d5c8-8f1a-1b2e-9c7d-3a5e2f6b1c04', + '0192d5c8-8f1a-4b2e-0c7d-3a5e2f6b1c04', + '0192d5c88f1a4b2e9c7d3a5e2f6b1c04', + ] + for (const value of bad) { + const randomUUID = jest.fn(() => value as `${string}-${string}-${string}-${string}-${string}`) + try { + withHostCrypto({ randomUUID }, () => webCryptoRandomUuidV4()) + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).toMatch(/did not return an RFC 4122 version 4 UUID/) + continue + } + throw new Error(`expected webCryptoRandomUuidV4 to reject ${JSON.stringify(value)}`) + } + }) +}) diff --git a/src/__test__/registrationAuthorization.test.ts b/src/__test__/registrationAuthorization.test.ts new file mode 100644 index 0000000..e3f238f --- /dev/null +++ b/src/__test__/registrationAuthorization.test.ts @@ -0,0 +1,280 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + authorizeRegistrationComplete, + type RegistrationAuthorizationClock, + type RegistrationCompleteAuthorizationRequest, +} from '../auth/registrationAuthorization' +import { webCryptoRegistrationFlowKeyProvider } from '../auth/RegistrationFlowKey' +import type { RegistrationFlowKey } from '../auth/RegistrationFlowKey' +import { fromBase64Url } from '../crypto/base64url' +import { serializeBody } from '../crypto/serialization' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { InMemorySecureKeyStore } from '../testing' + +const CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000001' +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const FLOW_JTI = '33333333-3333-4333-8333-333333333333' +const DEVICE_JTI = '44444444-4444-4444-8444-444444444444' +const NOW = 1_785_990_000 + +const REQUEST_CLAIMS = [ + 'aud', + 'body_sha256', + 'canonical_path', + 'discriminator', + 'exp', + 'iat', + 'idempotency_key', + 'jti', + 'method', + 'schema_version', +] +const BINDING_CLAIMS = [ + 'auth_key_thumbprint', + 'code_verifier_sha256', + 'profile_id', + 'registration_handle_sha256', +] + +function makeClock(): RegistrationAuthorizationClock { + let calls = 0 + return { + nowEpochSeconds: () => NOW, + jti: () => { + calls += 1 + return calls === 1 ? FLOW_JTI : DEVICE_JTI + }, + } +} + +async function registeredAuthKey(): Promise { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + await key.acknowledgeRegistration() + return key +} + +async function flowKey(): Promise { + return webCryptoRegistrationFlowKeyProvider().generate() +} + +function baseRequest(overrides: Partial = {}): Omit< + RegistrationCompleteAuthorizationRequest, + 'flowKey' | 'authKey' +> & { + flowKey?: RegistrationFlowKey + authKey?: OwnerAuthKey +} { + return { + bodyBytes: serializeBody({ + idempotencyKey: IDEMPOTENCY_KEY, + registrationHandle: 'h'.repeat(32), + registrationCodeVerifier: 'v'.repeat(43), + authKeyPublicKey: 'I'.repeat(122), + }), + registrationHandle: 'h'.repeat(32), + registrationCodeVerifier: 'v'.repeat(43), + clientEntityId: CLIENT_ENTITY_ID, + ...overrides, + } +} + +function splitCompact(compact: string): { header: string; payload: string; signature: string } { + const parts = compact.split('.') + if ( + parts.length !== 3 || + parts[0] === undefined || + parts[1] === undefined || + parts[2] === undefined + ) { + throw new Error('expected compact JWS') + } + return { header: parts[0], payload: parts[1], signature: parts[2] } +} + +function jsonOf(segment: string): unknown { + return JSON.parse(new TextDecoder().decode(fromBase64Url(segment))) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('authorizeRegistrationComplete', () => { + it('rejects a non-UUID clientEntityId', async () => { + const request = { + ...baseRequest({ clientEntityId: 'not-a-uuid' }), + flowKey: await flowKey(), + authKey: await registeredAuthKey(), + } + expect(await detailOf(authorizeRegistrationComplete(request, makeClock()))).toEqual({ + kind: 'contract_violation', + }) + }) + + it('rejects a signed body missing idempotencyKey', async () => { + const request = { + ...baseRequest({ + bodyBytes: serializeBody({ + registrationHandle: 'h'.repeat(32), + registrationCodeVerifier: 'v'.repeat(43), + authKeyPublicKey: 'I'.repeat(122), + }), + }), + flowKey: await flowKey(), + authKey: await registeredAuthKey(), + } + expect(await detailOf(authorizeRegistrationComplete(request, makeClock()))).toEqual({ + kind: 'contract_violation', + }) + }) + + it('rejects a device signature that is not 64 bytes', async () => { + const authKey: OwnerAuthKey = { + publicKeySpkiBase64Url: async () => (await registeredAuthKey()).publicKeySpkiBase64Url(), + thumbprint: async () => 'x', + resolution: () => 'existing', + acknowledgeRegistration: async () => undefined, + signExactBytes: async () => { + throw new Error('signExactBytes should not be reached for the registration device proof') + }, + signRegistrationDeviceAuthorization: async () => new Uint8Array(63), + } + const request = { ...baseRequest(), flowKey: await flowKey(), authKey } + expect(await detailOf(authorizeRegistrationComplete(request, makeClock()))).toEqual({ + kind: 'contract_violation', + }) + }) + + it('signs the registration device proof through signRegistrationDeviceAuthorization, never signExactBytes', async () => { + let registrationCalls = 0 + let exactBytesCalls = 0 + const real = await registeredAuthKey() + const authKey: OwnerAuthKey = { + publicKeySpkiBase64Url: () => real.publicKeySpkiBase64Url(), + thumbprint: () => real.thumbprint(), + resolution: () => real.resolution(), + acknowledgeRegistration: () => real.acknowledgeRegistration(), + signExactBytes: async (message) => { + exactBytesCalls += 1 + return real.signExactBytes(message) + }, + signRegistrationDeviceAuthorization: async (message) => { + registrationCalls += 1 + // Reuse the same underlying key material so the produced JWS is still + // a valid 64-byte signature; only the routing is under test here. + return real.signExactBytes(message) + }, + } + const request = { ...baseRequest(), flowKey: await flowKey(), authKey } + await authorizeRegistrationComplete(request, makeClock()) + + expect(registrationCalls).toBe(1) + expect(exactBytesCalls).toBe(0) + }) + + it('rejects a flow signature that is not 64 bytes', async () => { + const badFlowKey: RegistrationFlowKey = { + publicKeySpkiBase64Url: async () => (await flowKey()).publicKeySpkiBase64Url(), + signExactBytes: async () => new Uint8Array(63), + release: async () => undefined, + } + const request = { ...baseRequest(), flowKey: badFlowKey, authKey: await registeredAuthKey() } + expect(await detailOf(authorizeRegistrationComplete(request, makeClock()))).toEqual({ + kind: 'contract_violation', + }) + }) + + it('signs the device and flow JWS with their own typ, sharing the request claims bar jti', async () => { + const request = { + ...baseRequest(), + flowKey: await flowKey(), + authKey: await registeredAuthKey(), + } + const { deviceJws, flowJws } = await authorizeRegistrationComplete(request, makeClock()) + + const deviceHeader = jsonOf(splitCompact(deviceJws).header) + const flowHeader = jsonOf(splitCompact(flowJws).header) + expect(deviceHeader).toMatchObject({ alg: 'ES256', typ: 'daa-device-authorization+jws' }) + expect(flowHeader).toMatchObject({ + alg: 'ES256', + typ: 'daa-registration-flow-authorization+jws', + }) + + const devicePayload = jsonOf(splitCompact(deviceJws).payload) as Record + const flowPayload = jsonOf(splitCompact(flowJws).payload) as Record + expect(devicePayload).toMatchObject({ + discriminator: 'device_key_registration.v1', + schema_version: 1, + jti: DEVICE_JTI, + }) + expect(flowPayload).toMatchObject({ + discriminator: 'device_key_registration.v1', + schema_version: 1, + profile_id: CLIENT_ENTITY_ID, + jti: FLOW_JTI, + }) + // The request claims carry the same values in both proofs, bar jti. + for (const claim of REQUEST_CLAIMS.filter((name) => name !== 'jti')) { + expect(devicePayload[claim]).toEqual(flowPayload[claim]) + } + expect(devicePayload.jti).not.toBe(flowPayload.jti) + }) + + it('sends exactly the 10 request claims in the device proof and none of the binding claims', async () => { + const request = { + ...baseRequest(), + flowKey: await flowKey(), + authKey: await registeredAuthKey(), + } + const { deviceJws } = await authorizeRegistrationComplete(request, makeClock()) + + const devicePayload = jsonOf(splitCompact(deviceJws).payload) as Record + expect(Object.keys(devicePayload).sort()).toEqual(REQUEST_CLAIMS) + for (const claim of BINDING_CLAIMS) { + expect(devicePayload).not.toHaveProperty(claim) + } + }) + + it('sends all 14 claims in the flow proof: the request claims plus the binding claims', async () => { + const request = { + ...baseRequest(), + flowKey: await flowKey(), + authKey: await registeredAuthKey(), + } + const { flowJws } = await authorizeRegistrationComplete(request, makeClock()) + + const flowPayload = jsonOf(splitCompact(flowJws).payload) as Record + expect(Object.keys(flowPayload).sort()).toEqual([...REQUEST_CLAIMS, ...BINDING_CLAIMS].sort()) + }) +}) diff --git a/src/__test__/registrationCodeVerifier.test.ts b/src/__test__/registrationCodeVerifier.test.ts new file mode 100644 index 0000000..35432b8 --- /dev/null +++ b/src/__test__/registrationCodeVerifier.test.ts @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + REGISTRATION_CODE_CHALLENGE_METHOD, + newRegistrationCodeVerifier, + registrationCodeChallengeS256, +} from '../auth/registrationCodeVerifier' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { sha256 } from '../crypto/sha256' + +/** + * The registration handoff's secret half. + * + * The construction is RFC 7636's, so its published test vector is the strongest + * available check that the digest is taken over the right bytes — a challenge + * derived from the raw random bytes instead of the verifier *string* would look + * perfectly well-formed and would never match server-side. + */ + +// RFC 7636 Appendix B. +const RFC7636_VERIFIER = 'dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk' +const RFC7636_CHALLENGE = 'E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM' + +const BASE64URL_43 = /^[A-Za-z0-9_-]{43}$/ + +describe('registrationCodeChallengeS256', () => { + it('matches the RFC 7636 Appendix B vector', () => { + expect(registrationCodeChallengeS256(RFC7636_VERIFIER)).toBe(RFC7636_CHALLENGE) + }) + + it('is the digest of the verifier string, not of the bytes it was encoded from', () => { + const verifier = newRegistrationCodeVerifier() + // Hashing the 32 random bytes the verifier was encoded from is the plausible + // wrong implementation: same length, same charset, and the server would + // reject every completion. Pinned explicitly rather than left to the RFC + // vector above, which only covers a verifier the SDK did not generate. + const overRawBytes = toBase64Url(sha256(fromBase64Url(verifier))) + expect(registrationCodeChallengeS256(verifier)).not.toBe(overRawBytes) + }) + + it('always produces the 43-character unpadded Base64URL the contract pins', () => { + for (let i = 0; i < 16; i++) { + expect(registrationCodeChallengeS256(newRegistrationCodeVerifier())).toMatch(BASE64URL_43) + } + }) + + it('is deterministic for one verifier', () => { + const verifier = newRegistrationCodeVerifier() + expect(registrationCodeChallengeS256(verifier)).toBe(registrationCodeChallengeS256(verifier)) + }) +}) + +describe('newRegistrationCodeVerifier', () => { + it('carries 256 bits of entropy in the contract charset', () => { + const verifier = newRegistrationCodeVerifier() + expect(verifier).toMatch(BASE64URL_43) + // minLength: 43 on CompleteDeviceRegistrationRequest.registrationCodeVerifier. + expect(verifier.length).toBeGreaterThanOrEqual(43) + expect(fromBase64Url(verifier)).toHaveLength(32) + }) + + it('is fresh per attempt', () => { + const verifiers = new Set() + for (let i = 0; i < 64; i++) { + verifiers.add(newRegistrationCodeVerifier()) + } + expect(verifiers.size).toBe(64) + }) +}) + +describe('the challenge method', () => { + it('is the only value the contract enum allows', () => { + expect(REGISTRATION_CODE_CHALLENGE_METHOD).toBe('S256') + }) +}) diff --git a/src/__test__/registrationFlowKey.test.ts b/src/__test__/registrationFlowKey.test.ts new file mode 100644 index 0000000..c3d213c --- /dev/null +++ b/src/__test__/registrationFlowKey.test.ts @@ -0,0 +1,331 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { + defaultRegistrationFlowKeyProvider, + nativeRegistrationFlowKeyProvider, + webCryptoRegistrationFlowKeyProvider, +} from '../auth/RegistrationFlowKey' +import type { DaaRegistrationNativeModule } from '../auth/daaRegistrationNative' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { isDaaError } from '../errors' +import { InMemorySecureKeyStore } from '../securekey/InMemorySecureKey' + +/** + * The ephemeral registration-flow key. + * + * These tests are as much about what the key is NOT as what it is: it is not an + * AuthKey, it does not come from `SecureKeyStore`, it exposes no generic + * signing member, + * and it is fresh per attempt. Those are the properties the login contract relies + * on: Prepare sends the ephemeral public key, never an AuthKey public key. + */ + +const BASE64URL_122 = /^[A-Za-z0-9_-]{122}$/ + +async function withoutWebCrypto(operation: () => Promise): Promise { + const host = globalThis as { crypto: Crypto | undefined } + const original = host.crypto + // `getRandomValues` stays available; only `subtle` is removed, which is the + // real Hermes shape once a random-only polyfill is installed. + host.crypto = { getRandomValues: original?.getRandomValues.bind(original) } as Crypto + try { + return await operation() + } finally { + host.crypto = original + } +} + +describe('webCryptoRegistrationFlowKeyProvider', () => { + it('exports the 122-character unpadded Base64URL P-256 SPKI the contract pins', async () => { + const key = await webCryptoRegistrationFlowKeyProvider().generate() + const spki = await key.publicKeySpkiBase64Url() + + expect(spki).toMatch(BASE64URL_122) + const bytes = fromBase64Url(spki) + expect(bytes).toHaveLength(91) + // Uncompressed point marker at the fixed P-256 SPKI offset. A compressed + // point would be 59 bytes and is rejected by the length check above. + expect(bytes[26]).toBe(0x04) + }) + + it('mints a distinct key per attempt', async () => { + const provider = webCryptoRegistrationFlowKeyProvider() + const first = await (await provider.generate()).publicKeySpkiBase64Url() + const second = await (await provider.generate()).publicKeySpkiBase64Url() + expect(first).not.toBe(second) + }) + + it('is stable for one key', async () => { + const key = await webCryptoRegistrationFlowKeyProvider().generate() + expect(await key.publicKeySpkiBase64Url()).toBe(await key.publicKeySpkiBase64Url()) + }) + + it('signs exact bytes with ES256 JOSE R||S and does not expose a generic sign', async () => { + const key = await webCryptoRegistrationFlowKeyProvider().generate() + const surface = key as unknown as Record + for (const name of ['sign', 'privateKey', 'thumbprint', 'keyPair']) { + expect(surface[name]).toBeUndefined() + } + expect(Object.getOwnPropertyNames(Object.getPrototypeOf(key)).sort()).toEqual([ + 'constructor', + 'publicKeySpkiBase64Url', + 'release', + 'signExactBytes', + ]) + expect(Object.isFrozen(key)).toBe(true) + const signature = await key.signExactBytes(new TextEncoder().encode('abc')) + expect(signature).toHaveLength(64) + }) + + it('is not an AuthKey: no SPKI it produces is one the secure-key store would resolve', async () => { + // Not a cryptographic claim — two independently generated P-256 keys never + // collide. The point is structural: the flow key comes from its own provider, + // and nothing in this path constructs an identity, an alias, or a store. + const flowKey = await webCryptoRegistrationFlowKeyProvider().generate() + const authKey = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: '00000000-0000-4000-8000-000000000001', + }) + expect(await flowKey.publicKeySpkiBase64Url()).not.toBe(await authKey.publicKeySpkiBase64Url()) + // And unlike an AuthKey, the flow key has no registration state at all. + expect((flowKey as unknown as Record).resolution).toBeUndefined() + expect((flowKey as unknown as Record).acknowledgeRegistration).toBeUndefined() + }) + + it('fails closed when the host has no crypto.subtle, rather than weakening key generation', async () => { + await withoutWebCrypto(async () => { + const provider = webCryptoRegistrationFlowKeyProvider() + try { + await provider.generate() + } catch (err) { + expect(isDaaError(err)).toBe(true) + if (isDaaError(err)) { + expect(err.detail.kind).toBe('contract_violation') + expect(err.message).toMatch(/crypto\.subtle is required/) + } + return + } + throw new Error('expected registration-flow key generation to fail closed') + }) + }) +}) + +const requireNative = jest.mocked(requireOptionalNativeModule) +const defaultNativeImpl = requireNative.getMockImplementation() + +afterEach(() => { + requireNative.mockReset() + if (defaultNativeImpl !== undefined) { + requireNative.mockImplementation(defaultNativeImpl) + } +}) + +function fakeSpki(distinct: number): string { + const bytes = new Uint8Array(91) + bytes[26] = 0x04 + bytes[90] = distinct + return toBase64Url(bytes) +} + +function fakeSignature(distinct: number): string { + const bytes = new Uint8Array(64) + bytes[63] = distinct + return toBase64Url(bytes) +} + +function fakeRegistrationNative(): DaaRegistrationNativeModule { + const exported = new Map() + let next = 0 + return { + randomBytes: jest.fn(), + randomUuidV4: jest.fn(), + generateRegistrationFlowKey: jest.fn(() => { + const id = `flow-${next}` + exported.set(id, fakeSpki(next)) + next += 1 + return id + }), + registrationFlowPublicKeySpkiBase64Url: jest.fn((id: string) => { + const spki = exported.get(id) + if (spki === undefined) { + throw new Error(`no flow key ${id}`) + } + return spki + }), + // Models the native cache: release really drops it, so a released key + // cannot still export. A no-op fake here would let a missing release pass. + releaseRegistrationFlowKey: jest.fn((id: string) => { + exported.delete(id) + }), + // Models the typed native sign: it does not decode or reinterpret the + // signing input, it just proves it received the exact Base64URL bytes by + // handing back a deterministic, distinguishable fake signature. + signRegistrationAuthorization: jest.fn((id: string, signingInputBase64Url: string) => { + if (!exported.has(id)) { + throw new Error(`no flow key ${id}`) + } + void signingInputBase64Url + return fakeSignature(next) + }), + verifyPrepareReceiptSignature: jest.fn(async () => false), + } +} + +describe('registration-flow key release', () => { + it('drops the native key so its private half stops being held', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + await key.publicKeySpkiBase64Url() + + await key.release() + + expect(native.releaseRegistrationFlowKey).toHaveBeenCalledTimes(1) + // The native cache is process-lifetime, so "released" has to mean the key + // is actually gone, not merely that a method was called. Exporting after + // release must fail rather than return a stale value. + await expect(key.publicKeySpkiBase64Url()).rejects.toThrow() + }) + + it('is idempotent, so a finally block can release unconditionally', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + + await key.release() + await expect(key.release()).resolves.toBeUndefined() + }) + + it('tolerates a host module that predates the release function', async () => { + // An older linked module simply has no releaseRegistrationFlowKey. Cleanup + // must not throw over that; the caller is usually already in a finally. + const native = fakeRegistrationNative() + delete (native as { releaseRegistrationFlowKey?: unknown }).releaseRegistrationFlowKey + const key = await nativeRegistrationFlowKeyProvider(native).generate() + + await expect(key.release()).resolves.toBeUndefined() + }) + + it('has a release on the WebCrypto stand-in too, so one interface covers both', async () => { + const key = await webCryptoRegistrationFlowKeyProvider().generate() + await expect(key.release()).resolves.toBeUndefined() + // Unlike the native key, nothing is freed, so export still works. + expect(await key.publicKeySpkiBase64Url()).toHaveLength(122) + }) +}) + +describe('nativeRegistrationFlowKeyProvider', () => { + it('exports the 122-character unpadded Base64URL P-256 SPKI the contract pins', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + const spki = await key.publicKeySpkiBase64Url() + + expect(spki).toMatch(BASE64URL_122) + const bytes = fromBase64Url(spki) + expect(bytes).toHaveLength(91) + expect(bytes[26]).toBe(0x04) + expect(native.generateRegistrationFlowKey).toHaveBeenCalledTimes(1) + expect(native.registrationFlowPublicKeySpkiBase64Url).toHaveBeenCalledWith('flow-0') + }) + + it('mints a distinct key per attempt', async () => { + const native = fakeRegistrationNative() + const provider = nativeRegistrationFlowKeyProvider(native) + const first = await (await provider.generate()).publicKeySpkiBase64Url() + const second = await (await provider.generate()).publicKeySpkiBase64Url() + expect(first).not.toBe(second) + }) + + it('is stable for one key', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + expect(await key.publicKeySpkiBase64Url()).toBe(await key.publicKeySpkiBase64Url()) + }) + + it('signs exact bytes through the native typed sign and does not expose a generic sign', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + const surface = key as unknown as Record + for (const name of ['sign', 'privateKey', 'thumbprint', 'keyPair']) { + expect(surface[name]).toBeUndefined() + } + expect(Object.getOwnPropertyNames(Object.getPrototypeOf(key)).sort()).toEqual([ + 'constructor', + 'publicKeySpkiBase64Url', + 'release', + 'signExactBytes', + ]) + expect(Object.isFrozen(key)).toBe(true) + + const message = new TextEncoder().encode('{"idempotencyKey":"k"}') + const signature = await key.signExactBytes(message) + + expect(signature).toHaveLength(64) + expect(native.signRegistrationAuthorization).toHaveBeenCalledTimes(1) + expect(native.signRegistrationAuthorization).toHaveBeenCalledWith( + 'flow-0', + toBase64Url(message), + ) + }) + + it('surfaces a contract violation when the native sign call fails', async () => { + const native = fakeRegistrationNative() + const failing: DaaRegistrationNativeModule = { + ...native, + signRegistrationAuthorization: jest.fn(() => { + throw new Error('native signing failed') + }), + } + const key = await nativeRegistrationFlowKeyProvider(failing).generate() + await expect(key.signExactBytes(new Uint8Array([1]))).rejects.toMatchObject({ + detail: { kind: 'contract_violation' }, + }) + }) + + it('keeps the private key behind the native handle — JS only holds an id', async () => { + const native = fakeRegistrationNative() + const key = await nativeRegistrationFlowKeyProvider(native).generate() + expect(JSON.stringify(key)).toBe('{}') + }) +}) + +describe('defaultRegistrationFlowKeyProvider', () => { + it('uses the native Expo module when it is present', async () => { + const native = fakeRegistrationNative() + requireNative.mockImplementation((name: string) => (name === 'DaaRegistration' ? native : null)) + const key = await defaultRegistrationFlowKeyProvider().generate() + await key.publicKeySpkiBase64Url() + expect(native.generateRegistrationFlowKey).toHaveBeenCalledTimes(1) + }) + + it('fails closed when the Expo module is absent, rather than using WebCrypto', async () => { + requireNative.mockImplementation(() => null) + const provider = defaultRegistrationFlowKeyProvider() + try { + await provider.generate() + } catch (err) { + expect(isDaaError(err)).toBe(true) + if (isDaaError(err)) { + expect(err.message).toMatch(/native DaaRegistration module is not available/) + } + return + } + throw new Error('expected default provider to fail closed without native module') + }) +}) diff --git a/src/__test__/resourceRequest.test.ts b/src/__test__/resourceRequest.test.ts new file mode 100644 index 0000000..5a0379e --- /dev/null +++ b/src/__test__/resourceRequest.test.ts @@ -0,0 +1,250 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { idempotencyConflict, isDaaError } from '../errors' +import { postResource, readResource } from '../api/resourceRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { MalformedPayloadError } from '../wire/payload' + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +async function detailOf(operation: Promise) { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('readResource', () => { + it('sends the bodyless by-id GET shape and decodes the data envelope', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: {}, + bodyBytes: bytes('{"data":{"id":"resource-1"}}'), + }) + + const result = await readResource({ + transport, + path: '/v1/resources/resource-1', + decode: (value) => (value as { id: string }).id, + }) + + expect(result).toBe('resource-1') + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/resources/resource-1', + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + }) + + it('rejects every status other than the documented 200', async () => { + for (const status of [201, 204, 299, 400, Number.NaN]) { + const transport = new RecordingTransport({ + status, + headers: { 'x-request-id': 'req-1' }, + bodyBytes: bytes('{"status":{"code":"UNEXPECTED"}}'), + }) + const detail = await detailOf( + readResource({ transport, path: '/v1/resources/resource-1', decode: (value) => value }), + ) + expect(detail).toMatchObject({ + kind: 'api', + httpStatus: status, + daaStatusCode: 'UNEXPECTED', + }) + } + }) + + it('carries the root numeric code of the flat body DAA sends', async () => { + const transport = new RecordingTransport({ + status: 400, + headers: { 'x-request-id': 'req-1' }, + bodyBytes: bytes('{"code":420001,"message":"internal detail","externalMessage":"rejected"}'), + }) + const detail = await detailOf( + readResource({ transport, path: '/v1/resources/resource-1', decode: (value) => value }), + ) + expect(detail).toEqual({ + kind: 'api', + httpStatus: 400, + daaStatusCode: 420001, + retryable: false, + }) + }) + + it('maps malformed decoded payloads to contract violations with the correlation id', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes('{"data":{}}'), + }) + await expect( + detailOf( + readResource({ + transport, + path: '/v1/resources/resource-1', + decode: () => { + throw new MalformedPayloadError('id') + }, + }), + ), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-2' }) + }) + + it('preserves transport failures unchanged', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + await expect( + readResource({ transport, path: '/v1/resources/resource-1', decode: (value) => value }), + ).rejects.toBe(failure) + }) +}) + +describe('postResource', () => { + it('sends the final request bytes unchanged and decodes the expected response', async () => { + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: bytes('{"data":{"id":"resource-1"}}'), + }) + const bodyBytes = bytes('{"idempotencyKey":"request-1"}') + const headers = Object.freeze({ + 'Content-Type': 'application/json', + 'X-Device-Signature': 'signature-1', + }) + + const result = await postResource({ + transport, + path: '/v1/resources', + query: 'custodyType=self', + headers, + bodyBytes, + expectedStatus: 201, + decode: (value) => (value as { id: string }).id, + }) + + expect(result).toBe('resource-1') + expect(transport.sent).toEqual([ + { + method: 'POST', + path: '/v1/resources', + query: 'custodyType=self', + headers, + bodyBytes, + }, + ]) + expect(transport.sent[0]?.bodyBytes).toBe(bodyBytes) + }) + + it('throws an endpoint-specific failure before the expected-status check', async () => { + const response = { status: 409, headers: {}, bodyBytes: bytes('{"code":420034}') } + const transport = new RecordingTransport(response) + const conflict = idempotencyConflict('request-1', null) + const seen: unknown[] = [] + + await expect( + postResource({ + transport, + path: '/v1/resources', + query: null, + headers: {}, + bodyBytes: bytes('{}'), + expectedStatus: 201, + decode: (value) => value, + failure: (received) => { + seen.push(received) + return conflict + }, + }), + ).rejects.toBe(conflict) + expect(seen).toEqual([response]) + }) + + it('applies the common contract when the endpoint-specific failure returns null', async () => { + const transport = new RecordingTransport({ + status: 201, + headers: {}, + bodyBytes: bytes('{"data":{"id":"resource-1"}}'), + }) + + await expect( + postResource({ + transport, + path: '/v1/resources', + query: null, + headers: {}, + bodyBytes: bytes('{}'), + expectedStatus: 201, + decode: (value) => (value as { id: string }).id, + failure: () => null, + }), + ).resolves.toBe('resource-1') + }) + + it('requires the endpoint-specific expected status', async () => { + const transport = new RecordingTransport({ + status: 200, + headers: { 'x-request-id': 'req-post' }, + bodyBytes: bytes('{"data":{"id":"resource-1"}}'), + }) + + await expect( + detailOf( + postResource({ + transport, + path: '/v1/resources', + query: null, + headers: {}, + bodyBytes: bytes('{}'), + expectedStatus: 201, + decode: (value) => value, + }), + ), + ).resolves.toEqual({ + kind: 'api', + httpStatus: 200, + retryable: false, + }) + }) +}) diff --git a/src/__test__/responseErrorRequestId.test.ts b/src/__test__/responseErrorRequestId.test.ts new file mode 100644 index 0000000..aeb40c3 --- /dev/null +++ b/src/__test__/responseErrorRequestId.test.ts @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AuthClient } from '../api/AuthClient' +import { toBase64Url } from '../crypto/base64url' +import type { DaaSdkError } from '../errors' +import type { DaaHttpResponse } from '../transport/DaaTransport' +import { generateReceiptSigningKey, trustAnchorFor } from './prepareReceiptSigning' +import { + ALL_CALLS, + bytes, + CLIENT_ENTITY_ID, + daaErrorOf, + EXPIRES_AT, + LOGIN_CALLS, + REGISTRATION_HANDLE, + REQUEST_ID, + ScriptedTransport, + serviceError, + SIGNED_CALLS, + type ScriptedCall, +} from './scriptedCalls' + +/** + * Every error the SDK builds from a DAA response names that response's + * `X-Request-Id` in its message, whatever the kind. + * + * The request id is what lets support find the call server-side, and + * `message` is what an application logs. A kind that drops it leaves a + * developer with an error nobody can trace. The table is every kind a response + * can produce on each call, so a new kind or a new call that forgets the id + * fails here. + */ + +type ErrorCase = Readonly<{ + label: string + kind: DaaSdkError['kind'] + response: (call: ScriptedCall, headers: Readonly>) => DaaHttpResponse + appliesTo: (call: ScriptedCall) => boolean +}> + +const CORRELATED_KINDS = new Set([ + 'contract_violation', + 'idempotency_conflict', +]) +const SIGNED = new Set(SIGNED_CALLS.map((call) => call.name)) +const LOGIN = new Set(LOGIN_CALLS.map((call) => call.name)) + +const CASES: readonly ErrorCase[] = [ + { + label: 'an unclassified 4xx', + kind: 'api', + response: (_call, headers) => serviceError(400, 420014, 'Insufficient balance', headers), + appliesTo: () => true, + }, + { + label: 'a success status with a body that is not the contract', + kind: 'contract_violation', + response: (call, headers) => ({ + status: call.successStatus, + headers, + bodyBytes: bytes('{"data":{}}'), + }), + appliesTo: () => true, + }, + { + label: '410', + kind: 'login_request_expired', + response: (_call, headers) => + serviceError(410, 420035, 'The login request has expired', headers), + appliesTo: (call) => LOGIN.has(call.name), + }, + { + label: '409 / 420034', + kind: 'idempotency_conflict', + response: (_call, headers) => + serviceError( + 409, + 420034, + 'The idempotency key was already used with a different request body', + headers, + ), + appliesTo: (call) => call.idempotent, + }, + { + label: '409 / 420039', + kind: 'contract_violation', + response: (_call, headers) => serviceError(409, 420039, 'The login request was used', headers), + appliesTo: (call) => LOGIN.has(call.name), + }, + { + label: '400 / 420031', + kind: 'contract_violation', + response: (_call, headers) => + serviceError(400, 420031, 'The device authorization is invalid', headers), + appliesTo: (call) => SIGNED.has(call.name), + }, + { + label: '409 / 420043', + kind: 'contract_violation', + response: (_call, headers) => + serviceError(409, 420043, 'The device authorization was replayed', headers), + appliesTo: (call) => SIGNED.has(call.name), + }, +] + +const ROWS = ALL_CALLS.flatMap((call) => + CASES.filter((errorCase) => errorCase.appliesTo(call)).map( + (errorCase) => [call.name, errorCase.label, call, errorCase] as const, + ), +) + +describe.each(ROWS)('%s, %s', (_name, _label, call, errorCase) => { + it('names the request id in the message', async () => { + const { call: pending } = await call.run(() => + errorCase.response(call, { 'X-Request-Id': REQUEST_ID }), + ) + const err = await daaErrorOf(pending) + + expect(err.detail.kind).toBe(errorCase.kind) + expect(err.message.endsWith(` (requestId=${REQUEST_ID})`)).toBe(true) + // The two kinds that model a correlation id carry it on the detail too, for + // a host that reports `err.detail` rather than the message. + if (CORRELATED_KINDS.has(err.detail.kind)) { + expect(err.detail).toHaveProperty('correlationId', REQUEST_ID) + } + }) + + it('adds no request id when the response has none', async () => { + const { call: pending } = await call.run(() => errorCase.response(call, {})) + const err = await daaErrorOf(pending) + + expect(err.detail.kind).toBe(errorCase.kind) + expect(err.message).not.toMatch(/requestId=/) + expect(err.detail).not.toHaveProperty('correlationId') + }) +}) + +/** + * Checks that run on a decoded success response: the Prepare receipt and the + * Owner grant's flow-key binding. The failure is in that response, so it names + * that response's request id too. + */ +describe('a check on a decoded response', () => { + const PREPARED = { + loginRequestId: '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + oidcNonce: 'n'.repeat(48), + oidcState: 's'.repeat(48), + expiresAt: EXPIRES_AT, + } + + function prepared(receipt: unknown, headers: Readonly>): DaaHttpResponse { + return { + status: 201, + headers, + bodyBytes: bytes(JSON.stringify({ data: { ...PREPARED, prepareReceiptJws: receipt } })), + } + } + + async function prepareWithAnchor(response: DaaHttpResponse) { + const transport = new ScriptedTransport([], () => response) + const auth = new AuthClient({ + transport, + environment: 'sandbox', + prepareReceiptTrustAnchor: trustAnchorFor([await generateReceiptSigningKey()]), + }) + return daaErrorOf(auth.prepareSocialLogin({ provider: 'GOOGLE' })) + } + + it.each([ + ['a missing receipt', null], + ['a malformed receipt', 'not-a-jws'], + ])('names the request id when the Prepare response carries %s', async (_label, receipt) => { + const err = await prepareWithAnchor(prepared(receipt, { 'X-Request-Id': REQUEST_ID })) + + expect(err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + expect(err.message.endsWith(` (requestId=${REQUEST_ID})`)).toBe(true) + }) + + it('adds no request id to a rejected receipt when the response has none', async () => { + const err = await prepareWithAnchor(prepared(null, {})) + + expect(err.detail).toEqual({ kind: 'prepare_receipt_invalid' }) + expect(err.message).not.toMatch(/requestId=/) + }) + + it.each([ + ['with', { 'X-Request-Id': REQUEST_ID }], + ['without', {}], + ])( + 'carries the request id on an unbound Owner grant only %s the header', + async (label, headers) => { + const encode = (value: object) => toBase64Url(bytes(JSON.stringify(value))) + const grant = `${encode({ alg: 'ES256' })}.${encode({ + registrationFlowKeyThumbprint: 'c'.repeat(43), + })}.c2ln` + const session = LOGIN_CALLS.find((call) => call.name === 'Social Session') as ScriptedCall + const { call } = await session.run(() => ({ + status: 200, + headers, + bodyBytes: bytes( + JSON.stringify({ + data: { + registrationHandle: REGISTRATION_HANDLE, + clientEntityId: CLIENT_ENTITY_ID, + expiresAt: EXPIRES_AT, + ownerGrant: grant, + }, + }), + ), + })) + const err = await daaErrorOf(call) + + if (label === 'with') { + expect(err.detail).toEqual({ kind: 'contract_violation', correlationId: REQUEST_ID }) + expect(err.message.endsWith(` (requestId=${REQUEST_ID})`)).toBe(true) + } else { + expect(err.detail).toEqual({ kind: 'contract_violation' }) + expect(err.message).not.toMatch(/requestId=/) + } + expect(err.message).toMatch(/does not match the registration-flow key/) + }, + ) +}) diff --git a/src/__test__/scaClient.test.ts b/src/__test__/scaClient.test.ts new file mode 100644 index 0000000..5ec6acb --- /dev/null +++ b/src/__test__/scaClient.test.ts @@ -0,0 +1,318 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createScaClient, isScaError, mapNativeScaError, ScaError } from '../sca/ScaClient' +import type { ScaConfig } from '../sca/ScaClient' + +const config: ScaConfig = { + environment: 'sandbox', + redirectUri: 'https://app.example.com/sca/callback', +} + +// The fixed `message` the SDK sets for each code. +const MESSAGE = { + Cancelled: 'The SCA ceremony was cancelled', + Expired: 'The SCA ceremony deadline passed', + Unsupported: 'This device or app cannot run the SCA ceremony', + AlreadyEnrolled: 'A passkey is already enrolled on this authenticator', + Protocol: 'The SCA ceremony failed with a protocol error', + Transport: 'The SCA ceremony failed on a transport error', + InvalidConfiguration: 'The SCA configuration was rejected', + CeremonyInProgress: 'Another SCA ceremony is still open', + NativeModuleUnavailable: 'The DaaSca native module is not linked in this build', +} as const + +function nativeError(code: string, message: string): Error & { code: string } { + return Object.assign(new Error(message), { code }) +} + +function fakeNative( + overrides: Partial> = {}, +) { + return { + approve: overrides.approve ?? jest.fn(async () => '{"id":"assertion"}'), + enroll: overrides.enroll ?? jest.fn(async () => '{"id":"registration"}'), + capabilities: + overrides.capabilities ?? + jest.fn(async () => ({ + protocolVersion: 1, + surface: 'customTab', + callbackReady: true, + callbackVerified: null, + callbackTaskIsolated: true, + platformPasskeys: true, + })), + } +} + +describe('createScaClient', () => { + it('passes the frozen config and frame token to native and returns the text unchanged', async () => { + const native = fakeNative() + const client = createScaClient(config, native) + + await expect(client.approve('token-1')).resolves.toBe('{"id":"assertion"}') + await expect(client.enroll('token-2')).resolves.toBe('{"id":"registration"}') + + expect(native.approve).toHaveBeenCalledWith(config, 'token-1') + expect(native.enroll).toHaveBeenCalledWith(config, 'token-2') + expect(Object.isFrozen(client.config)).toBe(true) + }) + + it('refuses an unsupported environment or a missing redirect URI up front', () => { + for (const bad of [ + { ...config, environment: 'not-an-environment' }, + { ...config, environment: 'Sandbox' }, + { ...config, redirectUri: '' }, + ]) { + expect(() => createScaClient(bad as ScaConfig, fakeNative())).toThrow( + expect.objectContaining({ code: 'InvalidConfiguration' }), + ) + } + }) + + it('refuses an empty frame token without calling native', async () => { + const native = fakeNative() + await expect(createScaClient(config, native).approve('')).rejects.toMatchObject({ + code: 'InvalidConfiguration', + }) + expect(native.approve).not.toHaveBeenCalled() + }) + + it('rejects a second ceremony while one is open and leaves the open one alone', async () => { + let finish: (value: string) => void = () => {} + const native = fakeNative({ + approve: jest.fn(() => new Promise((resolve) => (finish = resolve))), + }) + const client = createScaClient(config, native) + + const first = client.approve('token-1') + await expect(client.enroll('token-2')).rejects.toMatchObject({ code: 'CeremonyInProgress' }) + await expect(client.approve('token-3')).rejects.toMatchObject({ code: 'CeremonyInProgress' }) + finish('done') + + await expect(first).resolves.toBe('done') + expect(native.enroll).not.toHaveBeenCalled() + expect(native.approve).toHaveBeenCalledTimes(1) + + native.approve.mockResolvedValueOnce('again') + await expect(client.approve('token-4')).resolves.toBe('again') + }) + + it('frees the slot after a failure', async () => { + const native = fakeNative({ + approve: jest + .fn() + .mockRejectedValueOnce(nativeError('SCA_CANCELLED', 'x')) + .mockResolvedValue('{"id":"assertion"}'), + }) + const client = createScaClient(config, native) + + await expect(client.approve('t')).rejects.toMatchObject({ code: 'Cancelled' }) + await expect(client.approve('t')).resolves.toBe('{"id":"assertion"}') + }) + + it('maps every native code to the shared vocabulary, with the reason', async () => { + const cases: [string, string, keyof typeof MESSAGE, string | null][] = [ + ['SCA_CANCELLED', 'The ceremony was cancelled', 'Cancelled', null], + ['SCA_EXPIRED', 'The ceremony deadline passed', 'Expired', null], + ['SCA_UNSUPPORTED:NoAllowedBrowser', 'no allowed browser', 'Unsupported', 'NoAllowedBrowser'], + ['SCA_UNSUPPORTED:CallbackNotRouted', 'not routed', 'Unsupported', 'CallbackNotRouted'], + ['SCA_UNSUPPORTED:SessionUnavailable', 'no window', 'Unsupported', 'SessionUnavailable'], + ['SCA_UNSUPPORTED:PasskeyUnavailable', 'no passkeys', 'Unsupported', 'PasskeyUnavailable'], + ['SCA_ALREADY_ENROLLED', 'already', 'AlreadyEnrolled', null], + ['SCA_PROTOCOL:StateMismatch', 'the callback did not belong', 'Protocol', 'StateMismatch'], + ['SCA_PROTOCOL:InvalidFrameToken', 'frameToken is too long', 'Protocol', 'InvalidFrameToken'], + ['SCA_PROTOCOL', 'bad callback', 'Protocol', null], + ['SCA_TRANSPORT', 'verification timed out', 'Transport', null], + ['SCA_INVALID_CONFIGURATION', 'invalidRedirectURI', 'InvalidConfiguration', null], + ['SCA_CEREMONY_IN_PROGRESS', 'open', 'CeremonyInProgress', null], + ['SOMETHING_ELSE', 'surprise', 'Protocol', null], + ] + for (const [nativeCode, message, code, reason] of cases) { + const native = fakeNative({ + approve: jest.fn().mockRejectedValue(nativeError(nativeCode, message)), + }) + const err = await createScaClient(config, native) + .approve('t') + .catch((e: unknown) => e) + expect(isScaError(err)).toBe(true) + expect(err).toMatchObject({ code, reason, message: MESSAGE[code] }) + } + }) + + it('keeps the reason when Expo wraps an async rejection', async () => { + // The shape Expo produces for an async function: its own message with the + // native exception as the cause, and the native exception's code unchanged. + const wrapped = nativeError( + 'SCA_UNSUPPORTED:SessionUnavailable', + "Calling the 'approve' function has failed\n→ Caused by: No session could be presented", + ) + const native = fakeNative({ approve: jest.fn().mockRejectedValue(wrapped) }) + + await expect(createScaClient(config, native).approve('t')).rejects.toMatchObject({ + code: 'Unsupported', + reason: 'SessionUnavailable', + message: MESSAGE.Unsupported, + }) + + const nested = nativeError( + 'SCA_PROTOCOL:StateMismatch', + "Calling the 'enroll' function has failed\n→ Caused by: outer\n→ Caused by: The callback did not belong to this ceremony", + ) + expect(mapNativeScaError(nested)).toMatchObject({ + code: 'Protocol', + reason: 'StateMismatch', + message: MESSAGE.Protocol, + }) + }) + + it('reads the code from the tagged message when the rejection has none (iOS)', async () => { + // The shape observed on iOS: no `code`, and Expo's wrapped message. + const cases: [string, keyof typeof MESSAGE, string | null][] = [ + ['[SCA_CANCELLED] The ceremony was cancelled', 'Cancelled', null], + ['[SCA_EXPIRED] The ceremony deadline passed', 'Expired', null], + [ + '[SCA_ALREADY_ENROLLED] This end user already has a passkey on this authenticator.', + 'AlreadyEnrolled', + null, + ], + ['[SCA_CEREMONY_IN_PROGRESS] Another SCA ceremony is still open', 'CeremonyInProgress', null], + [ + '[SCA_UNSUPPORTED:SessionUnavailable] No session could be presented', + 'Unsupported', + 'SessionUnavailable', + ], + ['[SCA_NOT_A_CODE] surprise', 'Protocol', null], + ['The ceremony deadline passed', 'Protocol', null], + ] + for (const [inner, code, reason] of cases) { + const rejection = new Error( + `Calling the 'approve' function has failed\n→ Caused by: ${inner}`, + ) + const native = fakeNative({ approve: jest.fn().mockRejectedValue(rejection) }) + const err = await createScaClient(config, native) + .approve('t') + .catch((e: unknown) => e) + expect(err).toMatchObject({ code, reason, message: MESSAGE[code] }) + } + }) + + it('prefers a known code over the tag', () => { + expect( + mapNativeScaError(nativeError('SCA_EXPIRED', '[SCA_EXPIRED] The ceremony deadline passed')), + ).toMatchObject({ code: 'Expired', reason: null, message: MESSAGE.Expired }) + expect( + mapNativeScaError(nativeError('SCA_CANCELLED', '[SCA_EXPIRED] The ceremony deadline passed')), + ).toMatchObject({ code: 'Cancelled' }) + expect( + mapNativeScaError( + nativeError('ERR_FUNCTION_CALL', '[SCA_CANCELLED] The ceremony was cancelled'), + ), + ).toMatchObject({ code: 'Cancelled', message: MESSAGE.Cancelled }) + }) + + it('never puts native text in the message, and keeps it only on a non-enumerable cause', async () => { + const secret = 'keychain item 0x7f3a at /private/var/containers/internal-detail' + const rejections: unknown[] = [ + nativeError('SCA_PROTOCOL', secret), + nativeError( + 'SCA_UNSUPPORTED:SessionUnavailable', + `[SCA_UNSUPPORTED:SessionUnavailable] ${secret}`, + ), + nativeError('SOMETHING_ELSE', secret), + new Error(`Calling the 'approve' function has failed\n→ Caused by: [SCA_EXPIRED] ${secret}`), + new Error(secret), + ] + for (const rejection of rejections) { + const native = fakeNative({ approve: jest.fn().mockRejectedValue(rejection) }) + const err = (await createScaClient(config, native) + .approve('t') + .catch((e: unknown) => e)) as ScaError + + expect(isScaError(err)).toBe(true) + expect(err.message).not.toContain('keychain') + expect(String(err)).not.toContain('keychain') + expect(err.cause).toBe(rejection) + expect(Object.getOwnPropertyDescriptor(err, 'cause')?.enumerable).toBe(false) + expect(Object.keys(err)).not.toContain('cause') + expect(JSON.stringify(err)).not.toContain('keychain') + } + }) + + it('drops a reason that is not a plain name', () => { + const err = mapNativeScaError( + nativeError('SCA_UNSUPPORTED:no browser at /data/app/internal', 'x'), + ) + expect(err).toMatchObject({ code: 'Unsupported', reason: null, message: MESSAGE.Unsupported }) + }) + + it('sets the fixed message on the errors the SDK raises itself', async () => { + await expect(createScaClient(config, null).approve('t')).rejects.toMatchObject({ + message: MESSAGE.NativeModuleUnavailable, + }) + let finish: (value: string) => void = () => {} + const native = fakeNative({ + approve: jest.fn(() => new Promise((resolve) => (finish = resolve))), + }) + const client = createScaClient(config, native) + const first = client.approve('t1') + await expect(client.approve('t2')).rejects.toMatchObject({ + message: MESSAGE.CeremonyInProgress, + }) + finish('done') + await first + }) + + it('fails closed on codes that only exist on the object prototype', () => { + for (const key of ['constructor', 'toString', '__proto__', 'hasOwnProperty']) { + expect(mapNativeScaError(nativeError(key, 'x')).code).toBe('Protocol') + } + }) + + it('normalizes capabilities and maps their failures', async () => { + const client = createScaClient(config, fakeNative()) + await expect(client.capabilities()).resolves.toEqual({ + protocolVersion: 1, + surface: 'customTab', + callbackReady: true, + callbackVerified: null, + callbackTaskIsolated: true, + platformPasskeys: true, + }) + + const failing = createScaClient( + config, + fakeNative({ + capabilities: jest.fn().mockRejectedValue(nativeError('SCA_INVALID_CONFIGURATION', 'bad')), + }), + ) + await expect(failing.capabilities()).rejects.toMatchObject({ code: 'InvalidConfiguration' }) + }) + + it('reports a missing native module as NativeModuleUnavailable', async () => { + const client = createScaClient(config, null) + await expect(client.approve('t')).rejects.toMatchObject({ code: 'NativeModuleUnavailable' }) + await expect(client.capabilities()).rejects.toMatchObject({ code: 'NativeModuleUnavailable' }) + }) + + it('passes an existing ScaError through unchanged', () => { + const original = new ScaError('Expired', 'x') + expect(mapNativeScaError(original)).toBe(original) + expect(original.cause).toBeUndefined() + }) +}) diff --git a/src/__test__/scriptedCalls.ts b/src/__test__/scriptedCalls.ts new file mode 100644 index 0000000..60ed921 --- /dev/null +++ b/src/__test__/scriptedCalls.ts @@ -0,0 +1,275 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Every SDK call that turns a DAA response into an error, driven through the +// real clients with one response scripted to fail. +// +// The tests that sweep the error paths (the request id, the service's own error +// bodies, no secret in an error) share this table, so a call added here is +// swept by all of them. +// +// Not a test file — Jest's `testMatch` is `**/__test__/**/*.test.ts`, so this +// module is only ever imported, never collected. + +import { AuthClient } from '../api/AuthClient' +import { createDaaUserClient } from '../api/DaaUserClient' +import { webCryptoRegistrationFlowKeyProvider } from '../auth/RegistrationFlowKey' +import { isDaaError, type DaaError } from '../errors' +import { InMemorySecureKeyStore } from '../securekey/InMemorySecureKey' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { registeredAuthKey, signingFor } from './userClientSigning' + +/** + * The shape of `X-Request-Id` in a Circle test environment: 32 lowercase hex + * characters. Not a captured value. + */ +export const REQUEST_ID = '694b122b43d1b62dc75be5c6252f4de1' + +export const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +export const CLIENT_ENTITY_ID = '33333333-3333-4333-b333-333333333333' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const DESTINATION_ID = '55555555-5555-4555-8555-555555555555' +const ACCOUNT_ID = '66666666-6666-4666-8666-666666666666' +const LOGIN_REQUEST_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +export const EXPIRES_AT = '2026-08-26T12:00:00Z' + +/** A provider ID token shaped like a JWT, so a leak would also match `eyJ`. */ +export const ID_TOKEN = + 'eyJhbGciOiJSUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ0ZXN0LWlkLXRva2VuIn0.dGVzdC1zaWduYXR1cmU' +/** Distinctive enough that a substring match can only be this value. */ +export const REGISTRATION_HANDLE = 'test-registration-handle-7f3c9e1b2a' + +const PREPARED = `{"loginRequestId":"${LOGIN_REQUEST_ID}","oidcNonce":"${'n'.repeat(48)}","oidcState":"${'s'.repeat(48)}","expiresAt":"${EXPIRES_AT}"}` +const SESSION = `{"registrationHandle":"${REGISTRATION_HANDLE}","clientEntityId":"${CLIENT_ENTITY_ID}","expiresAt":"${EXPIRES_AT}"}` + +export function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +/** A DAA error body in the shape the service sends: `{"code":…,"message":…}`. */ +export function serviceError( + status: number, + code: number, + message: string, + headers: Readonly> = { 'X-Request-Id': REQUEST_ID }, +): DaaHttpResponse { + return { status, headers, bodyBytes: bytes(JSON.stringify({ code, message })) } +} + +function ok(status: number, payload: string): DaaHttpResponse { + return { status, headers: { 'X-Request-Id': 'req-ok' }, bodyBytes: bytes(`{"data":${payload}}`) } +} + +/** Builds the failing response, optionally from the request it answers. */ +export type Responder = (request: DaaHttpRequest) => DaaHttpResponse + +/** Records every request; the scripted step answers with the responder. */ +export class ScriptedTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor( + private readonly before: readonly DaaHttpResponse[], + private readonly respond: Responder, + ) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const index = this.sent.length - 1 + if (index < this.before.length) { + return this.before[index] as DaaHttpResponse + } + if (index === this.before.length) { + return this.respond(request) + } + throw new Error(`unexpected request ${request.method} ${request.path}`) + } +} + +export type ScriptedCall = Readonly<{ + name: string + /** `login` for the three ceremony calls, `user` for a `DaaUserClient` call. */ + surface: 'login' | 'user' + /** The documented success status, for a malformed-success case. */ + successStatus: number + /** Whether the request carries an idempotency key (`idempotency_conflict`). */ + idempotent: boolean + run: (respond: Responder) => Promise<{ call: Promise; transport: ScriptedTransport }> +}> + +function loginClient(transport: DaaTransport): AuthClient { + return new AuthClient({ + transport, + registrationFlowKeys: webCryptoRegistrationFlowKeyProvider(), + secureKeys: new InMemorySecureKeyStore(), + identity: { appId: 'app-123', environment: 'sandbox' }, + }) +} + +async function userCall( + respond: Responder, + invoke: (user: ReturnType) => Promise, +) { + const transport = new ScriptedTransport([], respond) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { transport, call: invoke(createDaaUserClient(transport, 'production', signing)) } +} + +export const LOGIN_CALLS: readonly ScriptedCall[] = [ + { + name: 'Prepare', + surface: 'login', + successStatus: 201, + idempotent: true, + run: async (respond) => { + const transport = new ScriptedTransport([], respond) + return { transport, call: loginClient(transport).prepareSocialLogin({ provider: 'GOOGLE' }) } + }, + }, + { + name: 'Social Session', + surface: 'login', + successStatus: 200, + idempotent: true, + run: async (respond) => { + const transport = new ScriptedTransport([ok(201, PREPARED)], respond) + const prepared = await loginClient(transport).prepareSocialLogin({ provider: 'GOOGLE' }) + return { + transport, + call: prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }), + } + }, + }, + { + name: 'Device Registration Complete', + surface: 'login', + successStatus: 200, + idempotent: true, + run: async (respond) => { + const transport = new ScriptedTransport([ok(201, PREPARED), ok(200, SESSION)], respond) + const prepared = await loginClient(transport).prepareSocialLogin({ provider: 'GOOGLE' }) + const pending = await prepared.completeSocialSession({ + idToken: ID_TOKEN, + clientEntityId: CLIENT_ENTITY_ID, + }) + return { transport, call: pending.complete() } + }, + }, +] + +export const SIGNED_CALLS: readonly ScriptedCall[] = [ + { + name: 'accounts.create', + surface: 'user', + successStatus: 201, + idempotent: true, + run: (respond) => + userCall(respond, (user) => + user.accounts.create({ + idempotencyKey: IDEMPOTENCY_KEY, + clientEntityId: CLIENT_ENTITY_ID, + custodyType: 'self', + type: 'third_party', + purpose: 'custody', + description: 'Primary', + blockchain: 'ARC', + }), + ), + }, + { + name: 'transfers.create', + surface: 'user', + successStatus: 201, + idempotent: true, + run: (respond) => + userCall(respond, (user) => + user.transfers.create({ + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'account', id: ACCOUNT_ID }, + amount: { amount: '10.25', currency: 'USD' }, + }), + ), + }, + { + name: 'withdrawals.create', + surface: 'user', + successStatus: 201, + idempotent: true, + run: (respond) => + userCall(respond, (user) => + user.withdrawals.create({ + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'wire', id: DESTINATION_ID }, + amount: { amount: '10.25', currency: 'USD' }, + }), + ), + }, + { + name: 'refreshContext', + surface: 'user', + successStatus: 200, + idempotent: false, + run: (respond) => userCall(respond, (user) => user.refreshContext()), + }, +] + +export const UNSIGNED_CALLS: readonly ScriptedCall[] = [ + { + name: 'depositAddresses.create', + surface: 'user', + successStatus: 201, + idempotent: true, + run: (respond) => + userCall(respond, (user) => + user.depositAddresses.create({ + idempotencyKey: IDEMPOTENCY_KEY, + accountId: ACCOUNT_ID, + currency: 'USD', + chain: 'ETH', + }), + ), + }, + { + name: 'accounts.get', + surface: 'user', + successStatus: 200, + idempotent: false, + run: (respond) => userCall(respond, (user) => user.accounts.get(ACCOUNT_ID)), + }, +] + +export const ALL_CALLS: readonly ScriptedCall[] = [ + ...LOGIN_CALLS, + ...SIGNED_CALLS, + ...UNSIGNED_CALLS, +] + +/** The `DaaError` the call failed with; anything else fails the test. */ +export async function daaErrorOf(call: Promise): Promise { + try { + await call + } catch (err) { + if (isDaaError(err)) { + return err + } + throw err + } + throw new Error('expected the call to fail') +} diff --git a/src/__test__/secureKey.test.ts b/src/__test__/secureKey.test.ts new file mode 100644 index 0000000..da9b709 --- /dev/null +++ b/src/__test__/secureKey.test.ts @@ -0,0 +1,163 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fromBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { InMemorySecureKeyStore } from '../testing' + +const CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000001' + +const identity = { + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, +} as const + +describe('InMemorySecureKeyStore', () => { + it('returns the same installation key for the same identity', async () => { + const store = new InMemorySecureKeyStore() + const a = await store.resolveOrCreate(identity) + const b = await store.resolveOrCreate(identity) + expect(a).toBe(b) + }) + + it('reports created until acknowledgement, then existing', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate(identity) + expect(key.resolution()).toBe('created') + await key.acknowledgeRegistration() + expect(key.resolution()).toBe('existing') + }) + + it('exposes a non-empty SPKI public key and a stable thumbprint', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate(identity) + const spki = await key.publicKeySpkiBase64Url() + expect(spki.length).toBeGreaterThan(0) + + const t1 = await key.thumbprint() + const t2 = await key.thumbprint() + expect(t1).toBe(t2) + expect(t1.length).toBeGreaterThan(0) + }) + + it('signs exact bytes as a 64-byte ES256 (R||S) signature that verifies', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate(identity) + const message = new TextEncoder().encode('{"idempotencyKey":"k"}') + const sig = await key.signExactBytes(message) + expect(sig.length).toBe(64) + + const spki = fromBase64Url(await key.publicKeySpkiBase64Url()) + const verifyKey = await globalThis.crypto.subtle.importKey( + 'spki', + toArrayBuffer(spki), + { name: 'ECDSA', namedCurve: 'P-256' }, + false, + ['verify'], + ) + const ok = await globalThis.crypto.subtle.verify( + { name: 'ECDSA', hash: 'SHA-256' }, + verifyKey, + toArrayBuffer(sig), + toArrayBuffer(message), + ) + expect(ok).toBe(true) + }) + + it('signs the registration device proof as a 64-byte ES256 (R||S) signature that verifies', async () => { + const key = await new InMemorySecureKeyStore().resolveOrCreate(identity) + const message = new TextEncoder().encode('{"idempotencyKey":"k"}') + const sig = await key.signRegistrationDeviceAuthorization(message) + expect(sig.length).toBe(64) + + const spki = fromBase64Url(await key.publicKeySpkiBase64Url()) + const verifyKey = await globalThis.crypto.subtle.importKey( + 'spki', + toArrayBuffer(spki), + { name: 'ECDSA', namedCurve: 'P-256' }, + false, + ['verify'], + ) + const ok = await globalThis.crypto.subtle.verify( + { name: 'ECDSA', hash: 'SHA-256' }, + verifyKey, + toArrayBuffer(sig), + toArrayBuffer(message), + ) + expect(ok).toBe(true) + }) + + it('derives distinct keys per environment namespace', async () => { + const store = new InMemorySecureKeyStore() + const sandbox = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: CLIENT_ENTITY_ID, + }) + const production = await store.resolveOrCreate({ + appId: 'app-123', + environment: 'production', + clientEntityId: CLIENT_ENTITY_ID, + }) + expect(sandbox).not.toBe(production) + expect(await sandbox.thumbprint()).not.toBe(await production.thumbprint()) + }) + + it('derives distinct keys per Owner namespace', async () => { + const store = new InMemorySecureKeyStore() + const ownerA = await store.resolveOrCreate(identity) + const ownerB = await store.resolveOrCreate({ + ...identity, + clientEntityId: '00000000-0000-4000-8000-000000000002', + }) + expect(ownerA).not.toBe(ownerB) + expect(await ownerA.thumbprint()).not.toBe(await ownerB.thumbprint()) + }) + + it('fails closed when constructed in a production build', () => { + const g = globalThis as { __DEV__?: boolean | undefined } + const prev = g.__DEV__ + g.__DEV__ = false + try { + expect(() => new InMemorySecureKeyStore()).toThrow(/must not be used in\s+production/) + } finally { + g.__DEV__ = prev + } + }) + + it('fails closed when no development marker is present', () => { + const g = globalThis as { + __DEV__?: boolean | undefined + process?: { env?: { NODE_ENV?: string } } + } + const previousDev = g.__DEV__ + const environment = g.process?.env + const previousNodeEnvironment = environment?.NODE_ENV + g.__DEV__ = undefined + if (environment !== undefined) delete environment.NODE_ENV + try { + expect(() => new InMemorySecureKeyStore()).toThrow( + /requires an explicit development or test environment marker/, + ) + } finally { + g.__DEV__ = previousDev + if (environment !== undefined) { + if (previousNodeEnvironment === undefined) delete environment.NODE_ENV + else environment.NODE_ENV = previousNodeEnvironment + } + } + }) +}) diff --git a/src/__test__/serialization.test.ts b/src/__test__/serialization.test.ts new file mode 100644 index 0000000..13f7cb6 --- /dev/null +++ b/src/__test__/serialization.test.ts @@ -0,0 +1,45 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody, serializeEmptyBody } from '../crypto/serialization' + +describe('serializeBody', () => { + it('produces exact UTF-8 bytes of the JSON encoding', () => { + const bytes = serializeBody({ a: 1, b: 'x' }) + expect(new TextDecoder().decode(bytes)).toBe('{"a":1,"b":"x"}') + }) + + it('is deterministic for the same input', () => { + const a = serializeBody({ idempotencyKey: 'k', amount: '1.00' }) + const b = serializeBody({ idempotencyKey: 'k', amount: '1.00' }) + expect(Array.from(a)).toEqual(Array.from(b)) + }) + + it('preserves author key order (serialize once, do not canonicalize)', () => { + const bytes = serializeBody({ b: 1, a: 2 }) + expect(new TextDecoder().decode(bytes)).toBe('{"b":1,"a":2}') + }) + + it('throws when the value is not JSON-serializable', () => { + expect(() => serializeBody(undefined)).toThrow(/not JSON-serializable/) + }) + + it('encodes a body-less request as the empty byte array', () => { + expect(serializeEmptyBody().length).toBe(0) + }) +}) diff --git a/src/__test__/sha256.test.ts b/src/__test__/sha256.test.ts new file mode 100644 index 0000000..ec97143 --- /dev/null +++ b/src/__test__/sha256.test.ts @@ -0,0 +1,68 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { sha256 } from '../crypto/sha256' +import { AUTH_KEY_WIRE_V1_SHA256, readAuthKeyWireFixtureBytes } from './authKeyWireFixture' + +function hex(bytes: Uint8Array): string { + return Array.from(bytes) + .map((b) => b.toString(16).padStart(2, '0')) + .join('') +} + +describe('sha256', () => { + it('matches known FIPS 180-4 vectors', () => { + expect(hex(sha256(new TextEncoder().encode('')))).toBe( + 'e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855', + ) + expect(hex(sha256(new TextEncoder().encode('abc')))).toBe( + 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad', + ) + // 56-byte input exercises the two-block padding path. + expect( + hex( + sha256( + new TextEncoder().encode('abcdbcdecdefdefgefghfghighijhijkijkljklmklmnlmnomnopnopq'), + ), + ), + ).toBe('248d6a61d20638b8e5c026930c3e6039a33ce45964ff2167f6ecedd419db06c1') + }) + + it('agrees with WebCrypto across every length through two blocks', async () => { + // Exhaustive so every padding path is covered, incl. the 55/56 and 64/128 + // block-boundary transitions where the length math is easiest to get wrong. + for (let len = 0; len <= 130; len++) { + const bytes = new Uint8Array(len) + for (let i = 0; i < len; i++) bytes[i] = (i * 31 + 7) & 0xff + const ref = new Uint8Array( + await globalThis.crypto.subtle.digest('SHA-256', toArrayBuffer(bytes)), + ) + expect(toBase64Url(sha256(bytes))).toBe(toBase64Url(ref)) + } + }) + + it('matches the published digest of the canonical AuthKeyWireV1 fixture', () => { + // The fixture carries no standalone digest vector, but its own published + // SHA-256 is one: a multi-kilobyte, many-block input whose expected digest + // is fixed by daa-ios-sdk and independently asserted by daa-android-sdk. + // This is also what makes the loader's drift guard trustworthy. + expect(hex(sha256(readAuthKeyWireFixtureBytes()))).toBe(AUTH_KEY_WIRE_V1_SHA256) + }) +}) diff --git a/src/__test__/signedResource.test.ts b/src/__test__/signedResource.test.ts new file mode 100644 index 0000000..b8727bc --- /dev/null +++ b/src/__test__/signedResource.test.ts @@ -0,0 +1,451 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { getSignedResource, postSignedResource } from '../api/signedResource' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { serializeBody } from '../crypto/serialization' +import { sha256 } from '../crypto/sha256' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { InMemorySecureKeyStore } from '../testing' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const PATH = '/v1/accounts/transfers' + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const next = this.responses.shift() + if (next === undefined) { + throw new Error('transport has no more responses') + } + return next + } +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function errorBody(code: string | number): Uint8Array { + return bytes(`{"status":{"code":${JSON.stringify(code)}}}`) +} + +async function registeredKey(): Promise { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: '00000000-0000-4000-8000-000000000001', + }) + await key.acknowledgeRegistration() + return key +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +async function post( + transport: DaaTransport, + bodyBytes: Uint8Array, + authKey: OwnerAuthKey, +): Promise { + return postSignedResource({ + transport, + operation: 'transfer', + authKey, + authKeyId: AUTH_KEY_ID, + bodyBytes, + expectedStatus: 201, + decode: (value) => { + if (typeof value !== 'object' || value === null || !('id' in value)) { + throw new Error('missing id') + } + const id = value.id + if (typeof id !== 'string') { + throw new Error('id is not a string') + } + return id + }, + }) +} + +describe('postSignedResource', () => { + it('sends the exact body bytes with a compact X-Device-Authorization JWS and query=null', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + const transport = new SequenceTransport([ + { status: 201, headers: {}, bodyBytes: envelope('{"id":"transfer-1"}') }, + ]) + + await expect(post(transport, bodyBytes, authKey)).resolves.toBe('transfer-1') + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + expect(request?.method).toBe('POST') + expect(request?.path).toBe(PATH) + expect(request?.query).toBeNull() + expect(request?.bodyBytes).toBe(bodyBytes) + expect(request?.headers['Content-Type']).toBe('application/json') + const compact = request?.headers[DEVICE_AUTHORIZATION_HEADER] + expect(compact).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/) + + if (compact === undefined) { + throw new Error('missing device authorization') + } + const payloadJson = new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? '')) + const payload: unknown = JSON.parse(payloadJson) + expect(payload).toMatchObject({ + canonical_path: PATH, + method: 'POST', + discriminator: 'transfer', + schema_version: 1, + idempotency_key: IDEMPOTENCY_KEY, + }) + }) + + it('rejects a GET registry operation', async () => { + const authKey = await registeredKey() + const transport = new SequenceTransport([]) + expect( + await detailOf( + postSignedResource({ + transport, + operation: 'get_device_context', + authKey, + authKeyId: AUTH_KEY_ID, + bodyBytes: serializeBody({}), + expectedStatus: 200, + decode: (value) => value, + }), + ), + ).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) + + it('does not retry DEVICE_AUTHORIZATION_REPLAYED (420043) and maps it to contract_violation', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY }) + const transport = new SequenceTransport([ + { + status: 401, + headers: { 'X-Request-Id': 'req-replayed' }, + bodyBytes: errorBody(420043), + }, + ]) + + expect(await detailOf(post(transport, bodyBytes, authKey))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-replayed', + }) + expect(transport.sent).toHaveLength(1) + }) + + it('maps DEVICE_AUTHORIZATION_REQUEST_MISMATCH (420036) to contract_violation without retrying', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY }) + const transport = new SequenceTransport([ + { + status: 403, + headers: { 'X-Request-Id': 'req-mismatch' }, + bodyBytes: errorBody(420036), + }, + ]) + + expect(await detailOf(post(transport, bodyBytes, authKey))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-mismatch', + }) + expect(transport.sent).toHaveLength(1) + }) + + it('maps DEVICE_AUTHORIZATION_INVALID (420031) to contract_violation without a JWS in the message', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY }) + const transport = new SequenceTransport([ + { + status: 400, + headers: { 'X-Request-Id': 'req-invalid' }, + bodyBytes: errorBody(420031), + }, + ]) + + const err = await post(transport, bodyBytes, authKey).catch((e: unknown) => e) + expect(isDaaError(err)).toBe(true) + if (!isDaaError(err)) return + expect(err.detail).toEqual({ kind: 'contract_violation', correlationId: 'req-invalid' }) + expect(err.message).not.toMatch(/[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/) + expect(err.message).not.toMatch(/eyJ/) + expect(transport.sent).toHaveLength(1) + }) + + // A non-numeric string code classifies as `api`, even when it spells a known + // error name. Sent once: there is no fresh-JWS + // retry, because DAA has no expiry code that could trigger one. + it.each(['DEVICE_AUTHORIZATION_INVALID', 'DEVICE_AUTHORIZATION_EXPIRED'])( + 'classifies the name string %s as api and sends once', + async (name) => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY }) + const transport = new SequenceTransport([ + { status: 401, headers: {}, bodyBytes: errorBody(name) }, + { status: 201, headers: {}, bodyBytes: envelope('{"id":"transfer-2"}') }, + ]) + + expect(await detailOf(post(transport, bodyBytes, authKey))).toEqual({ + kind: 'api', + httpStatus: 401, + daaStatusCode: name, + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }, + ) + + it('maps a 409 IDEMPOTENCY_KEY_REUSED (420034) to idempotency_conflict with the signed request’s own key', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + const transport = new SequenceTransport([ + { + status: 409, + headers: { 'X-Request-Id': 'req-conflict' }, + bodyBytes: errorBody(420034), + }, + ]) + + expect(await detailOf(post(transport, bodyBytes, authKey))).toEqual({ + kind: 'idempotency_conflict', + idempotencyKey: IDEMPOTENCY_KEY, + correlationId: 'req-conflict', + }) + expect(transport.sent).toHaveLength(1) + }) + + it('keeps a 409 with the name string IDEMPOTENCY_KEY_REUSED an api failure and sends once', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + const transport = new SequenceTransport([ + { + status: 409, + headers: { 'X-Request-Id': 'req-conflict-name' }, + bodyBytes: errorBody('IDEMPOTENCY_KEY_REUSED'), + }, + { status: 201, headers: {}, bodyBytes: envelope('{"id":"transfer-2"}') }, + ]) + + expect(await detailOf(post(transport, bodyBytes, authKey))).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 'IDEMPOTENCY_KEY_REUSED', + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }) + + it('does not map a 409 for a different reason to idempotency_conflict even with a recoverable idempotency key', async () => { + const authKey = await registeredKey() + const bodyBytes = serializeBody({ idempotencyKey: IDEMPOTENCY_KEY, amount: '1.00' }) + const transport = new SequenceTransport([ + { + status: 409, + headers: { 'X-Request-Id': 'req-conflict-other' }, + // A 409 whose body carries some other status code entirely — not the + // one that means "safe to retry with the same key and bytes". A body + // that merely has the right HTTP status must not be trusted into + // `idempotency_conflict` on that basis alone. + bodyBytes: errorBody('SOME_OTHER_CONFLICT'), + }, + ]) + + const detail = await detailOf(post(transport, bodyBytes, authKey)) + expect(detail.kind).not.toBe('idempotency_conflict') + expect(detail).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 'SOME_OTHER_CONFLICT', + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }) +}) + +const CONTEXT_PATH = '/v1/accounts/auth/context' + +async function get(transport: DaaTransport, authKey: OwnerAuthKey): Promise { + return getSignedResource({ + transport, + operation: 'get_device_context', + authKey, + authKeyId: AUTH_KEY_ID, + expectedStatus: 200, + decode: (value) => { + if (typeof value !== 'object' || value === null || !('authKeyId' in value)) { + throw new Error('missing authKeyId') + } + const authKeyId = value.authKeyId + if (typeof authKeyId !== 'string') { + throw new Error('authKeyId is not a string') + } + return authKeyId + }, + }) +} + +describe('getSignedResource', () => { + it('sends a bodyless GET with a compact X-Device-Authorization JWS and query=null', async () => { + const authKey = await registeredKey() + const transport = new SequenceTransport([ + { status: 200, headers: {}, bodyBytes: envelope(`{"authKeyId":"${AUTH_KEY_ID}"}`) }, + ]) + + await expect(get(transport, authKey)).resolves.toBe(AUTH_KEY_ID) + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + expect(request?.method).toBe('GET') + expect(request?.path).toBe(CONTEXT_PATH) + expect(request?.query).toBeNull() + // No body to describe, so no Content-Type — the same bodyless shape + // `resourceRequest.ts`'s unsigned `readResource` sends. + expect(request?.bodyBytes).toBeNull() + // No Content-Type either: the only header a bodyless signed GET carries is + // the authorization JWS. + expect(Object.keys(request?.headers ?? {})).toEqual([DEVICE_AUTHORIZATION_HEADER]) + const compact = request?.headers[DEVICE_AUTHORIZATION_HEADER] + expect(compact).toMatch(/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/) + + if (compact === undefined) { + throw new Error('missing device authorization') + } + const payloadJson = new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? '')) + const payload: unknown = JSON.parse(payloadJson) + expect(payload).toMatchObject({ + canonical_path: CONTEXT_PATH, + method: 'GET', + discriminator: 'get_device_context', + schema_version: 1, + aud: 'circle-digital-asset-accounts', + }) + // The bodyless rule: hash the empty byte array and omit idempotency_key. + expect(payload).not.toHaveProperty('idempotency_key') + expect((payload as { body_sha256: string }).body_sha256).toBe( + toBase64Url(sha256(new Uint8Array(0))), + ) + }) + + it('rejects a POST registry operation', async () => { + const authKey = await registeredKey() + const transport = new SequenceTransport([]) + expect( + await detailOf( + getSignedResource({ + transport, + operation: 'transfer', + authKey, + authKeyId: AUTH_KEY_ID, + expectedStatus: 201, + decode: (value) => value, + }), + ), + ).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) + + it.each(['DEVICE_AUTHORIZATION_INVALID', 'DEVICE_AUTHORIZATION_EXPIRED'])( + 'classifies the name string %s as api and sends once', + async (name) => { + const authKey = await registeredKey() + const transport = new SequenceTransport([ + { status: 403, headers: {}, bodyBytes: errorBody(name) }, + { status: 200, headers: {}, bodyBytes: envelope(`{"authKeyId":"${AUTH_KEY_ID}"}`) }, + ]) + + expect(await detailOf(get(transport, authKey))).toEqual({ + kind: 'api', + httpStatus: 403, + daaStatusCode: name, + retryable: false, + }) + expect(transport.sent).toHaveLength(1) + }, + ) + + it('maps DEVICE_AUTHORIZATION_REPLAYED (420043) to contract_violation without retrying', async () => { + const authKey = await registeredKey() + const transport = new SequenceTransport([ + { + status: 401, + headers: { 'X-Request-Id': 'req-replayed' }, + bodyBytes: errorBody(420043), + }, + ]) + + expect(await detailOf(get(transport, authKey))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-replayed', + }) + expect(transport.sent).toHaveLength(1) + }) + + it('accepts only the documented 200', async () => { + const authKey = await registeredKey() + for (const status of [201, 204, 299]) { + const transport = new SequenceTransport([ + { status, headers: {}, bodyBytes: envelope(`{"authKeyId":"${AUTH_KEY_ID}"}`) }, + ]) + const detail = await detailOf(get(transport, authKey)) + expect(detail).toEqual({ kind: 'api', httpStatus: status, retryable: false }) + } + }) + + it('has no idempotency key to recover from a bodyless GET, so a 409 stays an api failure', async () => { + const authKey = await registeredKey() + const transport = new SequenceTransport([ + { + status: 409, + headers: { 'X-Request-Id': 'req-409' }, + bodyBytes: errorBody(420034), + }, + ]) + + expect(await detailOf(get(transport, authKey))).toEqual({ + kind: 'api', + httpStatus: 409, + daaStatusCode: 420034, + retryable: false, + }) + }) +}) diff --git a/src/__test__/socialLoginRequestPayload.test.ts b/src/__test__/socialLoginRequestPayload.test.ts new file mode 100644 index 0000000..68b4399 --- /dev/null +++ b/src/__test__/socialLoginRequestPayload.test.ts @@ -0,0 +1,187 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { checkPrepareReceipt } from '../auth/prepareReceipt' +import { MalformedPayloadError } from '../wire/payload' +import { toSocialLoginRequest } from '../wire/socialLoginRequestPayload' + +/** The `SocialLoginRequest` decoder: the contract's five required fields. */ + +const LOGIN_REQUEST_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const NONCE = 'n'.repeat(32) +const STATE = 's'.repeat(32) +const RECEIPT = `eyJhbGciOiJFUzI1NiJ9.${'p'.repeat(64)}.c2ln` + +/** + * A `201` body captured verbatim from the service for the SDK's own Prepare + * request. Four fields, no `prepareReceiptJws`, and + * `expiresAt` as a JSON number of epoch milliseconds rather than the contract's ISO-8601 + * string. Kept as a literal so it stays what the service actually said. + */ +const CAPTURED_PREPARE_RESPONSE = { + loginRequestId: '9f6ead8b-ff88-43fc-af00-7016eef7f4b3', + oidcNonce: 'V3dQJq2pX2-t70oIlt0EX7I6oZLo_id94-43ywbCAL8', + oidcState: 'VVOX5X68MHIBzK2K8eVOtad3pQAFGs2vDxY43QosYAA', + expiresAt: 1788290024580, +} + +/** `CAPTURED_PREPARE_RESPONSE.expiresAt` in the form the decoder must normalise to. */ +const CAPTURED_EXPIRES_AT_ISO = '2026-09-01T19:13:44.580Z' + +function payload(overrides: Record = {}): Record { + return { + loginRequestId: LOGIN_REQUEST_ID, + oidcNonce: NONCE, + oidcState: STATE, + expiresAt: '2026-08-26T12:00:00Z', + prepareReceiptJws: RECEIPT, + ...overrides, + } +} + +describe('toSocialLoginRequest', () => { + it('reads every field the contract guarantees', () => { + expect(toSocialLoginRequest(payload())).toEqual({ + loginRequestId: LOGIN_REQUEST_ID, + oidcNonce: NONCE, + oidcState: STATE, + expiresAt: '2026-08-26T12:00:00Z', + prepareReceiptJws: RECEIPT, + }) + }) + + it('treats a missing receipt as null rather than malformed', () => { + const { prepareReceiptJws, ...withoutReceipt } = payload() + expect(prepareReceiptJws).toBe(RECEIPT) + expect(toSocialLoginRequest(withoutReceipt).prepareReceiptJws).toBeNull() + expect(toSocialLoginRequest(payload({ prepareReceiptJws: null })).prepareReceiptJws).toBeNull() + }) + + it('ignores unknown fields rather than failing the response', () => { + const decoded = toSocialLoginRequest(payload({ authKeyId: LOGIN_REQUEST_ID, extra: 1 })) + expect(Object.keys(decoded).sort()).toEqual([ + 'expiresAt', + 'loginRequestId', + 'oidcNonce', + 'oidcState', + 'prepareReceiptJws', + ]) + }) + + it('carries a receipt through raw, whatever it is, for the receipt check to judge', () => { + // Rejecting a malformed receipt here would fail login on an SDK with no + // trust anchor, which is meant to ignore the receipt. + for (const receipt of ['', 'not-a-jws', `${'a'.repeat(30)}.${'b'.repeat(30)}`, 42, {}]) { + expect(toSocialLoginRequest(payload({ prepareReceiptJws: receipt })).prepareReceiptJws).toBe( + receipt, + ) + } + }) + + it('rejects a non-UUID login request id', () => { + expect(() => toSocialLoginRequest(payload({ loginRequestId: 'login-1' }))).toThrow( + MalformedPayloadError, + ) + }) + + it('enforces the contract length bounds on the OIDC values', () => { + // Both bounds are stated as reject-just-outside plus accept-exactly-at. + // The base fixture is 32 characters, so the accept-at-minimum case is + // asserted on its own: an off-by-one that widens the minimum fails here. + for (const field of ['oidcNonce', 'oidcState']) { + expect(() => toSocialLoginRequest(payload({ [field]: 'x'.repeat(31) }))).toThrow( + MalformedPayloadError, + ) + expect(toSocialLoginRequest(payload({ [field]: 'x'.repeat(32) }))).toBeDefined() + expect(toSocialLoginRequest(payload({ [field]: 'x'.repeat(256) }))).toBeDefined() + expect(() => toSocialLoginRequest(payload({ [field]: 'x'.repeat(257) }))).toThrow( + MalformedPayloadError, + ) + } + }) + + it('rejects a timestamp that is not the service ISO-8601 form', () => { + for (const expiresAt of ['2026-08-26', '2026-08-26 12:00:00Z', 'later']) { + expect(() => toSocialLoginRequest(payload({ expiresAt }))).toThrow(MalformedPayloadError) + } + expect( + toSocialLoginRequest(payload({ expiresAt: '2026-08-26T12:00:00.123+02:00' })), + ).toBeDefined() + }) + + it('decodes the response the service sends', () => { + // Number `expiresAt`, no receipt. Both diverge from the contract OpenAPI and + // both are what the service returns, so the decoder has to take them. + expect(toSocialLoginRequest(CAPTURED_PREPARE_RESPONSE)).toEqual({ + loginRequestId: '9f6ead8b-ff88-43fc-af00-7016eef7f4b3', + oidcNonce: 'V3dQJq2pX2-t70oIlt0EX7I6oZLo_id94-43ywbCAL8', + oidcState: 'VVOX5X68MHIBzK2K8eVOtad3pQAFGs2vDxY43QosYAA', + expiresAt: CAPTURED_EXPIRES_AT_ISO, + prepareReceiptJws: null, + }) + }) + + it('normalises epoch milliseconds to the same text the string form carries', () => { + // Pinned, not assumed: an off-by-a-unit reading (seconds, or microseconds) + // would still produce a `DATE_TIME`-shaped string and pass a shape-only check. + expect(toSocialLoginRequest(payload({ expiresAt: 1788290024580 })).expiresAt).toBe( + CAPTURED_EXPIRES_AT_ISO, + ) + expect(toSocialLoginRequest(payload({ expiresAt: 1 })).expiresAt).toBe( + '1970-01-01T00:00:00.001Z', + ) + // The string form is passed through untouched, so both wire forms land on one + // public type without the ISO input being rewritten. + expect(toSocialLoginRequest(payload({ expiresAt: '2026-08-26T12:00:00Z' })).expiresAt).toBe( + '2026-08-26T12:00:00Z', + ) + }) + + it('rejects an epoch timestamp that is not a plausible count of milliseconds', () => { + for (const expiresAt of [ + 1788290024580.5, // fractional + -1788290024580, // negative + 0, // the epoch itself is a dropped field, not an expiry + 8.64e15 + 1, // past the largest instant `Date` represents + 1e15, // renders a year `DATE_TIME` cannot spell + Number.NaN, + Number.POSITIVE_INFINITY, + Number.MAX_SAFE_INTEGER, + ]) { + expect(() => toSocialLoginRequest(payload({ expiresAt }))).toThrow(MalformedPayloadError) + } + }) + + it('leaves the receipt decision to the check, which ignores any receipt without an anchor', async () => { + // Decoding a receipt, or its absence, buys no trust: with no trust anchor + // pinned the check ignores both alike, and with one it requires a receipt. + const decoded = toSocialLoginRequest(CAPTURED_PREPARE_RESPONSE) + expect(decoded.prepareReceiptJws).toBeNull() + const expected = (): never => { + throw new Error('no expectation is computed without an anchor') + } + await expect(checkPrepareReceipt(decoded.prepareReceiptJws, null, expected)).resolves.toBeNull() + await expect(checkPrepareReceipt(RECEIPT, null, expected)).resolves.toBeNull() + }) + + it('rejects a payload that is not an object', () => { + for (const value of [null, [], 'x', 7]) { + expect(() => toSocialLoginRequest(value)).toThrow(MalformedPayloadError) + } + }) +}) diff --git a/src/__test__/transactionPayload.test.ts b/src/__test__/transactionPayload.test.ts new file mode 100644 index 0000000..4d0643a --- /dev/null +++ b/src/__test__/transactionPayload.test.ts @@ -0,0 +1,268 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import { Transaction, TransactionBlockchainLocation } from '../models/Transaction' +import { MalformedPayloadError } from '../wire/payload' +import { toTransaction, toTransactions } from '../wire/transactionPayload' + +/** + * Decoding tests for the transaction model. These go through the real parse and + * mapping rather than constructing a payload object directly, because the wire + * spellings, the number handling, and the required/optional line are the things + * under test — see the class note on `Transaction`. + */ + +const REQUIRED = + '"id":"txn-1","type":"transfer","status":"pending",' + + '"amount":{"amount":"10.00","currency":"USD"},' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z"' + +function decode(body: string): Transaction { + return toTransaction(JSON.parse(body) as unknown) +} + +function decodeComplete(extra = ''): Transaction { + return decode(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) +} + +function transactionWith(field: string, value: string): Transaction { + return decodeComplete(`"${field}":${value}`) +} + +describe('required and optional fields', () => { + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + id: '"txn-1"', + type: '"transfer"', + status: '"pending"', + amount: '{"amount":"10.00","currency":"USD"}', + createDate: '"2026-01-01T00:00:00Z"', + updateDate: '"2026-01-02T00:00:00Z"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + expect(decode(body(complete)).id).toBe('txn-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toTransaction(null)).toThrow(MalformedPayloadError) + expect(() => toTransaction([])).toThrow(MalformedPayloadError) + }) + + it('rejects an explicit null on a guaranteed field', () => { + expect(() => + decode( + '{"id":null,"type":"transfer","status":"pending",' + + '"amount":{"amount":"10.00","currency":"USD"},' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z"}', + ), + ).toThrow(MalformedPayloadError) + }) + + it('rejects a field carried in the wrong shape', () => { + expect(() => transactionWith('id', '{}')).toThrow(MalformedPayloadError) + expect(() => transactionWith('id', 'true')).toThrow(MalformedPayloadError) + expect(() => transactionWith('amount', '"nope"')).toThrow(MalformedPayloadError) + expect(() => transactionWith('createDate', '7')).toThrow(MalformedPayloadError) + expect(() => transactionWith('source', '"account"')).toThrow(MalformedPayloadError) + }) + + it('tolerates absent source and destination', () => { + const transaction = decodeComplete() + expect(transaction.source).toBeNull() + expect(transaction.destination).toBeNull() + }) + + it('treats an explicit null source or destination as absence', () => { + const transaction = decodeComplete('"source":null,"destination":null') + expect(transaction.source).toBeNull() + expect(transaction.destination).toBeNull() + }) +}) + +describe('closed sets and locations', () => { + it('decodes each documented type and status', () => { + expect(transactionWith('type', '"deposit"').type).toEqual({ kind: 'deposit' }) + expect(transactionWith('type', '"withdrawal"').type).toEqual({ kind: 'withdrawal' }) + expect(transactionWith('type', '"fx"').type).toEqual({ kind: 'fx' }) + expect(transactionWith('type', '"fee"').type).toEqual({ kind: 'fee' }) + expect(transactionWith('type', '"credit"').type).toEqual({ kind: 'credit' }) + expect(transactionWith('type', '"other"').type).toEqual({ kind: 'other' }) + expect(transactionWith('status', '"complete"').status).toEqual({ kind: 'complete' }) + expect(transactionWith('status', '"failed"').status).toEqual({ kind: 'failed' }) + expect(transactionWith('status', '"returned"').status).toEqual({ kind: 'returned' }) + }) + + it('degrades an unfamiliar type or status to unrecognized without failing the row', () => { + expect(transactionWith('type', '"rebate"').type).toEqual({ + kind: 'unrecognized', + rawValue: 'rebate', + }) + expect(transactionWith('status', '"settling"').status).toEqual({ + kind: 'unrecognized', + rawValue: 'settling', + }) + }) + + it('decodes an account leg', () => { + const transaction = decodeComplete('"source":{"type":"account","id":"1000662322"}') + expect(transaction.source).toEqual({ kind: 'account', accountId: '1000662322' }) + }) + + it('decodes a blockchain destination with a redacted address', () => { + const transaction = decodeComplete( + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest","addressTag":"memo"}', + ) + expect(transaction.destination).toBeInstanceOf(TransactionBlockchainLocation) + if (!(transaction.destination instanceof TransactionBlockchainLocation)) { + throw new Error('expected a blockchain destination') + } + expect(transaction.destination.chain).toBe('ETH') + expect(transaction.destination.address).toBe('0xdest') + expect(transaction.destination.addressTag).toBe('memo') + }) + + it('accepts a blockchain source with only a chain', () => { + const transaction = decodeComplete('"source":{"type":"blockchain","chain":"SOL"}') + expect(transaction.source).toBeInstanceOf(TransactionBlockchainLocation) + if (!(transaction.source instanceof TransactionBlockchainLocation)) { + throw new Error('expected a blockchain source') + } + expect(transaction.source.chain).toBe('SOL') + expect(transaction.source.address).toBeNull() + }) + + it('decodes wire and ach fiat legs', () => { + const wire = decodeComplete( + '"source":{"type":"wire","id":"3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8","name":"Bank of Example"}', + ) + expect(wire.source).toEqual({ + kind: 'wire', + fiatAccountId: '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + name: 'Bank of Example', + }) + + const ach = decodeComplete( + '"destination":{"type":"ach","id":"4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8"}', + ) + expect(ach.destination).toEqual({ + kind: 'ach', + fiatAccountId: '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8', + name: null, + }) + }) + + it('degrades an unfamiliar location type to unrecognized', () => { + const transaction = decodeComplete('"source":{"type":"verified_blockchain","id":"addr-1"}') + expect(transaction.source).toEqual({ kind: 'unrecognized', rawValue: 'verified_blockchain' }) + }) + + it('rejects a fiat or account leg missing its id', () => { + expect(() => decodeComplete('"source":{"type":"account"}')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"destination":{"type":"wire","name":"Bank"}')).toThrow( + MalformedPayloadError, + ) + }) + + it('ignores unknown response fields wherever they appear', () => { + const transaction = decode( + '{"id":"txn-1","type":"transfer","status":"pending",' + + '"amount":{"amount":"1","currency":"USD","futureScale":"2"},' + + '"source":{"type":"account","id":"acct-src","futureField":true},' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z",' + + '"settlementTier":"gold"}', + ) + expect(transaction.id).toBe('txn-1') + expect(transaction.source).toEqual({ kind: 'account', accountId: 'acct-src' }) + expect(Object.keys(transaction)).not.toContain('settlementTier') + }) +}) + +describe('list decoding', () => { + it('decodes an array of transactions and freezes it', () => { + const items = toTransactions([JSON.parse(`{${REQUIRED}}`)]) + expect(items).toHaveLength(1) + expect(items[0]?.id).toBe('txn-1') + expect(Object.isFrozen(items)).toBe(true) + }) + + it('rejects a non-array collection payload', () => { + expect(() => toTransactions({})).toThrow(MalformedPayloadError) + expect(() => toTransactions(null)).toThrow(MalformedPayloadError) + }) +}) + +describe('redaction', () => { + const transaction = decodeComplete( + '"destination":{"type":"blockchain","chain":"ETH","address":"0xSECRET","addressTag":"tag-SECRET"}', + ) + const secrets = ['0xSECRET', 'tag-SECRET', '10.00'] + + it('keeps every sensitive value off the transaction object as an own property', () => { + expect(Object.getOwnPropertyNames(transaction).sort()).toEqual( + ['id', 'type', 'status', 'source', 'destination', 'createDate', 'updateDate'].sort(), + ) + expect(Object.getOwnPropertyNames(transaction.destination as object).sort()).toEqual( + ['kind', 'chain'].sort(), + ) + }) + + it.each([ + ['JSON.stringify', (value: unknown): string => JSON.stringify(value) ?? ''], + ['util.inspect (what console.log renders)', (value: unknown): string => inspect(value)], + ['String()', (value: unknown): string => String(value)], + [ + 'spread into a plain object', + (value: unknown): string => JSON.stringify({ ...(value as object) }) ?? '', + ], + ])('reveals no sensitive value through %s', (_name, render) => { + for (const rendered of [render(transaction), render(transaction.destination)]) { + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + } + }) + + it('redacts amount and blockchain address in toJSON', () => { + expect(JSON.parse(JSON.stringify(transaction))).toMatchObject({ + id: 'txn-1', + amount: { amount: '', currency: 'USD' }, + destination: { + kind: 'blockchain', + chain: 'ETH', + address: '', + addressTag: '', + }, + }) + }) + + it('still reveals hidden fields when inspect is asked to', () => { + const revealing = inspect(transaction, { showHidden: true, getters: true, depth: null }) + expect(revealing).toContain('10.00') + expect(revealing).toContain('0xSECRET') + }) +}) diff --git a/src/__test__/transactionsClient.test.ts b/src/__test__/transactionsClient.test.ts new file mode 100644 index 0000000..a900236 --- /dev/null +++ b/src/__test__/transactionsClient.test.ts @@ -0,0 +1,223 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import { TransactionBlockchainLocation } from '../models/Transaction' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +const ORIGIN = 'https://api.circle.com' +const CURSOR_AFTER = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CURSOR_BEFORE = '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = '5f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const TRANSACTION = + '{"id":"txn-1","type":"transfer","status":"pending",' + + '"amount":{"amount":"10.00","currency":"USDC"},' + + '"source":{"type":"account","id":"1000662322"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest"},' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function pageBody(transaction = TRANSACTION): Uint8Array { + return bytes(`{"data":[${transaction}]}`) +} + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: readonly DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) throw new Error('unexpected request') + return response + } +} + +function response(headers: Readonly> = {}): DaaHttpResponse { + return { status: 200, headers, bodyBytes: pageBody() } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('transactions list', () => { + it('loads and freezes transactions over the exact public collection path', async () => { + const transport = new SequenceTransport([response()]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).transactions.list() + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/accounts/transactions', + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(page.items[0]?.id).toBe('txn-1') + expect(page.items[0]?.type).toEqual({ kind: 'transfer' }) + expect(page.items[0]?.destination).toBeInstanceOf(TransactionBlockchainLocation) + expect(Object.isFrozen(page)).toBe(true) + expect(Object.isFrozen(page.items)).toBe(true) + expect(Object.isFrozen(page.items[0])).toBe(true) + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + }) + + it('serializes the documented transaction filters in deterministic order', async () => { + const transport = new SequenceTransport([response()]) + const transactions = createDaaUserClient(transport, 'production', NO_SIGNING).transactions + + await transactions.list({ + custodyType: 'segregated', + accountId: '1000662322', + clientEntityId: CLIENT_ENTITY_ID, + isAttributed: true, + type: ['transfer', 'deposit'], + status: ['pending', 'complete'], + currency: 'USDC', + from: '2026-08-01T00:00:00Z', + to: '2026-08-18T00:00:00Z', + pageAfter: CURSOR_AFTER, + pageSize: 50, + }) + + expect(transport.sent[0]?.query).toBe( + 'custodyType=segregated&accountId=1000662322' + + `&clientEntityId=${CLIENT_ENTITY_ID}&isAttributed=true` + + '&type=transfer&type=deposit&status=pending&status=complete' + + '¤cy=USDC' + + '&from=2026-08-01T00%3A00%3A00Z&to=2026-08-18T00%3A00%3A00Z' + + `&pageAfter=${CURSOR_AFTER}&pageSize=50`, + ) + }) + + it('follows only the same transaction collection and preserves its opaque query', async () => { + const nextQuery = 'z=last&pageAfter=backing%2Fcursor%3D&repeat=1&repeat=2&reserved=%2B%26' + const previousQuery = 'pageBefore=opaque-value&pageSize=2' + const transport = new SequenceTransport([ + response({ + Link: + `<${ORIGIN}/v1/accounts/transactions?${nextQuery}>; rel="next", ` + + `<${ORIGIN}/v1/accounts/transactions?${previousQuery}>; rel="prev"`, + }), + response(), + response(), + ]) + + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).transactions.list() + await page.next() + await page.previous() + + expect(transport.sent[1]?.query).toBe(nextQuery) + expect(transport.sent[2]?.query).toBe(previousQuery) + for (const request of transport.sent) { + expect(request.path).toBe('/v1/accounts/transactions') + expect(request.method).toBe('GET') + expect(request.bodyBytes).toBeNull() + } + }) + + it.each([ + `${ORIGIN}/v1/accounts?pageAfter=${CURSOR_AFTER}`, + `${ORIGIN}/v1/accounts/transfers?pageAfter=${CURSOR_AFTER}`, + `https://evil.example/v1/accounts/transactions?pageAfter=${CURSOR_AFTER}`, + ])('rejects navigation outside the trusted transaction collection: %s', async (target) => { + const transport = new SequenceTransport([response({ Link: `<${target}>; rel="next"` })]) + + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).transactions.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it('uses the configured environment as the pagination trust anchor', async () => { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts/transactions?pageAfter=x>; rel="next"` }), + ]) + + const detail = await detailOf( + createDaaUserClient(transport, 'sandbox', NO_SIGNING).transactions.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + null, + [], + { pageAfter: CURSOR_AFTER, pageBefore: CURSOR_BEFORE }, + { pageAfter: 'not-a-uuid' }, + { pageBefore: 'not-a-uuid' }, + { clientEntityId: 'not-a-uuid' }, + { custodyType: 'unknown' }, + { type: ['wallet'] }, + { status: ['settling'] }, + { accountId: '' }, + { currency: '' }, + { from: '' }, + { to: '' }, + { isAttributed: 'true' }, + { pageSize: 0 }, + { pageSize: 1.5 }, + ])('rejects an invalid initial query without sending it: %o', async (query) => { + const transport = new SequenceTransport([]) + const transactions = createDaaUserClient(transport, 'production', NO_SIGNING).transactions + + expect((await detailOf(transactions.list(query as never))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('maps malformed list bodies and undocumented success statuses through shared rules', async () => { + const malformed = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-list' }, bodyBytes: bytes('{"data":{}}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformed, 'production', NO_SIGNING).transactions.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-list' }) + + const malformedItem = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-item' }, bodyBytes: bytes('{"data":[{}]}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformedItem, 'production', NO_SIGNING).transactions.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-item' }) + + const wrongStatus = new SequenceTransport([{ status: 201, headers: {}, bodyBytes: pageBody() }]) + await expect( + detailOf(createDaaUserClient(wrongStatus, 'production', NO_SIGNING).transactions.list()), + ).resolves.toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) diff --git a/src/__test__/transferPayload.test.ts b/src/__test__/transferPayload.test.ts new file mode 100644 index 0000000..3219631 --- /dev/null +++ b/src/__test__/transferPayload.test.ts @@ -0,0 +1,674 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' +import type { Money } from '../models/Money' +import { + Transfer, + TransferDestinationAccountLocation, + TransferDestinationBlockchainLocation, +} from '../models/Transfer' +import { MalformedPayloadError } from '../wire/payload' +import { toTransfer } from '../wire/transferPayload' + +/** + * Decoding tests for the transfer model. As in `accountPayload.test.ts`, these + * go through the real parse and mapping rather than constructing a payload + * object directly — the wire spellings, the required/optional line, and the + * polymorphic locations are the things under test. + */ + +/** + * A representative complete transfer. Only `id`, `amount`, and `status` are + * actually guaranteed (see `models/Transfer.ts`'s file-level note on why the + * OpenAPI schema's required marking is not proof) — `source` and `destination` + * are included here too so most tests below exercise an ordinary account leg + * rather than the fiat-absent edge case, which is covered on its own further + * down. + */ +const REQUIRED = + '"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"10.00","currency":"USD"},"status":"pending"' + +function decode(body: string): Transfer { + return toTransfer(JSON.parse(body) as unknown) +} + +function decodeComplete(extra = ''): Transfer { + return decode(`{${REQUIRED}${extra === '' ? '' : `,${extra}`}}`) +} + +describe('required and optional fields', () => { + /** + * A response missing something the service actually guarantees is malformed, + * not a transfer with holes in it — same rule as `Account`. Only `id`, + * `amount`, and `status` belong in this set: `source`/`destination` are marked + * required in the same way but the service can omit them (see the + * `locations` describe block below), so they are deliberately excluded here + * rather than trusted on the schema alone. + */ + it('rejects a response missing any guaranteed field', () => { + const complete: Record = { + id: '"tr-1"', + amount: '{"amount":"10.00","currency":"USD"}', + status: '"pending"', + } + const body = (fields: Record): string => + `{${Object.entries(fields) + .map(([k, v]) => `"${k}":${v}`) + .join(',')}}` + + // Sanity: the complete body decodes, or every assertion below is vacuous. + expect(decode(body(complete)).id).toBe('tr-1') + + for (const omitted of Object.keys(complete)) { + const partial = { ...complete } + delete partial[omitted] + expect(() => decode(body(partial))).toThrow(MalformedPayloadError) + } + + expect(() => decode('{}')).toThrow(MalformedPayloadError) + expect(() => toTransfer(null)).toThrow(MalformedPayloadError) + expect(() => toTransfer([])).toThrow(MalformedPayloadError) + }) + + it('rejects an explicit null on a guaranteed field', () => { + expect(() => + decode( + '{"id":null,"source":{"type":"account","id":"a"},' + + '"destination":{"type":"account","id":"b"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ), + ).toThrow(MalformedPayloadError) + }) + + it('rejects a field carried in the wrong shape', () => { + expect(() => decodeComplete('"id":7')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"transactionHash":true')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"destinationTransactionHash":true')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"source":"nope"')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"policyEvaluation":"nope"')).toThrow(MalformedPayloadError) + }) + + /** A JSON number in the amount field is a shape error, not a value to coerce — see `Money`. */ + it('rejects a transfer amount sent as a JSON number rather than coercing it', () => { + expect(() => + decode( + '{"id":"tr-1","source":{"type":"account","id":"a"},' + + '"destination":{"type":"account","id":"b"},' + + '"amount":{"amount":10.5,"currency":"USD"},"status":"pending"}', + ), + ).toThrow(MalformedPayloadError) + }) + + /** + * `createDate` is not marked required in the OpenAPI schema at all, unlike + * `id`/`amount`/`status` — the same kind of gap as `Account.description`, + * which the service can omit. Treated as optional here rather than rejecting + * an otherwise-readable transfer. + */ + it('tolerates a transfer with no createDate', () => { + expect(decodeComplete().createDate).toBeNull() + expect(decodeComplete('"createDate":"2026-01-01T00:00:00Z"').createDate).toBe( + '2026-01-01T00:00:00Z', + ) + }) + + it('reports every other absent optional field as absent', () => { + const transfer = decodeComplete() + expect(transfer.transactionHash).toBeNull() + expect(transfer.destinationTransactionHash).toBeNull() + expect(transfer.errorCode).toBeNull() + expect(transfer.policyEvaluation).toBeNull() + expect(transfer.fees).toEqual([]) + }) + + it('carries transactionHash, errorCode, and policyEvaluation when present', () => { + const transfer = decodeComplete( + '"transactionHash":"0xhash","status":"failed","errorCode":"insufficient_funds",' + + '"policyEvaluation":{"status":"approved"}', + ) + expect(transfer.transactionHash).toBe('0xhash') + expect(transfer.errorCode).toEqual({ kind: 'insufficient_funds' }) + expect(transfer.policyEvaluation).toEqual({ status: 'approved' }) + }) + + /** + * `destinationTransactionHash` is the CCTP destination-mint hash — a + * distinct field from the source-side `transactionHash`, present only once + * the destination leg has minted. + */ + it('carries destinationTransactionHash when present, independently of transactionHash', () => { + const transfer = decodeComplete( + '"transactionHash":"0xsource","destinationTransactionHash":"0xdestination"', + ) + expect(transfer.transactionHash).toBe('0xsource') + expect(transfer.destinationTransactionHash).toBe('0xdestination') + }) +}) + +describe('closed-set fields', () => { + it('maps every known status and falls back for the rest', () => { + expect(decodeComplete('"status":"pending"').status).toEqual({ kind: 'pending' }) + expect(decodeComplete('"status":"complete"').status).toEqual({ kind: 'complete' }) + expect(decodeComplete('"status":"failed"').status).toEqual({ kind: 'failed' }) + // A value the service adds later must read as unrecognized rather than + // failing the whole transfer, and must keep the string. + expect(decodeComplete('"status":"settling"').status).toEqual({ + kind: 'unrecognized', + rawValue: 'settling', + }) + }) + + it('maps every known error code and falls back for the rest', () => { + for (const code of [ + 'transfer_failed', + 'transfer_denied', + 'blockchain_error', + 'insufficient_funds', + 'invalid_crypto_address', + ]) { + expect(decodeComplete(`"errorCode":"${code}"`).errorCode).toEqual({ kind: code }) + } + expect(decodeComplete('"errorCode":"self_sends_unsupported"').errorCode).toEqual({ + kind: 'unrecognized', + rawValue: 'self_sends_unsupported', + }) + }) + + /** `errorCode` absent is `null` — a distinct state from an unrecognized-but-present value. */ + it('treats an absent errorCode as null, not unrecognized', () => { + expect(decodeComplete().errorCode).toBeNull() + }) + + /** A JavaScript hazard with no Kotlin/Swift equivalent — see `accountPayload.test.ts`'s identical case. */ + it('treats a value spelled like an Object.prototype member as unrecognized', () => { + for (const hostile of ['constructor', 'toString', 'hasOwnProperty', '__proto__']) { + expect(decodeComplete(`"status":"${hostile}"`).status).toEqual({ + kind: 'unrecognized', + rawValue: hostile, + }) + } + }) +}) + +describe('locations', () => { + it('decodes an account source location', () => { + const transfer = decodeComplete() + expect(transfer.source).toEqual({ kind: 'account', accountId: 'acct-src' }) + }) + + it('decodes a blockchain source location', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"blockchain","chain":"ETH"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toEqual({ kind: 'blockchain', chain: 'ETH' }) + }) + + /** + * `chain` is nullable on a source blockchain leg, despite the OpenAPI schema + * marking `TransferSourceBlockchainLocation.chain` required: the service can + * return a source blockchain leg with no `chain`. Rejecting it would reject a + * real, ordinary transfer. + */ + it('decodes a blockchain source location with no chain metadata as a null chain', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"blockchain"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toEqual({ kind: 'blockchain', chain: null }) + }) + + /** A source location kind this SDK does not recognise degrades rather than failing the read. */ + it('falls back to unrecognized for a source location kind it does not recognise', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"wire","routingNumber":"1"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toEqual({ kind: 'unrecognized', rawValue: 'wire' }) + }) + + /** + * `source`/`destination` are themselves optional: the service reports no leg + * for a fiat source or destination, and a fiat leg — an ordinary + * onramp/offramp — is a real, common transfer. The service omits a null leg, + * so it is simply absent from the JSON body, which is exactly what these + * payloads simulate. + */ + it('decodes a transfer with a fiat source (an onramp) as a null source', () => { + const transfer = decode( + '{"id":"tr-1","destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toBeNull() + expect(transfer.destination).toEqual({ kind: 'account', accountId: 'acct-dst' }) + }) + + it('decodes a transfer with a fiat destination (an offramp) as a null destination', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toEqual({ kind: 'account', accountId: 'acct-src' }) + expect(transfer.destination).toBeNull() + }) + + /** A verified-blockchain source also has no leg — a transfer can lack both legs at once. */ + it('decodes a transfer with neither a source nor a destination as both null', () => { + const transfer = decode( + '{"id":"tr-1","amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toBeNull() + expect(transfer.destination).toBeNull() + }) + + /** An explicit JSON `null` is treated the same as an absent key, consistent with every other optional field. */ + it('treats an explicit null source or destination the same as an absent one', () => { + const transfer = decode( + '{"id":"tr-1","source":null,"destination":null,' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.source).toBeNull() + expect(transfer.destination).toBeNull() + }) + + it('decodes an account destination location with no on-chain deposit fields', () => { + const transfer = decodeComplete() + const destination = transfer.destination as TransferDestinationAccountLocation + expect(destination).toBeInstanceOf(TransferDestinationAccountLocation) + expect(destination.kind).toBe('account') + expect(destination.accountId).toBe('acct-dst') + expect(destination.address).toBeNull() + expect(destination.addressTag).toBeNull() + }) + + it('decodes an account destination location that received an on-chain deposit', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst","address":"0xdeposit","addressTag":"tag-1"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const destination = transfer.destination as TransferDestinationAccountLocation + expect(destination.address).toBe('0xdeposit') + expect(destination.addressTag).toBe('tag-1') + }) + + it('decodes a blockchain destination location', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest","addressTag":null},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const destination = transfer.destination as TransferDestinationBlockchainLocation + expect(destination).toBeInstanceOf(TransferDestinationBlockchainLocation) + expect(destination.kind).toBe('blockchain') + expect(destination.chain).toBe('ETH') + expect(destination.address).toBe('0xdest') + expect(destination.addressTag).toBeNull() + }) + + /** + * `address` is nullable on a destination blockchain leg, despite the OpenAPI + * schema marking it required: the service can return a destination + * `type: "blockchain"` leg with no `address`. Rejecting a null address would + * reject that real case. + */ + it('decodes a blockchain destination location with no address as a null address', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain","chain":"ETH"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const destination = transfer.destination as TransferDestinationBlockchainLocation + expect(destination.chain).toBe('ETH') + expect(destination.address).toBeNull() + }) + + /** `chain` on a destination blockchain leg is nullable, as on the source shape: the service can omit it. */ + it('decodes a blockchain destination location with no chain as a null chain', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain","address":"0xdest"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const destination = transfer.destination as TransferDestinationBlockchainLocation + expect(destination.chain).toBeNull() + expect(destination.address).toBe('0xdest') + }) + + /** A destination location kind this SDK does not recognise degrades rather than failing the read. */ + it('falls back to unrecognized for a destination location kind it does not recognise', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"verified_blockchain","addressId":"addr-1"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + expect(transfer.destination).toEqual({ kind: 'unrecognized', rawValue: 'verified_blockchain' }) + }) + + /** A missing `type` discriminator is malformed — it is the one field every location shape requires. */ + it('rejects a source or destination location missing the type discriminator', () => { + expect(() => + decode( + '{"id":"tr-1","source":{"id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ), + ).toThrow(MalformedPayloadError) + expect(() => + decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ), + ).toThrow(MalformedPayloadError) + }) +}) + +describe('fees', () => { + it('decodes an empty fee list as an empty list', () => { + expect(decodeComplete().fees).toEqual([]) + }) + + it('decodes one or more fees', () => { + const transfer = decodeComplete( + '"fees":[{"amount":"0.50","currency":"USD","type":"network"},' + + '{"amount":"0.01","currency":"ETH","type":"network"}]', + ) + expect(transfer.fees).toHaveLength(2) + expect((transfer.fees[0]?.amount as Money).amount).toBe('0.50') + expect((transfer.fees[0]?.amount as Money).currency).toBe('USD') + expect(transfer.fees[0]?.type).toBe('network') + expect((transfer.fees[1]?.amount as Money).amount).toBe('0.01') + }) + + it('rejects a fee entry missing a guaranteed field', () => { + expect(() => decodeComplete('"fees":[{"currency":"USD","type":"network"}]')).toThrow( + MalformedPayloadError, + ) + expect(() => decodeComplete('"fees":[{"amount":"1","currency":"USD"}]')).toThrow( + MalformedPayloadError, + ) + expect(() => decodeComplete('"fees":[{"amount":"1","type":"network"}]')).toThrow( + MalformedPayloadError, + ) + }) + + it('rejects fees carried in the wrong shape', () => { + expect(() => decodeComplete('"fees":{}')).toThrow(MalformedPayloadError) + expect(() => decodeComplete('"fees":["not-an-object"]')).toThrow(MalformedPayloadError) + }) +}) + +describe('forward compatibility', () => { + /** + * Forward-compatible decoding, same pairing as `accountPayload.test.ts`: + * an unknown response field and an unrecognised closed-set/location value + * decode together without failing the read. + */ + it('ignores unknown response fields wherever they appear', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src","futureField":true},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD","futureScale":"2"},"status":"pending",' + + '"settlementTier":"gold","fees":[{"amount":"0.1","currency":"USD","type":"network","meta":{}}]}', + ) + expect(transfer.id).toBe('tr-1') + expect(transfer.source).toEqual({ kind: 'account', accountId: 'acct-src' }) + expect(transfer.fees).toHaveLength(1) + expect(Object.keys(transfer)).not.toContain('settlementTier') + }) + + it('decodes a response carrying an unknown field and an unknown status at once', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"settling","tierMetadata":{"a":1}}', + ) + expect(transfer.id).toBe('tr-1') + expect(transfer.status).toEqual({ kind: 'unrecognized', rawValue: 'settling' }) + }) +}) + +describe('redaction', () => { + const transfer = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xSECRET","addressTag":"tag-SECRET"},' + + '"amount":{"amount":"12345.67","currency":"USD"},"status":"pending",' + + '"fees":[{"amount":"99.99","currency":"USD","type":"network"}]}', + ) + const secrets = ['0xSECRET', 'tag-SECRET', '12345.67', '99.99'] + + it('keeps every sensitive value off the transfer object as an own property', () => { + expect(Object.getOwnPropertyNames(transfer).sort()).toEqual( + [ + 'id', + 'source', + 'destination', + 'status', + 'errorCode', + 'transactionHash', + 'destinationTransactionHash', + 'policyEvaluation', + 'createDate', + ].sort(), + ) + expect(Object.getOwnPropertyNames(transfer.destination as object).sort()).toEqual( + ['kind', 'chain'].sort(), + ) + expect(Object.getOwnPropertyNames(transfer.fees[0] as object).sort()).toEqual( + ['amount', 'type'].sort(), + ) + }) + + it.each([ + ['JSON.stringify', (value: unknown): string => JSON.stringify(value) ?? ''], + ['util.inspect (what console.log renders)', (value: unknown): string => inspect(value)], + ['util.inspect at full depth', (value: unknown): string => inspect(value, { depth: null })], + ['String()', (value: unknown): string => String(value)], + ['template literal', (value: unknown): string => `${String(value)}`], + [ + 'spread into a plain object', + (value: unknown): string => JSON.stringify({ ...(value as object) }) ?? '', + ], + [ + 'for...in', + (value: unknown): string => { + let out = '' + for (const key in value as Record) { + out += `${key}=${String((value as Record)[key])};` + } + return out + }, + ], + ])('reveals no sensitive value through %s', (_name, render) => { + for (const rendered of [ + render(transfer), + render(transfer.destination), + render(transfer.amount), + render(transfer.fees), + render(transfer.fees[0]), + render((transfer.fees[0] as { amount: unknown }).amount), + ]) { + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + } + }) + + /** + * The account-leg redaction path is separate code from the blockchain-leg + * one above (`TransferDestinationAccountLocation` vs. + * `TransferDestinationBlockchainLocation`), so it needs its own case rather + * than trusting the blockchain leg's coverage to stand in for it. + */ + it('reveals no sensitive value on a destination account leg that received a deposit', () => { + const accountDestination = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst","address":"0xACCTSECRET","addressTag":"tag-ACCTSECRET"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const accountSecrets = ['0xACCTSECRET', 'tag-ACCTSECRET'] + + for (const rendered of [ + JSON.stringify(accountDestination.destination), + inspect(accountDestination.destination), + inspect(accountDestination.destination, { depth: null }), + String(accountDestination.destination), + `${String(accountDestination.destination)}`, + JSON.stringify({ ...(accountDestination.destination as object) }), + ]) { + for (const secret of accountSecrets) { + expect(rendered).not.toContain(secret) + } + } + expect(JSON.parse(JSON.stringify(accountDestination.destination))).toMatchObject({ + address: '', + addressTag: '', + }) + }) + + it('still renders the identifiers and states that make a log line useful', () => { + expect(String(transfer)).toContain('tr-1') + expect(String(transfer)).toContain('pending') + expect(JSON.stringify(transfer)).toContain('tr-1') + expect(inspect(transfer)).toContain('tr-1') + // The chain is not sensitive and still renders on the destination leg. + expect(String(transfer.destination)).toContain('ETH') + expect(JSON.stringify(transfer.destination)).toContain('ETH') + }) + + it('renders a fee count in place of the fees, and the amount withheld', () => { + expect(String(transfer)).toContain('fees=1 entries') + expect(JSON.parse(JSON.stringify(transfer))).toMatchObject({ fees: '1 entries' }) + expect(JSON.parse(JSON.stringify(transfer))).toMatchObject({ + amount: { amount: '', currency: 'USD' }, + }) + }) + + it('says the destination address was withheld rather than omitting it silently', () => { + expect(String(transfer.destination)).toContain('address=') + expect(JSON.parse(JSON.stringify(transfer.destination))).toMatchObject({ + address: '', + addressTag: '', + }) + }) + + /** A destination account leg that never received a deposit reports `null`, not a redacted placeholder. */ + it('reports a null destination account address as null rather than as withheld', () => { + const noDeposit = decodeComplete() + const destination = noDeposit.destination as TransferDestinationAccountLocation + expect(String(destination)).toContain('address=null') + expect(JSON.parse(JSON.stringify(destination))).toMatchObject({ + address: null, + addressTag: null, + }) + }) + + /** + * The same as above, but for a destination blockchain leg with no address — + * the folded verified-blockchain-with-no-metadata case. A `null` address must + * render as `null`, not as a redacted placeholder that implies a secret is + * being withheld when there is none. + */ + it('reports a null destination blockchain address and chain as null rather than as withheld', () => { + const noMetadata = decode( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain"},' + + '"amount":{"amount":"1","currency":"USD"},"status":"pending"}', + ) + const destination = noMetadata.destination as TransferDestinationBlockchainLocation + expect(String(destination)).toContain('chain=null') + expect(String(destination)).toContain('address=null') + expect(JSON.parse(JSON.stringify(destination))).toMatchObject({ + chain: null, + address: null, + addressTag: null, + }) + }) + + /** The honest limit, same as `Money`/`Account`: an inspector explicitly asked to evaluate accessors sees everything. */ + it('does not withhold from an inspector explicitly asked to evaluate accessors', () => { + const revealing = inspect(transfer, { showHidden: true, getters: true, depth: null }) + expect(revealing).toContain('12345.67') + expect(revealing).toContain('0xSECRET') + expect((transfer.amount as Money).amount).toBe('12345.67') + expect((transfer.destination as TransferDestinationBlockchainLocation).address).toBe('0xSECRET') + }) +}) + +describe('immutability', () => { + const transfer = decodeComplete( + '"fees":[{"amount":"1","currency":"USD","type":"network"},' + + '{"amount":"2","currency":"EUR","type":"network"}]', + ) + + it('freezes the transfer, its fee list, each fee, and each location', () => { + expect(Object.isFrozen(transfer)).toBe(true) + expect(Object.isFrozen(transfer.fees)).toBe(true) + expect(Object.isFrozen(transfer.fees[0])).toBe(true) + expect(Object.isFrozen(transfer.source)).toBe(true) + expect(Object.isFrozen(transfer.destination)).toBe(true) + }) + + it('refuses a write through a cast', () => { + const mutable = transfer as unknown as Record + expect(() => { + mutable['id'] = 'tr-forged' + }).toThrow(TypeError) + expect(() => { + mutable['newField'] = 'x' + }).toThrow(TypeError) + expect(transfer.id).toBe('tr-1') + }) + + it('refuses a mutation of the returned fee array', () => { + const mutable = transfer.fees as unknown[] + expect(() => mutable.push(mutable[0])).toThrow(TypeError) + expect(() => mutable.pop()).toThrow(TypeError) + expect(transfer.fees).toHaveLength(2) + }) +}) + +describe('consumer construction', () => { + it('does not accept a look-alike object as a transfer', () => { + const fabricated = { + id: 'tr-forged', + source: { kind: 'account', accountId: 'a' }, + destination: { kind: 'account', accountId: 'b' }, + status: { kind: 'pending' }, + errorCode: null, + transactionHash: null, + policyEvaluation: null, + createDate: null, + } + + expect(fabricated instanceof Transfer).toBe(false) + expect(decodeComplete() instanceof Transfer).toBe(true) + }) + + it('does not accept a look-alike object as a destination location class', () => { + const fabricated = { kind: 'account', accountId: 'a', address: null, addressTag: null } + expect(fabricated instanceof TransferDestinationAccountLocation).toBe(false) + }) +}) diff --git a/src/__test__/transfersClient.test.ts b/src/__test__/transfersClient.test.ts new file mode 100644 index 0000000..23888aa --- /dev/null +++ b/src/__test__/transfersClient.test.ts @@ -0,0 +1,398 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import type { TransfersClient } from '../api/TransfersClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The transfer read, end to end through the client: request shape, envelope, + * decoding, and status mapping. Mirrors `accountsClient.test.ts`'s structure — + * same client shape, same envelope, same error mapping, different model. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +/** The service types this path parameter as a UUID, so every read uses one. */ +const TRANSFER_ID = '7c2d9e10-3b4f-4a52-9d6e-0f1a2b3c4d5e' + +/** A complete transfer: every field the service guarantees. */ +const COMPLETE_TRANSFER = + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"10.00","currency":"USD"},"status":"pending"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + transfers: TransfersClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { + transfers: createDaaUserClient(transport, 'production', NO_SIGNING).transfers, + transport, + } +} + +function okClient(payload = COMPLETE_TRANSFER) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the request', () => { + it('reads a transfer over the transfers path', async () => { + const { transfers, transport } = okClient() + + const transfer = await transfers.get(TRANSFER_ID) + + expect(transport.sent).toHaveLength(1) + const sent = transport.sent[0] as DaaHttpRequest + expect(sent.method).toBe('GET') + expect(sent.path).toBe(`/v1/accounts/transfers/${TRANSFER_ID}`) + expect(sent.query).toBeNull() + expect(sent.bodyBytes).toBeNull() + expect(sent.headers).toEqual({}) + expect(transfer.id).toBe('tr-1') + expect(transfer.status).toEqual({ kind: 'pending' }) + }) + + /** + * A `transferId` carrying a path separator would address a different + * operation rather than fail. An empty one addresses the collection instead + * of a member. + */ + it('rejects a transferId that would address a different route', async () => { + const { transfers, transport } = okClient() + + for (const bad of [`${TRANSFER_ID}/other`, `${TRANSFER_ID}/`, `/${TRANSFER_ID}`, '', 'a/b/c']) { + const detail = await detailOf(transfers.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a transferId carrying an encoded separator or other unsafe character', async () => { + const { transfers, transport } = okClient() + + for (const bad of [ + `${TRANSFER_ID}%2Fother`, + 'tr%2f1', + `${TRANSFER_ID}?x=1`, + `${TRANSFER_ID}#frag`, + `${TRANSFER_ID} `, + // Written as an escape, not a literal byte: a literal NUL makes git treat + // the file as binary. + `${TRANSFER_ID}\u0000`, + `${TRANSFER_ID}\r\nX-Injected: 1`, + '.', + '..', + 'tr/../other', + ]) { + const detail = await detailOf(transfers.get(bad)) + expect(detail.kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts a UUID-formatted id in either case', async () => { + for (const good of [TRANSFER_ID, TRANSFER_ID.toUpperCase()]) { + const { transfers, transport } = okClient() + await transfers.get(good) + expect(transport.sent[0]?.path).toBe(`/v1/accounts/transfers/${good}`) + } + }) + + /** + * The SDK contract types this parameter `transferId: UUID`, unlike + * `accounts.get`, whose id is a `string` because public account ids may be + * numeric. An id that would pass a generic path-segment guard is still + * rejected here: it cannot resolve to a transfer, so sending it would only + * turn a caller's mistake into a round trip and a `400`. The near-miss UUIDs + * are the cases a loose check waves through. + */ + it('rejects an id that is well-formed as a path segment but is not a UUID', async () => { + const { transfers, transport } = okClient() + + for (const bad of [ + 'tr-1', + 'TR_1', + 'a.b~c', + '0123456789', + '7c2d9e103b4f4a529d6e0f1a2b3c4d5e', + '7c2d9e10-3b4f-4a52-9d6e-0f1a2b3c4d5', + '7c2d9e10-3b4f-4a52-9d6e-0f1a2b3c4d5ef', + '7g2d9e10-3b4f-4a52-9d6e-0f1a2b3c4d5e', + ]) { + expect((await detailOf(transfers.get(bad))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('the success path', () => { + it('accepts the documented 200 success', async () => { + const { transfers } = clientFor({ + status: 200, + bodyBytes: envelope(COMPLETE_TRANSFER), + }) + expect((await transfers.get(TRANSFER_ID)).id).toBe('tr-1') + }) + + /** The payload sits under `data`; a body with it at the root is malformed, not a value-less transfer. */ + it('rejects a body whose transfer sits at the root instead of the envelope', async () => { + const { transfers } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-2' }, + bodyBytes: bytes(COMPLETE_TRANSFER), + }) + + expect(await detailOf(transfers.get(TRANSFER_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-2', + }) + }) + + /** An envelope present but empty is malformed — the wrapper is not optional on a 200. */ + it('rejects an empty envelope, an empty body, and no body at all', async () => { + for (const bodyBytes of [bytes('{"data":null}'), bytes(''), null]) { + const { transfers } = clientFor({ status: 200, bodyBytes }) + expect((await detailOf(transfers.get(TRANSFER_ID))).kind).toBe('contract_violation') + } + }) + + /** + * A `200` whose transfer is missing something the service guarantees must + * reach the caller as a broken contract, not as a successful transfer with + * holes in it. The correlation id has to survive. + */ + it('reports a transfer missing guaranteed fields as a broken contract with the correlation id', async () => { + const payloads = [ + '{}', + '{"id":"tr-1"}', + '{"id":"tr-1","source":{"type":"account","id":"a"},"status":"pending"}', + // A guaranteed money amount the SDK cannot read is the same defect. + '{"id":"tr-1","source":{"type":"account","id":"a"},' + + '"destination":{"type":"account","id":"b"},' + + '"amount":{"amount":"nope","currency":"USD"},"status":"pending"}', + ] + + for (const payload of payloads) { + const { transfers } = clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-13' }, + bodyBytes: envelope(payload), + }) + expect(await detailOf(transfers.get(TRANSFER_ID))).toEqual({ + kind: 'contract_violation', + correlationId: 'req-13', + }) + } + }) + + it('treats a non-integer status as a failure rather than a success', async () => { + for (const status of [Number.NaN, 200.5, Number.POSITIVE_INFINITY]) { + const { transfers } = clientFor({ + status: status as number, + bodyBytes: envelope(COMPLETE_TRANSFER), + }) + + const detail = await detailOf(transfers.get(TRANSFER_ID)) + expect(detail.kind).toBe('api') + } + }) + + /** No field name from the response reaches the error a consumer sees. */ + it('does not put a response field name in the error message', async () => { + const { transfers } = clientFor({ status: 200, bodyBytes: envelope('{"id":"tr-1"}') }) + + try { + await transfers.get(TRANSFER_ID) + throw new Error('expected the read to fail') + } catch (err) { + expect(isDaaError(err)).toBe(true) + expect((err as Error).message).not.toContain('destination') + expect((err as Error).message).not.toContain('amount') + } + }) + + /** A destination on-chain address is the field a caller resolving a transfer needs, and it must decode. */ + it('surfaces a blockchain destination leg and its fees', async () => { + const { transfers } = okClient( + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest","addressTag":null},' + + '"amount":{"amount":"10.500000","currency":"USD"},"status":"complete",' + + '"fees":[{"amount":"0.01","currency":"ETH","type":"network"}]}', + ) + + const transfer = await transfers.get(TRANSFER_ID) + + expect(transfer.destination?.kind).toBe('blockchain') + expect(transfer.status).toEqual({ kind: 'complete' }) + expect(transfer.fees).toHaveLength(1) + expect(transfer.amount.amount).toBe('10.500000') + }) + + /** + * A fiat leg is an ordinary onramp/offramp, not a defect: the service reports + * no leg for it and omits the key, which must decode as `null` rather than a + * thrown error. A client resolving a real onramp transfer + * must be able to read it. + */ + it('surfaces a transfer with a fiat source (an onramp) as a null source', async () => { + const { transfers } = okClient( + '{"id":"tr-1","destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"100.00","currency":"USD"},"status":"complete"}', + ) + + const transfer = await transfers.get(TRANSFER_ID) + + expect(transfer.source).toBeNull() + expect(transfer.destination?.kind).toBe('account') + }) +}) + +describe('the failure path', () => { + it('maps every status other than 200 onto the api error carrying the status', async () => { + for (const status of [201, 204, 299, 400, 401, 404, 409, 500, 503]) { + const { transfers } = clientFor({ + status, + headers: { 'X-Request-Id': `req-${status}` }, + bodyBytes: bytes(`{"status":{"code":${status * 10},"message":"nope"}}`), + }) + + const detail = await detailOf(transfers.get(TRANSFER_ID)) + expect(detail).toEqual({ + kind: 'api', + httpStatus: status, + daaStatusCode: status * 10, + retryable: status === 429 || status >= 500, + }) + } + }) + + it('marks only 429 and 5xx retryable', async () => { + for (const [status, retryable] of [ + [400, false], + [404, false], + [428, false], + [429, true], + [499, false], + [500, true], + [599, true], + ] as const) { + const { transfers } = clientFor({ status }) + expect(await detailOf(transfers.get(TRANSFER_ID))).toMatchObject({ kind: 'api', retryable }) + } + }) + + it('reports the api error even when the body carries no readable status code', async () => { + for (const bodyBytes of [ + null, + bytes(''), + bytes('gateway timeout'), + bytes('{}'), + bytes('{"status":{}}'), + ]) { + const { transfers } = clientFor({ status: 502, bodyBytes }) + expect(await detailOf(transfers.get(TRANSFER_ID))).toEqual({ + kind: 'api', + httpStatus: 502, + retryable: true, + }) + } + }) + + it('finds the correlation id whichever casing the transport uses', async () => { + for (const name of ['X-Request-Id', 'x-request-id', 'X-REQUEST-ID']) { + const { transfers } = clientFor({ status: 404, headers: { [name]: 'req-9' } }) + try { + await transfers.get(TRANSFER_ID) + throw new Error('expected the read to fail') + } catch (err) { + expect((err as Error).message).toContain('req-9') + } + } + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).transfers.get(TRANSFER_ID), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) + +describe('reachability', () => { + it('is reached through the internal user-client factory', () => { + const transport: DaaTransport = { + async send() { + return { status: 200, headers: {}, bodyBytes: null } + }, + } + const client = createDaaUserClient(transport, 'production', NO_SIGNING).transfers + expect(typeof client.get).toBe('function') + expect(Object.isFrozen(client)).toBe(true) + }) +}) diff --git a/src/__test__/transfersCreate.test.ts b/src/__test__/transfersCreate.test.ts new file mode 100644 index 0000000..ff30f9f --- /dev/null +++ b/src/__test__/transfersCreate.test.ts @@ -0,0 +1,373 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { sha256 } from '../crypto/sha256' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { CreateTransferRequest } from '../models/CreateTransferRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { registeredAuthKey, signingFor, unregisteredAuthKey } from './userClientSigning' + +/** + * The signed transfer create, end to end through the client. Mirrors + * `accountsCreate.test.ts`'s structure — same discipline, different operation. + * + * Every wire fact here is a literal rather than a comparison against the + * constant the production code reads, for the reason that file gives: an + * assertion that moves with the defect catches nothing. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const ADDRESS_ID = '44444444-4444-4444-8444-444444444444' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' + +/** A complete transfer: every field the service guarantees. */ +const CREATED_TRANSFER = + '{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"10.25","currency":"USD"},"status":"pending"}' + +const VALID_REQUEST: CreateTransferRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'account', id: 'acct-dst' }, + amount: { amount: '10.25', currency: 'USD' }, +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +async function createdClient(payload = CREATED_TRANSFER) { + const transport = new RecordingTransport({ + status: 201, + headers: { 'X-Request-Id': 'req-create', Location: '/v1/accounts/transfers/tr-1' }, + bodyBytes: envelope(payload), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { transfers: createDaaUserClient(transport, 'production', signing).transfers, transport } +} + +function claimsOf(request: DaaHttpRequest): Record { + const compact = request.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('missing device authorization') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? ''))) +} + +function sentBodyText(transport: RecordingTransport): string { + const sent = transport.sent[0]?.bodyBytes + if (sent == null) throw new Error('no body was sent') + return new TextDecoder().decode(sent) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the signed request', () => { + it('posts the registry canonical path with the transfer discriminator', async () => { + const { transfers, transport } = await createdClient() + + await transfers.create(VALID_REQUEST) + + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + if (request === undefined) throw new Error('no request was sent') + expect(request.method).toBe('POST') + expect(request.path).toBe('/v1/accounts/transfers') + expect(request.query).toBeNull() + expect(request.headers['Content-Type']).toBe('application/json') + expect(claimsOf(request)).toMatchObject({ + canonical_path: '/v1/accounts/transfers', + method: 'POST', + discriminator: 'transfer', + schema_version: 1, + aud: 'circle-digital-asset-accounts', + idempotency_key: IDEMPOTENCY_KEY, + }) + }) + + it('sends exactly the registry properties, in the registry order, at every level', async () => { + const { transfers, transport } = await createdClient() + + await transfers.create({ + idempotencyKey: IDEMPOTENCY_KEY, + source: { type: 'account', id: 'acct-src' }, + destination: { type: 'account', id: 'acct-dst' }, + amount: { amount: '10.25', currency: 'USD' }, + riskSignals: { ipAddress: '198.51.100.7', deviceId: 'device-1' }, + }) + + expect(sentBodyText(transport)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","source":{"type":"account","id":"acct-src"},` + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"10.25","currency":"USD"},' + + '"riskSignals":{"ipAddress":"198.51.100.7","deviceId":"device-1"}}', + ) + const body = JSON.parse(sentBodyText(transport)) + expect(Object.keys(body)).toEqual([ + 'idempotencyKey', + 'source', + 'destination', + 'amount', + 'riskSignals', + ]) + expect(Object.keys(body.destination)).toEqual(['type', 'id']) + expect(Object.keys(body.amount)).toEqual(['amount', 'currency']) + }) + + it('sends the verified_blockchain destination arm with its own property set', async () => { + const { transfers, transport } = await createdClient() + + await transfers.create({ + ...VALID_REQUEST, + destination: { type: 'verified_blockchain', addressId: ADDRESS_ID }, + }) + + expect(sentBodyText(transport)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}",` + + `"destination":{"type":"verified_blockchain","addressId":"${ADDRESS_ID}"},` + + '"amount":{"amount":"10.25","currency":"USD"}}', + ) + }) + + it('sends the amount as a decimal string, not a JSON number', async () => { + const { transfers, transport } = await createdClient() + + // Eighteen significant digits: a value `JSON.stringify` would round if this + // ever became a numeric literal, and the rounded value is what the Owner + // would then be signing for. + await transfers.create({ + ...VALID_REQUEST, + amount: { amount: '1234567890123456.78', currency: 'USD' }, + }) + + expect(sentBodyText(transport)).toContain('"amount":{"amount":"1234567890123456.78"') + }) + + it('snapshots amount fields before validation and serialization', async () => { + const { transfers, transport } = await createdClient() + let reads = 0 + const amount = { currency: 'USD' } as CreateTransferRequest['amount'] + Object.defineProperty(amount, 'amount', { + enumerable: true, + get: () => { + reads += 1 + return reads === 1 ? '10.25' : '999.99' + }, + }) + + await transfers.create({ ...VALID_REQUEST, amount }) + + expect(reads).toBe(1) + expect(sentBodyText(transport)).toContain('"amount":{"amount":"10.25","currency":"USD"}') + }) + + it('snapshots source and destination fields before validation and serialization', async () => { + const { transfers, transport } = await createdClient() + const reads = { + sourceType: 0, + sourceId: 0, + destinationType: 0, + destinationId: 0, + } + const source = new Proxy( + { type: 'account' as const, id: 'acct-src' }, + { + get(target, property, receiver) { + if (property === 'type') reads.sourceType += 1 + if (property === 'id') reads.sourceId += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + const destination = new Proxy( + { type: 'account' as const, id: 'acct-dst' }, + { + get(target, property, receiver) { + if (property === 'type') reads.destinationType += 1 + if (property === 'id') reads.destinationId += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + + await transfers.create({ ...VALID_REQUEST, source, destination }) + + expect(reads).toEqual({ sourceType: 1, sourceId: 1, destinationType: 1, destinationId: 1 }) + expect(sentBodyText(transport)).toContain( + '"source":{"type":"account","id":"acct-src"},"destination":{"type":"account","id":"acct-dst"}', + ) + }) + + it('snapshots the verified destination fields before validation and serialization', async () => { + const { transfers, transport } = await createdClient() + const reads = { type: 0, addressId: 0 } + const destination = new Proxy( + { type: 'verified_blockchain' as const, addressId: ADDRESS_ID }, + { + get(target, property, receiver) { + if (property === 'type') reads.type += 1 + if (property === 'addressId') reads.addressId += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + + await transfers.create({ ...VALID_REQUEST, destination }) + + expect(reads).toEqual({ type: 1, addressId: 1 }) + expect(sentBodyText(transport)).toContain( + `"destination":{"type":"verified_blockchain","addressId":"${ADDRESS_ID}"}`, + ) + }) + + it('binds body_sha256 to the exact bytes it transmits', async () => { + const { transfers, transport } = await createdClient() + + await transfers.create(VALID_REQUEST) + + const request = transport.sent[0] + if (request?.bodyBytes == null) throw new Error('no body was sent') + expect(claimsOf(request).body_sha256).toBe(toBase64Url(sha256(request.bodyBytes))) + }) + + it('decodes the documented 201 into a transfer', async () => { + const { transfers } = await createdClient() + + const transfer = await transfers.create(VALID_REQUEST) + + expect(transfer.id).toBe('tr-1') + expect(transfer.status).toEqual({ kind: 'pending' }) + expect(transfer.amount.amount).toBe('10.25') + }) + + it('treats another 2xx as an API failure rather than a created transfer', async () => { + const transport = new RecordingTransport({ + status: 202, + headers: { 'X-Request-Id': 'req-202' }, + bodyBytes: envelope(CREATED_TRANSFER), + }) + const transfers = createDaaUserClient( + transport, + 'production', + signingFor(await registeredAuthKey(), AUTH_KEY_ID), + ).transfers + + expect(await detailOf(transfers.create(VALID_REQUEST))).toEqual({ + kind: 'api', + httpStatus: 202, + retryable: false, + }) + }) +}) + +describe('local rejection', () => { + async function rejectingClient() { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { + transfers: createDaaUserClient(transport, 'production', signing).transfers, + transport, + signing, + } + } + + it('refuses a property the registry schema does not name, at any level', async () => { + const unknownProperties: readonly CreateTransferRequest[] = [ + { ...VALID_REQUEST, memo: 'rent' } as never, + { ...VALID_REQUEST, destination: { type: 'account', id: 'acct-dst', chain: 'ARC' } } as never, + { ...VALID_REQUEST, amount: { amount: '10.25', currency: 'USD', scale: 2 } } as never, + { ...VALID_REQUEST, riskSignals: { ip: '198.51.100.7' } } as never, + ] + + for (const request of unknownProperties) { + const { transfers, transport, signing } = await rejectingClient() + expect((await detailOf(transfers.create(request))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + // Nothing was signed either: an Owner signature is not spent on bytes + // that cannot succeed. + expect(signing.resolutions()).toBe(0) + } + }) + + it('refuses each field the registry constrains, without sending anything', async () => { + const invalid: readonly CreateTransferRequest[] = [ + { ...VALID_REQUEST, idempotencyKey: 'not-a-uuid' }, + { ...VALID_REQUEST, destination: { type: 'account', id: '' } }, + { ...VALID_REQUEST, destination: { type: 'blockchain', address: '0x1' } } as never, + { ...VALID_REQUEST, destination: { type: 'verified_blockchain', addressId: 'nope' } }, + { ...VALID_REQUEST, source: { type: 'blockchain', id: 'x' } } as never, + // A JSON number, which is exactly what the string form exists to avoid. + { ...VALID_REQUEST, amount: { amount: 10.25, currency: 'USD' } } as never, + { ...VALID_REQUEST, amount: { amount: '10.25', currency: '' } }, + { ...VALID_REQUEST, amount: { amount: 'ten', currency: 'USD' } }, + { ...VALID_REQUEST, riskSignals: { ipAddress: '' } }, + 'not an object' as never, + ] + + for (const request of invalid) { + const { transfers, transport } = await rejectingClient() + expect((await detailOf(transfers.create(request))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + } + }) + + it('fails closed while the AuthKey is not yet registered', async () => { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + // `created`, not `existing`: Device Registration Complete has not + // acknowledged this key, so it may sign the Complete call and nothing else. + const authKey = await unregisteredAuthKey() + expect(authKey.resolution()).toBe('created') + const transfers = createDaaUserClient( + transport, + 'production', + signingFor(authKey, AUTH_KEY_ID), + ).transfers + + expect(await detailOf(transfers.create(VALID_REQUEST))).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) +}) diff --git a/src/__test__/transfersPagination.test.ts b/src/__test__/transfersPagination.test.ts new file mode 100644 index 0000000..50e9f1b --- /dev/null +++ b/src/__test__/transfersPagination.test.ts @@ -0,0 +1,218 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +const ORIGIN = 'https://api.circle.com' +const CURSOR_AFTER = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CURSOR_BEFORE = '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = '5f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const TRANSFER = + '{"id":"tr-1","source":{"type":"account","id":"1000662322"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest"},' + + '"amount":{"amount":"10.00","currency":"USDC"},"status":"pending"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function pageBody(transfer = TRANSFER): Uint8Array { + return bytes(`{"data":[${transfer}]}`) +} + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: readonly DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) throw new Error('unexpected request') + return response + } +} + +function response(headers: Readonly> = {}): DaaHttpResponse { + return { status: 200, headers, bodyBytes: pageBody() } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('transfers pagination', () => { + it('loads and freezes transfers over the exact public collection path', async () => { + const transport = new SequenceTransport([response()]) + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).transfers.list() + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/accounts/transfers', + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(page.items[0]?.id).toBe('tr-1') + expect(page.items[0]?.destination?.kind).toBe('blockchain') + expect(Object.isFrozen(page)).toBe(true) + expect(Object.isFrozen(page.items)).toBe(true) + expect(Object.isFrozen(page.items[0])).toBe(true) + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + }) + + it('serializes the documented transfer filters in deterministic order', async () => { + const transport = new SequenceTransport([response()]) + const transfers = createDaaUserClient(transport, 'production', NO_SIGNING).transfers + + await transfers.list({ + custodyType: 'segregated', + accountId: '1000662322', + sourceAccountId: 'source/account', + destinationAccountId: '0xdest?tag=1', + clientEntityId: CLIENT_ENTITY_ID, + sourceType: 'account', + destinationType: 'blockchain', + from: '2026-08-01T00:00:00Z', + to: '2026-08-18T00:00:00Z', + pageAfter: CURSOR_AFTER, + pageSize: 50, + }) + + expect(transport.sent[0]?.query).toBe( + 'custodyType=segregated&accountId=1000662322&sourceAccountId=source%2Faccount' + + '&destinationAccountId=0xdest%3Ftag%3D1' + + `&clientEntityId=${CLIENT_ENTITY_ID}&sourceType=account&destinationType=blockchain` + + '&from=2026-08-01T00%3A00%3A00Z&to=2026-08-18T00%3A00%3A00Z' + + `&pageAfter=${CURSOR_AFTER}&pageSize=50`, + ) + }) + + it('follows only the same transfer collection and preserves its opaque query', async () => { + const nextQuery = 'z=last&pageAfter=backing%2Fcursor%3D&repeat=1&repeat=2&reserved=%2B%26' + const previousQuery = 'pageBefore=opaque-value&pageSize=2' + const transport = new SequenceTransport([ + response({ + Link: + `<${ORIGIN}/v1/accounts/transfers?${nextQuery}>; rel="next", ` + + `<${ORIGIN}/v1/accounts/transfers?${previousQuery}>; rel="prev"`, + }), + response(), + response(), + ]) + + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).transfers.list() + await page.next() + await page.previous() + + expect(transport.sent[1]?.query).toBe(nextQuery) + expect(transport.sent[2]?.query).toBe(previousQuery) + for (const request of transport.sent) { + expect(request.path).toBe('/v1/accounts/transfers') + expect(request.method).toBe('GET') + expect(request.bodyBytes).toBeNull() + } + }) + + it.each([ + `${ORIGIN}/v1/accounts?pageAfter=${CURSOR_AFTER}`, + `${ORIGIN}/v1/accounts/deposits?pageAfter=${CURSOR_AFTER}`, + `https://evil.example/v1/accounts/transfers?pageAfter=${CURSOR_AFTER}`, + ])('rejects navigation outside the trusted transfer collection: %s', async (target) => { + const transport = new SequenceTransport([response({ Link: `<${target}>; rel="next"` })]) + + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).transfers.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it('uses the configured environment as the pagination trust anchor', async () => { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts/transfers?pageAfter=x>; rel="next"` }), + ]) + + const detail = await detailOf( + createDaaUserClient(transport, 'sandbox', NO_SIGNING).transfers.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + null, + [], + { pageAfter: CURSOR_AFTER, pageBefore: CURSOR_BEFORE }, + { pageAfter: 'not-a-uuid' }, + { pageBefore: 'not-a-uuid' }, + { clientEntityId: 'not-a-uuid' }, + { custodyType: 'unknown' }, + { sourceType: 'wallet' }, + { destinationType: 'wire' }, + { accountId: '' }, + { sourceAccountId: '' }, + { destinationAccountId: '' }, + { from: '' }, + { to: '' }, + { pageSize: 0 }, + { pageSize: 1.5 }, + ])('rejects an invalid initial query without sending it: %o', async (query) => { + const transport = new SequenceTransport([]) + const transfers = createDaaUserClient(transport, 'production', NO_SIGNING).transfers + + expect((await detailOf(transfers.list(query as never))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('maps malformed list bodies and undocumented success statuses through shared rules', async () => { + const malformed = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-list' }, bodyBytes: bytes('{"data":{}}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformed, 'production', NO_SIGNING).transfers.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-list' }) + + const malformedItem = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-item' }, bodyBytes: bytes('{"data":[{}]}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformedItem, 'production', NO_SIGNING).transfers.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-item' }) + + const wrongStatus = new SequenceTransport([{ status: 201, headers: {}, bodyBytes: pageBody() }]) + await expect( + detailOf(createDaaUserClient(wrongStatus, 'production', NO_SIGNING).transfers.list()), + ).resolves.toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) diff --git a/src/__test__/transport.test.ts b/src/__test__/transport.test.ts new file mode 100644 index 0000000..77adca5 --- /dev/null +++ b/src/__test__/transport.test.ts @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody } from '../crypto/serialization' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +class RecordingTransport implements DaaTransport { + public last: DaaHttpRequest | undefined + async send(request: DaaHttpRequest): Promise { + this.last = request + return { status: 200, headers: {}, bodyBytes: null } + } +} + +describe('DaaTransport boundary', () => { + it('carries the exact serialized body bytes without mutation', async () => { + const transport = new RecordingTransport() + const body = serializeBody({ idempotencyKey: 'k', amount: '1.00' }) + + const request: DaaHttpRequest = { + method: 'POST', + path: '/v1/accounts/transfers', + query: null, // signed v1 operations require query=null + headers: { 'Content-Type': 'application/json' }, + bodyBytes: body, + } + await transport.send(request) + + expect(transport.last?.bodyBytes).toBe(body) // same immutable slice + expect(new TextDecoder().decode(transport.last!.bodyBytes!)).toBe( + '{"idempotencyKey":"k","amount":"1.00"}', + ) + expect(transport.last?.query).toBeNull() + }) +}) diff --git a/src/__test__/transportFailure.test.ts b/src/__test__/transportFailure.test.ts new file mode 100644 index 0000000..929da7f --- /dev/null +++ b/src/__test__/transportFailure.test.ts @@ -0,0 +1,202 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { contractViolation, DaaError, isDaaError, transportFailure } from '../errors' +import type { CreateTransferRequest } from '../models/CreateTransferRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { NO_SIGNING, registeredAuthKey, signingFor } from './userClientSigning' + +/** + * The SDK's `transport` error: what a `DaaUserClient` operation throws when + * the consumer's transport throws instead of returning a response. + */ + +const IDEMPOTENCY_KEY = '22222222-2222-4222-a222-222222222222' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' +const TRANSFER_ID = '33333333-3333-4333-8333-333333333333' + +const CREATED_TRANSFER = + '{"data":{"id":"tr-1","source":{"type":"account","id":"acct-src"},' + + '"destination":{"type":"account","id":"acct-dst"},' + + '"amount":{"amount":"10.25","currency":"USD"},"status":"pending"}}' + +const VALID_REQUEST: CreateTransferRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'account', id: 'acct-dst' }, + amount: { amount: '10.25', currency: 'USD' }, +} + +/** Throws `failures` in order, then answers with `response`. Records every request. */ +class FlakyTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor( + private readonly failures: unknown[], + private readonly response: DaaHttpResponse = { status: 500, headers: {}, bodyBytes: null }, + ) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + if (this.failures.length > 0) { + throw this.failures.shift() + } + return this.response + } +} + +async function caught(operation: Promise): Promise { + const err = await operation.then( + () => { + throw new Error('expected the operation to fail') + }, + (e: unknown) => e, + ) + if (!isDaaError(err)) { + throw new Error(`expected a DaaError, got ${String(err)}`) + } + return err +} + +describe('transportFailure', () => { + it('is retryable, carries the key only when given, and keeps the cause off message', () => { + const cause = new Error('connect ECONNREFUSED 10.0.0.7:8443 Authorization: Bearer secret') + + const keyed = transportFailure(cause, IDEMPOTENCY_KEY) + expect(keyed.detail).toEqual({ + kind: 'transport', + retryable: true, + idempotencyKey: IDEMPOTENCY_KEY, + }) + expect(transportFailure(cause).detail).toEqual({ kind: 'transport', retryable: true }) + + expect(keyed.cause).toBe(cause) + expect(keyed.message).toBe('DAA: the transport failed before a response was received') + expect(Object.getOwnPropertyDescriptor(keyed, 'cause')?.enumerable).toBe(false) + expect(JSON.stringify(keyed)).not.toContain('secret') + }) +}) + +describe('DaaUserClient transport failures', () => { + it('reports a failed read as transport, with no idempotency key', async () => { + const failure = new Error('dns') + const transport = new FlakyTransport([failure]) + + const err = await caught( + createDaaUserClient(transport, 'production', NO_SIGNING).transfers.get(TRANSFER_ID), + ) + + expect(err.detail).toEqual({ kind: 'transport', retryable: true }) + expect(err.cause).toBe(failure) + }) + + it('reports a failed signed create with the key the retry must reuse', async () => { + const failure = new Error('socket hang up') + const transport = new FlakyTransport([failure]) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + + const err = await caught( + createDaaUserClient(transport, 'production', signing).transfers.create(VALID_REQUEST), + ) + + expect(err.detail).toEqual({ + kind: 'transport', + retryable: true, + idempotencyKey: IDEMPOTENCY_KEY, + }) + expect(err.cause).toBe(failure) + }) + + it('lets the same request be resent with the same body bytes after a transport failure', async () => { + const transport = new FlakyTransport([new Error('timeout')], { + status: 201, + headers: { Location: '/v1/accounts/transfers/tr-1' }, + bodyBytes: new TextEncoder().encode(CREATED_TRANSFER), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + const transfers = createDaaUserClient(transport, 'production', signing).transfers + + const err = await caught(transfers.create(VALID_REQUEST)) + expect(err.detail).toMatchObject({ kind: 'transport', retryable: true }) + await expect(transfers.create(VALID_REQUEST)).resolves.toMatchObject({ id: 'tr-1' }) + + expect(transport.sent).toHaveLength(2) + expect(transport.sent[1]?.bodyBytes).toEqual(transport.sent[0]?.bodyBytes) + }) + + it('reports a failed signed context refresh as transport, with no idempotency key', async () => { + const failure = new Error('offline') + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + + const err = await caught( + createDaaUserClient(new FlakyTransport([failure]), 'production', signing).refreshContext(), + ) + + expect(err.detail).toEqual({ kind: 'transport', retryable: true }) + expect(err.cause).toBe(failure) + }) + + it('reports a failed page follow as transport, with no idempotency key', async () => { + const failure = new Error('connection reset') + const firstPage: DaaHttpResponse = { + status: 200, + headers: { + Link: '; rel="next"', + }, + bodyBytes: new TextEncoder().encode( + '{"data":[{"id":"tr-1","source":{"type":"account","id":"1000662322"},' + + '"destination":{"type":"blockchain","chain":"ETH","address":"0xdest"},' + + '"amount":{"amount":"10.00","currency":"USDC"},"status":"pending"}]}', + ), + } + let calls = 0 + const transport: DaaTransport = { + async send() { + calls += 1 + if (calls === 1) return firstPage + throw failure + }, + } + + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).transfers.list() + const err = await caught(page.next()) + + expect(err.detail).toEqual({ kind: 'transport', retryable: true }) + expect(err.cause).toBe(failure) + }) + + it('passes a DaaError the transport threw through unchanged', async () => { + const own = contractViolation('relay refused the request') + const transport = new FlakyTransport([own]) + + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).transfers.get(TRANSFER_ID), + ).rejects.toBe(own) + }) + + it('does not report a closed client as a transport failure', async () => { + const transport = new FlakyTransport([]) + const user = createDaaUserClient(transport, 'production', NO_SIGNING) + user.close() + + const err = await caught(user.transfers.get(TRANSFER_ID)) + + expect(err.detail).toEqual({ kind: 'contract_violation' }) + expect(transport.sent).toHaveLength(0) + }) +}) diff --git a/src/__test__/userClientSigning.ts b/src/__test__/userClientSigning.ts new file mode 100644 index 0000000..067ba1b --- /dev/null +++ b/src/__test__/userClientSigning.ts @@ -0,0 +1,86 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Signing material for tests that build a `DaaUserClient` directly. +// +// `createDaaUserClient` takes it as a required argument, which is the point: +// the surface cannot be constructed without a credential to sign writes with. +// A read test still has to supply one, so this is what it supplies. +// +// Not a test file — Jest's `testMatch` is `**/__test__/**/*.test.ts`, so this +// module is only ever imported, never collected. + +import type { DaaUserSigning } from '../api/signedResource' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { InMemorySecureKeyStore } from '../testing' + +/** The `kid` these tests pin. Any UUID; `authorizeExactRequest` requires one. */ +export const TEST_AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' + +/** The Owner these tests resolve an AuthKey for. Any UUID; namespaces the key. */ +export const TEST_CLIENT_ENTITY_ID = '00000000-0000-4000-8000-000000000001' + +/** + * Signing for a test that must not sign anything. + * + * Resolving throws rather than returning an unusable key, so a read that + * quietly grew a signature would fail here instead of passing with one nobody + * asserted on. + */ +export const NO_SIGNING: DaaUserSigning = Object.freeze({ + authKeyId: TEST_AUTH_KEY_ID, + resolveAuthKey: async (): Promise => { + throw new Error('this test must not resolve the AuthKey') + }, +}) + +/** An AuthKey the SDK has recorded Circle's registration acknowledgement for. */ +export async function registeredAuthKey(): Promise { + const key = await new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: TEST_CLIENT_ENTITY_ID, + }) + await key.acknowledgeRegistration() + return key +} + +/** An AuthKey still awaiting that acknowledgement: `resolution()` is `created`. */ +export async function unregisteredAuthKey(): Promise { + return new InMemorySecureKeyStore().resolveOrCreate({ + appId: 'app-123', + environment: 'sandbox', + clientEntityId: TEST_CLIENT_ENTITY_ID, + }) +} + +/** Signing that resolves to a given key, and records how often it was asked. */ +export function signingFor( + authKey: OwnerAuthKey, + authKeyId: string = TEST_AUTH_KEY_ID, +): DaaUserSigning & { readonly resolutions: () => number } { + let resolutions = 0 + return { + authKeyId, + resolveAuthKey: async () => { + resolutions += 1 + return authKey + }, + resolutions: () => resolutions, + } +} diff --git a/src/__test__/uuid.test.ts b/src/__test__/uuid.test.ts new file mode 100644 index 0000000..5b9a803 --- /dev/null +++ b/src/__test__/uuid.test.ts @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isUuid, isUuidV4 } from '../validation/uuid' + +describe('isUuid', () => { + it.each(['8f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6b', '8F3C1E2A-4B5D-4E6F-9A0B-1C2D3E4F5A6B'])( + 'accepts a hyphenated UUID: %s', + (value) => { + expect(isUuid(value)).toBe(true) + }, + ) + + it.each([ + '', + 'not-a-uuid', + '8f3c1e2a4b5d4e6f9a0b1c2d3e4f5a6b', + '8f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6', + '8f3c1e2a-4b5d-4e6f-9a0b-1c2d3e4f5a6b/', + ])('rejects a value that is not a UUID: %s', (value) => { + expect(isUuid(value)).toBe(false) + }) +}) + +describe('isUuidV4', () => { + it('accepts UUID v4 values with every RFC variant nibble', () => { + for (const variant of ['8', '9', 'a', 'B']) { + expect(isUuidV4(`22222222-2222-4222-${variant}222-222222222222`)).toBe(true) + } + }) + + it('rejects other versions, invalid variants, and generic malformed UUIDs', () => { + for (const value of [ + '22222222-2222-1222-a222-222222222222', + '22222222-2222-5222-a222-222222222222', + '22222222-2222-4222-7222-222222222222', + '22222222-2222-4222-c222-222222222222', + 'not-a-uuid', + ]) { + expect(isUuidV4(value)).toBe(false) + } + }) +}) diff --git a/src/__test__/wireFiatAccountsClient.test.ts b/src/__test__/wireFiatAccountsClient.test.ts new file mode 100644 index 0000000..6064bee --- /dev/null +++ b/src/__test__/wireFiatAccountsClient.test.ts @@ -0,0 +1,259 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { WireFiatAccountsClient } from '../api/WireFiatAccountsClient' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { NO_SIGNING } from './userClientSigning' + +/** + * The wire fiat-account reads, end to end through the client: request shape, + * envelope, decoding, and status mapping. Mirrors `withdrawalsClient.test.ts` + * / `depositsClient.test.ts`. Reached through the internal user-client + * factory, the same path `DaaClient.forUser` uses. A read must not resolve the + * AuthKey — `NO_SIGNING` throws if anything tries — because fiat-account + * list/get and instructions reads are ordinary typed reads with no device + * signature. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const FIAT_ACCOUNT_ID = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CLIENT_ENTITY_ID = '11111111-1111-4111-8111-111111111111' + +const COMPLETE_WIRE = + '{"id":"3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8","status":"complete",' + + '"description":"WELLS FARGO BANK, NA ****0010","trackingRef":"CIR1",' + + '"fingerprint":"eb170539-9e1c-4e92-bf4f-1d09534fdca2",' + + '"billingDetails":{"name":"Satoshi Nakamoto","city":"Boston","country":"US",' + + '"line1":"100 Money Street","postalCode":"01234"},' + + '"createDate":"2026-01-01T00:00:00Z","updateDate":"2026-01-02T00:00:00Z"}' + +const COMPLETE_INSTRUCTION = + '{"trackingRef":"CIR1","beneficiary":{"name":"CIRCLE INTERNET FINANCIAL INC"},' + + '"beneficiaryBank":{"routingNumber":"121000248","accountNumber":"****7427"}}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +function clientFor(response: Partial): { + wires: WireFiatAccountsClient + transport: RecordingTransport +} { + const transport = new RecordingTransport({ + status: response.status ?? 200, + headers: response.headers ?? {}, + bodyBytes: response.bodyBytes ?? null, + }) + return { + wires: createDaaUserClient(transport, 'production', NO_SIGNING).fiatAccounts.wires, + transport, + } +} + +function okClient(payload: string) { + return clientFor({ + status: 200, + headers: { 'X-Request-Id': 'req-1' }, + bodyBytes: envelope(payload), + }) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('wires.list', () => { + it('reads the unpaginated collection over the public wires path with no query by default', async () => { + const { wires, transport } = okClient(`[${COMPLETE_WIRE}]`) + + const result = await wires.list() + + expect(transport.sent).toEqual([ + { method: 'GET', path: '/v1/banks/wires', query: null, headers: {}, bodyBytes: null }, + ]) + expect(result).toHaveLength(1) + expect(result[0]?.id).toBe(FIAT_ACCOUNT_ID) + // Plain array, not this SDK's opaque-cursor Page. + expect(Array.isArray(result)).toBe(true) + expect((result as unknown as { next?: unknown }).next).toBeUndefined() + }) + + it('sends clientEntityId as an optional exact query when supplied', async () => { + const { wires, transport } = okClient('[]') + + await wires.list({ clientEntityId: CLIENT_ENTITY_ID }) + + expect(transport.sent[0]?.query).toBe(`clientEntityId=${CLIENT_ENTITY_ID}`) + }) + + it('rejects a non-UUID clientEntityId locally without sending a request', async () => { + const { wires, transport } = okClient('[]') + + expect((await detailOf(wires.list({ clientEntityId: 'not-a-uuid' }))).kind).toBe( + 'contract_violation', + ) + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a non-object query locally without sending a request', async () => { + const { wires, transport } = okClient('[]') + + expect((await detailOf(wires.list(['not', 'an', 'object'] as never))).kind).toBe( + 'contract_violation', + ) + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('wires.get', () => { + it('reads one wire over the public by-id path with an empty unsigned GET', async () => { + const { wires, transport } = okClient(COMPLETE_WIRE) + + const wire = await wires.get(FIAT_ACCOUNT_ID) + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: `/v1/banks/wires/${FIAT_ACCOUNT_ID}`, + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(wire.id).toBe(FIAT_ACCOUNT_ID) + expect(wire.status).toEqual({ kind: 'complete' }) + }) + + it('rejects a non-UUID fiatAccountId locally without sending a request', async () => { + const { wires, transport } = okClient(COMPLETE_WIRE) + + for (const bad of ['', 'wire-1', `${FIAT_ACCOUNT_ID}/other`, `${FIAT_ACCOUNT_ID}%2Fother`]) { + expect((await detailOf(wires.get(bad))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts only the documented 200', async () => { + const { wires } = clientFor({ status: 201, bodyBytes: envelope(COMPLETE_WIRE) }) + const detail = await detailOf(wires.get(FIAT_ACCOUNT_ID)) + expect(detail).toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) + +describe('wires.getInstructions', () => { + it('reads instructions over the public instructions path with no query by default', async () => { + const { wires, transport } = okClient(COMPLETE_INSTRUCTION) + + const instruction = await wires.getInstructions(FIAT_ACCOUNT_ID) + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: `/v1/banks/wires/${FIAT_ACCOUNT_ID}/instructions`, + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(instruction.trackingRef).toBe('CIR1') + expect(instruction.beneficiaryBank?.routingNumber).toBe('121000248') + }) + + it('sends the optional public accountId query exactly, including a numeric string', async () => { + const { wires, transport } = okClient(COMPLETE_INSTRUCTION) + + await wires.getInstructions(FIAT_ACCOUNT_ID, { accountId: '1000662322' }) + + expect(transport.sent[0]?.query).toBe('accountId=1000662322') + }) + + it('rejects an empty accountId locally without sending a request', async () => { + const { wires, transport } = okClient(COMPLETE_INSTRUCTION) + + expect((await detailOf(wires.getInstructions(FIAT_ACCOUNT_ID, { accountId: '' }))).kind).toBe( + 'contract_violation', + ) + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a non-object query locally without sending a request', async () => { + const { wires, transport } = okClient(COMPLETE_INSTRUCTION) + + expect((await detailOf(wires.getInstructions(FIAT_ACCOUNT_ID, 'nope' as never))).kind).toBe( + 'contract_violation', + ) + expect(transport.sent).toHaveLength(0) + }) + + it('rejects a non-UUID fiatAccountId locally without sending a request', async () => { + const { wires, transport } = okClient(COMPLETE_INSTRUCTION) + expect((await detailOf(wires.getInstructions('not-a-uuid'))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) +}) + +describe('failure mapping', () => { + it('maps a status other than 200 onto the api error carrying the status', async () => { + const { wires } = clientFor({ status: 404, bodyBytes: bytes('{"status":{"code":4004}}') }) + expect(await detailOf(wires.get(FIAT_ACCOUNT_ID))).toMatchObject({ + kind: 'api', + httpStatus: 404, + daaStatusCode: 4004, + }) + }) + + it('reports a consumer transport failure as a transport error with it as the cause', async () => { + const failure = new Error('dns') + const transport: DaaTransport = { + async send() { + throw failure + }, + } + await expect( + createDaaUserClient(transport, 'production', NO_SIGNING).fiatAccounts.wires.get( + FIAT_ACCOUNT_ID, + ), + ).rejects.toMatchObject({ + detail: { kind: 'transport', retryable: true }, + cause: failure, + }) + }) +}) diff --git a/src/__test__/wirePayload.test.ts b/src/__test__/wirePayload.test.ts new file mode 100644 index 0000000..8aa7749 --- /dev/null +++ b/src/__test__/wirePayload.test.ts @@ -0,0 +1,264 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' + +import { toWire, toWireInstruction, toWireSummaries, toWireSummary } from '../wire/wirePayload' + +const COMPLETE_WIRE = { + id: 'a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd', + type: 'wire', + status: 'complete', + description: 'WELLS FARGO BANK, NA ****0010', + trackingRef: 'CIR1A2B3C4', + fingerprint: 'eb170539-9e1c-4e92-bf4f-1d09534fdca2', + billingDetails: { + name: 'Satoshi Nakamoto', + city: 'Boston', + country: 'US', + line1: '100 Money Street', + postalCode: '01234', + }, + createDate: '2026-01-01T00:00:00Z', + updateDate: '2026-01-02T00:00:00Z', +} + +function decodeSummary(extra: Record = {}) { + return toWireSummary({ ...COMPLETE_WIRE, ...extra }) +} + +function decodeWire(extra: Record = {}) { + return toWire({ ...COMPLETE_WIRE, ...extra }) +} + +describe('wire summary payload', () => { + it('decodes the guaranteed core and defaults every absent enrichment', () => { + const wire = decodeSummary() + + expect(wire.id).toBe(COMPLETE_WIRE.id) + expect(wire.type).toBe('wire') + expect(wire.status).toEqual({ kind: 'complete' }) + expect(wire.description).toBe(COMPLETE_WIRE.description) + expect(wire.trackingRef).toBe(COMPLETE_WIRE.trackingRef) + expect(wire.fingerprint).toBe(COMPLETE_WIRE.fingerprint) + expect(wire.billingDetails.name).toBe('Satoshi Nakamoto') + expect(wire.bankAddress).toBeNull() + expect(wire.virtualAccountEnabled).toBeNull() + expect(wire.ffcMemo).toBeNull() + expect(wire.updateDate).toBe(COMPLETE_WIRE.updateDate) + }) + + it('rejects a wire missing a guaranteed field', () => { + const partial: Record = { ...COMPLETE_WIRE } + delete partial.billingDetails + expect(() => toWireSummary(partial)).toThrow() + }) + + it('decodes bank address, virtual-account flag, and ffcMemo when present', () => { + const wire = decodeSummary({ + bankAddress: { country: 'US', bankName: 'WELLS FARGO', city: 'SAN FRANCISCO' }, + virtualAccountEnabled: true, + ffcMemo: 'FFC for Jane Doe', + }) + + expect(wire.bankAddress?.country).toBe('US') + expect(wire.bankAddress?.bankName).toBe('WELLS FARGO') + expect(wire.virtualAccountEnabled).toBe(true) + expect(wire.ffcMemo).toBe('FFC for Jane Doe') + }) + + it('preserves an unrecognized status rather than failing the response', () => { + const wire = decodeSummary({ status: 'archived' }) + expect(wire.status).toEqual({ kind: 'unrecognized', rawValue: 'archived' }) + }) + + it('decodes the unpaginated collection array', () => { + const wires = toWireSummaries([COMPLETE_WIRE, { ...COMPLETE_WIRE, id: 'other-id' }]) + expect(wires).toHaveLength(2) + expect(wires[1]?.id).toBe('other-id') + }) + + it('rejects a collection body that is not an array', () => { + expect(() => toWireSummaries(COMPLETE_WIRE)).toThrow() + }) + + /** + * `billingDetails` and `bankAddress` must never enter logs, traces, crash + * reports, or analytics. `JSON.stringify` and `console.log`/`util.inspect` + * are the mechanisms this SDK cannot control once a caller hands a model to + * either, so both are asserted directly, per `models/BusinessPii.ts`'s own + * test convention. + */ + it('redacts billingDetails and bankAddress from JSON, string, and default inspection', () => { + const wire = decodeSummary({ bankAddress: { country: 'US' } }) + + expect(JSON.stringify(wire)).not.toContain('Satoshi') + expect(JSON.stringify(wire)).not.toContain('Money Street') + expect(wire.toString()).not.toContain('Satoshi') + expect(inspect(wire)).not.toContain('Satoshi') + expect(inspect(wire.billingDetails)).not.toContain('Satoshi') + expect(Object.keys(wire)).not.toContain('billingDetails') + expect(JSON.stringify(wire.billingDetails)).toBe('"BillingDetails()"') + }) + + /** + * `ffcMemo` is not one of the named restricted fields, but a + * for-further-credit memo carries the end beneficiary's name, so it is held + * to the same standard as `billingDetails.name`: absent from JSON, + * `toString`, default inspection, and enumeration, and reachable only through + * its accessor. + */ + it('redacts a name-bearing ffcMemo from JSON, string, inspection, and enumeration', () => { + const wire = decodeSummary({ ffcMemo: 'FFC for Jane Doe' }) + + expect(JSON.stringify(wire)).not.toContain('Jane Doe') + expect((JSON.parse(JSON.stringify(wire)) as { ffcMemo: string }).ffcMemo).toBe('') + expect(wire.toString()).not.toContain('Jane Doe') + expect(inspect(wire)).not.toContain('Jane Doe') + expect(Object.keys(wire)).not.toContain('ffcMemo') + expect(JSON.stringify({ ...wire })).not.toContain('Jane Doe') + expect(wire.ffcMemo).toBe('FFC for Jane Doe') + }) + + it('renders a null ffcMemo distinctly from a redacted one', () => { + expect((JSON.parse(JSON.stringify(decodeSummary())) as { ffcMemo: null }).ffcMemo).toBeNull() + }) + + it('renders a null bankAddress distinctly from a redacted one', () => { + const withAddress = decodeSummary({ bankAddress: { country: 'US' } }) + const withoutAddress = decodeSummary() + + expect((JSON.parse(JSON.stringify(withAddress)) as { bankAddress: string }).bankAddress).toBe( + '', + ) + expect( + (JSON.parse(JSON.stringify(withoutAddress)) as { bankAddress: string | null }).bankAddress, + ).toBeNull() + }) +}) + +describe('wire payload', () => { + it('decodes every WireSummary field plus transferTypesInfo', () => { + const wire = decodeWire({ + transferTypesInfo: { wire: { currencies: ['USD', 'EUR'] } }, + }) + + expect(wire.id).toBe(COMPLETE_WIRE.id) + expect(wire.transferTypesInfo).toEqual({ wire: { currencies: ['USD', 'EUR'] } }) + }) + + it('defaults transferTypesInfo to null when absent', () => { + expect(decodeWire().transferTypesInfo).toBeNull() + }) + + it('rejects a transferTypesInfo entry with a non-string currency', () => { + expect(() => decodeWire({ transferTypesInfo: { wire: { currencies: [1] } } })).toThrow() + }) + + it('keeps hostile transfer type names as data rather than object properties', () => { + const transferTypesInfo = JSON.parse( + '{"__proto__":{"currencies":["USD"]},"constructor":{"currencies":["EUR"]}}', + ) as Record + const wire = decodeWire({ transferTypesInfo }) + const decoded = wire.transferTypesInfo + + if (decoded === null) { + throw new Error('expected transferTypesInfo') + } + expect(Object.getPrototypeOf(decoded)).toBeNull() + expect(Object.keys(decoded)).toEqual(['__proto__', 'constructor']) + expect(decoded['__proto__']).toEqual({ currencies: ['USD'] }) + expect(decoded.constructor).toEqual({ currencies: ['EUR'] }) + }) + + it('redacts billingDetails and bankAddress the same way WireSummary does', () => { + const wire = decodeWire({ bankAddress: { country: 'US' } }) + expect(JSON.stringify(wire)).not.toContain('Satoshi') + expect(inspect(wire)).not.toContain('Satoshi') + }) + + it('redacts a name-bearing ffcMemo the same way WireSummary does', () => { + const wire = decodeWire({ ffcMemo: 'FFC for Jane Doe' }) + + expect(JSON.stringify(wire)).not.toContain('Jane Doe') + expect((JSON.parse(JSON.stringify(wire)) as { ffcMemo: string }).ffcMemo).toBe('') + expect(wire.toString()).not.toContain('Jane Doe') + expect(inspect(wire)).not.toContain('Jane Doe') + expect(Object.keys(wire)).not.toContain('ffcMemo') + expect(wire.ffcMemo).toBe('FFC for Jane Doe') + }) +}) + +describe('wire instruction payload', () => { + const INSTRUCTION = { + trackingRef: 'CIR1A2B3C4', + beneficiary: { + name: 'CIRCLE INTERNET FINANCIAL INC', + address1: '99 HIGH STREET', + address2: 'BOSTON MA 02110', + }, + beneficiaryBank: { + name: 'WELLS FARGO BANK', + swiftCode: 'WFBIUS6SXXX', + routingNumber: '121000248', + accountNumber: '****7427', + currency: 'USD', + address: '4250 EXECUTIVE SQUARE SUITE 300', + city: 'LA JOLLA', + postalCode: '02110', + country: 'US', + }, + virtualAccountEnabled: false, + } + + it('decodes every field, including the Circle beneficiary identity unredacted', () => { + const instruction = toWireInstruction(INSTRUCTION) + + expect(instruction.trackingRef).toBe('CIR1A2B3C4') + expect(instruction.beneficiary).toEqual(INSTRUCTION.beneficiary) + expect(instruction.virtualAccountEnabled).toBe(false) + expect(instruction.beneficiaryBank?.routingNumber).toBe('121000248') + expect(instruction.beneficiaryBank?.accountNumber).toBe('****7427') + }) + + it('defaults every field to null when the instruction is empty', () => { + const instruction = toWireInstruction({}) + expect(instruction.trackingRef).toBeNull() + expect(instruction.beneficiary).toBeNull() + expect(instruction.beneficiaryBank).toBeNull() + expect(instruction.virtualAccountEnabled).toBeNull() + }) + + /** + * `routingNumber` is restricted PII. It — and the rest of `beneficiaryBank` + * — must not enter `JSON.stringify`, `toString`, or default inspection; the + * Circle beneficiary identity is not restricted PII and is asserted present, + * unredacted, in the same assertion. + */ + it('redacts beneficiaryBank (routingNumber, accountNumber) but not the Circle beneficiary', () => { + const instruction = toWireInstruction(INSTRUCTION) + + const json = JSON.stringify(instruction) + expect(json).not.toContain('121000248') + expect(json).not.toContain('7427') + expect(json).toContain('CIRCLE INTERNET FINANCIAL INC') + expect(instruction.toString()).not.toContain('121000248') + expect(inspect(instruction)).not.toContain('121000248') + expect(inspect(instruction.beneficiaryBank)).not.toContain('121000248') + }) +}) diff --git a/src/__test__/withdrawalPayload.test.ts b/src/__test__/withdrawalPayload.test.ts new file mode 100644 index 0000000..4e97280 --- /dev/null +++ b/src/__test__/withdrawalPayload.test.ts @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { inspect } from 'node:util' + +import { MalformedPayloadError } from '../wire/payload' +import { toWithdrawalDetail } from '../wire/withdrawalPayload' + +const COMPLETE = { + id: 'a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd', + sourceAccountId: '1000662322', + destination: { type: 'wire', id: '0db1c81a-d36d-4777-8774-9682d96d82c8', name: 'Bank' }, + amount: { amount: '10.00', currency: 'USD' }, + status: 'complete', + createDate: '2026-01-01T00:00:00Z', +} + +function decode(extra: Record = {}) { + return toWithdrawalDetail({ ...COMPLETE, ...extra }) +} + +describe('withdrawal detail payload', () => { + it('decodes the guaranteed core and defaults every absent enrichment', () => { + const withdrawal = decode() + + expect(withdrawal.id).toBe(COMPLETE.id) + expect(withdrawal.sourceAccountId).toBe('1000662322') + expect(withdrawal.destination).toEqual({ + type: { kind: 'wire' }, + id: '0db1c81a-d36d-4777-8774-9682d96d82c8', + name: 'Bank', + }) + expect(withdrawal.amount.amount).toBe('10.00') + expect(withdrawal.status).toEqual({ kind: 'complete' }) + expect(withdrawal.toAmount).toBeNull() + expect(withdrawal.fees).toBeNull() + expect(withdrawal.errorCode).toBeNull() + expect(withdrawal.adjustments).toBeNull() + expect(withdrawal.returnObject).toBeNull() + expect(withdrawal.subAccountSweeps).toEqual([]) + expect(withdrawal.policyEvaluation).toBeNull() + expect(withdrawal.updateDate).toBeNull() + }) + + it('decodes every enrichment shape', () => { + const withdrawal = decode({ + toAmount: { amount: '9.50', currency: 'EUR' }, + fees: { amount: '0.50', currency: 'USD' }, + trackingRef: 'TRK-1', + errorCode: 'transaction_returned', + externalRef: 'IMAD-9', + riskEvaluation: { decision: 'denied', reason: 'risk-rule' }, + adjustments: { + fxCredit: { amount: '0.20', currency: 'USD' }, + fxDebit: { amount: '0.10', currency: 'USD' }, + }, + return: { + id: 'return-id', + payoutId: COMPLETE.id, + amount: { amount: '8.50', currency: 'USD' }, + fees: { amount: '0.25', currency: 'USD' }, + reason: 'bank-return', + status: 'complete', + createDate: '2026-01-02T00:00:00Z', + updateDate: '2026-01-03T00:00:00Z', + }, + customerExternalRef: 'customer-ref-123', + burnAll: true, + subAccountSweeps: [ + { + subAccountId: 'sub-1', + amount: { amount: '4.00', currency: 'USD' }, + status: 'skipped', + }, + ], + updateDate: '2026-01-01T00:05:00Z', + policyEvaluation: { status: 'approved' }, + }) + + expect(withdrawal.toAmount?.amount).toBe('9.50') + expect(withdrawal.fees?.amount).toBe('0.50') + expect(withdrawal.errorCode).toEqual({ kind: 'transaction_returned' }) + expect(withdrawal.adjustments?.fxCredit?.amount).toBe('0.20') + expect(withdrawal.returnObject?.amount?.amount).toBe('8.50') + expect(withdrawal.subAccountSweeps[0]?.status).toEqual({ kind: 'skipped' }) + expect(withdrawal.policyEvaluation).toEqual({ status: 'approved' }) + }) + + it('keeps closed sets forward-compatible and hostile object keys unrecognized', () => { + for (const raw of ['settling', 'constructor', 'toString', '__proto__']) { + expect(decode({ status: raw }).status).toEqual({ kind: 'unrecognized', rawValue: raw }) + } + expect(decode({ errorCode: 'new_failure' }).errorCode).toEqual({ + kind: 'unrecognized', + rawValue: 'new_failure', + }) + expect(decode({ destination: { type: 'sepa', id: 'bank-id' } }).destination.type).toEqual({ + kind: 'unrecognized', + rawValue: 'sepa', + }) + }) + + it('keeps nested return and sweep statuses forward-compatible', () => { + const withdrawal = decode({ + return: { status: 'reversing' }, + subAccountSweeps: [{ status: 'queued' }], + }) + + expect(withdrawal.returnObject?.status).toEqual({ + kind: 'unrecognized', + rawValue: 'reversing', + }) + expect(withdrawal.subAccountSweeps[0]?.status).toEqual({ + kind: 'unrecognized', + rawValue: 'queued', + }) + }) + + it('rejects missing core fields and malformed enrichment', () => { + for (const name of ['id', 'sourceAccountId', 'destination', 'amount', 'status', 'createDate']) { + const payload = { ...COMPLETE } as Record + delete payload[name] + expect(() => toWithdrawalDetail(payload)).toThrow(MalformedPayloadError) + } + expect(() => decode({ amount: { amount: 10, currency: 'USD' } })).toThrow(MalformedPayloadError) + expect(() => decode({ toAmount: { amount: 'not-a-number', currency: 'USD' } })).toThrow( + MalformedPayloadError, + ) + expect(() => decode({ burnAll: 'true' })).toThrow(MalformedPayloadError) + expect(() => decode({ subAccountSweeps: {} })).toThrow(MalformedPayloadError) + expect(() => decode({ policyEvaluation: { status: null } })).toThrow(MalformedPayloadError) + }) + + it('freezes the aggregate and nested collections', () => { + const withdrawal = decode({ subAccountSweeps: [{ subAccountId: 'sub-1' }] }) + expect(Object.isFrozen(withdrawal)).toBe(true) + expect(Object.isFrozen(withdrawal.destination)).toBe(true) + expect(Object.isFrozen(withdrawal.subAccountSweeps)).toBe(true) + expect(Object.isFrozen(withdrawal.subAccountSweeps[0])).toBe(true) + }) +}) + +describe('withdrawal detail redaction', () => { + const secrets = [ + '123456.789', + '98.50', + '0.75', + '0.20', + '0.10', + '87.25', + '0.25', + '4.00', + 'IMAD-SECRET', + 'CUSTOMER-SECRET', + ] + + function enriched() { + return decode({ + amount: { amount: secrets[0], currency: 'USD' }, + toAmount: { amount: secrets[1], currency: 'EUR' }, + fees: { amount: secrets[2], currency: 'USD' }, + externalRef: secrets[8], + customerExternalRef: secrets[9], + adjustments: { + fxCredit: { amount: secrets[3], currency: 'USD' }, + fxDebit: { amount: secrets[4], currency: 'USD' }, + }, + return: { + amount: { amount: secrets[5], currency: 'USD' }, + fees: { amount: secrets[6], currency: 'USD' }, + }, + subAccountSweeps: [{ amount: { amount: secrets[7], currency: 'USD' } }], + }) + } + + function expectRedacted(rendered: string): void { + for (const secret of secrets) { + expect(rendered).not.toContain(secret) + } + } + + it('redacts JSON.stringify and toString', () => { + const withdrawal = enriched() + expectRedacted(JSON.stringify(withdrawal)) + expectRedacted(withdrawal.toString()) + }) + + it('redacts Node inspection at default and unlimited depth', () => { + const withdrawal = enriched() + expectRedacted(inspect(withdrawal)) + expectRedacted(inspect(withdrawal, { depth: null })) + }) + + it('keeps sensitive fields out of enumeration, spread, and own keys', () => { + const withdrawal = enriched() + const ownKeys = Object.keys(withdrawal) + for (const key of [ + 'amount', + 'toAmount', + 'fees', + 'externalRef', + 'adjustments', + 'returnObject', + 'customerExternalRef', + 'subAccountSweeps', + ]) { + expect(ownKeys).not.toContain(key) + } + expectRedacted(JSON.stringify({ ...withdrawal })) + const enumerated: Record = {} + for (const key in withdrawal) { + enumerated[key] = withdrawal[key as keyof typeof withdrawal] + } + expectRedacted(JSON.stringify(enumerated)) + }) + + it('still exposes exact values through explicit accessors', () => { + const withdrawal = enriched() + expect(withdrawal.amount.amount).toBe(secrets[0]) + expect(withdrawal.toAmount?.amount).toBe(secrets[1]) + expect(withdrawal.externalRef).toBe(secrets[8]) + expect(withdrawal.customerExternalRef).toBe(secrets[9]) + }) +}) diff --git a/src/__test__/withdrawalsClient.test.ts b/src/__test__/withdrawalsClient.test.ts new file mode 100644 index 0000000..5896bc8 --- /dev/null +++ b/src/__test__/withdrawalsClient.test.ts @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { WithdrawalsClient } from '../api/WithdrawalsClient' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { NO_SIGNING } from './userClientSigning' + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const WITHDRAWAL_ID = 'a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd' +const PAYLOAD = + '{"id":"a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd",' + + '"sourceAccountId":"1000662322",' + + '"destination":{"type":"wire","id":"0db1c81a-d36d-4777-8774-9682d96d82c8"},' + + '"amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function clientFor(status = 200, body = `{"data":${PAYLOAD}}`) { + const transport = new RecordingTransport({ status, headers: {}, bodyBytes: bytes(body) }) + // A read must not resolve the AuthKey; `NO_SIGNING` throws if it tries. + return { + withdrawals: new WithdrawalsClient(transport, 'https://api.circle.com', NO_SIGNING), + transport, + } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (error) { + if (isDaaError(error)) return error.detail + throw error + } + throw new Error('expected failure') +} + +describe('withdrawals get', () => { + it('uses the public route with an empty unsigned GET', async () => { + const { withdrawals, transport } = clientFor() + const result = await withdrawals.get(WITHDRAWAL_ID) + + expect(result.id).toBe(WITHDRAWAL_ID) + expect(transport.sent).toEqual([ + { + method: 'GET', + path: `/v1/accounts/withdrawals/${WITHDRAWAL_ID}`, + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + }) + + it('rejects non-UUID identifiers without transport', async () => { + const { withdrawals, transport } = clientFor() + for (const bad of ['', 'withdrawal-1', `${WITHDRAWAL_ID}/other`, `${WITHDRAWAL_ID}%2Fother`]) { + expect((await detailOf(withdrawals.get(bad))).kind).toBe('contract_violation') + } + expect(transport.sent).toHaveLength(0) + }) + + it('accepts only the documented 200', async () => { + for (const status of [201, 204, 299]) { + const { withdrawals } = clientFor(status) + const detail = await detailOf(withdrawals.get(WITHDRAWAL_ID)) + expect(detail.kind).toBe('api') + if (detail.kind === 'api') expect(detail.httpStatus).toBe(status) + } + }) + + it('maps a malformed data envelope to a contract violation', async () => { + const { withdrawals } = clientFor(200, '{}') + expect((await detailOf(withdrawals.get(WITHDRAWAL_ID))).kind).toBe('contract_violation') + }) +}) diff --git a/src/__test__/withdrawalsCreate.test.ts b/src/__test__/withdrawalsCreate.test.ts new file mode 100644 index 0000000..286db67 --- /dev/null +++ b/src/__test__/withdrawalsCreate.test.ts @@ -0,0 +1,402 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { DEVICE_AUTHORIZATION_HEADER } from '../auth/deviceAuthorization' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { sha256 } from '../crypto/sha256' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { CreateWithdrawalRequest } from '../models/CreateWithdrawalRequest' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { registeredAuthKey, signingFor, unregisteredAuthKey } from './userClientSigning' + +/** + * The signed withdrawal create, end to end through the client. Mirrors + * `transfersCreate.test.ts`'s structure — same discipline, different operation. + * + * Every wire fact here is a literal rather than a comparison against the + * constant the production code reads, for the reason that file gives: an + * assertion that moves with the defect catches nothing. + */ + +class RecordingTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly response: DaaHttpResponse) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + return this.response + } +} + +const IDEMPOTENCY_KEY = '33333333-3333-4333-a333-333333333333' +const DESTINATION_ID = '55555555-5555-4555-8555-555555555555' +const AUTH_KEY_ID = '11111111-1111-4111-8111-111111111111' + +/** A complete withdrawal: every field the service guarantees. */ +const CREATED_WITHDRAWAL = + '{"id":"w-1","sourceAccountId":"acct-src",' + + '"destination":{"type":"wire","id":"55555555-5555-4555-8555-555555555555"},' + + '"amount":{"amount":"10.25","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}' + +const VALID_REQUEST: CreateWithdrawalRequest = { + idempotencyKey: IDEMPOTENCY_KEY, + destination: { type: 'wire', id: DESTINATION_ID }, + amount: { amount: '10.25', currency: 'USD' }, +} + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function envelope(payload: string): Uint8Array { + return bytes(`{"data":${payload}}`) +} + +async function createdClient(payload = CREATED_WITHDRAWAL) { + const transport = new RecordingTransport({ + status: 201, + headers: { 'X-Request-Id': 'req-create', Location: '/v1/accounts/withdrawals/w-1' }, + bodyBytes: envelope(payload), + }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { + withdrawals: createDaaUserClient(transport, 'production', signing).withdrawals, + transport, + } +} + +function claimsOf(request: DaaHttpRequest): Record { + const compact = request.headers[DEVICE_AUTHORIZATION_HEADER] + if (compact === undefined) { + throw new Error('missing device authorization') + } + return JSON.parse(new TextDecoder().decode(fromBase64Url(compact.split('.')[1] ?? ''))) +} + +function sentBodyText(transport: RecordingTransport): string { + const sent = transport.sent[0]?.bodyBytes + if (sent == null) throw new Error('no body was sent') + return new TextDecoder().decode(sent) +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) { + return err.detail + } + throw err + } + throw new Error('expected the operation to fail') +} + +describe('the signed request', () => { + it('posts the registry canonical path with the withdrawal discriminator', async () => { + const { withdrawals, transport } = await createdClient() + + await withdrawals.create(VALID_REQUEST) + + expect(transport.sent).toHaveLength(1) + const request = transport.sent[0] + if (request === undefined) throw new Error('no request was sent') + expect(request.method).toBe('POST') + expect(request.path).toBe('/v1/accounts/withdrawals') + expect(request.query).toBeNull() + expect(request.headers['Content-Type']).toBe('application/json') + expect(claimsOf(request)).toMatchObject({ + canonical_path: '/v1/accounts/withdrawals', + method: 'POST', + discriminator: 'withdrawal', + schema_version: 1, + aud: 'circle-digital-asset-accounts', + idempotency_key: IDEMPOTENCY_KEY, + }) + }) + + it('sends exactly the registry properties, in the registry order, at every level', async () => { + const { withdrawals, transport } = await createdClient() + + await withdrawals.create({ + idempotencyKey: IDEMPOTENCY_KEY, + source: { type: 'account', id: 'acct-src' }, + destination: { type: 'wire', id: DESTINATION_ID, name: 'My Bank' }, + amount: { amount: '10.25', currency: 'USD' }, + toAmount: { amount: '9.00', currency: 'EUR' }, + riskSignals: { ipAddress: '198.51.100.7', deviceId: 'device-1' }, + burnAll: true, + }) + + expect(sentBodyText(transport)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}","source":{"type":"account","id":"acct-src"},` + + `"destination":{"type":"wire","id":"${DESTINATION_ID}","name":"My Bank"},` + + '"amount":{"amount":"10.25","currency":"USD"},' + + '"toAmount":{"amount":"9.00","currency":"EUR"},' + + '"riskSignals":{"ipAddress":"198.51.100.7","deviceId":"device-1"},' + + '"burnAll":true}', + ) + const body = JSON.parse(sentBodyText(transport)) + expect(Object.keys(body)).toEqual([ + 'idempotencyKey', + 'source', + 'destination', + 'amount', + 'toAmount', + 'riskSignals', + 'burnAll', + ]) + expect(Object.keys(body.destination)).toEqual(['type', 'id', 'name']) + expect(Object.keys(body.amount)).toEqual(['amount', 'currency']) + expect(Object.keys(body.toAmount)).toEqual(['amount', 'currency']) + }) + + it('sends the ach destination arm with the same property set as wire', async () => { + const { withdrawals, transport } = await createdClient() + + await withdrawals.create({ ...VALID_REQUEST, destination: { type: 'ach', id: DESTINATION_ID } }) + + expect(sentBodyText(transport)).toBe( + `{"idempotencyKey":"${IDEMPOTENCY_KEY}",` + + `"destination":{"type":"ach","id":"${DESTINATION_ID}"},` + + '"amount":{"amount":"10.25","currency":"USD"}}', + ) + }) + + it('omits toAmount.amount when the caller lets DAA resolve the conversion', async () => { + const { withdrawals, transport } = await createdClient() + + await withdrawals.create({ ...VALID_REQUEST, toAmount: { currency: 'EUR' } }) + + expect(sentBodyText(transport)).toContain('"toAmount":{"currency":"EUR"}') + }) + + it('sends the amount as a decimal string, not a JSON number', async () => { + const { withdrawals, transport } = await createdClient() + + // Eighteen significant digits: a value `JSON.stringify` would round if this + // ever became a numeric literal, and the rounded value is what the Owner + // would then be signing for. + await withdrawals.create({ + ...VALID_REQUEST, + amount: { amount: '1234567890123456.78', currency: 'USD' }, + }) + + expect(sentBodyText(transport)).toContain('"amount":{"amount":"1234567890123456.78"') + }) + + it('snapshots amount fields before validation and serialization', async () => { + const { withdrawals, transport } = await createdClient() + let reads = 0 + const amount = { currency: 'USD' } as CreateWithdrawalRequest['amount'] + Object.defineProperty(amount, 'amount', { + enumerable: true, + get: () => { + reads += 1 + return reads === 1 ? '10.25' : '999.99' + }, + }) + + await withdrawals.create({ ...VALID_REQUEST, amount }) + + expect(reads).toBe(1) + expect(sentBodyText(transport)).toContain('"amount":{"amount":"10.25","currency":"USD"}') + }) + + it('snapshots source, destination, and toAmount fields before serialization', async () => { + const { withdrawals, transport } = await createdClient() + const reads = { + sourceType: 0, + sourceId: 0, + destinationType: 0, + destinationId: 0, + destinationName: 0, + toAmount: 0, + toCurrency: 0, + } + const source = new Proxy( + { type: 'account' as const, id: 'acct-src' }, + { + get(target, property, receiver) { + if (property === 'type') reads.sourceType += 1 + if (property === 'id') reads.sourceId += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + const destination = new Proxy( + { type: 'wire' as const, id: DESTINATION_ID, name: 'My Bank' }, + { + get(target, property, receiver) { + if (property === 'type') reads.destinationType += 1 + if (property === 'id') reads.destinationId += 1 + if (property === 'name') reads.destinationName += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + const toAmount = new Proxy( + { amount: '9.00', currency: 'EUR' as const }, + { + get(target, property, receiver) { + if (property === 'amount') reads.toAmount += 1 + if (property === 'currency') reads.toCurrency += 1 + return Reflect.get(target, property, receiver) + }, + }, + ) + + await withdrawals.create({ ...VALID_REQUEST, source, destination, toAmount }) + + expect(reads).toEqual({ + sourceType: 1, + sourceId: 1, + destinationType: 1, + destinationId: 1, + destinationName: 1, + toAmount: 1, + toCurrency: 1, + }) + expect(sentBodyText(transport)).toContain( + '"source":{"type":"account","id":"acct-src"},' + + `"destination":{"type":"wire","id":"${DESTINATION_ID}","name":"My Bank"},` + + '"amount":{"amount":"10.25","currency":"USD"},' + + '"toAmount":{"amount":"9.00","currency":"EUR"}', + ) + }) + + it('binds body_sha256 to the exact bytes it transmits', async () => { + const { withdrawals, transport } = await createdClient() + + await withdrawals.create(VALID_REQUEST) + + const request = transport.sent[0] + if (request?.bodyBytes == null) throw new Error('no body was sent') + expect(claimsOf(request).body_sha256).toBe(toBase64Url(sha256(request.bodyBytes))) + }) + + it('decodes the documented 201 into a withdrawal detail', async () => { + const { withdrawals } = await createdClient() + + const withdrawal = await withdrawals.create(VALID_REQUEST) + + expect(withdrawal.id).toBe('w-1') + expect(withdrawal.status).toEqual({ kind: 'pending' }) + expect(withdrawal.amount.amount).toBe('10.25') + }) + + it('treats another 2xx as an API failure rather than a created withdrawal', async () => { + const transport = new RecordingTransport({ + status: 202, + headers: { 'X-Request-Id': 'req-202' }, + bodyBytes: envelope(CREATED_WITHDRAWAL), + }) + const withdrawals = createDaaUserClient( + transport, + 'production', + signingFor(await registeredAuthKey(), AUTH_KEY_ID), + ).withdrawals + + expect(await detailOf(withdrawals.create(VALID_REQUEST))).toEqual({ + kind: 'api', + httpStatus: 202, + retryable: false, + }) + }) +}) + +describe('local rejection', () => { + async function rejectingClient() { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + const signing = signingFor(await registeredAuthKey(), AUTH_KEY_ID) + return { + withdrawals: createDaaUserClient(transport, 'production', signing).withdrawals, + transport, + signing, + } + } + + it('refuses a property the registry schema does not name, at any level', async () => { + const unknownProperties: readonly CreateWithdrawalRequest[] = [ + { ...VALID_REQUEST, memo: 'rent' } as never, + { + ...VALID_REQUEST, + destination: { type: 'wire', id: DESTINATION_ID, chain: 'ARC' }, + } as never, + { ...VALID_REQUEST, amount: { amount: '10.25', currency: 'USD', scale: 2 } } as never, + { ...VALID_REQUEST, toAmount: { currency: 'USD', fee: '1.00' } } as never, + { ...VALID_REQUEST, riskSignals: { ip: '198.51.100.7' } } as never, + ] + + for (const request of unknownProperties) { + const { withdrawals, transport, signing } = await rejectingClient() + expect((await detailOf(withdrawals.create(request))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + // Nothing was signed either: an Owner signature is not spent on bytes + // that cannot succeed. + expect(signing.resolutions()).toBe(0) + } + }) + + it('refuses each field the registry constrains, without sending anything', async () => { + const invalid: readonly CreateWithdrawalRequest[] = [ + { ...VALID_REQUEST, idempotencyKey: 'not-a-uuid' }, + { ...VALID_REQUEST, destination: { type: 'wire', id: 'not-a-uuid' } }, + { ...VALID_REQUEST, destination: { type: 'ach', id: '' } as never }, + { ...VALID_REQUEST, destination: { type: 'check', id: DESTINATION_ID } } as never, + { ...VALID_REQUEST, destination: { type: 'wire', id: DESTINATION_ID, name: '' } }, + { ...VALID_REQUEST, source: { type: 'blockchain', id: 'x' } } as never, + // A JSON number, which is exactly what the string form exists to avoid. + { ...VALID_REQUEST, amount: { amount: 10.25, currency: 'USD' } } as never, + { ...VALID_REQUEST, amount: { amount: '10.25', currency: '' } }, + { ...VALID_REQUEST, amount: { amount: 'ten', currency: 'USD' } }, + { ...VALID_REQUEST, toAmount: { currency: 'GBP' } } as never, + { ...VALID_REQUEST, toAmount: { amount: 9.0, currency: 'USD' } } as never, + { ...VALID_REQUEST, riskSignals: { ipAddress: '' } }, + { ...VALID_REQUEST, burnAll: 'yes' } as never, + 'not an object' as never, + ] + + for (const request of invalid) { + const { withdrawals, transport } = await rejectingClient() + expect((await detailOf(withdrawals.create(request))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + } + }) + + it('fails closed while the AuthKey is not yet registered', async () => { + const transport = new RecordingTransport({ status: 201, headers: {}, bodyBytes: null }) + // `created`, not `existing`: Device Registration Complete has not + // acknowledged this key, so it may sign the Complete call and nothing else. + const authKey = await unregisteredAuthKey() + expect(authKey.resolution()).toBe('created') + const withdrawals = createDaaUserClient( + transport, + 'production', + signingFor(authKey, AUTH_KEY_ID), + ).withdrawals + + expect(await detailOf(withdrawals.create(VALID_REQUEST))).toEqual({ + kind: 'contract_violation', + }) + expect(transport.sent).toHaveLength(0) + }) +}) diff --git a/src/__test__/withdrawalsPagination.test.ts b/src/__test__/withdrawalsPagination.test.ts new file mode 100644 index 0000000..db6e967 --- /dev/null +++ b/src/__test__/withdrawalsPagination.test.ts @@ -0,0 +1,220 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { createDaaUserClient } from '../api/DaaUserClient' +import { NO_SIGNING } from './userClientSigning' +import { isDaaError } from '../errors' +import type { DaaSdkError } from '../errors' +import type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' + +/** + * The withdrawal list, end to end through the client. Mirrors + * `transfersPagination.test.ts`'s structure — same discipline, different + * resource. Every wire fact here is a literal, and every test also confirms + * `list()` does not resolve the AuthKey: `NO_SIGNING` throws if it tries, the + * same guard `withdrawalsClient.test.ts`'s `get` tests use. + */ + +const ORIGIN = 'https://api.circle.com' +const CURSOR_AFTER = '3f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const CURSOR_BEFORE = '4f1a2b4c-5d6e-4f70-8192-a3b4c5d6e7f8' +const WITHDRAWAL = + '{"id":"a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd","sourceAccountId":"1000662322",' + + '"destination":{"type":"wire","id":"0db1c81a-d36d-4777-8774-9682d96d82c8"},' + + '"amount":{"amount":"10.00","currency":"USD"},"status":"pending",' + + '"createDate":"2026-01-01T00:00:00Z"}' + +function bytes(text: string): Uint8Array { + return new TextEncoder().encode(text) +} + +function pageBody(withdrawal = WITHDRAWAL): Uint8Array { + return bytes(`{"data":[${withdrawal}]}`) +} + +class SequenceTransport implements DaaTransport { + readonly sent: DaaHttpRequest[] = [] + + constructor(private readonly responses: readonly DaaHttpResponse[]) {} + + async send(request: DaaHttpRequest): Promise { + this.sent.push(request) + const response = this.responses[this.sent.length - 1] + if (response === undefined) throw new Error('unexpected request') + return response + } +} + +function response(headers: Readonly> = {}): DaaHttpResponse { + return { status: 200, headers, bodyBytes: pageBody() } +} + +async function detailOf(operation: Promise): Promise { + try { + await operation + } catch (err) { + if (isDaaError(err)) return err.detail + throw err + } + throw new Error('expected the operation to fail') +} + +describe('withdrawals pagination', () => { + it('loads and freezes withdrawals over the exact public collection path, unsigned', async () => { + const transport = new SequenceTransport([response()]) + // `NO_SIGNING` throws if `list()` ever asks for the AuthKey — a read must + // not sign, unlike `create`. + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).withdrawals.list() + + expect(transport.sent).toEqual([ + { + method: 'GET', + path: '/v1/accounts/withdrawals', + query: null, + headers: {}, + bodyBytes: null, + }, + ]) + expect(page.items[0]?.id).toBe('a49f9b1d-75e0-44a9-b8d2-4293b3f11ebd') + expect(page.items[0]?.destination.type).toEqual({ kind: 'wire' }) + expect(page.items[0]?.status).toEqual({ kind: 'pending' }) + expect(Object.isFrozen(page)).toBe(true) + expect(Object.isFrozen(page.items)).toBe(true) + expect(Object.isFrozen(page.items[0])).toBe(true) + await expect(page.next()).resolves.toBeNull() + await expect(page.previous()).resolves.toBeNull() + }) + + it('serializes the documented withdrawal filters in deterministic order', async () => { + const transport = new SequenceTransport([response()]) + const withdrawals = createDaaUserClient(transport, 'production', NO_SIGNING).withdrawals + + await withdrawals.list({ + custodyType: 'segregated', + accountId: '1000662322', + status: ['pending', 'failed'], + from: '2026-08-01T00:00:00Z', + to: '2026-08-18T00:00:00Z', + pageAfter: CURSOR_AFTER, + pageSize: 50, + }) + + expect(transport.sent[0]?.query).toBe( + 'custodyType=segregated&accountId=1000662322&status=pending&status=failed' + + '&from=2026-08-01T00%3A00%3A00Z&to=2026-08-18T00%3A00%3A00Z' + + `&pageAfter=${CURSOR_AFTER}&pageSize=50`, + ) + }) + + it('follows only the same withdrawal collection and preserves its opaque query', async () => { + const nextQuery = 'z=last&pageAfter=backing%2Fcursor%3D&repeat=1&repeat=2&reserved=%2B%26' + const previousQuery = 'pageBefore=opaque-value&pageSize=2' + const transport = new SequenceTransport([ + response({ + Link: + `<${ORIGIN}/v1/accounts/withdrawals?${nextQuery}>; rel="next", ` + + `<${ORIGIN}/v1/accounts/withdrawals?${previousQuery}>; rel="prev"`, + }), + response(), + response(), + ]) + + const page = await createDaaUserClient(transport, 'production', NO_SIGNING).withdrawals.list() + await page.next() + await page.previous() + + expect(transport.sent[1]?.query).toBe(nextQuery) + expect(transport.sent[2]?.query).toBe(previousQuery) + for (const request of transport.sent) { + expect(request.path).toBe('/v1/accounts/withdrawals') + expect(request.method).toBe('GET') + expect(request.bodyBytes).toBeNull() + } + }) + + it.each([ + `${ORIGIN}/v1/accounts?pageAfter=${CURSOR_AFTER}`, + `${ORIGIN}/v1/accounts/transfers?pageAfter=${CURSOR_AFTER}`, + `https://evil.example/v1/accounts/withdrawals?pageAfter=${CURSOR_AFTER}`, + ])('rejects navigation outside the trusted withdrawal collection: %s', async (target) => { + const transport = new SequenceTransport([response({ Link: `<${target}>; rel="next"` })]) + + const detail = await detailOf( + createDaaUserClient(transport, 'production', NO_SIGNING).withdrawals.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it('uses the configured environment as the pagination trust anchor', async () => { + const transport = new SequenceTransport([ + response({ Link: `<${ORIGIN}/v1/accounts/withdrawals?pageAfter=x>; rel="next"` }), + ]) + + const detail = await detailOf( + createDaaUserClient(transport, 'sandbox', NO_SIGNING).withdrawals.list(), + ) + + expect(detail.kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(1) + }) + + it.each([ + null, + [], + { pageAfter: CURSOR_AFTER, pageBefore: CURSOR_BEFORE }, + { pageAfter: 'not-a-uuid' }, + { pageBefore: 'not-a-uuid' }, + { custodyType: 'unknown' }, + { accountId: '' }, + { status: [] }, + { status: ['unknown'] }, + { from: '' }, + { to: '' }, + { pageSize: 0 }, + { pageSize: 1.5 }, + ])('rejects an invalid initial query without sending it: %o', async (query) => { + const transport = new SequenceTransport([]) + const withdrawals = createDaaUserClient(transport, 'production', NO_SIGNING).withdrawals + + expect((await detailOf(withdrawals.list(query as never))).kind).toBe('contract_violation') + expect(transport.sent).toHaveLength(0) + }) + + it('maps malformed list bodies and undocumented success statuses through shared rules', async () => { + const malformed = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-list' }, bodyBytes: bytes('{"data":{}}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformed, 'production', NO_SIGNING).withdrawals.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-list' }) + + const malformedItem = new SequenceTransport([ + { status: 200, headers: { 'X-Request-Id': 'req-item' }, bodyBytes: bytes('{"data":[{}]}') }, + ]) + await expect( + detailOf(createDaaUserClient(malformedItem, 'production', NO_SIGNING).withdrawals.list()), + ).resolves.toEqual({ kind: 'contract_violation', correlationId: 'req-item' }) + + const wrongStatus = new SequenceTransport([{ status: 201, headers: {}, bodyBytes: pageBody() }]) + await expect( + detailOf(createDaaUserClient(wrongStatus, 'production', NO_SIGNING).withdrawals.list()), + ).resolves.toMatchObject({ kind: 'api', httpStatus: 201 }) + }) +}) diff --git a/src/api/AccountLimitsClient.ts b/src/api/AccountLimitsClient.ts new file mode 100644 index 0000000..77fc804 --- /dev/null +++ b/src/api/AccountLimitsClient.ts @@ -0,0 +1,146 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { AccountLimitsUsage } from '../models/AccountLimitsUsage' +import type { DaaTransport } from '../transport/DaaTransport' +import { toAccountLimitsUsage } from '../wire/accountLimitsUsagePayload' +import { appendEnum } from './queryParameters' +import { readResource } from './resourceRequest' + +/** + * `GET /v1/accounts/{accountId}/limits/usage` — the public path documented at + * https://developers.circle.com/api-reference/digital-asset-accounts/all/list-account-limits-usage. + * + * The public API reference above is this client's contract. + */ +const ACCOUNT_LIMITS_USAGE_PATH_PREFIX = '/v1/accounts/' +const ACCOUNT_LIMITS_USAGE_PATH_SUFFIX = '/limits/usage' + +/** + * The public reference's documented pattern for this path parameter: + * `^\d{1,10}$`. This is stricter than `AccountsClient.get`'s `accountId` + * guard: account ids are strings in general, but this endpoint's reference + * constrains the parameter to a numeric shape, so the guard follows the + * documented contract for *this* endpoint. The same reasoning distinguishes `DepositsClient.get`'s UUID + * guard from `AccountsClient.get`'s path-segment one. + */ +const ACCOUNT_ID_PATTERN = /^\d{1,10}$/ + +const OPERATIONS = Object.freeze([ + 'deposit', + 'withdrawal', + 'receive', + 'send', + 'send_count', + 'address_linking', + 'fiat_linking', + 'deposit_return_count', + 'balance_cap', +] as const) + +const ASSET_TYPES = Object.freeze(['fiat', 'crypto'] as const) + +const WINDOWS = Object.freeze(['PT24H', 'P30D'] as const) + +/** Filters accepted by the account limits/usage read, all optional. */ +export type AccountLimitsUsageQuery = Readonly<{ + operation?: (typeof OPERATIONS)[number] + assetType?: (typeof ASSET_TYPES)[number] + /** ISO 8601 rolling-window duration. */ + window?: (typeof WINDOWS)[number] +}> + +/** + * Reads over an account's limits and current usage, as the SDK contract's + * `AccountLimitsClient`. + * + * A dedicated client rather than a method on `AccountsClient`, matching this + * SDK's pattern: every distinct resource type — accounts, deposits, deposit + * addresses, transactions, transfers, withdrawals, fiat accounts — gets its + * own client class rather than being folded into a sibling's. `limitsUsage` is its own resource with its own + * wire shape, so it gets its own class too. + * + * {@link get} is an **ordinary typed read** (the classification for every + * by-id read in this SDK): it needs no device signature. Neither the public + * reference nor the Owner-authorization registry names a signed "limits" + * operation. + * + * The API additionally rejects `window=PT24H` combined with + * `operation=fiat_linking` or `operation=deposit_return_count`. That + * constraint is not pre-validated here: it is a business rule about which + * *values* of two independent query parameters may combine, not a structural + * rule about the request shape, and this SDK's existing cross-field query + * checks (`pageAfter`/`pageBefore` mutual exclusion on every paged list) are + * all of the latter kind. Rejecting it locally would mean this SDK + * hard-codes a business rule that can change on the service side without a + * client release to match; the service's own `400` is the source of truth. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#transport` field makes the type nominal. + */ +export class AccountLimitsClient { + readonly #transport: DaaTransport + + /** @internal Constructed only through the internal user-client factory. */ + constructor(transport: DaaTransport) { + this.#transport = transport + Object.freeze(this) + } + + /** + * Read one account's limits and current usage. + * + * @param accountId The service-assigned identifier. The public reference + * types this path parameter `^\d{1,10}$`; anything else is rejected + * locally rather than sent, because it cannot resolve on the service side. + * @param query Optional `operation`/`assetType`/`window` filters. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `accountId` or query, or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200` + * (including the `400` the API returns for `window=PT24H` combined + * with `operation=fiat_linking`/`deposit_return_count`); + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async get(accountId: string, query?: AccountLimitsUsageQuery): Promise { + if (!ACCOUNT_ID_PATTERN.test(accountId)) { + throw contractViolation('accountId must match ^\\d{1,10}$') + } + + return readResource({ + transport: this.#transport, + path: ACCOUNT_LIMITS_USAGE_PATH_PREFIX + accountId + ACCOUNT_LIMITS_USAGE_PATH_SUFFIX, + query: accountLimitsUsageQuery(query), + decode: toAccountLimitsUsage, + }) + } +} + +function accountLimitsUsageQuery(query: AccountLimitsUsageQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('account limits usage query must be an object') + } + + const parts: string[] = [] + appendEnum(parts, 'operation', query.operation, OPERATIONS) + appendEnum(parts, 'assetType', query.assetType, ASSET_TYPES) + appendEnum(parts, 'window', query.window, WINDOWS) + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/AccountsClient.ts b/src/api/AccountsClient.ts new file mode 100644 index 0000000..57288ce --- /dev/null +++ b/src/api/AccountsClient.ts @@ -0,0 +1,305 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody } from '../crypto/serialization' +import { contractViolation } from '../errors' +import type { Account } from '../models/Account' +import type { CreateAccountRequest } from '../models/CreateAccountRequest' +import type { Page } from '../models/Page' +import type { DaaTransport } from '../transport/DaaTransport' +import { requireBodyObject, requireKnownProperties } from '../validation/requestBody' +import { isUuid, isUuidV4 } from '../validation/uuid' +import { toAccount, toAccounts } from '../wire/accountPayload' +import { readPage } from './pagination' +import { + append, + appendEnum, + appendEnums, + appendString, + appendStrings, + appendUuid, +} from './queryParameters' +import { readResource } from './resourceRequest' +import { postSignedResource, type DaaUserSigning } from './signedResource' + +/** + * `GET /v1/accounts/{accountId}` — the **public** path, which is what a + * consumer's transport is handed. The SDK contract gives canonical paths in + * this form, such as `/v1/accounts/transfers`. + */ +/** + * The RFC 3986 unreserved set, which is what the native SDKs' request type + * enforces on a whole path. Anything outside it — `%`, `/`, `?`, `#`, a control + * character — is refused before a request is built. + */ +const SAFE_PATH_SEGMENT = /^[A-Za-z0-9._~-]+$/ + +const ACCOUNT_PATH_PREFIX = '/v1/accounts/' +const ACCOUNT_COLLECTION_PATH = '/v1/accounts' + +/** + * The properties the Owner-authorization registry's `create_account` schema + * names, in the order it names them. + * + * Order matters because these are the bytes that get signed: the body is + * serialized once from this shape and that exact slice is hashed into + * `body_sha256` and put on the wire. Building it here rather than forwarding + * the caller's object also means the property order does not vary with how the + * caller happened to write its literal. + */ +const CREATE_ACCOUNT_PROPERTIES = Object.freeze([ + 'idempotencyKey', + 'clientEntityId', + 'custodyType', + 'type', + 'purpose', + 'description', + 'blockchain', +]) + +export type AccountListQuery = Readonly<{ + custodyType?: 'omnibus' | 'segregated' | 'self' + clientEntityId?: string + type?: 'first_party' | 'third_party' + isAttributed?: boolean + purpose?: 'custody' | 'payments' + status?: readonly ('active' | 'pending' | 'rejected' | 'archived')[] + description?: string + currencies?: readonly string[] + groupId?: string + from?: string + to?: string + pageAfter?: string + pageBefore?: string + pageSize?: number +}> + +/** + * Reads over DAA accounts, plus the signed account create, as the SDK + * contract's `AccountsClient`. + * + * {@link list} returns a page whose navigation is derived only from same-origin + * RFC 8288 links bound to this collection. + * + * An account read is an **ordinary typed read**: it needs no device signature. + * {@link create} is the opposite: it is an Owner-authorized write, so it + * carries an `X-Device-Authorization` bound to the exact bytes it sends and + * cannot happen without the registered AuthKey `forUser` supplies. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#transport` field makes the type nominal. + */ +export class AccountsClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + readonly #signing: DaaUserSigning + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport, publicApiOrigin: string, signing: DaaUserSigning) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + this.#signing = signing + Object.freeze(this) + } + + /** List accounts and retain the API's opaque navigation queries unchanged. */ + async list(query?: AccountListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: ACCOUNT_COLLECTION_PATH, + query: accountListQuery(query), + decode: toAccounts, + }) + } + + /** + * Read one account. + * + * @param accountId The service-assigned identifier. + * @throws DaaError with `detail.kind === 'contract_violation'` for a rejected + * `accountId` or a response the SDK cannot read, and `detail.kind === 'api'` + * for a status other than the documented `200`; `detail.kind === 'transport'` + * if the consumer's transport throws, with the thrown value as `err.cause`. + */ + async get(accountId: string): Promise { + // A path separator would silently extend the path into a sibling route rather + // than fail: "acct-1/transfers" addresses /v1/accounts/acct-1/transfers, a + // real and different operation. An empty id would likewise address the + // collection instead of a member. Nothing is sent in either case. + // + // Rejecting only a literal `/` is not enough here, and this SDK has less to + // fall back on than the native ones: their request type refuses any + // character outside the RFC 3986 unreserved set, so a percent-encoded + // separator never reaches the wire. `DaaTransport` is an interface a + // consumer implements, so there is no equivalent runtime check downstream — + // "acct-1%2Ftransfers" would be concatenated verbatim and reintroduce the + // route confusion the moment anything decodes it. So the id is held to the + // unreserved set, which excludes `%` along with everything else risky. + // `.` is itself unreserved, so the pattern alone admits the dot-segments + // `.` and `..` — which resolve upward rather than naming a member. The + // native request type rejects them separately for the same reason. + if (!SAFE_PATH_SEGMENT.test(accountId) || accountId === '.' || accountId === '..') { + throw contractViolation( + 'accountId must be a single non-empty path segment of unreserved characters', + ) + } + + return readResource({ + transport: this.#transport, + path: ACCOUNT_PATH_PREFIX + accountId, + decode: toAccount, + }) + } + + /** + * Create a self-custody account, authorized by the registered device key. + * + * The body is validated, serialized **once**, and that exact byte slice is + * both hashed into the authorization's `body_sha256` claim and sent as the + * request entity. Nothing between here and the transport re-serializes it, + * which is the whole point: a re-encoding that changed so much as a space + * would produce a signature over bytes the service never receives. + * + * Neither the method nor the path is chosen here. `postSignedResource` + * resolves both from the registry entry for `create_account`, so a signed + * write cannot be aimed somewhere the operation does not name. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for a request + * the registry schema would reject, for an AuthKey that is not yet + * registered — the create is refused locally, before anything is signed or + * sent — for a rejected or replayed authorization (including a key that is + * no longer active: DAA has no revoked-credential code, so this never + * throws `device_revoked`), and for a response the SDK cannot read; + * `detail.kind === 'api'` for a status other than the documented `201`; and + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause` and the request's `idempotencyKey` on the + * detail. + */ + async create(request: CreateAccountRequest): Promise { + const bodyBytes = serializeBody(createAccountBody(request)) + return postSignedResource({ + transport: this.#transport, + operation: 'create_account', + authKey: await this.#signing.resolveAuthKey(), + authKeyId: this.#signing.authKeyId, + bodyBytes, + // The contract documents exactly 201, with a Location header. Another + // 2xx is an observable API failure rather than a silently accepted + // variant, the same rule the by-id reads apply to 200. + expectedStatus: 201, + decode: toAccount, + }) + } +} + +/** + * Project a validated request onto the registry's `create_account` shape. + * + * Returned rather than serialized here so the caller can hold the one byte + * slice this body becomes; see {@link AccountsClient.create}. + */ +function createAccountBody(request: CreateAccountRequest): object { + requireBodyObject(request, 'account create request') + requireKnownProperties(request, CREATE_ACCOUNT_PROPERTIES, 'account create request') + + const { idempotencyKey, clientEntityId, custodyType, type, purpose, description, blockchain } = + request + + // UUID v4 specifically, which is stricter than the registry's `format: uuid` + // (DAA only parses it). The contract's own + // `SelfCustodyAccountCreationRequest` documents this field as "UUID v4 + // identifying this account-creation attempt", and this SDK already holds + // `GenerateAddressRequest.idempotencyKey` to the same rule. The transfer + // create is deliberately not held to it — nothing in its contract says v4. + if (typeof idempotencyKey !== 'string' || !isUuidV4(idempotencyKey)) { + throw contractViolation('idempotencyKey must be a UUID v4') + } + if (typeof clientEntityId !== 'string' || !isUuid(clientEntityId)) { + throw contractViolation('clientEntityId is required and must be a UUID') + } + if (custodyType !== 'self') { + throw contractViolation('custodyType must be self') + } + if (type !== 'third_party') { + throw contractViolation('type must be third_party') + } + if (purpose !== 'custody') { + throw contractViolation('purpose must be custody') + } + if (typeof description !== 'string') { + throw contractViolation('description must be a string') + } + if (description.length > 255) { + throw contractViolation('description must be 255 characters or fewer') + } + if (blockchain !== undefined && (typeof blockchain !== 'string' || blockchain.length === 0)) { + throw contractViolation('blockchain must be a non-empty string when supplied') + } + + // `blockchain` is the one optional property here: an omitted value is left + // out of the object rather than set to `undefined`, so `JSON.stringify` + // drops it identically either way, but only the omission says so in the + // source. Every other property is required and validated above. + return { + idempotencyKey, + clientEntityId, + custodyType, + type, + purpose, + description, + ...(blockchain === undefined ? {} : { blockchain }), + } +} + +function accountListQuery(query: AccountListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('account list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendUuid(parts, 'clientEntityId', query.clientEntityId) + appendEnum(parts, 'type', query.type, ['first_party', 'third_party']) + if (query.isAttributed !== undefined) { + if (typeof query.isAttributed !== 'boolean') { + throw contractViolation('isAttributed must be a boolean') + } + append(parts, 'isAttributed', String(query.isAttributed)) + } + appendEnum(parts, 'purpose', query.purpose, ['custody', 'payments']) + appendEnums(parts, 'status', query.status, ['active', 'pending', 'rejected', 'archived']) + appendString(parts, 'description', query.description) + appendStrings(parts, 'currencies', query.currencies) + appendUuid(parts, 'groupId', query.groupId) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + appendString(parts, 'pageAfter', query.pageAfter) + appendString(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + append(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/AchFiatAccountsClient.ts b/src/api/AchFiatAccountsClient.ts new file mode 100644 index 0000000..a7bfbb6 --- /dev/null +++ b/src/api/AchFiatAccountsClient.ts @@ -0,0 +1,147 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { ACH, ACHInstruction } from '../models/Ach' +import type { DaaTransport } from '../transport/DaaTransport' +import { isUuid } from '../validation/uuid' +import { toAch, toAchInstruction, toAchList } from '../wire/achPayload' +import { appendUuid } from './queryParameters' +import { readResource } from './resourceRequest' + +const ACH_COLLECTION_PATH = '/v1/banks/ach' +const ACH_PATH_PREFIX = '/v1/banks/ach/' + +/** + * The ACH collection's list query: unlike wire's, `clientEntityId` is + * **required** for the ACH collection read, because ACH listing covers + * third-party accounts only. + */ +export type AchFiatAccountListQuery = Readonly<{ + clientEntityId: string +}> + +/** + * Reads over ACH fiat accounts. + * + * Every operation here is an **ordinary typed read with no device signature**, + * the same classification `WireFiatAccountsClient` carries. + * + * {@link list} requires `clientEntityId` — see that field's doc — and, like + * `get`, decodes the full `ACH` projection, for consistency with the by-id + * read, so there is no separate `ACHSummary` the way `WireSummary` exists for + * wire. {@link getInstructions} is a plain typed read of the public + * instruction route, like `WireFiatAccountsClient.getInstructions`: it returns + * Circle's receiving instructions and does not resolve a self-custody + * pass-through account. Unlike wire's instruction read, it takes no query: the + * ACH route has no public `accountId`. + * + * An environment without `GET /v1/banks/ach` surfaces the ordinary `api` error + * for whatever status it returns; this client has no distinguished + * unsupported-capability error. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#transport` field makes the type nominal. + */ +export class AchFiatAccountsClient { + readonly #transport: DaaTransport + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport) { + this.#transport = transport + Object.freeze(this) + } + + /** + * List ACH fiat accounts for one client entity. + * + * `query` and `query.clientEntityId` are both required — the signature is + * `list(query: AchFiatAccountListQuery)`, not `query?`. See + * {@link AchFiatAccountListQuery} for why. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * missing or invalid `clientEntityId`, or a response the SDK cannot read, + * and `detail.kind === 'api'` for a status other than the documented + * `200`; `detail.kind === 'transport'` if the consumer's transport throws, + * with the thrown value as `err.cause`. + */ + async list(query: AchFiatAccountListQuery): Promise> { + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('ach list query must be an object') + } + + const parts: string[] = [] + if (query.clientEntityId === undefined) { + throw contractViolation('clientEntityId is required for the ACH collection read') + } + appendUuid(parts, 'clientEntityId', query.clientEntityId) + + return readResource({ + transport: this.#transport, + path: ACH_COLLECTION_PATH, + query: parts.join('&'), + decode: toAchList, + }) + } + + /** + * Read one ACH fiat account. + * + * @param fiatAccountId The service-assigned UUID. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `fiatAccountId` or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200`; + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async get(fiatAccountId: string): Promise { + if (!isUuid(fiatAccountId)) { + throw contractViolation('fiatAccountId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: ACH_PATH_PREFIX + fiatAccountId, + decode: toAch, + }) + } + + /** + * Read Circle receiving instructions for an ACH fiat account. + * + * A plain typed read of the public instruction route — see the class doc. + * + * @param fiatAccountId The service-assigned UUID. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `fiatAccountId` or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200`; + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async getInstructions(fiatAccountId: string): Promise { + if (!isUuid(fiatAccountId)) { + throw contractViolation('fiatAccountId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: ACH_PATH_PREFIX + fiatAccountId + '/instructions', + decode: toAchInstruction, + }) + } +} diff --git a/src/api/AuthClient.ts b/src/api/AuthClient.ts new file mode 100644 index 0000000..964f48d --- /dev/null +++ b/src/api/AuthClient.ts @@ -0,0 +1,331 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + newRegistrationCodeVerifier, + registrationCodeChallengeS256, +} from '../auth/registrationCodeVerifier' +import { + checkPrepareReceipt, + pinnedPrepareReceiptTrustAnchor, + type PrepareReceiptTrustAnchor, +} from '../auth/prepareReceipt' +import { + defaultRegistrationFlowKeyProvider, + releaseQuietly, + type RegistrationFlowKeyProvider, +} from '../auth/RegistrationFlowKey' +import type { DaaEnvironment } from '../config' +import { fromBase64Url } from '../crypto/base64url' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { randomUuidV4 } from '../crypto/random' +import { serializeBody } from '../crypto/serialization' +import { contractViolation, isDaaError, withRequestId } from '../errors' +import { PreparedSocialLogin } from '../models/PreparedSocialLogin' +import { + createOwnerAuthKeyResolver, + type AppAuthKeyResolver, +} from '../securekey/ownerAuthKeyResolver' +import type { AppKeyIdentity, OwnerAuthKey, SecureKeyStore } from '../securekey/SecureKey' +import type { DaaTransport } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { toSocialLoginRequest } from '../wire/socialLoginRequestPayload' +import { loginStepFailure } from './loginFailure' +import { decodeResourceResponse } from './resourceRequest' + +/** + * `POST /v1/accounts/auth/loginRequests` — the contract's `prepareSocialLogin` + * operation, on the **public** path — the form a consumer's transport is + * handed, as for every other client here. + * + * There is no `/social/` segment. The contract path is + * `/v1/accounts/auth/loginRequests` (camelCase), and its sibling + * Social Session call is `/v1/accounts/auth/sessions`. + */ +const PREPARE_SOCIAL_LOGIN_PATH = '/v1/accounts/auth/loginRequests' + +/** + * Uppercase provider key, matching `PrepareSocialLoginRequest.provider` + * (`^[A-Z][A-Z0-9_]*$`, `maxLength: 64`). Providers are application-registry + * keys such as `GOOGLE` or `APPLE`, not raw issuer URLs. + */ +const PROVIDER = /^[A-Z][A-Z0-9_]{0,63}$/ + +/** + * Unpadded Base64URL of a 91-byte P-256 SPKI is always 122 characters, and the + * contract pins `registrationFlowPublicKey` to exactly that length. The charset + * is the one this SDK's Base64URL codec emits. + */ +const FLOW_PUBLIC_KEY = /^[A-Za-z0-9_-]{122}$/ + +/** `registrationCodeChallenge` is an unpadded Base64URL SHA-256 digest: 43 characters. */ +const CODE_CHALLENGE = /^[A-Za-z0-9_-]{43}$/ + +/** + * The social-login entry point: `AuthClient`. + * + * Login is split into three calls — Prepare, Social Session, Device + * Registration Complete. Prepare lives here; Session and Complete live on the + * values Prepare returns (`PreparedSocialLogin.completeSocialSession`, + * `PendingDeviceRegistration.complete`). + * + * Prepare does not touch an AuthKey. AuthKey selection happens only after + * the Social Session response, via the injected store (tests) or the native + * store (production). Prepare does check the DAA-signed Prepare receipt, before + * it returns anything to the application — see `prepareSocialLogin`. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#transport` field makes the type nominal. + */ +export class AuthClient { + readonly #transport: DaaTransport + readonly #registrationFlowKeys: RegistrationFlowKeyProvider + readonly #authKeys: AppAuthKeyResolver + readonly #environment: DaaEnvironment | null + readonly #prepareReceiptTrustAnchor: PrepareReceiptTrustAnchor | null + + /** @internal Constructed only through `DaaClient`. */ + constructor(args: { + transport: DaaTransport + /** + * Defaults to native `DaaRegistrationFlowKey` via the Expo module. Injectable + * so tests can substitute; not reachable from `DaaSdkConfiguration`, so a + * consumer cannot substitute the key that proves its own registration handoff. + */ + registrationFlowKeys?: RegistrationFlowKeyProvider + /** + * AuthKey store used after Social Session. Tests inject `./testing`'s + * in-memory store; production leaves this unset and the resolver builds + * `NativeSecureKeyStore` on first selection, because `DaaClient` + * construction does not require the Expo `DaaSecureKey` module. + */ + secureKeys?: SecureKeyStore + /** + * The consumer's app-level identity (`appId`, `environment`) — NOT the full + * `OwnerKeyIdentity`: the Owner (`clientEntityId`) is not known until Social + * Session responds, so it is supplied per call rather than here. Required + * before AuthKey selection. + */ + identity?: AppKeyIdentity + /** + * The resolver `DaaClient` shares between login and `forUser`, so both reach + * one store and one in-flight `resolveOrCreate` map for this identity. + * Unset, this client builds its own from `identity`/`secureKeys` — which is + * what a test constructing `AuthClient` directly wants, since it has no + * second holder to share with. + */ + authKeys?: AppAuthKeyResolver + /** + * The configured environment: selects the pinned Prepare-receipt trust + * anchor and is the value the receipt's `environment` claim must name. + * Falls back to `identity.environment`. + */ + environment?: DaaEnvironment + /** + * Test-only override of the pinned receipt trust anchor. Not reachable from + * `DaaSdkConfiguration`: a consumer cannot choose the key that vouches for + * its own relay's responses. + */ + prepareReceiptTrustAnchor?: PrepareReceiptTrustAnchor | null + }) { + this.#transport = args.transport + this.#registrationFlowKeys = args.registrationFlowKeys ?? defaultRegistrationFlowKeyProvider() + this.#authKeys = + args.authKeys ?? createOwnerAuthKeyResolver(args.identity ?? null, args.secureKeys ?? null) + this.#environment = args.environment ?? args.identity?.environment ?? null + this.#prepareReceiptTrustAnchor = + args.prepareReceiptTrustAnchor !== undefined + ? args.prepareReceiptTrustAnchor + : this.#environment === null + ? null + : pinnedPrepareReceiptTrustAnchor(this.#environment) + Object.freeze(this) + } + + /** + * Start one social-login attempt. + * + * The SDK owns the body `idempotencyKey`. Each call mints a new one and + * serializes the body once for that request; the key is kept on the returned + * `PreparedSocialLogin` so an ambiguous in-process retry can resend identical + * bytes. Durable persistence across a restart is not implemented — see + * `models/PreparedSocialLogin.ts`. + * + * The Prepare receipt is checked before this resolves, so an application + * never holds a nonce from a response that failed that check. With no trust + * anchor pinned for the environment — every environment in this release — + * the SDK does no receipt work: a receipt the service sends is ignored, login + * proceeds as if none arrived, and `prepareReceiptJws` is null. With an + * anchor pinned, the receipt is required and must verify. See + * `checkPrepareReceipt` in + * `auth/prepareReceipt.ts`. + * + * @throws DaaError with `detail.kind === 'prepare_receipt_invalid'` when an + * anchor is pinned and the receipt is missing, malformed, fails its + * signature or claim checks, has expired, or the platform verifier is + * missing or fails; `contract_violation` for a rejected provider, unusable + * local key material, a missing native DaaRegistration module, or a + * response the SDK cannot read; + * `login_request_expired` for `410`; `idempotency_conflict` for a `409` + * with `IDEMPOTENCY_KEY_REUSED` (`420034`); `contract_violation` with the + * correlation id for `LOGIN_REQUEST_CONSUMED` (`420039`); and `api` for any + * other status besides the documented `201`, including any other `409`. + * Whatever the consumer's transport throws is rethrown unchanged. + */ + async prepareSocialLogin(input: { provider: string }): Promise { + if (typeof input !== 'object' || input === null || Array.isArray(input)) { + throw contractViolation('prepareSocialLogin input must be an object') + } + if (typeof input.provider !== 'string' || !PROVIDER.test(input.provider)) { + throw contractViolation( + 'provider must be an uppercase identity-provider key of at most 64 characters', + ) + } + const provider = input.provider + + // Ordering: verifier and flow key exist BEFORE Prepare is sent. + const registrationCodeVerifier = newRegistrationCodeVerifier() + const registrationCodeChallenge = registrationCodeChallengeS256(registrationCodeVerifier) + if (!CODE_CHALLENGE.test(registrationCodeChallenge)) { + throw contractViolation( + 'registration code challenge must be a 43-character unpadded Base64URL SHA-256 digest', + ) + } + const registrationFlowKey = await this.#registrationFlowKeys.generate() + try { + const registrationFlowPublicKey = await registrationFlowKey.publicKeySpkiBase64Url() + if (!FLOW_PUBLIC_KEY.test(registrationFlowPublicKey)) { + throw contractViolation( + 'registration-flow public key must be a 122-character unpadded Base64URL P-256 SPKI', + ) + } + + const idempotencyKey = newIdempotencyKey() + // Serialized once. These are the bytes that go on the wire, and the bytes an + // exact retry has to reproduce; nothing downstream re-serializes them. + // + // idempotencyKey + provider are required; challenge and flow key are + // optional. The service rejects unknown members with `400`, so + // `registrationCodeChallengeMethod` is not sent. Always send challenge + + // flow key; hold the verifier for Complete. + const bodyBytes = serializeBody({ + idempotencyKey, + provider, + registrationCodeChallenge, + registrationFlowPublicKey, + }) + const response = await this.#transport.send({ + method: 'POST', + path: PREPARE_SOCIAL_LOGIN_PATH, + query: null, + headers: { 'Content-Type': 'application/json' }, + bodyBytes, + }) + + const failure = loginStepFailure(response, idempotencyKey) + if (failure !== null) { + throw failure + } + + const prepared = decodeResourceResponse({ + response, + expectedStatus: 201, + decode: toSocialLoginRequest, + }) + const verifiedReceipt = await checkPrepareReceipt( + prepared.prepareReceiptJws, + this.#prepareReceiptTrustAnchor, + () => ({ + loginRequestId: prepared.loginRequestId, + nonce: prepared.oidcNonce, + provider, + environment: this.#requireEnvironmentForReceipt(), + // The SDK's own values, generated before Prepare was sent: the two a + // relay substituting another attempt cannot make match. + registrationCodeChallenge, + registrationFlowKeyThumbprint: p256JwkThumbprint( + fromBase64Url(registrationFlowPublicKey), + ), + }), + ).catch((err: unknown) => { + // A rejected receipt came from this response, so it names the + // response's request id. A `contract_violation` from the check is this + // SDK's own configuration fault and is left as it is. + throw isDaaError(err) && err.detail.kind === 'prepare_receipt_invalid' + ? withRequestId(err, headerValueIgnoringCase(response.headers, 'X-Request-Id')) + : err + }) + return new PreparedSocialLogin({ + loginRequestId: prepared.loginRequestId, + oidcNonce: prepared.oidcNonce, + oidcState: prepared.oidcState, + // Only a receipt that verified; an ignored one is not handed on. + prepareReceiptJws: verifiedReceipt === null ? null : verifiedReceipt.compactJws, + expiresAt: prepared.expiresAt, + registrationCodeVerifier, + registrationFlowKey, + idempotencyKey, + transport: this.#transport, + resolveAuthKey: (clientEntityId: string) => this.#resolveAuthKey(clientEntityId), + }) + } catch (error) { + // Keep the key on a successful PreparedSocialLogin — Complete still needs + // the private half. A failed attempt has no holder, so drop the native + // cache entry rather than leaking it for the process lifetime. + await releaseQuietly(registrationFlowKey) + throw error + } + } + + /** + * Select or create the installation AuthKey only after Social Session. + * Prepare never calls this. + * + * `clientEntityId` namespaces the key per Owner. The caller — + * `PreparedSocialLogin.completeSocialSession` — passes the Social Session + * response's OWN echo of `clientEntityId`, not the value the application + * supplied to that call, because the response is the server-confirmed one. + * + * Private, and it stays private — with an ECMAScript `#` private field, not + * TypeScript's `private` keyword, which is erased at build time and would + * leave an ordinary callable method on the prototype. `AuthClient` is + * reachable from a consumer as `DaaClient.auth`, so a merely + * compile-time-private method here would hand out an `OwnerAuthKey` — and + * with it `signExactBytes` — which is the generic signing surface this SDK + * does not have. `forUser` reaches the same key through the resolver + * `DaaClient` owns, not through this client. + */ + async #resolveAuthKey(clientEntityId: string): Promise { + return this.#authKeys(clientEntityId) + } + + /** + * Reached only when a receipt is being verified against an anchor. A missing + * environment is this SDK's own wiring fault, so it stays `contract_violation`. + */ + #requireEnvironmentForReceipt(): DaaEnvironment { + if (this.#environment === null) { + throw contractViolation('verifying a Prepare receipt requires the configured environment') + } + return this.#environment + } +} + +function newIdempotencyKey(): string { + return randomUuidV4() +} diff --git a/src/api/DaaUserClient.ts b/src/api/DaaUserClient.ts new file mode 100644 index 0000000..4c76a97 --- /dev/null +++ b/src/api/DaaUserClient.ts @@ -0,0 +1,270 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { publicApiOriginFor } from '../config' +import type { DaaEnvironment } from '../config' +import { idempotencyKeyFromExactBody } from '../auth/deviceAuthorization' +import { contractViolation, DaaError, transportFailure } from '../errors' +import type { DeviceContext } from '../models/DaaUserContext' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import type { DaaHttpRequest, DaaTransport } from '../transport/DaaTransport' +import { toDeviceContext } from '../wire/deviceContextPayload' +import { AccountLimitsClient } from './AccountLimitsClient' +import { AccountsClient } from './AccountsClient' +import { DepositAddressesClient } from './DepositAddressesClient' +import { DepositsClient } from './DepositsClient' +import { FiatAccountsClient } from './FiatAccountsClient' +import { getSignedResource, type DaaUserSigning } from './signedResource' +import { TransactionsClient } from './TransactionsClient' +import { TransfersClient } from './TransfersClient' +import { WithdrawalsClient } from './WithdrawalsClient' + +/** + * The authenticated operations surface, as the SDK contract's `DaaUserClient`. + * + * The contract reaches this through the root client's `forUser(context)`, and every + * operation lives here rather than on the root client — the root client has only + * `auth` and `forUser`. + * + * Every resource client here has at least one operation; the surface never + * exposes a client with none. + * + * Signing material reaches only the clients that have a signed operation. + * Account limits, deposits, deposit addresses, transactions, and fiat + * accounts read (and, for deposit addresses, write unsigned) and so are + * handed none — a client that cannot sign cannot be made to sign by a later + * edit that forgets which calls are authorized. Fiat-account reads and + * get-instructions are both unsigned operations; for account limits/usage, + * see `AccountLimitsClient`'s class note for why it is unsigned. + */ +export class DaaUserClient { + /** Reads over DAA accounts, and the signed account create. */ + readonly accounts: AccountsClient + /** Reads over an account's limits and current usage. */ + readonly accountLimits: AccountLimitsClient + /** Reads over DAA deposit addresses. */ + readonly depositAddresses: DepositAddressesClient + /** Reads over DAA deposits, and the paged deposit list. */ + readonly deposits: DepositsClient + /** Reads over DAA unified account activity. */ + readonly transactions: TransactionsClient + /** Reads over DAA transfers, and the signed transfer create. */ + readonly transfers: TransfersClient + /** Reads over DAA withdrawals, and the signed withdrawal create. */ + readonly withdrawals: WithdrawalsClient + /** Reads over wire and ACH fiat accounts, and their receiving instructions. */ + readonly fiatAccounts: FiatAccountsClient + + readonly #transport: DaaTransport + readonly #signing: DaaUserSigning + readonly #markClosed: () => void + + /** @internal Constructed only through {@link createDaaUserClient}. */ + constructor( + transport: DaaTransport, + environment: DaaEnvironment, + signing: DaaUserSigning, + publicApiOriginOverride?: string, + ) { + const publicApiOrigin = publicApiOriginOverride ?? publicApiOriginFor(environment) + + // `close()` has to reach every signed operation this surface + // exposes, not just `refreshContext` — an accounts/transfers/withdrawals + // `create` reached through a "closed" client is exactly the further use + // `close()` exists to refuse. Every signed client below is handed this one + // wrapper rather than the caller's `signing` directly, so flipping `closed` + // here closes all of them at once without editing any resource client. + let closed = false + const assertOpen = (): void => { + if (closed) { + throw contractViolation( + 'DaaUserClient is closed; call DaaClient.forUser again to resume operations', + ) + } + } + const guardedSigning: DaaUserSigning = Object.freeze({ + authKeyId: signing.authKeyId, + resolveAuthKey: async () => { + assertOpen() + return guardAuthKey(await signing.resolveAuthKey(), assertOpen) + }, + }) + + // The transport guard closes unsent unsigned work too: a retained Page's + // next()/previous() closure still holds the client it was created from, + // so handing every resource client this wrapper makes close() reach those + // later sends without editing each pagination client. + // + // It is also the one place every operation on this surface reaches the + // consumer's transport, so it is where a throw from that transport becomes + // the SDK's `transport` error (see `transportFailure`). Only the send is + // wrapped: a closed client's `contract_violation` is the SDK's own refusal, + // not a transport failure, and is thrown before anything is sent. + const guardedTransport: DaaTransport = Object.freeze({ + send: async (request: DaaHttpRequest) => { + assertOpen() + try { + return await transport.send(request) + } catch (err) { + throw asTransportFailure(err, request) + } + }, + }) + + this.accounts = new AccountsClient(guardedTransport, publicApiOrigin, guardedSigning) + this.accountLimits = new AccountLimitsClient(guardedTransport) + this.depositAddresses = new DepositAddressesClient(guardedTransport, publicApiOrigin) + this.deposits = new DepositsClient(guardedTransport, publicApiOrigin) + this.transactions = new TransactionsClient(guardedTransport, publicApiOrigin) + this.transfers = new TransfersClient(guardedTransport, publicApiOrigin, guardedSigning) + this.withdrawals = new WithdrawalsClient(guardedTransport, publicApiOrigin, guardedSigning) + this.fiatAccounts = new FiatAccountsClient(guardedTransport) + + this.#transport = guardedTransport + this.#signing = guardedSigning + this.#markClosed = () => { + closed = true + } + Object.freeze(this) + } + + /** + * Signed context refresh (`refreshContext`). + * + * `get_device_context` (`GET /v1/accounts/auth/context`) is a registered-device + * authorization operation, not an ordinary unsigned read: the device + * authorization payload applies to registered-device authorization for + * protected writes and signed context refresh, alongside `transfer` and + * `withdrawal`, and `securekey/SecureKey.ts` names "signed context refresh" + * alongside "protected writes" as one of the defined DAA operations signing is + * reachable for. There is no request body: `getSignedResource` signs over the + * empty byte array per the bodyless-request rule and sends nothing as + * the request entity. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for an AuthKey + * that is not yet registered, for a rejected or replayed authorization + * (including a key that is no longer active: DAA has no revoked-credential + * code, so this never throws `device_revoked`), for a response the SDK + * cannot read, and once this client is {@link close}d; + * `detail.kind === 'api'` for a status other than the documented `200`; and + * `detail.kind === 'transport'` if the consumer's transport throws, with + * the thrown value as `err.cause`. + */ + async refreshContext(): Promise { + return getSignedResource({ + transport: this.#transport, + operation: 'get_device_context', + authKey: await this.#signing.resolveAuthKey(), + authKeyId: this.#signing.authKeyId, + expectedStatus: 200, + decode: toDeviceContext, + }) + } + + /** + * `DaaUserClient.close()` clears active context from memory and cancels + * unsent work. It preserves an active profile-scoped AuthKey and credential; + * application logout is not device revocation. + * + * This class holds no `DaaUserContext` object and no cancellable in-flight + * work of its own to release — the context a caller passed to `forUser` is + * never retained here, only the plain `authKeyId` string and a resolver + * closure, and every call this SDK makes is a single `transport.send` awaited + * to completion with no cancellation token in the transport contract to + * cancel. Concretely, close() revokes this instance's own capability to + * produce a fresh `X-Device-Authorization` at all, so `refreshContext` and + * every signed `create` on `accounts` / `transfers` / `withdrawals` fail + * closed with `contract_violation` from this point on instead of silently + * continuing to sign. The guarded transport also refuses unsigned reads, writes, and + * retained Page navigation closures after close, so unsent work cannot + * outlive the user surface that created it. The registered AuthKey and + * Circle's registration acknowledgement are untouched — nothing here calls + * the native store, so there is nothing here that could revoke either. + * Idempotent: closing an already-closed client is a no-op. + */ + close(): void { + this.#markClosed() + } +} + +/** + * Keep an in-flight signed operation tied to this user's lifecycle. The + * resolver guard prevents new operations after `close()`, while the signing + * guard also covers an operation that started before `close()` and would + * otherwise sign with the already-resolved AuthKey. + */ +function guardAuthKey(authKey: OwnerAuthKey, assertOpen: () => void): OwnerAuthKey { + return Object.freeze({ + publicKeySpkiBase64Url: () => authKey.publicKeySpkiBase64Url(), + thumbprint: () => authKey.thumbprint(), + resolution: () => authKey.resolution(), + acknowledgeRegistration: () => authKey.acknowledgeRegistration(), + signExactBytes: async (message: Uint8Array) => { + assertOpen() + return authKey.signExactBytes(message) + }, + signRegistrationDeviceAuthorization: async (message: Uint8Array) => { + assertOpen() + return authKey.signRegistrationDeviceAuthorization(message) + }, + }) +} + +/** + * Build the operations surface over a transport. + * + * Deliberately **not** exported from `index.ts`, and deliberately not a member of + * `DaaClient`: a consumer must not reach this without the user context that + * `forUser` requires, decoded from an `ACTIVE` Device Registration Complete. + * + * `publicApiOrigin` is the override `DaaClient` has already validated. Without + * it, the environment's public API origin is the pagination trust anchor. + */ +export function createDaaUserClient( + transport: DaaTransport, + environment: DaaEnvironment, + signing: DaaUserSigning, + publicApiOrigin?: string, +): DaaUserClient { + return new DaaUserClient(transport, environment, signing, publicApiOrigin) +} + +/** + * Wrap a throw from the consumer's transport as a `transport` error. An error + * that is already a `DaaError` passes through unchanged, as in + * `mapNativeError`. + * + * The idempotency key is read from the exact bytes that were handed to the + * transport, with the same reader the signed `409` mapping uses. A body the + * reader cannot parse leaves the key off rather than replacing the transport + * failure with a different error. + */ +function asTransportFailure(err: unknown, request: DaaHttpRequest): DaaError { + if (err instanceof DaaError) { + return err + } + let idempotencyKey: string | undefined + if (request.bodyBytes !== null) { + try { + idempotencyKey = idempotencyKeyFromExactBody(request.bodyBytes) + } catch { + idempotencyKey = undefined + } + } + return transportFailure(err, idempotencyKey) +} diff --git a/src/api/DepositAddressesClient.ts b/src/api/DepositAddressesClient.ts new file mode 100644 index 0000000..a987f20 --- /dev/null +++ b/src/api/DepositAddressesClient.ts @@ -0,0 +1,239 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody } from '../crypto/serialization' +import { contractViolation, idempotencyConflict } from '../errors' +import type { AddressObject } from '../models/AddressObject' +import type { GenerateAddressRequest } from '../models/GenerateAddressRequest' +import type { Page } from '../models/Page' +import type { DaaTransport } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { isUuid, isUuidV4 } from '../validation/uuid' +import { toAddressObject, toAddressObjects } from '../wire/addressObjectPayload' +import { isDaaStatus } from '../wire/daaStatusCodes' +import { readDaaStatusCode } from '../wire/errorEnvelope' +import { readPage } from './pagination' +import { appendEnum, appendString, appendUuid } from './queryParameters' +import { postResource, readResource } from './resourceRequest' + +/** + * `GET /v1/accounts/addresses/deposit/{depositId}` — the **public** path, + * which is what a consumer's transport is handed, as `AccountsClient` + * documents for `/v1/accounts/{accountId}`. + */ +const DEPOSIT_ADDRESS_PATH_PREFIX = '/v1/accounts/addresses/deposit/' +const DEPOSIT_ADDRESS_COLLECTION_PATH = '/v1/accounts/addresses/deposit' + +/** Filters and keyset pagination accepted by the deposit-address collection. */ +export type DepositAddressListQuery = Readonly<{ + custodyType?: 'omnibus' | 'segregated' | 'self' + accountId?: string + chain?: string + currency?: string + from?: string + to?: string + pageAfter?: string + pageBefore?: string + pageSize?: number +}> + +/** + * Reads over DAA deposit addresses, as the SDK contract's + * `DepositAddressesClient`. + * + * {@link get} reads an existing address. {@link create} is the unsigned + * create-or-resolve call for a named account: DAA creates the address for an + * omnibus `accountId` and returns the already-authoritative address for a + * segregated/self-custody one. See `GenerateAddressRequest`'s class doc for + * why this SDK's typed client does not expose the broader Accounts API's + * omission of `accountId` (the caller's omnibus master account). {@link list} + * returns trusted pages bound to the deposit-address collection. + * + * {@link create} throws `idempotency_conflict` for a `409` with + * `IDEMPOTENCY_KEY_REUSED` (`420034`). DAA sends it when an omnibus create + * reuses an `idempotencyKey` that was already used for a different account. + * The same key for the same account returns the original address, even with a + * different `chain` or `currency`. A segregated or self-custody create only + * resolves an existing address, so it never sends it. Any other `409` stays + * `api`. + * + * A deposit-address read is an **ordinary typed read**, the same + * classification `AccountsClient.get` carries: it needs no device signature. + * It is reachable the same way: through the `DaaUserClient` that `forUser` + * returns for a real user context. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#transport` field makes the type nominal. + */ +export class DepositAddressesClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport, publicApiOrigin: string) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + Object.freeze(this) + } + + /** List deposit addresses and retain the API's opaque navigation queries unchanged. */ + async list(query?: DepositAddressListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: DEPOSIT_ADDRESS_COLLECTION_PATH, + query: depositAddressListQuery(query), + decode: toAddressObjects, + }) + } + + /** + * Read one deposit address. + * + * @param depositId The service-assigned identifier. The service types this + * as a required UUID — a genuine UUID, not + * an arbitrary account-style id — so a value that is not UUID-formatted + * is rejected locally rather than sent: it cannot resolve to an address on + * the service side, and a UUID-formatted identifier also contains none of the + * characters (`/`, `%`, `.`, control bytes) that could redirect the + * request into a sibling route, the concern `AccountsClient.get`'s + * character-class check exists for. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `depositId` or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200`; + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async get(depositId: string): Promise { + if (!isUuid(depositId)) { + throw contractViolation( + 'depositId must be a UUID — the service types it as one, and anything else cannot resolve to a deposit address', + ) + } + + return readResource({ + transport: this.#transport, + path: DEPOSIT_ADDRESS_PATH_PREFIX + depositId, + decode: toAddressObject, + }) + } + + /** + * Create the deposit address for a named omnibus account, or resolve a + * segregated/self-custody account's already-authoritative one. + * + * The request has no `custodyType`; DAA derives custody from `accountId` when + * it is omitted. That is the only option that cannot disagree with the + * account's authoritative custody type. + * + * `accountId` is required — see {@link GenerateAddressRequest}'s class doc + * for why this SDK does not expose the broader Accounts API's omission of + * `accountId` (the caller's omnibus master account). + * + * This call is unsigned by contract. Its body is projected to the documented + * wire shape, serialized once, and the resulting bytes are sent unchanged. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for an invalid + * request or a response the SDK cannot read; `idempotency_conflict`, with + * the request's key, for a `409` with `IDEMPOTENCY_KEY_REUSED` (`420034`): + * the key was already used for a different account, so reconcile the + * original create with that key and do not mint a new key for it; + * `detail.kind === 'api'` for any other status than the documented `201`; + * and `detail.kind === 'transport'` if the consumer's transport + * throws, with the thrown value as `err.cause` and the request's + * `idempotencyKey` on the detail. + */ + async create(request: GenerateAddressRequest): Promise { + if (typeof request !== 'object' || request === null || Array.isArray(request)) { + throw contractViolation('deposit address request must be an object') + } + + const { idempotencyKey, accountId, currency, chain } = request + if (typeof idempotencyKey !== 'string' || !isUuidV4(idempotencyKey)) { + throw contractViolation('idempotencyKey must be a UUID v4') + } + if (typeof accountId !== 'string' || accountId.length === 0) { + throw contractViolation('accountId must be a non-empty string') + } + if (currency !== 'USD' && currency !== 'EUR') { + throw contractViolation('currency must be USD or EUR') + } + // `chain` is optional (resolves to the account's home blockchain when + // omitted) and, when supplied, is checked only for a plausible shape, not + // against a hardcoded catalog — see `models/GenerateAddressRequest.ts`'s + // `DEPOSIT_ADDRESS_CHAINS` doc for why a closed local allowlist here is a + // forward-compatibility hazard rather than a safety net. + if (chain !== undefined && (typeof chain !== 'string' || chain.length === 0)) { + throw contractViolation('chain must be a non-empty string when supplied') + } + + const bodyBytes = serializeBody({ + idempotencyKey, + accountId, + currency, + ...(chain === undefined ? {} : { chain }), + }) + return postResource({ + transport: this.#transport, + path: '/v1/accounts/addresses/deposit', + query: null, + headers: { 'Content-Type': 'application/json' }, + bodyBytes, + expectedStatus: 201, + decode: toAddressObject, + // Gated on both the status and the code, as on the signed writes. The + // call is unsigned, so the key is the one this request was checked with. + failure: (response) => + response.status === 409 && + isDaaStatus(readDaaStatusCode(response.bodyBytes), 'IDEMPOTENCY_KEY_REUSED') + ? idempotencyConflict( + idempotencyKey, + headerValueIgnoringCase(response.headers, 'X-Request-Id'), + ) + : null, + }) + } +} + +function depositAddressListQuery(query: DepositAddressListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('deposit address list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendString(parts, 'accountId', query.accountId) + appendString(parts, 'chain', query.chain) + appendString(parts, 'currency', query.currency) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + // Unlike account cursors, the service models deposit-address cursors as UUID ids. + appendUuid(parts, 'pageAfter', query.pageAfter) + appendUuid(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + appendString(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/DepositsClient.ts b/src/api/DepositsClient.ts new file mode 100644 index 0000000..e5bf76d --- /dev/null +++ b/src/api/DepositsClient.ts @@ -0,0 +1,208 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { Deposit } from '../models/Deposit' +import type { DepositSummary } from '../models/DepositSummary' +import type { Page } from '../models/Page' +import type { DaaTransport } from '../transport/DaaTransport' +import { isUuid } from '../validation/uuid' +import { toDeposit, toDepositSummaries } from '../wire/depositPayload' +import { readPage } from './pagination' +import { appendEnum, appendEnums, appendString, appendUuid } from './queryParameters' +import { readResource } from './resourceRequest' + +/* + * A deposit id is a UUID, and is checked as one rather than as a generic path + * segment. + * + * The SDK contract types this parameter `depositId: UUID`, and the service + * agrees, typing it as a required UUID. That is deliberately unlike + * `AccountsClient`, whose signature is `accountId: string`, because public + * account ids are strings, including numeric IDs. So the two guards differ on + * purpose; applying one rule to both would make one of them wrong. + * + * A UUID-formatted identifier also contains none of the characters — `/`, `%`, + * `.`, control bytes — that could redirect the request into a sibling route, so + * this subsumes the path-segment check rather than merely differing from it. + */ +/** + * `GET /v1/accounts/deposits/{id}` — the **public** path, which is what a + * consumer's transport is handed, exactly as for `AccountsClient`. + */ +const DEPOSIT_PATH_PREFIX = '/v1/accounts/deposits/' +const DEPOSIT_COLLECTION_PATH = '/v1/accounts/deposits' + +/** + * The wire values of `DepositType` (`models/Deposit.ts`), in the order that + * model declares them. Kept local to this query builder rather than exported + * off the model — `AccountsClient`'s and `TransfersClient`'s query builders do + * the same for their own filters — because the set a filter accepts is a + * query-parameter concern, not something a decoded response needs to expose. + * + * This is **not** a runtime allowlist, despite the server's own `DepositType` + * being a closed set. Deposit rails are a server-owned, externally-growing + * catalog — each entry is a distinct banking network Circle integrates with — + * and a new rail can arrive with no advance notice. `type` is used only as a + * passthrough query filter — this SDK does no per-rail branching — so a locally + * rejected filter value costs the caller a legitimate query with no + * compensating safety benefit; the server remains the authority and 400s on a + * genuinely unsupported value. Kept as a `const` union for editor autocomplete/typo + * protection only, and exported so a test can pin it against the server's + * `DepositType` wire values without duplicating the list. + */ +export const DEPOSIT_TYPES = Object.freeze([ + 'wire', + 'ach', + 'cbit', + 'rtgs', + 'rtp', + 'xpay', + 'signet', + 'sepa', + 'sepa_instant', + 'sen', + 'pix', + 'cubix', + 'book_transfer', + 'fed_now', +] as const) + +const DEPOSIT_STATUSES = Object.freeze(['pending', 'complete', 'failed'] as const) + +/** + * Filters and keyset pagination accepted by the deposit collection. + * + * Mirrors the service's deposit-list query parameters exactly: + * `custodyType` is derived from `accountId` when omitted and otherwise + * defaults to omnibus; `type` is a single filter, not repeatable, unlike + * `status`, which the service accepts as a repeated parameter; + * `pageAfter`/`pageBefore` are deposit ids, so — like `TransfersClient`'s + * cursors and unlike `AccountsClient`'s opaque string ones — they are held to + * `appendUuid` on the initial call. A `Link`-derived navigation query is never + * parsed or rebuilt from this type; see `api/pagination.ts`. + */ +export type DepositListQuery = Readonly<{ + custodyType?: 'omnibus' | 'segregated' | 'self' + accountId?: string + type?: (typeof DEPOSIT_TYPES)[number] + status?: readonly (typeof DEPOSIT_STATUSES)[number][] + /** Inclusive RFC 3339 creation-time lower bound. */ + from?: string + /** Inclusive RFC 3339 creation-time upper bound. */ + to?: string + /** Initial forward keyset cursor (a deposit id). Link-derived navigation remains opaque. */ + pageAfter?: string + /** Initial backward keyset cursor (a deposit id). Link-derived navigation remains opaque. */ + pageBefore?: string + pageSize?: number +}> + +/** + * Reads over DAA deposits, as the SDK contract's `DepositsClient` + * (`list(query?: DepositListQuery): Promise>`, + * `get(depositId: UUID): Promise`). + * + * {@link list} returns the compact `DepositSummary` projection the collection + * endpoint actually serves — see `models/DepositSummary.ts`'s class note for + * why that is a distinct type rather than `Deposit` with fields left + * `undefined` — and retains the API's opaque navigation queries unchanged, the + * same contract `TransfersClient.list` and `AccountsClient.list` honor. + * {@link get} reads the full detail projection. Both are **ordinary typed + * reads**: like `AccountsClient.get`, they need no device signature. Reached + * through `DaaClient.forUser`. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#transport` field makes the type nominal. + */ +export class DepositsClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport, publicApiOrigin: string) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + Object.freeze(this) + } + + /** List compact deposits and retain the API's opaque navigation queries unchanged. */ + async list(query?: DepositListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: DEPOSIT_COLLECTION_PATH, + query: depositListQuery(query), + decode: toDepositSummaries, + }) + } + + /** + * Read one deposit. + * + * @param depositId The service-assigned identifier, a UUID. Anything else is + * rejected locally rather than sent: it cannot resolve to a deposit on the + * service side, so the round trip would only turn a caller's mistake into a + * `400`. + * @throws DaaError with `detail.kind === 'contract_violation'` for a rejected + * `depositId` or a response the SDK cannot read, and `detail.kind === 'api'` + * for a status other than the documented `200`; `detail.kind === 'transport'` + * if the consumer's transport throws, with the thrown value as `err.cause`. + */ + async get(depositId: string): Promise { + if (!isUuid(depositId)) { + throw contractViolation('depositId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: DEPOSIT_PATH_PREFIX + depositId, + decode: toDeposit, + }) + } +} + +function depositListQuery(query: DepositListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('deposit list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendString(parts, 'accountId', query.accountId) + // `type` is a growable rail catalog, not a closed business vocabulary — see + // `DEPOSIT_TYPES`'s doc above — so it is checked structurally, not against + // the hardcoded set. + appendString(parts, 'type', query.type) + appendEnums(parts, 'status', query.status, DEPOSIT_STATUSES) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + appendUuid(parts, 'pageAfter', query.pageAfter) + appendUuid(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + appendString(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/FiatAccountsClient.ts b/src/api/FiatAccountsClient.ts new file mode 100644 index 0000000..7e71635 --- /dev/null +++ b/src/api/FiatAccountsClient.ts @@ -0,0 +1,50 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { DaaTransport } from '../transport/DaaTransport' +import { AchFiatAccountsClient } from './AchFiatAccountsClient' +import { WireFiatAccountsClient } from './WireFiatAccountsClient' + +/** + * Reads over both fiat-account rails, as the SDK contract's + * `FiatAccountsClient`: `{ wires: WireFiatAccountsClient; ach: + * AchFiatAccountsClient }`. + * + * A thin composing wrapper, the same role `DaaUserClient` itself plays one + * level up: neither rail needs the other's state, and the SDK contract does + * not expose a rail selector — wire and ACH use distinct rail-specific + * collection paths — so nothing is shared here beyond the transport + * both sub-clients are constructed with. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and `WireFiatAccountsClient`/`AchFiatAccountsClient`'s own `#transport` + * fields make each nominal. + */ +export class FiatAccountsClient { + /** Reads over wire fiat accounts. */ + readonly wires: WireFiatAccountsClient + /** Reads over ACH fiat accounts. */ + readonly ach: AchFiatAccountsClient + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport) { + this.wires = new WireFiatAccountsClient(transport) + this.ach = new AchFiatAccountsClient(transport) + Object.freeze(this) + } +} diff --git a/src/api/TransactionsClient.ts b/src/api/TransactionsClient.ts new file mode 100644 index 0000000..351a8cd --- /dev/null +++ b/src/api/TransactionsClient.ts @@ -0,0 +1,137 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { Page } from '../models/Page' +import type { Transaction } from '../models/Transaction' +import type { DaaTransport } from '../transport/DaaTransport' +import { toTransactions } from '../wire/transactionPayload' +import { readPage } from './pagination' +import { append, appendEnum, appendEnums, appendString, appendUuid } from './queryParameters' + +/** + * `GET /v1/accounts/transactions` — the **public** path, exactly as for + * transfers. + */ +const TRANSACTION_COLLECTION_PATH = '/v1/accounts/transactions' + +const TRANSACTION_TYPES = Object.freeze([ + 'deposit', + 'withdrawal', + 'transfer', + 'fx', + 'fee', + 'credit', + 'other', +] as const) + +const TRANSACTION_STATUSES = Object.freeze(['pending', 'complete', 'failed', 'returned'] as const) + +export type TransactionListQuery = Readonly<{ + /** Select a backing source explicitly; omitted derives from `accountId` or defaults to omnibus. */ + custodyType?: 'omnibus' | 'segregated' | 'self' + /** Match activity for this public account id. */ + accountId?: string + /** Match activity for one end-user sub-entity. */ + clientEntityId?: string + isAttributed?: boolean + type?: readonly (typeof TRANSACTION_TYPES)[number][] + status?: readonly (typeof TRANSACTION_STATUSES)[number][] + /** ISO 4217 / crypto currency code; not constrained to a known set. */ + currency?: string + /** Inclusive RFC 3339 creation-time lower bound. */ + from?: string + /** Inclusive RFC 3339 creation-time upper bound. */ + to?: string + /** Initial forward keyset cursor. Link-derived navigation remains opaque. */ + pageAfter?: string + /** Initial backward keyset cursor. Link-derived navigation remains opaque. */ + pageBefore?: string + pageSize?: number +}> + +/** + * Reads over DAA unified account activity, as the SDK contract's + * `TransactionsClient`. + * + * Only {@link list} exists. There is no by-id read: the API has none, and + * this client does not invent a `GET .../{id}`. Listing is an **ordinary typed read + * with no device signature**. {@link list} retains the API's RFC 8288 + * navigation queries as opaque text. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#transport` field makes the type nominal. + */ +export class TransactionsClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + + /** @internal Constructed only through the internal user-client factory. */ + constructor(transport: DaaTransport, publicApiOrigin: string) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + Object.freeze(this) + } + + /** List transactions and retain the API's opaque navigation queries unchanged. */ + async list(query?: TransactionListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: TRANSACTION_COLLECTION_PATH, + query: transactionListQuery(query), + decode: toTransactions, + }) + } +} + +function transactionListQuery(query: TransactionListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('transaction list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendString(parts, 'accountId', query.accountId) + appendUuid(parts, 'clientEntityId', query.clientEntityId) + if (query.isAttributed !== undefined) { + if (typeof query.isAttributed !== 'boolean') { + throw contractViolation('isAttributed must be a boolean') + } + append(parts, 'isAttributed', String(query.isAttributed)) + } + appendEnums(parts, 'type', query.type, TRANSACTION_TYPES) + appendEnums(parts, 'status', query.status, TRANSACTION_STATUSES) + appendString(parts, 'currency', query.currency) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + // The service models transaction cursors as UUID transaction ids. + appendUuid(parts, 'pageAfter', query.pageAfter) + appendUuid(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + append(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/TransfersClient.ts b/src/api/TransfersClient.ts new file mode 100644 index 0000000..f514a1b --- /dev/null +++ b/src/api/TransfersClient.ts @@ -0,0 +1,361 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody } from '../crypto/serialization' +import { contractViolation } from '../errors' +import type { + CreateTransferAmount, + CreateTransferDestination, + CreateTransferRequest, + CreateTransferRiskSignals, + CreateTransferSource, +} from '../models/CreateTransferRequest' +import type { Transfer } from '../models/Transfer' +import type { Page } from '../models/Page' +import type { DaaTransport } from '../transport/DaaTransport' +import { requireBodyObject, requireKnownProperties } from '../validation/requestBody' +import { isUuid } from '../validation/uuid' +import { JSON_NUMBER } from '../wire/jsonNumber' +import { toTransfer, toTransfers } from '../wire/transferPayload' +import { readPage } from './pagination' +import { append, appendEnum, appendString, appendUuid } from './queryParameters' +import { readResource } from './resourceRequest' +import { postSignedResource, type DaaUserSigning } from './signedResource' + +/** + * `GET /v1/accounts/transfers/{transferId}` — the **public** path, exactly as + * for Accounts (`AccountsClient.ts`). The registry's + * `"canonical_path": "/v1/accounts/transfers"` and the `Location` header of + * `/v1/accounts/transfers/` on create both use it. + */ +const TRANSFER_PATH_PREFIX = '/v1/accounts/transfers/' +const TRANSFER_COLLECTION_PATH = '/v1/accounts/transfers' + +/** + * The properties the Owner-authorization registry's `transfer` schema names, in + * the order it names them, at each level of the body. + * + * Order matters because these are the bytes that get signed: the body is + * serialized once from these shapes and that exact slice is hashed into + * `body_sha256` and put on the wire. Building it here rather than forwarding + * the caller's object also means the property order does not vary with how the + * caller happened to write its literal. Every one of these objects is + * `additionalProperties: false` in the registry, so each level is checked, not + * just the top. + */ +const TRANSFER_PROPERTIES = Object.freeze([ + 'idempotencyKey', + 'source', + 'destination', + 'amount', + 'riskSignals', +]) +const TRANSFER_LOCATION_PROPERTIES = Object.freeze(['type', 'id']) +const TRANSFER_VERIFIED_BLOCKCHAIN_PROPERTIES = Object.freeze(['type', 'addressId']) +const TRANSFER_AMOUNT_PROPERTIES = Object.freeze(['amount', 'currency']) +const TRANSFER_RISK_SIGNAL_PROPERTIES = Object.freeze(['ipAddress', 'sessionId', 'deviceId']) + +export type TransferListQuery = Readonly<{ + /** Select a backing source explicitly; omitted derives from `accountId` or defaults to omnibus. */ + custodyType?: 'omnibus' | 'segregated' | 'self' + /** Match transfers where this public account id is either leg. */ + accountId?: string + /** Match this source leg id. Leg ids are strings and are not necessarily UUIDs. */ + sourceAccountId?: string + /** Match this destination leg id. Leg ids are strings and are not necessarily UUIDs. */ + destinationAccountId?: string + /** Match transfers for one end-user sub-entity. */ + clientEntityId?: string + sourceType?: 'account' | 'blockchain' + destinationType?: 'account' | 'blockchain' + /** Inclusive RFC 3339 creation-time lower bound. */ + from?: string + /** Inclusive RFC 3339 creation-time upper bound. */ + to?: string + /** Initial forward keyset cursor. Link-derived navigation remains opaque. */ + pageAfter?: string + /** Initial backward keyset cursor. Link-derived navigation remains opaque. */ + pageBefore?: string + pageSize?: number +}> + +/* + * A transfer id is a UUID, and is checked as one rather than as a generic path + * segment. + * + * The SDK contract types this parameter `transferId: UUID`. That is + * deliberately unlike `AccountsClient`, whose signature is + * `accountId: string`, because public account ids are strings, including + * numeric IDs. The two guards differ on purpose; applying one rule to + * both would make one of them wrong. + * + * A UUID-formatted identifier contains none of the characters — `/`, `%`, `.`, control + * bytes — that could redirect the request into a sibling route, so this subsumes + * the path-segment check rather than merely differing from it. + */ +/** + * Reads over DAA transfers, plus the signed transfer create, as the SDK + * contract's `TransfersClient`. + * + * {@link list} retains the API's RFC 8288 navigation queries as opaque text. + * {@link create} is an Owner-authorized write: it carries an + * `X-Device-Authorization` bound to the exact bytes it sends and cannot happen + * without the registered AuthKey `forUser` supplies. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#transport` field makes the type nominal. + */ +export class TransfersClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + readonly #signing: DaaUserSigning + + /** @internal Constructed only through the internal user-client factory. */ + constructor(transport: DaaTransport, publicApiOrigin: string, signing: DaaUserSigning) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + this.#signing = signing + Object.freeze(this) + } + + /** List transfers and retain the API's opaque navigation queries unchanged. */ + async list(query?: TransferListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: TRANSFER_COLLECTION_PATH, + query: transferListQuery(query), + decode: toTransfers, + }) + } + + /** + * Read one transfer. + * + * @param transferId The service-assigned UUID. Values that are not + * UUID-formatted are rejected locally because they cannot resolve to a + * transfer on the service side. + * @throws DaaError with `detail.kind === 'contract_violation'` for a rejected + * `transferId` or a response the SDK cannot read, and `detail.kind === 'api'` + * for a status other than the documented `200`; `detail.kind === 'transport'` + * if the consumer's transport throws, with the thrown value as `err.cause`. + */ + async get(transferId: string): Promise { + if (!isUuid(transferId)) { + throw contractViolation('transferId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: TRANSFER_PATH_PREFIX + transferId, + decode: toTransfer, + }) + } + + /** + * Create a transfer, authorized by the registered device key. + * + * The body is validated, serialized **once**, and that exact byte slice is + * both hashed into the authorization's `body_sha256` claim and sent as the + * request entity. Nothing between here and the transport re-serializes it, + * which is the whole point: a re-encoding that changed so much as a space + * would produce a signature over bytes the service never receives. + * + * Neither the method nor the path is chosen here. `postSignedResource` + * resolves both from the registry entry for `transfer`, so a signed write + * cannot be aimed somewhere the operation does not name. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for a request + * the registry schema would reject, for an AuthKey that is not yet + * registered — the create is refused locally, before anything is signed or + * sent — for a rejected or replayed authorization (including a key that is + * no longer active: DAA has no revoked-credential code, so this never + * throws `device_revoked`), and for a response the SDK cannot read; + * `idempotency_conflict`, with the request's key, for a `409` with + * `IDEMPOTENCY_KEY_REUSED` (`420034`): reconcile the original transfer with + * the same key; do not mint a new key for it; + * `detail.kind === 'api'` for a status other than the documented `201`; and + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause` and the request's `idempotencyKey` on the + * detail. + */ + async create(request: CreateTransferRequest): Promise { + const bodyBytes = serializeBody(createTransferBody(request)) + return postSignedResource({ + transport: this.#transport, + operation: 'transfer', + authKey: await this.#signing.resolveAuthKey(), + authKeyId: this.#signing.authKeyId, + bodyBytes, + // The contract documents exactly 201, with a Location header. Another + // 2xx is an observable API failure rather than a silently accepted + // variant, the same rule the by-id reads apply to 200. + expectedStatus: 201, + decode: toTransfer, + }) + } +} + +/** + * Project a validated request onto the registry's `transfer` shape. + * + * Returned rather than serialized here so the caller can hold the one byte + * slice this body becomes; see {@link TransfersClient.create}. + */ +function createTransferBody(request: CreateTransferRequest): object { + requireBodyObject(request, 'transfer create request') + requireKnownProperties(request, TRANSFER_PROPERTIES, 'transfer create request') + + const { idempotencyKey, source, destination, amount, riskSignals } = request + + // The registry types this `format: uuid`, and nothing in the transfer + // contract narrows it to v4 — unlike the account create, whose own contract + // text says v4. Requiring more here would reject a key DAA accepts. + if (typeof idempotencyKey !== 'string' || !isUuid(idempotencyKey)) { + throw contractViolation('idempotencyKey must be a UUID') + } + + return { + idempotencyKey, + ...(source === undefined ? {} : { source: transferSource(source) }), + destination: transferDestination(destination), + amount: transferAmount(amount), + ...(riskSignals === undefined ? {} : { riskSignals: transferRiskSignals(riskSignals) }), + } +} + +function transferSource(source: CreateTransferSource): object { + requireBodyObject(source, 'transfer source') + requireKnownProperties(source, TRANSFER_LOCATION_PROPERTIES, 'transfer source') + const { type, id } = source + if (type !== 'account') { + throw contractViolation('transfer source type must be account') + } + if (typeof id !== 'string' || id.length === 0) { + throw contractViolation('transfer source id must be a non-empty string') + } + return { type, id } +} + +/** + * Both `oneOf` arms, kept apart by their discriminator. + * + * The registry requires a destination to match exactly one arm, and the two are + * told apart by `type` alone — their required properties are disjoint (`id` + * against `addressId`) and neither admits additional ones. So an unfamiliar + * `type` is rejected here rather than guessed at: guessing would mean picking + * an arm DAA would not have picked, and signing that. + */ +function transferDestination(destination: CreateTransferDestination): object { + requireBodyObject(destination, 'transfer destination') + const { type } = destination + if (type === 'account') { + requireKnownProperties(destination, TRANSFER_LOCATION_PROPERTIES, 'transfer destination') + const { id } = destination + if (typeof id !== 'string' || id.length === 0) { + throw contractViolation('transfer destination id must be a non-empty string') + } + return { type, id } + } + if (type === 'verified_blockchain') { + requireKnownProperties( + destination, + TRANSFER_VERIFIED_BLOCKCHAIN_PROPERTIES, + 'transfer destination', + ) + const { addressId } = destination + if (typeof addressId !== 'string' || !isUuid(addressId)) { + throw contractViolation('transfer destination addressId must be a UUID') + } + return { type, addressId } + } + throw contractViolation('transfer destination type must be account or verified_blockchain') +} + +function transferAmount(amount: CreateTransferAmount): object { + requireBodyObject(amount, 'transfer amount') + requireKnownProperties(amount, TRANSFER_AMOUNT_PROPERTIES, 'transfer amount') + const { amount: amountValue, currency } = amount + // The registry's `decimal` accepts a JSON string or a JSON number and then + // parses it as an arbitrary-precision decimal, so it would also take forms + // JSON itself does not write — a bare leading `.`, a trailing `.`, a leading + // `+`. This narrows to the RFC 8259 number grammar the SDK already requires + // of a `Money` on the way in (`wire/jsonNumber.ts`), so the same literal + // means the same thing in both directions and the signed bytes are never + // ambiguous. + if (typeof amountValue !== 'string' || !JSON_NUMBER.test(amountValue)) { + throw contractViolation('transfer amount must be a decimal string, e.g. "10.25"') + } + if (typeof currency !== 'string' || currency.length === 0) { + throw contractViolation('transfer amount currency must be a non-empty string') + } + return { amount: amountValue, currency } +} + +function transferRiskSignals(riskSignals: CreateTransferRiskSignals): object { + requireBodyObject(riskSignals, 'transfer risk signals') + requireKnownProperties(riskSignals, TRANSFER_RISK_SIGNAL_PROPERTIES, 'transfer risk signals') + const { ipAddress, sessionId, deviceId } = riskSignals + requireOptionalRiskSignal(ipAddress, 'ipAddress') + requireOptionalRiskSignal(sessionId, 'sessionId') + requireOptionalRiskSignal(deviceId, 'deviceId') + // The registry requires none of these, so an object with none of them is a + // valid `riskSignals` and is sent as the empty object the caller asked for. + return { + ...(ipAddress === undefined ? {} : { ipAddress }), + ...(sessionId === undefined ? {} : { sessionId }), + ...(deviceId === undefined ? {} : { deviceId }), + } +} + +function requireOptionalRiskSignal(value: string | undefined, name: string): void { + if (value !== undefined && (typeof value !== 'string' || value.length === 0)) { + throw contractViolation(`transfer risk signal ${name} must be a non-empty string`) + } +} + +function transferListQuery(query: TransferListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('transfer list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendString(parts, 'accountId', query.accountId) + appendString(parts, 'sourceAccountId', query.sourceAccountId) + appendString(parts, 'destinationAccountId', query.destinationAccountId) + appendUuid(parts, 'clientEntityId', query.clientEntityId) + appendEnum(parts, 'sourceType', query.sourceType, ['account', 'blockchain']) + appendEnum(parts, 'destinationType', query.destinationType, ['account', 'blockchain']) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + // Unlike account cursors, the service models transfer cursors as UUID transfer ids. + appendUuid(parts, 'pageAfter', query.pageAfter) + appendUuid(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + append(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/WireFiatAccountsClient.ts b/src/api/WireFiatAccountsClient.ts new file mode 100644 index 0000000..11bcb39 --- /dev/null +++ b/src/api/WireFiatAccountsClient.ts @@ -0,0 +1,172 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { Wire, WireInstruction, WireSummary } from '../models/Wire' +import type { DaaTransport } from '../transport/DaaTransport' +import { isUuid } from '../validation/uuid' +import { toWire, toWireInstruction, toWireSummaries } from '../wire/wirePayload' +import { appendString, appendUuid } from './queryParameters' +import { readResource } from './resourceRequest' + +const WIRE_COLLECTION_PATH = '/v1/banks/wires' +const WIRE_PATH_PREFIX = '/v1/banks/wires/' + +/** The wire collection's list query: `clientEntityId` is optional. */ +export type WireFiatAccountListQuery = Readonly<{ + clientEntityId?: string +}> + +/** + * A public Accounts API `accountId` query value. These are strings, including + * numeric IDs — the same reason `AccountsClient.get` types its parameter + * `string` rather than `UUID`. + */ +export type PublicAccountId = string + +/** Optional query accepted by {@link WireFiatAccountsClient.getInstructions}. */ +export type WireInstructionQuery = Readonly<{ + accountId?: PublicAccountId +}> + +/** + * Reads over wire fiat accounts. + * + * Every operation here is an **ordinary typed read** — fiat-account list and + * get and the receiving-instructions read are all unsigned — so, like + * `AccountsClient.get`, none of it needs a device signature. + * + * {@link list} returns the API's **unpaginated list shape**: a plain `data` + * array, not this SDK's opaque-cursor `Page`. {@link get} and + * {@link getInstructions} are separate SDK methods and response types by + * design: {@link get} returns the linked bank account, {@link getInstructions} + * returns Circle receiving instructions for it. {@link getInstructions} is a + * plain typed read of the public instruction route: it returns Circle's + * receiving instructions and does not resolve a self-custody pass-through + * account. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#transport` field makes the type nominal. + */ +export class WireFiatAccountsClient { + readonly #transport: DaaTransport + + /** @internal Constructed only through `createDaaUserClient`. */ + constructor(transport: DaaTransport) { + this.#transport = transport + Object.freeze(this) + } + + /** + * List wire fiat accounts. + * + * `clientEntityId` is optional here — unlike `AchFiatAccountsClient.list`, + * where it is required. This is a deliberate asymmetry, not a typo: + * `WireFiatAccountListQuery.clientEntityId` is optional and + * `AchFiatAccountListQuery.clientEntityId` is required, because ACH listing + * covers third-party accounts only. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for an + * invalid query or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200`; + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async list(query?: WireFiatAccountListQuery): Promise> { + return readResource({ + transport: this.#transport, + path: WIRE_COLLECTION_PATH, + query: wireListQuery(query), + decode: toWireSummaries, + }) + } + + /** + * Read one wire fiat account. + * + * @param fiatAccountId The service-assigned UUID. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `fiatAccountId` or a response the SDK cannot read, and + * `detail.kind === 'api'` for a status other than the documented `200`; + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause`. + */ + async get(fiatAccountId: string): Promise { + if (!isUuid(fiatAccountId)) { + throw contractViolation('fiatAccountId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: WIRE_PATH_PREFIX + fiatAccountId, + decode: toWire, + }) + } + + /** + * Read Circle receiving instructions for a wire fiat account. + * + * A plain typed read of the public instruction route — see the class doc. + * + * @param fiatAccountId The service-assigned UUID. + * @param query Optional public `accountId`. The wire instruction route + * accepts this parameter; the ACH route does not. + * @throws DaaError with `detail.kind === 'contract_violation'` for a + * rejected `fiatAccountId`/`accountId` or a response the SDK cannot read, + * and `detail.kind === 'api'` for a status other than the documented + * `200`; `detail.kind === 'transport'` if the consumer's transport throws, + * with the thrown value as `err.cause`. + */ + async getInstructions( + fiatAccountId: string, + query?: WireInstructionQuery, + ): Promise { + if (!isUuid(fiatAccountId)) { + throw contractViolation('fiatAccountId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: WIRE_PATH_PREFIX + fiatAccountId + '/instructions', + query: wireInstructionQuery(query), + decode: toWireInstruction, + }) + } +} + +function wireListQuery(query: WireFiatAccountListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('wire list query must be an object') + } + + const parts: string[] = [] + appendUuid(parts, 'clientEntityId', query.clientEntityId) + return parts.length === 0 ? null : parts.join('&') +} + +function wireInstructionQuery(query: WireInstructionQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('wire instruction query must be an object') + } + + const parts: string[] = [] + appendString(parts, 'accountId', query.accountId) + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/WithdrawalsClient.ts b/src/api/WithdrawalsClient.ts new file mode 100644 index 0000000..c3d3437 --- /dev/null +++ b/src/api/WithdrawalsClient.ts @@ -0,0 +1,339 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { serializeBody } from '../crypto/serialization' +import { contractViolation } from '../errors' +import type { + CreateWithdrawalAmount, + CreateWithdrawalDestination, + CreateWithdrawalRequest, + CreateWithdrawalRiskSignals, + CreateWithdrawalSource, + CreateWithdrawalToAmount, +} from '../models/CreateWithdrawalRequest' +import type { Page } from '../models/Page' +import type { WithdrawalDetail } from '../models/Withdrawal' +import type { DaaTransport } from '../transport/DaaTransport' +import { requireBodyObject, requireKnownProperties } from '../validation/requestBody' +import { isUuid } from '../validation/uuid' +import { JSON_NUMBER } from '../wire/jsonNumber' +import { toWithdrawalDetail, toWithdrawalDetails } from '../wire/withdrawalPayload' +import { readPage } from './pagination' +import { append, appendEnum, appendEnums, appendString, appendUuid } from './queryParameters' +import { readResource } from './resourceRequest' +import { postSignedResource, type DaaUserSigning } from './signedResource' + +/** + * `GET /v1/accounts/withdrawals[/{withdrawalId}]` — the **public** path, + * exactly as for Transfers (`TransfersClient.ts`). + */ +const WITHDRAWAL_PATH_PREFIX = '/v1/accounts/withdrawals/' +const WITHDRAWAL_COLLECTION_PATH = '/v1/accounts/withdrawals' + +/** The closed set of withdrawal list statuses; mirrors `models/Withdrawal.ts`'s `WithdrawalStatus` kinds. */ +const WITHDRAWAL_LIST_STATUSES = Object.freeze(['pending', 'complete', 'failed'] as const) + +export type WithdrawalListQuery = Readonly<{ + /** Select a backing source explicitly; omitted derives from `accountId` or defaults to omnibus. */ + custodyType?: 'omnibus' | 'segregated' | 'self' + /** Match withdrawals funded from this source account. Account ids are strings, not necessarily UUIDs. */ + accountId?: string + /** Match any of these withdrawal statuses. Repeatable `status` query params. */ + status?: readonly (typeof WITHDRAWAL_LIST_STATUSES)[number][] + /** Inclusive RFC 3339 creation-time lower bound. */ + from?: string + /** Inclusive RFC 3339 creation-time upper bound. */ + to?: string + /** Initial forward keyset cursor. Link-derived navigation remains opaque. */ + pageAfter?: string + /** Initial backward keyset cursor. Link-derived navigation remains opaque. */ + pageBefore?: string + pageSize?: number +}> + +/** + * The properties the Owner-authorization registry's `withdrawal` schema names, + * in the order it names them, at each level of the body. See + * `TransfersClient`'s equivalent constant for why order matters: these are the + * bytes that get signed. + */ +const WITHDRAWAL_PROPERTIES = Object.freeze([ + 'idempotencyKey', + 'source', + 'destination', + 'amount', + 'toAmount', + 'riskSignals', + 'burnAll', +]) +const WITHDRAWAL_SOURCE_PROPERTIES = Object.freeze(['type', 'id']) +const WITHDRAWAL_DESTINATION_PROPERTIES = Object.freeze(['type', 'id', 'name']) +const WITHDRAWAL_AMOUNT_PROPERTIES = Object.freeze(['amount', 'currency']) +const WITHDRAWAL_TO_AMOUNT_PROPERTIES = Object.freeze(['amount', 'currency']) +const WITHDRAWAL_RISK_SIGNAL_PROPERTIES = Object.freeze(['ipAddress', 'sessionId', 'deviceId']) +const WITHDRAWAL_TO_AMOUNT_CURRENCIES = Object.freeze(['USD', 'EUR']) + +/** + * Reads over DAA withdrawals, plus the signed withdrawal create, as the SDK + * contract's `WithdrawalsClient`. + * + * {@link list} retains the API's RFC 8288 navigation queries as opaque text. + * Collection rows use the same public projection {@link get} uses; + * `policyEvaluation` is GET-only and is omitted (decoded as `null`) on list + * items. {@link create} is an Owner-authorized write: it carries an + * `X-Device-Authorization` bound to the exact bytes it sends and cannot happen + * without the registered AuthKey `forUser` supplies. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#transport` field makes the type nominal. + */ +export class WithdrawalsClient { + readonly #transport: DaaTransport + readonly #publicApiOrigin: string + readonly #signing: DaaUserSigning + + /** @internal Constructed only through the internal user-client factory. */ + constructor(transport: DaaTransport, publicApiOrigin: string, signing: DaaUserSigning) { + this.#transport = transport + this.#publicApiOrigin = publicApiOrigin + this.#signing = signing + Object.freeze(this) + } + + /** List withdrawals and retain the API's opaque navigation queries unchanged. */ + async list(query?: WithdrawalListQuery): Promise> { + return readPage({ + transport: this.#transport, + publicApiOrigin: this.#publicApiOrigin, + path: WITHDRAWAL_COLLECTION_PATH, + query: withdrawalListQuery(query), + decode: toWithdrawalDetails, + }) + } + + /** Read one withdrawal over the public Accounts route. */ + async get(withdrawalId: string): Promise { + if (!isUuid(withdrawalId)) { + throw contractViolation('withdrawalId must be a UUID') + } + + return readResource({ + transport: this.#transport, + path: WITHDRAWAL_PATH_PREFIX + withdrawalId, + decode: toWithdrawalDetail, + }) + } + + /** + * Create a withdrawal, authorized by the registered device key. + * + * The body is validated, serialized **once**, and that exact byte slice is + * both hashed into the authorization's `body_sha256` claim and sent as the + * request entity. Nothing between here and the transport re-serializes it. + * + * Neither the method nor the path is chosen here. `postSignedResource` + * resolves both from the registry entry for `withdrawal`, so a signed write + * cannot be aimed somewhere the operation does not name. + * + * The response decodes through the same public projection {@link get} uses: + * `policyEvaluation` is GET-only and is omitted (decoded as `null`) here too. + * + * @throws DaaError with `detail.kind === 'contract_violation'` for a request + * the registry schema would reject, for an AuthKey that is not yet + * registered — the create is refused locally, before anything is signed or + * sent — for a rejected or replayed authorization (including a key that is + * no longer active: DAA has no revoked-credential code, so this never + * throws `device_revoked`), and for a response the SDK cannot read; + * `idempotency_conflict`, with the request's key, for a `409` with + * `IDEMPOTENCY_KEY_REUSED` (`420034`): reconcile the original withdrawal with + * the same key; do not mint a new key for it; + * `detail.kind === 'api'` for a status other than the documented `201`; and + * `detail.kind === 'transport'` if the consumer's transport throws, with the + * thrown value as `err.cause` and the request's `idempotencyKey` on the + * detail. + */ + async create(request: CreateWithdrawalRequest): Promise { + const bodyBytes = serializeBody(createWithdrawalBody(request)) + return postSignedResource({ + transport: this.#transport, + operation: 'withdrawal', + authKey: await this.#signing.resolveAuthKey(), + authKeyId: this.#signing.authKeyId, + bodyBytes, + // The contract documents exactly 201, with a Location header. Another + // 2xx is an observable API failure rather than a silently accepted + // variant, the same rule the by-id read applies to 200. + expectedStatus: 201, + decode: toWithdrawalDetail, + }) + } +} + +/** + * Project a validated request onto the registry's `withdrawal` shape. + * + * Returned rather than serialized here so the caller can hold the one byte + * slice this body becomes; see {@link WithdrawalsClient.create}. + */ +function createWithdrawalBody(request: CreateWithdrawalRequest): object { + requireBodyObject(request, 'withdrawal create request') + requireKnownProperties(request, WITHDRAWAL_PROPERTIES, 'withdrawal create request') + + const { idempotencyKey, source, destination, amount, toAmount, riskSignals, burnAll } = request + + // The registry types this `format: uuid` and, like `transfer`, narrows it no + // further — unlike `create_account`, whose own contract text says v4. + if (typeof idempotencyKey !== 'string' || !isUuid(idempotencyKey)) { + throw contractViolation('idempotencyKey must be a UUID') + } + + return { + idempotencyKey, + ...(source === undefined ? {} : { source: withdrawalSource(source) }), + destination: withdrawalDestination(destination), + amount: withdrawalAmount(amount), + ...(toAmount === undefined ? {} : { toAmount: withdrawalToAmount(toAmount) }), + ...(riskSignals === undefined ? {} : { riskSignals: withdrawalRiskSignals(riskSignals) }), + ...(burnAll === undefined ? {} : { burnAll: withdrawalBurnAll(burnAll) }), + } +} + +function withdrawalSource(source: CreateWithdrawalSource): object { + requireBodyObject(source, 'withdrawal source') + requireKnownProperties(source, WITHDRAWAL_SOURCE_PROPERTIES, 'withdrawal source') + const { type, id } = source + if (type !== 'account') { + throw contractViolation('withdrawal source type must be account') + } + if (typeof id !== 'string' || id.length === 0) { + throw contractViolation('withdrawal source id must be a non-empty string') + } + return { type, id } +} + +function withdrawalDestination(destination: CreateWithdrawalDestination): object { + requireBodyObject(destination, 'withdrawal destination') + requireKnownProperties(destination, WITHDRAWAL_DESTINATION_PROPERTIES, 'withdrawal destination') + const { type, id, name } = destination + if (type !== 'wire' && type !== 'ach') { + throw contractViolation('withdrawal destination type must be wire or ach') + } + // Unlike a transfer's account-leg id, the registry types this `format: uuid`: + // a withdrawal destination names a registered fiat account, not a public + // account id. + if (typeof id !== 'string' || !isUuid(id)) { + throw contractViolation('withdrawal destination id must be a UUID') + } + if (name !== undefined && (typeof name !== 'string' || name.length === 0)) { + throw contractViolation('withdrawal destination name must be a non-empty string') + } + return { + type, + id, + ...(name === undefined ? {} : { name }), + } +} + +function withdrawalAmount(amount: CreateWithdrawalAmount): object { + requireBodyObject(amount, 'withdrawal amount') + requireKnownProperties(amount, WITHDRAWAL_AMOUNT_PROPERTIES, 'withdrawal amount') + const { amount: amountValue, currency } = amount + if (typeof amountValue !== 'string' || !JSON_NUMBER.test(amountValue)) { + throw contractViolation('withdrawal amount must be a decimal string, e.g. "10.25"') + } + if (typeof currency !== 'string' || currency.length === 0) { + throw contractViolation('withdrawal amount currency must be a non-empty string') + } + return { amount: amountValue, currency } +} + +function withdrawalToAmount(toAmount: CreateWithdrawalToAmount): object { + requireBodyObject(toAmount, 'withdrawal toAmount') + requireKnownProperties(toAmount, WITHDRAWAL_TO_AMOUNT_PROPERTIES, 'withdrawal toAmount') + const { amount, currency } = toAmount + if (amount !== undefined && (typeof amount !== 'string' || !JSON_NUMBER.test(amount))) { + throw contractViolation('withdrawal toAmount amount must be a decimal string, e.g. "10.25"') + } + if (typeof currency !== 'string' || !WITHDRAWAL_TO_AMOUNT_CURRENCIES.includes(currency)) { + throw contractViolation('withdrawal toAmount currency must be USD or EUR') + } + return { + ...(amount === undefined ? {} : { amount }), + currency, + } +} + +function withdrawalRiskSignals(riskSignals: CreateWithdrawalRiskSignals): object { + requireBodyObject(riskSignals, 'withdrawal risk signals') + requireKnownProperties(riskSignals, WITHDRAWAL_RISK_SIGNAL_PROPERTIES, 'withdrawal risk signals') + const { ipAddress, sessionId, deviceId } = riskSignals + requireOptionalRiskSignal(ipAddress, 'ipAddress') + requireOptionalRiskSignal(sessionId, 'sessionId') + requireOptionalRiskSignal(deviceId, 'deviceId') + // The registry requires none of these, so an object with none of them is a + // valid `riskSignals` and is sent as the empty object the caller asked for. + return { + ...(ipAddress === undefined ? {} : { ipAddress }), + ...(sessionId === undefined ? {} : { sessionId }), + ...(deviceId === undefined ? {} : { deviceId }), + } +} + +function requireOptionalRiskSignal(value: string | undefined, name: string): void { + if (value !== undefined && (typeof value !== 'string' || value.length === 0)) { + throw contractViolation(`withdrawal risk signal ${name} must be a non-empty string`) + } +} + +function withdrawalBurnAll(value: boolean): boolean { + if (typeof value !== 'boolean') { + throw contractViolation('withdrawal burnAll must be a boolean') + } + return value +} + +function withdrawalListQuery(query: WithdrawalListQuery | undefined): string | null { + if (query === undefined) return null + if (typeof query !== 'object' || query === null || Array.isArray(query)) { + throw contractViolation('withdrawal list query must be an object') + } + if (query.pageAfter !== undefined && query.pageBefore !== undefined) { + throw contractViolation('pageAfter and pageBefore cannot be used together') + } + if (query.status !== undefined && (!Array.isArray(query.status) || query.status.length === 0)) { + throw contractViolation('status must be a non-empty array') + } + + const parts: string[] = [] + appendEnum(parts, 'custodyType', query.custodyType, ['omnibus', 'segregated', 'self']) + appendString(parts, 'accountId', query.accountId) + appendEnums(parts, 'status', query.status, WITHDRAWAL_LIST_STATUSES) + appendString(parts, 'from', query.from) + appendString(parts, 'to', query.to) + // Unlike account cursors, the service models withdrawal cursors as UUID + // withdrawal ids — the same rule `get`'s `withdrawalId` guard applies. + appendUuid(parts, 'pageAfter', query.pageAfter) + appendUuid(parts, 'pageBefore', query.pageBefore) + if (query.pageSize !== undefined) { + if (!Number.isInteger(query.pageSize) || query.pageSize < 1) { + throw contractViolation('pageSize must be a positive integer') + } + append(parts, 'pageSize', String(query.pageSize)) + } + return parts.length === 0 ? null : parts.join('&') +} diff --git a/src/api/loginFailure.ts b/src/api/loginFailure.ts new file mode 100644 index 0000000..e817ad1 --- /dev/null +++ b/src/api/loginFailure.ts @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + contractViolation, + idempotencyConflict, + loginRequestExpired, + type DaaError, +} from '../errors' +import type { DaaHttpResponse } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { isDaaStatus } from '../wire/daaStatusCodes' +import { readDaaStatusCode } from '../wire/errorEnvelope' + +/** + * The failure the three login calls (Prepare, Social Session, and Device + * Registration Complete) classify themselves, or `null` when the response is + * left to `decodeResourceResponse`, which decodes the success status and turns + * every other status into `api`. + * + * Classified on the numeric code only (a non-numeric string `code`, even a + * name such as `IDEMPOTENCY_KEY_REUSED`, is left to `api`): + * + * - `410` is `login_request_expired`. + * - `IDEMPOTENCY_KEY_REUSED` (`420034`) on a `409` is `idempotency_conflict`, + * with the key the SDK minted for this request. That key is in the bytes the + * SDK serialized and sent, so it is never read from the response. + * - `LOGIN_REQUEST_CONSUMED` (`420039`) is `contract_violation`. An identical + * successful step converges and never returns it, so it means that a + * different request used the login request. + * - DAA also returns `409` for `AUTH_KEY_BINDING_CONFLICT` (`420038`), which + * classifies as `api`, not retryable. A `409` without a code that this + * SDK classifies, or without a readable body, is `api` too. So no status + * alone produces `idempotency_conflict`. + * + * A `2xx` response is never classified here, even when its body has a `code`. + */ +export function loginStepFailure( + response: DaaHttpResponse, + idempotencyKey: string, +): DaaError | null { + const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id') + if (response.status === 410) { + return loginRequestExpired(correlationId) + } + if (response.status >= 200 && response.status < 300) { + return null + } + const daaStatusCode = readDaaStatusCode(response.bodyBytes) + if (response.status === 409 && isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) { + return idempotencyConflict(idempotencyKey, correlationId) + } + if (isDaaStatus(daaStatusCode, 'LOGIN_REQUEST_CONSUMED')) { + return contractViolation( + 'the login request was already used by a different request', + correlationId, + ) + } + return null +} diff --git a/src/api/pagination.ts b/src/api/pagination.ts new file mode 100644 index 0000000..0dbd6d7 --- /dev/null +++ b/src/api/pagination.ts @@ -0,0 +1,63 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isDaaError, malformedResponse } from '../errors' +import { Page } from '../models/Page' +import type { DaaTransport } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { trustedPaginationTargets } from '../wire/paginationLinks' +import type { TrustedPaginationTargets } from '../wire/paginationLinks' +import { decodeResourceResponse } from './resourceRequest' + +type PageRequestOptions = Readonly<{ + transport: DaaTransport + publicApiOrigin: string + path: string + query: string | null + decode: (value: unknown) => readonly T[] +}> + +/** Load one exact collection request and bind its links to the same collection. */ +export async function readPage(options: PageRequestOptions): Promise> { + const response = await options.transport.send({ + method: 'GET', + path: options.path, + query: options.query, + headers: {}, + bodyBytes: null, + }) + const items = decodeResourceResponse({ response, expectedStatus: 200, decode: options.decode }) + let targets: TrustedPaginationTargets + try { + targets = trustedPaginationTargets(response, options.publicApiOrigin, options.path) + } catch (err) { + if (isDaaError(err) && err.detail.kind === 'contract_violation') { + throw malformedResponse(headerValueIgnoringCase(response.headers, 'X-Request-Id')) + } + throw err + } + const load = (query: string | null): Promise> => readPage({ ...options, query }) + const nextQuery = targets.next?.query + const previousQuery = targets.previous?.query + + return new Page( + items, + targets.next === null ? null : () => load(nextQuery ?? null), + targets.previous === null ? null : () => load(previousQuery ?? null), + ) +} diff --git a/src/api/queryParameters.ts b/src/api/queryParameters.ts new file mode 100644 index 0000000..ca30a36 --- /dev/null +++ b/src/api/queryParameters.ts @@ -0,0 +1,82 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import { isUuid } from '../validation/uuid' + +export function append(parts: string[], name: string, value: string): void { + try { + parts.push(`${name}=${encodeURIComponent(value)}`) + } catch { + throw contractViolation(`${name} contains an invalid Unicode value`) + } +} + +export function appendString(parts: string[], name: string, value: string | undefined): void { + if (value === undefined) return + if (typeof value !== 'string' || value.length === 0) { + throw contractViolation(`${name} must be a non-empty string`) + } + append(parts, name, value) +} + +export function appendStrings( + parts: string[], + name: string, + values: readonly string[] | undefined, +): void { + if (values === undefined) return + if (!Array.isArray(values)) { + throw contractViolation(`${name} must be an array`) + } + for (const value of values) appendString(parts, name, value) +} + +export function appendUuid(parts: string[], name: string, value: string | undefined): void { + if (value === undefined) return + if (typeof value !== 'string' || !isUuid(value)) { + throw contractViolation(`${name} must be a UUID`) + } + append(parts, name, value) +} + +export function appendEnum( + parts: string[], + name: string, + value: T | undefined, + allowed: readonly T[], +): void { + if (value === undefined) return + if (typeof value !== 'string' || !allowed.includes(value)) { + throw contractViolation(`${name} is not supported`) + } + append(parts, name, value) +} + +export function appendEnums( + parts: string[], + name: string, + values: readonly T[] | undefined, + allowed: readonly T[], +): void { + if (values === undefined) return + if (!Array.isArray(values)) { + throw contractViolation(`${name} must be an array`) + } + for (const value of values) appendEnum(parts, name, value, allowed) +} diff --git a/src/api/resourceRequest.ts b/src/api/resourceRequest.ts new file mode 100644 index 0000000..5d4729d --- /dev/null +++ b/src/api/resourceRequest.ts @@ -0,0 +1,135 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { apiFailure, malformedResponse, type DaaError } from '../errors' +import { headerValueIgnoringCase } from '../transport/headers' +import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { decodeDataEnvelope } from '../wire/dataEnvelope' +import { readDaaStatusCode } from '../wire/errorEnvelope' +import { MalformedPayloadError } from '../wire/payload' + +type ReadResourceOptions = Readonly<{ + transport: DaaTransport + path: string + /** + * Exact percent-encoded query without the leading `?`, or `null`/omitted for + * none. Unlike a signed write (signed v1 endpoints do not accept query + * parameters), an unsigned read may carry one — see the + * `DaaTransport.query` note — so this is opt-in per call. + */ + query?: string | null + decode: (value: unknown) => T +}> + +type PostResourceOptions = Readonly<{ + transport: DaaTransport + path: string + query: string | null + headers: Readonly> + /** Final serialized bytes. Signed writes must sign and pass this same slice. */ + bodyBytes: Uint8Array + expectedStatus: number + decode: (value: unknown) => T + /** + * Endpoint-specific classification of a response, checked before the + * expected status. + * A non-`null` result is thrown; `null` leaves the response to the common + * contract. + */ + failure?: (response: DaaHttpResponse) => DaaError | null +}> + +type DecodeResourceResponseOptions = Readonly<{ + response: DaaHttpResponse + expectedStatus: number + decode: (value: unknown) => T +}> + +/** Decode the common exact-status public resource response contract. */ +export function decodeResourceResponse({ + response, + expectedStatus, + decode, +}: DecodeResourceResponseOptions): T { + const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id') + + if (response.status !== expectedStatus) { + throw apiFailure({ + httpStatus: response.status, + daaStatusCode: readDaaStatusCode(response.bodyBytes), + correlationId, + }) + } + if (response.bodyBytes === null) { + throw malformedResponse(correlationId) + } + + const data = decodeDataEnvelope(response.bodyBytes, correlationId) + try { + return decode(data) + } catch (err) { + if (err instanceof MalformedPayloadError) { + throw malformedResponse(correlationId) + } + throw err + } +} + +/** Execute the common public GET contract, with an optional exact query string. */ +export async function readResource({ + transport, + path, + query, + decode, +}: ReadResourceOptions): Promise { + const response = await transport.send({ + method: 'GET', + path, + query: query ?? null, + headers: {}, + bodyBytes: null, + }) + // These by-id reads document exactly 200. Other statuses, including another + // 2xx, are observable API failures rather than silently accepted variants. + return decodeResourceResponse({ response, expectedStatus: 200, decode }) +} + +/** Execute a public POST without transforming its endpoint-specific request. */ +export async function postResource({ + transport, + path, + query, + headers, + bodyBytes, + expectedStatus, + decode, + failure, +}: PostResourceOptions): Promise { + const response = await transport.send({ + method: 'POST', + path, + query, + headers, + bodyBytes, + }) + const mapped = failure?.(response) ?? null + if (mapped !== null) { + throw mapped + } + return decodeResourceResponse({ response, expectedStatus, decode }) +} diff --git a/src/api/signedResource.ts b/src/api/signedResource.ts new file mode 100644 index 0000000..4693b1e --- /dev/null +++ b/src/api/signedResource.ts @@ -0,0 +1,267 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Signed public POST/GET: either serialize-once body bytes, or no body at all, +// plus a fresh `X-Device-Authorization` compact JWS. +// +// Signed v1 operations carry `query = null`. Failures are classified on the +// numeric DAA status code only, through `wire/daaStatusCodes.ts`. +// An invalid, missing, replayed, or mismatched authorization becomes +// `contract_violation`. A `409` whose body carries `IDEMPOTENCY_KEY_REUSED` +// (`420034`) becomes `idempotency_conflict`, with the key recovered from the +// same request bytes that were signed and sent, not the (unsigned) response +// body; the caller reconciles the original operation rather than replacing the +// key. +// +// DAA has no code for an expired device authorization, a missing one, or a +// revoked credential: it reports them as `DEVICE_AUTHORIZATION_INVALID` or, +// on context refresh, `DEVICE_AUTHORIZATION_REQUEST_MISMATCH`, and the SDK +// classifies the code it receives. So a signed call is sent once, with no +// fresh-JWS retry, and no DAA response produces `device_revoked`. A +// non-numeric string `code` is `api`, even when it is the name of one of these +// conditions or of a row this mapping classifies. +// +// `AccountsClient.create` (`create_account`), +// `TransfersClient.create` (`transfer`), and `WithdrawalsClient.create` +// (`withdrawal`) call `postSignedResource`. `DaaUserClient.refreshContext` +// (`get_device_context`) calls `getSignedResource` — the device-authorization +// contract treats "signed context refresh" alongside protected writes, and +// `securekey/SecureKey.ts` lists it alongside them as one of the defined DAA +// operations signing is reachable for. + +import { + authorizeExactRequest, + DEVICE_AUTHORIZATION_HEADER, + deviceAuthorizationProfile, + idempotencyKeyFromExactBody, + type DeviceAuthorizationOperation, +} from '../auth/deviceAuthorization' +import { apiFailure, contractViolation, idempotencyConflict, type DaaError } from '../errors' +import type { OwnerAuthKeyResolver } from '../securekey/ownerAuthKeyResolver' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import type { DaaHttpResponse, DaaTransport } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { isDaaStatus } from '../wire/daaStatusCodes' +import { readDaaStatusCode } from '../wire/errorEnvelope' +import { decodeResourceResponse } from './resourceRequest' + +/** + * What a resource client needs to authorize a signed write: the same pair + * `postSignedResource` takes, except the key is resolved when a write is + * actually made rather than held from the moment `forUser` returns. + * + * The two halves come from the same `ACTIVE` Device Registration Complete. + * `authKeyId` is the `DeviceContext` value the service assigned; the key itself + * is enclave-held and is not a field on that decoded result, so it is + * re-resolved by the `{appId, environment, clientEntityId}` alias login + * already used. + * + * Passed as one required value, because the failure this prevents is + * `DaaClient.forUser` validating a user context and then building the + * operations surface without it — leaving every write with nothing to sign + * with. A required constructor parameter makes that omission a compile error. + * + * Not on the public entry. A consumer holding one could reach + * `OwnerAuthKey.signExactBytes`, which is the generic signing surface this SDK + * deliberately does not expose. + */ +export type DaaUserSigning = Readonly<{ + /** Resolves the installation AuthKey. Signing fails closed until it is registered. */ + resolveAuthKey: OwnerAuthKeyResolver + /** `DeviceContext.authKeyId`, which becomes the authorization JWS `kid`. */ + authKeyId: string +}> + +export type PostSignedResourceOptions = Readonly<{ + transport: DaaTransport + operation: DeviceAuthorizationOperation + authKey: OwnerAuthKey + authKeyId: string + /** Final serialized bytes. Hashed and sent as this same slice. */ + bodyBytes: Uint8Array + expectedStatus: number + decode: (value: unknown) => T +}> + +/** Execute a public POST with a fresh registered-device authorization header. */ +export async function postSignedResource({ + transport, + operation, + authKey, + authKeyId, + bodyBytes, + expectedStatus, + decode, +}: PostSignedResourceOptions): Promise { + const profile = deviceAuthorizationProfile(operation) + if (profile.method !== 'POST') { + throw contractViolation('postSignedResource only sends POST registry operations') + } + + const response = await sendSignedPost({ + transport, + operation, + path: profile.canonicalPath, + authKey, + authKeyId, + bodyBytes, + }) + + if (response.status !== expectedStatus) { + throw mapSignedRequestFailure(response, bodyBytes) + } + return decodeResourceResponse({ response, expectedStatus, decode }) +} + +export type GetSignedResourceOptions = Readonly<{ + transport: DaaTransport + operation: DeviceAuthorizationOperation + authKey: OwnerAuthKey + authKeyId: string + expectedStatus: number + decode: (value: unknown) => T +}> + +/** No body to serialize for a bodyless signed read; the signature hashes the empty byte array. */ +const EMPTY_BODY = new Uint8Array(0) + +/** + * Execute a public GET with a fresh registered-device authorization header. + * + * The only registry operation this reaches is `get_device_context` + * (`DaaUserClient.refreshContext`). There is no request body to serialize or + * sign over: `authorizeExactRequest` hashes the empty byte array per the + * bodyless-request rule, and nothing is sent as a request entity — the same + * bodyless shape `resourceRequest.ts`'s unsigned `readResource` sends. + */ +export async function getSignedResource({ + transport, + operation, + authKey, + authKeyId, + expectedStatus, + decode, +}: GetSignedResourceOptions): Promise { + const profile = deviceAuthorizationProfile(operation) + if (profile.method !== 'GET') { + throw contractViolation('getSignedResource only sends GET registry operations') + } + + const response = await sendSignedGet({ + transport, + operation, + path: profile.canonicalPath, + authKey, + authKeyId, + }) + + if (response.status !== expectedStatus) { + throw mapSignedRequestFailure(response, EMPTY_BODY) + } + return decodeResourceResponse({ response, expectedStatus, decode }) +} + +async function sendSignedGet(args: { + transport: DaaTransport + operation: DeviceAuthorizationOperation + path: string + authKey: OwnerAuthKey + authKeyId: string +}): Promise { + const compactJws = await authorizeExactRequest({ + authKey: args.authKey, + authKeyId: args.authKeyId, + operation: args.operation, + bodyBytes: EMPTY_BODY, + }) + return args.transport.send({ + method: 'GET', + path: args.path, + query: null, + headers: { + [DEVICE_AUTHORIZATION_HEADER]: compactJws, + }, + bodyBytes: null, + }) +} + +async function sendSignedPost(args: { + transport: DaaTransport + operation: DeviceAuthorizationOperation + path: string + authKey: OwnerAuthKey + authKeyId: string + bodyBytes: Uint8Array +}): Promise { + const compactJws = await authorizeExactRequest({ + authKey: args.authKey, + authKeyId: args.authKeyId, + operation: args.operation, + bodyBytes: args.bodyBytes, + }) + return args.transport.send({ + method: 'POST', + path: args.path, + query: null, + headers: { + 'Content-Type': 'application/json', + [DEVICE_AUTHORIZATION_HEADER]: compactJws, + }, + bodyBytes: args.bodyBytes, + }) +} + +function mapSignedRequestFailure(response: DaaHttpResponse, bodyBytes: Uint8Array): DaaError { + const correlationId = headerValueIgnoringCase(response.headers, 'X-Request-Id') + const daaStatusCode = readDaaStatusCode(response.bodyBytes) + const fallback = (): DaaError => + apiFailure({ + httpStatus: response.status, + daaStatusCode, + correlationId, + }) + if (isDaaStatus(daaStatusCode, 'IDEMPOTENCY_KEY_REUSED')) { + // Gated on both the status code and the HTTP status, so a body that + // carries this code on some other status falls through to the generic + // `api` failure below rather than being trusted. The contract puts this + // code at `409`, which is where DAA's transfer and withdrawal + // create routes send it. Non-custodial account create never sends it (a + // reused key returns the original account). Recovered from the signed + // request's own bytes, not the response — `idempotencyKeyFromExactBody` + // returns `undefined` for a bodyless request (`getSignedResource`), so this + // never fires for `get_device_context`. + const idempotencyKey = + response.status === 409 ? idempotencyKeyFromExactBody(bodyBytes) : undefined + return idempotencyKey !== undefined + ? idempotencyConflict(idempotencyKey, correlationId) + : fallback() + } + if ( + isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REPLAYED') || + isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_REQUEST_MISMATCH') + ) { + return contractViolation( + 'the device authorization was replayed or did not match the request', + correlationId, + ) + } + if (isDaaStatus(daaStatusCode, 'DEVICE_AUTHORIZATION_INVALID')) { + return contractViolation('the device authorization was rejected', correlationId) + } + return fallback() +} diff --git a/src/auth/RegistrationFlowKey.ts b/src/auth/RegistrationFlowKey.ts new file mode 100644 index 0000000..18ddbaa --- /dev/null +++ b/src/auth/RegistrationFlowKey.ts @@ -0,0 +1,274 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The ephemeral registration-flow key. +// +// ============================================================================ +// THIS IS NOT AN AuthKey. Do not treat it as one, and do not route it through +// `SecureKeyStore`. +// ============================================================================ +// +// The login contract uses two different P-256 keys, and confusing +// them is the failure this file's naming exists to prevent: +// +// | | AuthKey (`OwnerAuthKey`, `securekey/`) | registration-flow key (this file) | +// | --- | --- | --- | +// | Lifetime | durable, survives the app | **one login attempt** | +// | Scope | `{environment, customer application, Owner (clientEntityId), installation}` | nothing; it is anonymous | +// | Storage | Secure Enclave / Android Keystore, via `SecureKeyStore` | process memory only | +// | Exported at | Device Registration Complete (`authKeyPublicKey`) | **Prepare** (`registrationFlowPublicKey`) | +// | Selected | only *after* the Social Session response | before Prepare | +// | Authorizes | DAA operations, via `X-Device-Authorization` | nothing | +// +// The contract says the same thing in one line on +// `PrepareSocialLoginRequest.registrationFlowPublicKey`: "Unpadded Base64URL DER +// SubjectPublicKeyInfo for an ephemeral P-256 flow key; **it is not an AuthKey**". +// +// Its whole job is to prove, at Device Registration Complete, that the caller +// completing the registration is the caller that prepared it — the flow-key JWS +// is one of the two fresh proofs over the exact Complete request bytes. Because +// it is per-attempt and anonymous, it deliberately does NOT go into the +// enclave: a key in the Secure Enclave is a key that outlives the attempt and +// acquires a namespace, which is exactly what this one must not have. +// +// Signing is a **typed Complete-only helper**, not a public `sign(bytes)`. The +// member is `signExactBytes` of the JWS signing input for +// `X-Registration-Flow-Authorization`. It is not exported from `index.ts`. +// Both the native Expo bridge (`DaaRegistrationFlowKey.signRegistrationAuthorization` +// on iOS and Android) and the WebCrypto test stand-in sign for real, so Device +// Registration Complete can finish on a physical device. + +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { contractViolation } from '../errors' +import { + nativeGenerateRegistrationFlowKey, + nativeRegistrationFlowPublicKeySpkiBase64Url, + nativeReleaseRegistrationFlowKey, + nativeSignRegistrationAuthorization, + requireDaaRegistrationNative, + type DaaRegistrationNativeModule, +} from './daaRegistrationNative' + +/** Byte length of a P-256 SubjectPublicKeyInfo. */ +const P256_SPKI_BYTE_LENGTH = 91 + +/** + * One attempt's registration-flow key. Not an AuthKey; see the file header. + * + * The interface carries the public-key export for Prepare, the Complete-only + * signing helper, and an explicit release: the native implementations hold the + * private key in a process-lifetime cache, so something has to say when it is + * no longer needed. + */ +export interface RegistrationFlowKey { + /** + * Unpadded Base64URL DER SubjectPublicKeyInfo of the public key, the exact + * form `PrepareSocialLoginRequest.registrationFlowPublicKey` wants. + */ + publicKeySpkiBase64Url(): Promise + + /** + * ES256 signature (JOSE `R || S`, 64 bytes) over the exact Device Registration + * Complete flow-JWS signing input. Not a public generic sign API. + */ + signExactBytes(message: Uint8Array): Promise + + /** + * Discard the key, so a native implementation stops holding its private half. + * + * Safe to call more than once and safe to call on a key that was never used. + * The key is dead afterwards: `publicKeySpkiBase64Url()` on a released native + * key fails closed rather than returning a stale value. + * + * Device Registration Complete is the owner of this call: it signs, then + * releases. `PreparedSocialLogin.abandon()` is the other caller when the user + * backs out of provider login. `PendingDeviceRegistration` has no + * `abandon()`: after Session, the key is held until Complete or until the + * process exits. + */ + release(): Promise +} + +/** + * Source of per-attempt registration-flow keys. + * + * A seam so `AuthClient` can switch providers without changing callers. + * Production generation is `DaaRegistrationFlowKey` in `daa-ios-sdk` / + * `daa-android-sdk` — not `DaaSecureKey`, which is the Owner AuthKey. The Expo + * `DaaRegistration` module bridges that type and keeps the private key in + * native memory. WebCrypto is an explicit test stand-in + * (`webCryptoRegistrationFlowKeyProvider`), never a fallback. A host missing + * the Expo module fails closed. The seam is not exported from `index.ts`: a + * consumer cannot substitute the key that proves its own registration handoff. + */ +export interface RegistrationFlowKeyProvider { + generate(): Promise +} + +class WebCryptoRegistrationFlowKey implements RegistrationFlowKey { + readonly #keyPair: CryptoKeyPair + + constructor(keyPair: CryptoKeyPair) { + this.#keyPair = keyPair + Object.freeze(this) + } + + // Nothing to free: the CryptoKey is ordinary garbage once the handle is + // dropped, and WebCrypto exposes no destroy. Present so the two providers + // satisfy one interface. + async release(): Promise {} + + async publicKeySpkiBase64Url(): Promise { + const spki = await subtle().exportKey('spki', this.#keyPair.publicKey) + const bytes = new Uint8Array(spki) + if (bytes.length !== P256_SPKI_BYTE_LENGTH) { + throw contractViolation( + 'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo', + ) + } + return toBase64Url(bytes) + } + + async signExactBytes(message: Uint8Array): Promise { + const signature = await subtle().sign( + { name: 'ECDSA', hash: 'SHA-256' }, + this.#keyPair.privateKey, + toArrayBuffer(message), + ) + return new Uint8Array(signature) + } +} + +class NativeRegistrationFlowKey implements RegistrationFlowKey { + readonly #native: DaaRegistrationNativeModule + readonly #id: string + + constructor(native: DaaRegistrationNativeModule, id: string) { + this.#native = native + this.#id = id + Object.freeze(this) + } + + async publicKeySpkiBase64Url(): Promise { + const spki = nativeRegistrationFlowPublicKeySpkiBase64Url(this.#native, this.#id) + const bytes = decodeSpki(spki) + return toBase64Url(bytes) + } + + async release(): Promise { + nativeReleaseRegistrationFlowKey(this.#native, this.#id) + } + + async signExactBytes(message: Uint8Array): Promise { + // The Expo module holds the private key; only the exact bytes and the + // resulting signature cross the bridge as Base64URL strings. + const signingInputBase64Url = toBase64Url(message) + return nativeSignRegistrationAuthorization(this.#native, this.#id, signingInputBase64Url) + } +} + +/** + * Production React Native provider: native `DaaRegistrationFlowKey` via the + * Expo `DaaRegistration` module. The private key never crosses the bridge. + */ +export function nativeRegistrationFlowKeyProvider( + native: DaaRegistrationNativeModule, +): RegistrationFlowKeyProvider { + return { + async generate(): Promise { + const id = nativeGenerateRegistrationFlowKey(native) + return new NativeRegistrationFlowKey(native, id) + }, + } +} + +/** + * Node/Jest stand-in: a non-extractable WebCrypto P-256 keypair per attempt. + * + * `extractable: false` is set even though the key never leaves the process. It + * costs nothing, and it means a future bug that hands the handle somewhere else + * still cannot export the private key. + * + * **Not the production RN path.** Production `defaultRegistrationFlowKeyProvider` + * never calls this. Absent `crypto.subtle`, `generate()` fails closed with + * `contract_violation` rather than weaker key generation. + */ +export function webCryptoRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider { + return { + async generate(): Promise { + const keyPair = (await subtle().generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, [ + 'sign', + 'verify', + ])) as CryptoKeyPair + return new WebCryptoRegistrationFlowKey(keyPair) + }, + } +} + +/** + * Native `DaaRegistrationFlowKey` via the Expo module. A missing module is a + * `contract_violation` — WebCrypto is never a fallback. The native module is + * resolved on `generate()`, not when this provider is constructed, so building + * a `DaaClient` does not require the Expo module to be linked. + */ +export function defaultRegistrationFlowKeyProvider(): RegistrationFlowKeyProvider { + return { + async generate(): Promise { + return nativeRegistrationFlowKeyProvider(requireDaaRegistrationNative()).generate() + }, + } +} + +/** Drop the key without replacing the failure that triggered cleanup. */ +export async function releaseQuietly(key: RegistrationFlowKey): Promise { + try { + await key.release() + } catch { + // Intentionally empty: a throwing release must not mask the originating error. + } +} + +function decodeSpki(spki: string): Uint8Array { + let bytes: Uint8Array + try { + bytes = fromBase64Url(spki) + } catch { + throw contractViolation( + 'registration-flow key did not export valid Base64URL SubjectPublicKeyInfo', + ) + } + if (bytes.length !== P256_SPKI_BYTE_LENGTH) { + throw contractViolation( + 'registration-flow key did not export a 91-byte P-256 SubjectPublicKeyInfo', + ) + } + return bytes +} + +function subtle(): SubtleCrypto { + const host = (globalThis as { crypto?: Crypto }).crypto + if (host === undefined || host.subtle === undefined) { + throw contractViolation( + 'crypto.subtle is required to generate the ephemeral registration-flow key; ' + + 'install a WebCrypto polyfill in the host app or supply a native ' + + 'DaaRegistrationFlowKey provider', + ) + } + return host.subtle +} diff --git a/src/auth/daaRegistrationNative.ts b/src/auth/daaRegistrationNative.ts new file mode 100644 index 0000000..e3c8ca9 --- /dev/null +++ b/src/auth/daaRegistrationNative.ts @@ -0,0 +1,236 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { contractViolation, isDaaError } from '../errors' + +// JS shape of the Expo `DaaRegistration` native module. Separate from +// `DaaSecureKey`: this module bridges DaaSecureRandom, DaaRegistrationFlowKey, +// and platform verification of the Prepare receipt signature. The flow-key +// private key stays in the native cache keyed by the handle id; only Base64URL +// strings cross the bridge. + +export const DAA_REGISTRATION_MODULE = 'DaaRegistration' + +export interface DaaRegistrationNativeModule { + randomBytes(count: number): string + randomUuidV4(): string + generateRegistrationFlowKey(): string + registrationFlowPublicKeySpkiBase64Url(id: string): string + releaseRegistrationFlowKey(id: string): void + /** + * Typed Complete-only sign — not a generic `sign(bytes)`. `signingInputBase64Url` + * is the exact Device Registration Complete flow-JWS signing input; the native + * module validates those bytes and signs that same slice with the cached flow + * key, returning unpadded Base64URL of the 64-byte JOSE `R || S` signature. + */ + signRegistrationAuthorization(id: string, signingInputBase64Url: string): string + /** + * Native ES256 verification of a Prepare receipt signature, delegated to the + * native SDKs' `DaaPrepareReceiptSignature` (CryptoKit on iOS, + * `java.security` on Android). All three arguments are unpadded + * Base64URL — the uncompressed P-256 point of a pinned key, the exact JWS + * signing input, and the 64-byte JOSE `R || S` signature. Resolves `true` + * only for a valid signature; rejects when the key is not a P-256 point. + */ + verifyPrepareReceiptSignature( + publicKeyX963Base64Url: string, + signingInputBase64Url: string, + signatureBase64Url: string, + ): Promise +} + +export function optionalDaaRegistrationNative(): DaaRegistrationNativeModule | null { + const native = requireOptionalNativeModule(DAA_REGISTRATION_MODULE) + if (native == null) { + return null + } + return native +} + +export function requireDaaRegistrationNative(): DaaRegistrationNativeModule { + const native = optionalDaaRegistrationNative() + if (native === null) { + throw contractViolation( + 'native DaaRegistration module is not available to mint or verify login-attempt material; ' + + 'include the DaaRegistration Expo module in the host app', + ) + } + return native +} + +function nativeCall(op: () => T): T { + try { + return op() + } catch (err) { + if (isDaaError(err)) { + throw err + } + throw contractViolation('native DaaRegistration operation failed') + } +} + +/** Verifier bytes from native `DaaSecureRandom`, decoded at the seam. */ +export function nativeRandomBytes(native: DaaRegistrationNativeModule, count: number): Uint8Array { + if (typeof native.randomBytes !== 'function') { + throw contractViolation('native DaaRegistration.randomBytes is required') + } + const encoded = nativeCall(() => native.randomBytes(count)) + if (typeof encoded !== 'string') { + throw contractViolation('native DaaSecureRandom did not return Base64URL') + } + let bytes: Uint8Array + try { + bytes = fromBase64Url(encoded) + } catch { + throw contractViolation('native DaaSecureRandom did not return valid Base64URL') + } + if (bytes.length !== count) { + throw contractViolation( + `native DaaSecureRandom must return ${count} bytes; got ${bytes.length}`, + ) + } + return bytes +} + +export function nativeRandomUuidV4(native: DaaRegistrationNativeModule): string { + if (typeof native.randomUuidV4 !== 'function') { + throw contractViolation('native DaaRegistration.randomUuidV4 is required') + } + const uuid = nativeCall(() => native.randomUuidV4()) + if (typeof uuid !== 'string') { + throw contractViolation('native randomUuidV4 did not return a string') + } + return uuid +} + +export function nativeGenerateRegistrationFlowKey(native: DaaRegistrationNativeModule): string { + if (typeof native.generateRegistrationFlowKey !== 'function') { + throw contractViolation('native DaaRegistration.generateRegistrationFlowKey is required') + } + const id = nativeCall(() => native.generateRegistrationFlowKey()) + if (typeof id !== 'string' || id.length === 0) { + throw contractViolation('native generateRegistrationFlowKey did not return a handle id') + } + return id +} + +export function nativeRegistrationFlowPublicKeySpkiBase64Url( + native: DaaRegistrationNativeModule, + id: string, +): string { + if (typeof native.registrationFlowPublicKeySpkiBase64Url !== 'function') { + throw contractViolation( + 'native DaaRegistration.registrationFlowPublicKeySpkiBase64Url is required', + ) + } + const spki = nativeCall(() => native.registrationFlowPublicKeySpkiBase64Url(id)) + if (typeof spki !== 'string') { + throw contractViolation('native registration-flow public key did not return a string') + } + return spki +} + +/** + * Sign the exact Device Registration Complete flow-JWS signing input with the + * cached native flow key. Returns unpadded Base64URL of the 64-byte JOSE + * `R || S` signature. Not a generic sign: `id` names a cached + * `DaaRegistrationFlowKey`, and native validates the bytes as a registration + * authorization signing input before it ever touches the private key. + */ +export function nativeSignRegistrationAuthorization( + native: DaaRegistrationNativeModule, + id: string, + signingInputBase64Url: string, +): Uint8Array { + if (typeof native.signRegistrationAuthorization !== 'function') { + throw contractViolation('native DaaRegistration.signRegistrationAuthorization is required') + } + const signature = nativeCall(() => + native.signRegistrationAuthorization(id, signingInputBase64Url), + ) + if (typeof signature !== 'string') { + throw contractViolation('native registration-flow signature did not return a string') + } + let bytes: Uint8Array + try { + bytes = fromBase64Url(signature) + } catch { + throw contractViolation('native registration-flow signature is not valid Base64URL') + } + if (bytes.length !== 64) { + throw contractViolation( + `native registration-flow signature must be 64 bytes (JOSE R||S); got ${bytes.length}`, + ) + } + return bytes +} + +/** + * Verify one ES256 signature with platform crypto. + * + * Only a literal `true` from native counts as verified. Anything else — `false`, + * a non-boolean, a rejection, a missing function on an older host build — is + * not a pass: a rejection or a missing function is a `contract_violation`, and + * any other value is `false`. + */ +export async function nativeVerifyPrepareReceiptSignature( + native: DaaRegistrationNativeModule, + args: Readonly<{ publicKeyX963: Uint8Array; signingInput: Uint8Array; signature: Uint8Array }>, +): Promise { + if (typeof native.verifyPrepareReceiptSignature !== 'function') { + throw contractViolation('native DaaRegistration.verifyPrepareReceiptSignature is required') + } + let result: unknown + try { + result = await native.verifyPrepareReceiptSignature( + toBase64Url(args.publicKeyX963), + toBase64Url(args.signingInput), + toBase64Url(args.signature), + ) + } catch (err) { + if (isDaaError(err)) { + throw err + } + throw contractViolation('native Prepare receipt signature verification failed') + } + return result === true +} + +/** + * Drop a cached native flow key. + * + * Cleanup, so it is forgiving: an older host app whose module predates this + * function, or an id the native side no longer holds, is not an error. The + * alternative would make a `finally` block throw over tidying up and mask the + * failure that sent it there. What it must not do is fail silently in a way + * that leaves key material resident — hence the explicit function check rather + * than an optional-call shrug. + */ +export function nativeReleaseRegistrationFlowKey( + native: DaaRegistrationNativeModule, + id: string, +): void { + if (typeof native.releaseRegistrationFlowKey !== 'function') { + return + } + nativeCall(() => { + native.releaseRegistrationFlowKey(id) + }) +} diff --git a/src/auth/deviceAuthorization.ts b/src/auth/deviceAuthorization.ts new file mode 100644 index 0000000..e7c6636 --- /dev/null +++ b/src/auth/deviceAuthorization.ts @@ -0,0 +1,302 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Registered-device authorization: a compact ES256 JWS in +// `X-Device-Authorization`, bound to the exact body bytes that will be sent. +// +// This is the post-activation header (`typ` in DEVICE_AUTHORIZATION_TYP). +// The SDK signs Device Registration Complete with its own two-JWS profile +// (`auth/registrationAuthorization.ts`), with its own `typ` values and header +// set. This module also maps the registry's `register_device_key` operation +// and accepts a not-yet-registered (`created`) AuthKey for that operation only; +// no SDK client signs it through this module. Not a public generic +// `sign(bytes)`. +// The only bytes the AuthKey signs are this JWS signing input. +// +// Operation identity is the digest-pinned Owner-authorization registry: +// `discriminator` + `schema_version` are the lookup key. The verifier resolves +// method and `canonical_path` from that entry; it does not infer the operation +// from the path. Callers name one of the six closed operations — they cannot +// pass a free-form `/v1` path. +// +// The header carries the published `typ` (`aw-device-authorization+jws`). +// +// Production `OwnerAuthKey.signExactBytes` reaches native +// `signDeviceAuthorization` via the Expo bridge. Tests use +// `InMemorySecureKeyStore`. The create-account, transfer, and withdrawal +// clients reach this through `api/signedResource.ts` rather than calling it +// directly. + +import { toBase64Url } from '../crypto/base64url' +import { randomUuidV4 } from '../crypto/random' +import { sha256 } from '../crypto/sha256' +import { contractViolation, mapNativeError } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { isUuid } from '../validation/uuid' + +export const DEVICE_AUTHORIZATION_HEADER = 'X-Device-Authorization' + +const DEVICE_AUTHORIZATION_TYP = 'aw-device-authorization+jws' +const DEVICE_AUTHORIZATION_AUD = 'circle-digital-asset-accounts' +const JOSE_SIGNATURE_LENGTH = 64 +/** Verifier ceiling: `exp - iat` must be at most 300 seconds. */ +const AUTHORIZATION_LIFETIME_SECONDS = 300 +const SCHEMA_VERSION = 1 + +/** + * Closed Owner-authorization registry (v1). Wire `discriminator` values from + * the registry schema. + */ +export type DeviceAuthorizationOperation = + | 'create_account' + | 'transfer' + | 'withdrawal' + | 'complete_social_login' + | 'get_device_context' + | 'register_device_key' + +export type DeviceAuthorizationProfile = Readonly<{ + discriminator: DeviceAuthorizationOperation + schemaVersion: typeof SCHEMA_VERSION + method: 'GET' | 'POST' + canonicalPath: string +}> + +export type DeviceAuthorizationRequest = Readonly<{ + authKey: OwnerAuthKey + /** Proposed `AuthKey` id at Complete, or `DeviceContext.authKeyId` after ACTIVE. */ + authKeyId: string + operation: DeviceAuthorizationOperation + /** Exact bytes that will be hashed and sent. Empty array for a bodyless call. */ + bodyBytes: Uint8Array +}> + +/** + * Test-only clock. Production code always uses the system clock. This + * module is not on the public `.` entry, and `postSignedResource` does not + * take a clock. `authorizeExactRequest` accepts one so tests can pin `iat`/`jti`. + */ +export type DeviceAuthorizationClock = Readonly<{ + nowEpochSeconds: () => number + jti: () => string +}> + +const DEFAULT_CLOCK: DeviceAuthorizationClock = { + nowEpochSeconds: () => Math.floor(Date.now() / 1000), + jti: randomUuidV4, +} + +/** Registry profile for one closed operation. Method and path are not caller-chosen. */ +export function deviceAuthorizationProfile( + operation: DeviceAuthorizationOperation, +): DeviceAuthorizationProfile { + switch (operation) { + case 'create_account': + return { + discriminator: 'create_account', + schemaVersion: SCHEMA_VERSION, + method: 'POST', + canonicalPath: '/v1/accounts', + } + case 'transfer': + return { + discriminator: 'transfer', + schemaVersion: SCHEMA_VERSION, + method: 'POST', + canonicalPath: '/v1/accounts/transfers', + } + case 'withdrawal': + return { + discriminator: 'withdrawal', + schemaVersion: SCHEMA_VERSION, + method: 'POST', + canonicalPath: '/v1/accounts/withdrawals', + } + case 'complete_social_login': + return { + discriminator: 'complete_social_login', + schemaVersion: SCHEMA_VERSION, + method: 'POST', + canonicalPath: '/v1/accounts/auth/sessions', + } + case 'get_device_context': + return { + discriminator: 'get_device_context', + schemaVersion: SCHEMA_VERSION, + method: 'GET', + canonicalPath: '/v1/accounts/auth/context', + } + case 'register_device_key': + return { + discriminator: 'register_device_key', + schemaVersion: SCHEMA_VERSION, + method: 'POST', + canonicalPath: '/v1/accounts/auth/deviceKeyRegistration', + } + default: { + const exhaustive: never = operation + void exhaustive + throw contractViolation('device authorization operation is not in the closed registry') + } + } +} + +/** + * Build a compact ES256 JWS over the exact request bytes. + * + * Serializes the protected header and payload with `JSON.stringify` (DAA + * verifies the transmitted signing input and parsed claim semantics, not a + * reconstructed JSON encoding). Signs the compact signing input + * `base64url(header) + "." + base64url(payload)` and appends a 64-byte JOSE + * `R || S` signature. + */ +export async function authorizeExactRequest( + request: DeviceAuthorizationRequest, + clock: DeviceAuthorizationClock = DEFAULT_CLOCK, +): Promise { + // `register_device_key` accepts a `created` AuthKey. Other operations + // require a registered key. `typ` lives in DEVICE_AUTHORIZATION_TYP, not at + // each call site. + if (request.operation !== 'register_device_key' && request.authKey.resolution() !== 'existing') { + throw contractViolation('X-Device-Authorization requires a registered AuthKey') + } + if (!isUuid(request.authKeyId)) { + throw contractViolation('authKeyId must be a UUID') + } + + const profile = deviceAuthorizationProfile(request.operation) + const idempotencyKey = idempotencyKeyFromExactBody(request.bodyBytes) + const iat = requireEpochSeconds(clock.nowEpochSeconds()) + const jti = clock.jti() + if (!isUuid(jti)) { + throw contractViolation('jti must be a UUID') + } + + const protectedHeader = { + alg: 'ES256', + kid: request.authKeyId, + typ: DEVICE_AUTHORIZATION_TYP, + } + const payload = payloadClaims({ + bodyBytes: request.bodyBytes, + profile, + idempotencyKey, + jti, + iat, + }) + + const signingInput = toBase64Url(utf8Json(protectedHeader)) + '.' + toBase64Url(utf8Json(payload)) + const signature = await signSigningInput(request.authKey, signingInput) + return signingInput + '.' + toBase64Url(signature) +} + +function payloadClaims(args: { + bodyBytes: Uint8Array + profile: DeviceAuthorizationProfile + idempotencyKey: string | undefined + jti: string + iat: number +}): object { + const bodySha256 = toBase64Url(sha256(args.bodyBytes)) + const exp = args.iat + AUTHORIZATION_LIFETIME_SECONDS + if (args.idempotencyKey === undefined) { + return { + body_sha256: bodySha256, + canonical_path: args.profile.canonicalPath, + method: args.profile.method, + aud: DEVICE_AUTHORIZATION_AUD, + discriminator: args.profile.discriminator, + schema_version: args.profile.schemaVersion, + jti: args.jti, + iat: args.iat, + exp, + } + } + return { + body_sha256: bodySha256, + idempotency_key: args.idempotencyKey, + canonical_path: args.profile.canonicalPath, + method: args.profile.method, + aud: DEVICE_AUTHORIZATION_AUD, + discriminator: args.profile.discriminator, + schema_version: args.profile.schemaVersion, + jti: args.jti, + iat: args.iat, + exp, + } +} + +async function signSigningInput(authKey: OwnerAuthKey, signingInput: string): Promise { + let signature: Uint8Array + try { + signature = await authKey.signExactBytes(new TextEncoder().encode(signingInput)) + } catch (err) { + throw mapNativeError(err) + } + if (signature.length !== JOSE_SIGNATURE_LENGTH) { + throw contractViolation('device authorization signature must be 64 bytes') + } + return signature +} + +function requireEpochSeconds(value: number): number { + if (!Number.isInteger(value) || value <= 0) { + throw contractViolation('device authorization clock must yield a positive Unix timestamp') + } + return value +} + +/** + * Read `idempotencyKey` from the already-serialized body. Parsing is observation + * only — the hashed and sent bytes are unchanged. + * + * Include `idempotency_key` iff the JSON body contains `idempotencyKey`, + * and omit it for a bodyless request. + * + * Exported so `api/signedResource.ts` can recover the same key when mapping a + * `409` `IDEMPOTENCY_KEY_REUSED` failure, rather than parsing the body a + * second, independent way. + */ +export function idempotencyKeyFromExactBody(bodyBytes: Uint8Array): string | undefined { + if (bodyBytes.length === 0) { + return undefined + } + + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bodyBytes)) + } catch { + throw contractViolation('signed request body is not UTF-8 JSON') + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + throw contractViolation('signed request body must be a JSON object') + } + if (!Object.prototype.hasOwnProperty.call(parsed, 'idempotencyKey')) { + return undefined + } + + const value = (parsed as Record).idempotencyKey + if (typeof value !== 'string' || !isUuid(value)) { + throw contractViolation('idempotencyKey must be a UUID when present on a signed body') + } + return value +} + +function utf8Json(value: object): Uint8Array { + return new TextEncoder().encode(JSON.stringify(value)) +} diff --git a/src/auth/ownerGrant.ts b/src/auth/ownerGrant.ts new file mode 100644 index 0000000..aaed237 --- /dev/null +++ b/src/auth/ownerGrant.ts @@ -0,0 +1,102 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Owner-grant claim check. The public Social Session contract does +// not return an Owner grant — Circle keeps that assertion internal. If a +// response nevertheless carries one, the SDK must not invent a grant shape and +// must not proceed without the flow-key binding Complete's dual headers rely on. +// +// Cryptographic verification of a grant is not done here. This +// only reads the compact-JWT payload and requires +// `registrationFlowKeyThumbprint`. The grant is never logged, stored, or +// forwarded to Device Registration Complete. + +import { fromBase64Url } from '../crypto/base64url' +import { contractViolation } from '../errors' + +/** RFC 7638 P-256 `jkt` is an unpadded Base64URL SHA-256 digest: 43 characters. */ +const JWK_THUMBPRINT = /^[A-Za-z0-9_-]{43}$/ + +function isJsonObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +/** + * Require a compact Owner grant to carry `registrationFlowKeyThumbprint`. + * + * `correlationId` is the `X-Request-Id` of the response that carried the grant, + * so the failure can be traced server-side like any other error built from a + * response. + * + * @throws DaaError `contract_violation` when the grant is missing, unreadable, + * missing the thumbprint, or bound to a different flow key. The grant itself + * is never interpolated into the error. + */ +export function requireOwnerGrantFlowKeyThumbprint( + ownerGrant: string, + expectedThumbprint: string, + correlationId: string | null, +): void { + const claims = compactJwtPayload(ownerGrant, correlationId) + const thumbprint = claims.registrationFlowKeyThumbprint + if (typeof thumbprint !== 'string' || !JWK_THUMBPRINT.test(thumbprint)) { + throw contractViolation('owner grant is missing registrationFlowKeyThumbprint', correlationId) + } + if (thumbprint !== expectedThumbprint) { + throw contractViolation( + 'owner grant registrationFlowKeyThumbprint does not match the registration-flow key', + correlationId, + ) + } +} + +function compactJwtPayload(compact: string, correlationId: string | null): Record { + const parts = compact.split('.') + const header = parts[0] + const payload = parts[1] + const signature = parts[2] + if ( + parts.length !== 3 || + header === undefined || + payload === undefined || + signature === undefined || + header.length === 0 || + payload.length === 0 || + signature.length === 0 + ) { + throw contractViolation('owner grant must be a compact JWT', correlationId) + } + + let bytes: Uint8Array + try { + bytes = fromBase64Url(payload) + } catch { + throw contractViolation('owner grant payload is not valid Base64URL', correlationId) + } + + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) + } catch { + throw contractViolation('owner grant payload is not JSON', correlationId) + } + if (!isJsonObject(parsed)) { + throw contractViolation('owner grant payload is not a JSON object', correlationId) + } + return parsed +} diff --git a/src/auth/prepareReceipt.ts b/src/auth/prepareReceipt.ts new file mode 100644 index 0000000..79f1011 --- /dev/null +++ b/src/auth/prepareReceipt.ts @@ -0,0 +1,522 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The DAA-signed Prepare receipt. +// +// When a trust anchor is pinned for the environment, the SDK verifies the +// returned Prepare receipt before starting provider login and fails closed if +// the receipt is missing or does not verify. With no anchor pinned, the SDK +// ignores the receipt (see below). +// +// **What it defends against.** The SDK reaches DAA through the application's +// own backend, which the trust model treats as untrusted. Without a verified +// receipt that relay can substitute a different login request — another +// attempt's `loginRequestId` and nonce — and the SDK would hand that nonce to +// provider login. The receipt is DAA-signed, so the relay cannot mint one for +// substituted values. What makes the signature an answer is binding its claims +// to values the relay cannot choose: the registration code challenge and the +// registration-flow key thumbprint the SDK generated itself, before Prepare +// was sent. Those two are the load-bearing checks. Tenant scope alone would not +// be: two attempts under one customer app carry identical tenant claims. +// +// **Claims.** The claim set DAA signs under `typ: daa-prepare-receipt+jws`: +// `iss`, `aud`, `iat`, `exp`, `jti`, `environment`, `customerAppId`, +// `parentEntityIdDigest`, `provider`, `loginRequestId`, `nonce`, +// `registrationCodeChallenge`, `registrationFlowKeyThumbprint`. The +// `nonce` claim carries the value the Prepare response calls `oidcNonce`. +// There is no state claim: `oidcState` is not bound by the receipt. +// +// **Tenant scope is not checked on the login path.** Comparing +// `customerAppId` / `parentEntityIdDigest` needs the parent entity the SDK +// expects, and the SDK defines no mapping from `DaaSdkConfiguration.appId` to +// DAA's parent entity. {@link requirePrepareReceiptTenantScope} is the +// comparison; the login path does not call it. +// +// **No trust anchor is pinned in this release.** The anchor (issuer, audience, +// signing keys, clock allowance) ships inside the SDK build, and +// {@link pinnedPrepareReceiptTrustAnchor} returns `null` for every environment. +// {@link checkPrepareReceipt} defines what login does in each case: with no +// anchor, the SDK ignores a receipt rather than failing on it. Ignoring loses +// nothing, because an SDK with no anchor could not verify the receipt anyway. +// It does mean `oidcNonce` and `oidcState` are not authenticated by the SDK: +// integrators bind the provider redirect with their own OAuth `state`. +// +// **Errors.** Every failure to verify a receipt the SDK needs is +// `prepare_receipt_invalid`. Faults in the SDK's own inputs — a +// malformed pinned anchor, an incomplete expectation, a bad test clock, a +// parent entity id that is not a canonical UUID — are `contract_violation`, +// because they describe this build, not the receipt. + +import type { DaaEnvironment } from '../config' +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { ownMember, verifyCompactEs256, type PinnedEs256Key } from '../crypto/es256Jws' +import type { P256PublicJwk } from '../crypto/jwkThumbprint' +import { sha256 } from '../crypto/sha256' +import { contractViolation, DaaError, isDaaError, prepareReceiptInvalid } from '../errors' +import { isUuid } from '../validation/uuid' + +/** Contract bounds on `SocialLoginRequest.prepareReceiptJws`. */ +export const PREPARE_RECEIPT_MIN_LENGTH = 64 +export const PREPARE_RECEIPT_MAX_LENGTH = 8192 + +/** The JWS `typ` DAA signs the receipt with. */ +export const PREPARE_RECEIPT_TYP = 'daa-prepare-receipt+jws' + +/** Widest clock skew an anchor may allow, so a configuration typo cannot disable expiry. */ +export const PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS = 300 + +/** Compact JWS serialization: three Base64URL segments separated by dots. */ +const COMPACT_JWS = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/ + +/** One pinned receipt-signing key, addressed by the `kid` DAA puts in the header. */ +export type PrepareReceiptVerificationKey = Readonly<{ kid: string; jwk: P256PublicJwk }> + +/** + * Everything a trust anchor pins, in one value. + * + * `verificationKeys` is pinned by the build and never derived from a receipt. + * More than one entry allows a rotation overlap; the receipt's `kid` selects + * among them and nothing else. + */ +export type PrepareReceiptTrustAnchor = Readonly<{ + /** Exact expected `iss`. */ + issuer: string + /** Exact expected `aud`, or one member of an `aud` array. */ + audience: string + verificationKeys: readonly PrepareReceiptVerificationKey[] + /** Allowance on `exp` / `iat` / `nbf`, in seconds. */ + maxClockSkewSeconds: number +}> + +/** + * The build-time pinned anchor for an environment. **`null` for every + * environment in this release.** + * + * A function rather than a `const`, so that its declared return type does not + * narrow the rest of this module to unreachable code. + */ +export function pinnedPrepareReceiptTrustAnchor( + environment: DaaEnvironment, +): PrepareReceiptTrustAnchor | null { + void environment + return null +} + +/** + * The values this attempt's receipt must name. The first two come from the + * Prepare response; the rest are the SDK's own. + */ +export type PrepareReceiptExpectation = Readonly<{ + loginRequestId: string + /** The Prepare response's `oidcNonce`; the receipt's `nonce` claim. */ + nonce: string + provider: string + environment: DaaEnvironment + registrationCodeChallenge: string + registrationFlowKeyThumbprint: string +}> + +/** + * Test-only clock, following `auth/deviceAuthorization.ts`: production code + * always uses the system clock, and no production caller passes one. + */ +export type PrepareReceiptClock = Readonly<{ nowEpochSeconds: () => number }> + +const SYSTEM_CLOCK: PrepareReceiptClock = { + nowEpochSeconds: () => Math.floor(Date.now() / 1000), +} + +/** What a verified receipt attested. Only ever returned after every check passed. */ +export type VerifiedPrepareReceipt = Readonly<{ + /** The receipt exactly as received. */ + compactJws: string + loginRequestId: string + nonce: string + expiresAtEpochSeconds: number + /** Signed but not compared on the login path; see {@link requirePrepareReceiptTenantScope}. */ + tenantScope: Readonly<{ customerAppId: unknown; parentEntityIdDigest: unknown }> +}> + +/** + * Whether a value is shaped like the compact JWS the contract describes and sits + * within its declared length bounds. Structural only: shape is not trust. + */ +export function isPrepareReceiptShape(value: string): boolean { + return ( + value.length >= PREPARE_RECEIPT_MIN_LENGTH && + value.length <= PREPARE_RECEIPT_MAX_LENGTH && + COMPACT_JWS.test(value) + ) +} + +/** + * What login does with the receipt, given the anchor for this environment. + * + * | Anchor | Receipt | Result | + * | ------ | ------- | ----------------------------------------------------------- | + * | unset | absent | `null`: nothing to verify, login proceeds | + * | unset | present | `null`: the receipt is ignored, login proceeds as if absent | + * | set | absent | `prepare_receipt_invalid`: the receipt is required | + * | set | present | {@link verifyPrepareReceipt}; any failure throws | + * + * `prepareReceiptJws` is the raw response member: `undefined` or `null` is + * absent, and anything else is present, whatever its type. In the first two + * rows it is not read at all, and `expected` is a thunk so they compute + * nothing: with no anchor, the login path does no receipt work. + * + * In the second row, an SDK without the anchor ignores the receipt: it could + * not verify it, so ignoring gives up no protection. An ignored receipt is + * never passed on as if it were checked: this returns `null` for it exactly as + * for no receipt, so the login path hands the application no receipt at all. + */ +export async function checkPrepareReceipt( + prepareReceiptJws: unknown, + anchor: PrepareReceiptTrustAnchor | null, + expected: () => PrepareReceiptExpectation, + clock: PrepareReceiptClock = SYSTEM_CLOCK, +): Promise { + if (anchor === null) { + return null + } + if (prepareReceiptJws === undefined || prepareReceiptJws === null) { + throw prepareReceiptInvalid( + 'the Prepare response carries no receipt, and this environment requires one', + ) + } + return verifyPrepareReceipt(prepareReceiptJws, anchor, expected(), clock) +} + +/** + * Verify the receipt against a trust anchor and this attempt's expectation. + * + * Order: the anchor and the expectation first, because a fault in either is a + * configuration error; then the receipt's shape; then its header and signature; + * and only then the claims, because a claim from an unverified token is not + * evidence of anything. + * + * A fault in the anchor, the expectation, or the clock is `contract_violation`; + * every rejection of the receipt itself, including a platform verifier that is + * missing or fails, is `prepare_receipt_invalid`. + * + * The receipt is never interpolated into an error: it is unverified + * server-supplied text, and a consumer is likely to log the message verbatim. + */ +export async function verifyPrepareReceipt( + prepareReceiptJws: unknown, + anchor: PrepareReceiptTrustAnchor, + expected: PrepareReceiptExpectation, + clock: PrepareReceiptClock = SYSTEM_CLOCK, +): Promise { + const keys = pinnedKeys(anchor) + requireExpectation(expected) + const now = clock.nowEpochSeconds() + if (!Number.isInteger(now) || now <= 0) { + throw contractViolation('the Prepare receipt clock must yield a positive Unix timestamp') + } + + if (typeof prepareReceiptJws !== 'string' || !isPrepareReceiptShape(prepareReceiptJws)) { + throw prepareReceiptInvalid( + 'the Prepare receipt is not a compact JWS within the contract length bounds', + ) + } + + const result = await platformVerify(prepareReceiptJws, keys) + if (!result.verified) { + throw prepareReceiptInvalid(`the Prepare receipt did not verify (${result.reason})`) + } + + const claims = result.payload + requireClaimEquals(claims, 'iss', anchor.issuer) + requireAudience(claims, anchor.audience) + requireNonEmptyClaim(claims, 'jti') + requireClaimEquals(claims, 'environment', expected.environment) + requireClaimEquals(claims, 'provider', expected.provider) + requireClaimEquals(claims, 'loginRequestId', expected.loginRequestId) + requireClaimEquals(claims, 'nonce', expected.nonce) + requireClaimEquals(claims, 'registrationCodeChallenge', expected.registrationCodeChallenge) + requireClaimEquals( + claims, + 'registrationFlowKeyThumbprint', + expected.registrationFlowKeyThumbprint, + ) + const expiresAtEpochSeconds = requireTimeClaims(claims, now, anchor.maxClockSkewSeconds) + + return { + compactJws: prepareReceiptJws, + loginRequestId: expected.loginRequestId, + nonce: expected.nonce, + expiresAtEpochSeconds, + tenantScope: { + customerAppId: ownMember(claims, 'customerAppId'), + parentEntityIdDigest: ownMember(claims, 'parentEntityIdDigest'), + }, + } +} + +/** + * The signature check, with a platform verifier that is missing or fails + * reported as the receipt failing to verify. + * + * `pinnedKeys` has already validated everything {@link verifyCompactEs256} + * would reject as a configuration error, so the only `DaaError` left to come + * out of it is the platform's: no `DaaRegistration` module, one without the + * verify function, or a native rejection. A native rejection also covers a + * pinned point the platform does not accept as on the curve — the one anchor + * fault only the platform can see, and indistinguishable here from the rest. + * The SDK's own message and the original error (as `cause`) are kept. + */ +async function platformVerify( + jws: string, + keys: readonly PinnedEs256Key[], +): Promise>> { + try { + return await verifyCompactEs256(jws, { keys, expectedTyp: PREPARE_RECEIPT_TYP }) + } catch (err) { + if (isDaaError(err) && err.detail.kind === 'contract_violation') { + throw new DaaError({ kind: 'prepare_receipt_invalid' }, err.message, err) + } + throw err + } +} + +/** + * Domain separator for `parentEntityIdDigest`, byte-for-byte the one DAA + * signs with. The trailing NUL is part of it. + */ +export const PARENT_ENTITY_ID_DIGEST_DOMAIN = 'daa-prepare-receipt-parent-entity-digest-v1\0' + +/** + * `base64url_nopad(SHA-256(utf8(domain) || utf8(parentEntityId)))`, where the + * id is the canonical lower-case hyphenated UUID — DAA's pinned formula. + */ +export function parentEntityIdDigest(parentEntityId: string): string { + if ( + typeof parentEntityId !== 'string' || + !isUuid(parentEntityId) || + parentEntityId !== parentEntityId.toLowerCase() + ) { + throw contractViolation('parentEntityId must be a canonical lower-case UUID') + } + const encoder = new TextEncoder() + const domain = encoder.encode(PARENT_ENTITY_ID_DIGEST_DOMAIN) + const id = encoder.encode(parentEntityId) + const input = new Uint8Array(domain.length + id.length) + input.set(domain) + input.set(id, domain.length) + return toBase64Url(sha256(input)) +} + +/** + * Tenant-scope comparison for a verified receipt. **Not called on the login + * path:** the SDK has no defined way to derive the expected parent entity from + * its configuration. A caller that has the expected values calls this after + * {@link verifyPrepareReceipt}. + */ +export function requirePrepareReceiptTenantScope( + receipt: VerifiedPrepareReceipt, + expected: Readonly<{ customerAppId: string; parentEntityId: string }>, +): void { + const { customerAppId, parentEntityIdDigest: digest } = receipt.tenantScope + if (typeof customerAppId !== 'string' || customerAppId !== expected.customerAppId) { + throw prepareReceiptInvalid('the Prepare receipt does not bind the expected customerAppId') + } + if (typeof digest !== 'string' || digest !== parentEntityIdDigest(expected.parentEntityId)) { + throw prepareReceiptInvalid( + 'the Prepare receipt does not bind the expected parentEntityIdDigest', + ) + } +} + +/** + * Validate the anchor and convert its keys to the points the platform verifies + * against. A malformed anchor is a configuration error, not a rejected receipt. + * Whether each point is on the curve is the platform's check. + */ +function pinnedKeys(anchor: PrepareReceiptTrustAnchor): readonly PinnedEs256Key[] { + if (typeof anchor !== 'object' || anchor === null) { + throw contractViolation('the Prepare receipt trust anchor must be an object') + } + if (typeof anchor.issuer !== 'string' || anchor.issuer.length === 0) { + throw contractViolation('the Prepare receipt trust anchor must name an issuer') + } + if (typeof anchor.audience !== 'string' || anchor.audience.length === 0) { + throw contractViolation('the Prepare receipt trust anchor must name an audience') + } + if ( + !Number.isInteger(anchor.maxClockSkewSeconds) || + anchor.maxClockSkewSeconds < 0 || + anchor.maxClockSkewSeconds > PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS + ) { + throw contractViolation( + 'the Prepare receipt trust anchor clock skew must be between 0 and ' + + `${PREPARE_RECEIPT_MAX_CLOCK_SKEW_SECONDS} seconds`, + ) + } + if (!Array.isArray(anchor.verificationKeys) || anchor.verificationKeys.length === 0) { + throw contractViolation('the Prepare receipt trust anchor must pin at least one P-256 key') + } + const kids = new Set() + for (const key of anchor.verificationKeys) { + if (typeof key !== 'object' || key === null) { + throw contractViolation('every Prepare receipt verification key must be an object') + } + if (typeof key.kid !== 'string' || key.kid.length === 0) { + throw contractViolation('every Prepare receipt verification key must have a non-empty kid') + } + if (kids.has(key.kid)) { + throw contractViolation('Prepare receipt verification keys must have distinct kids') + } + kids.add(key.kid) + } + return anchor.verificationKeys.map((key) => ({ + kid: key.kid, + publicKeyX963: x963FromJwk(key.jwk), + })) +} + +function x963FromJwk(jwk: P256PublicJwk): Uint8Array { + if (typeof jwk !== 'object' || jwk === null || jwk.kty !== 'EC' || jwk.crv !== 'P-256') { + throw contractViolation('a Prepare receipt verification key must be an EC P-256 JWK') + } + let x: Uint8Array + let y: Uint8Array + try { + x = fromBase64Url(jwk.x) + y = fromBase64Url(jwk.y) + } catch { + throw contractViolation('a Prepare receipt verification key has a non-Base64URL coordinate') + } + if (x.length !== 32 || y.length !== 32) { + throw contractViolation( + 'a Prepare receipt verification key must have 32-byte x and y coordinates', + ) + } + const point = new Uint8Array(65) + point[0] = 0x04 + point.set(x, 1) + point.set(y, 33) + return point +} + +function requireExpectation(expected: PrepareReceiptExpectation): void { + if (typeof expected !== 'object' || expected === null) { + throw contractViolation( + 'verifying a Prepare receipt requires the expected values for this attempt', + ) + } + for (const name of [ + 'loginRequestId', + 'nonce', + 'provider', + 'environment', + 'registrationCodeChallenge', + 'registrationFlowKeyThumbprint', + ] as const) { + const value = expected[name] + if (typeof value !== 'string' || value.length === 0) { + throw contractViolation(`verifying a Prepare receipt requires the expected ${name}`) + } + } +} + +/** + * Exact string equality on one claim. Not constant-time, and does not need to + * be: every value compared is one the SDK sent, generated, or relayed to the + * application; none is a secret. The claim name goes in the message — it is + * one of this module's literals — and the value never does. + */ +function requireClaimEquals( + claims: Readonly>, + name: string, + expected: string, +): void { + const actual = ownMember(claims, name) + if (typeof actual !== 'string' || actual !== expected) { + throw prepareReceiptInvalid(`the Prepare receipt does not bind the expected ${name}`) + } +} + +function requireNonEmptyClaim(claims: Readonly>, name: string): void { + const actual = ownMember(claims, name) + if (typeof actual !== 'string' || actual.length === 0) { + throw prepareReceiptInvalid(`the Prepare receipt does not carry a ${name}`) + } +} + +/** RFC 7519 §4.1.3: `aud` is a string or an array of strings that must contain ours. */ +function requireAudience(claims: Readonly>, audience: string): void { + const actual = ownMember(claims, 'aud') + if (typeof actual === 'string' && actual === audience) { + return + } + if (Array.isArray(actual) && actual.some((value) => value === audience)) { + return + } + throw prepareReceiptInvalid('the Prepare receipt does not bind the expected aud') +} + +/** + * `exp` and `iat` are required (DAA always sets both); `nbf` is checked when + * present. All are RFC 7519 NumericDates in seconds — deliberately not the + * epoch-millis tolerance `wire/instant.ts` carries for the Prepare body, since + * DAA's signer emits seconds. A millisecond value fails the upper bound below + * instead of passing as an expiry thousands of years out. + */ +function requireTimeClaims( + claims: Readonly>, + nowEpochSeconds: number, + maxClockSkewSeconds: number, +): number { + const exp = requireNumericDate(claims, 'exp') + const iat = requireNumericDate(claims, 'iat') + if (exp + maxClockSkewSeconds < nowEpochSeconds) { + throw prepareReceiptInvalid('the Prepare receipt has expired') + } + if (iat - maxClockSkewSeconds > nowEpochSeconds) { + throw prepareReceiptInvalid('the Prepare receipt is not valid yet (iat is in the future)') + } + if (iat > exp) { + throw prepareReceiptInvalid('the Prepare receipt expires before it was issued') + } + if (ownMember(claims, 'nbf') !== undefined) { + const nbf = requireNumericDate(claims, 'nbf') + if (nbf - maxClockSkewSeconds > nowEpochSeconds) { + throw prepareReceiptInvalid('the Prepare receipt is not valid yet (nbf is in the future)') + } + } + return exp +} + +/** Past year 9999 is not a clock; it is a unit mistake or a receipt that never expires. */ +const MAX_NUMERIC_DATE = 253402300799 + +function requireNumericDate(claims: Readonly>, name: string): number { + const value = ownMember(claims, name) + if (value === undefined) { + throw prepareReceiptInvalid(`the Prepare receipt does not carry an ${name}`) + } + if ( + typeof value !== 'number' || + !Number.isInteger(value) || + value <= 0 || + value > MAX_NUMERIC_DATE + ) { + throw prepareReceiptInvalid(`the Prepare receipt carries a malformed ${name}`) + } + return value +} diff --git a/src/auth/registrationAuthorization.ts b/src/auth/registrationAuthorization.ts new file mode 100644 index 0000000..3d23c17 --- /dev/null +++ b/src/auth/registrationAuthorization.ts @@ -0,0 +1,306 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Device Registration Complete dual-header proofs. +// +// Complete sends two JWSs, in two headers: +// +// X-Registration-Flow-Authorization typ=daa-registration-flow-authorization+jws +// X-Device-Authorization typ=daa-device-authorization+jws +// +// Both embed the signer's P-256 public JWK (no trusted server `kid`) and both +// carry the request claims — discriminator, schema_version, aud, method, +// canonical_path, body digest, idempotency_key, jti, iat, exp — with the same +// values, except `jti`, which must differ between the two proofs. +// +// The two claim sets are NOT the same. The flow proof alone also carries the +// binding claims: the registration handle digest, profile_id (the session's +// clientEntityId), the submitted AuthKey's thumbprint, and the code-verifier +// digest. The device proof carries only the request claims above. It proves +// that the holder of the AuthKey in its embedded JWK signed this exact +// request; the flow proof's `auth_key_thumbprint` is what binds that AuthKey +// to the registration attempt. DAA decodes the device proof's claims +// strictly and rejects any field outside that set, so adding a binding claim +// to the device proof makes Complete fail. Keep the two builders separate. +// Native's registration validator (`DaaRegistrationAuthorizationSigningInput`) +// must accept this request-claims-only device payload: a native SDK that +// requires the binding claims refuses to sign it, and Complete fails on device +// before any request is sent. +// +// The only bytes each key signs are its own JWS signing input. This module is +// not exported from `index.ts`. +// +// The two proofs sign through two DIFFERENT seams on purpose, even though both +// signing inputs are built by the same `compactJws`. The flow proof signs via +// `RegistrationFlowKey` (see that module — it has its own native path). The +// device proof signs via `OwnerAuthKey.signRegistrationDeviceAuthorization`, +// NOT `signExactBytes`: +// `signExactBytes` reaches native `signDeviceAuthorization`, which is the +// post-activation seam (`auth/deviceAuthorization.ts`) and validates against a +// different `typ`, a `kid`-only header, and a different claim set. Signing the +// registration device proof through that seam would validate cleanly in this +// SDK's own JWS construction but fail on native's real validator. Keep the two +// seams separate; see `securekey/SecureKey.ts`. + +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { p256JwkThumbprint, p256PublicJwkFromSpki } from '../crypto/jwkThumbprint' +import { randomUuidV4 } from '../crypto/random' +import { sha256 } from '../crypto/sha256' +import { contractViolation, mapNativeError } from '../errors' +import type { RegistrationFlowKey } from './RegistrationFlowKey' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import { isUuid } from '../validation/uuid' +import { registrationCodeChallengeS256 } from './registrationCodeVerifier' + +export const REGISTRATION_FLOW_AUTHORIZATION_HEADER = 'X-Registration-Flow-Authorization' +export const REGISTRATION_DEVICE_AUTHORIZATION_HEADER = 'X-Device-Authorization' + +/** Public path of `completeDeviceRegistration` (OpenAPI + signed `canonical_path`). */ +export const DEVICE_REGISTRATION_COMPLETE_PATH = '/v1/accounts/auth/deviceKeyRegistration' + +const FLOW_TYP = 'daa-registration-flow-authorization+jws' +const DEVICE_TYP = 'daa-device-authorization+jws' +const AUDIENCE = 'circle-digital-asset-accounts' +const JOSE_SIGNATURE_LENGTH = 64 +/** Verifier ceiling: `exp - iat` must be at most 300 seconds. */ +const AUTHORIZATION_LIFETIME_SECONDS = 300 +/** The closed discriminator/schema-version pair DAA accepts. */ +const DISCRIMINATOR = 'device_key_registration.v1' +const SCHEMA_VERSION = 1 + +export type RegistrationAuthorizationClock = Readonly<{ + nowEpochSeconds: () => number + jti: () => string +}> + +const DEFAULT_CLOCK: RegistrationAuthorizationClock = { + nowEpochSeconds: () => Math.floor(Date.now() / 1000), + jti: randomUuidV4, +} + +export type RegistrationCompleteProofs = Readonly<{ + flowJws: string + deviceJws: string +}> + +export type RegistrationCompleteAuthorizationRequest = Readonly<{ + bodyBytes: Uint8Array + registrationHandle: string + registrationCodeVerifier: string + /** The bound Owner's durable identifier; signed as `profile_id`. */ + clientEntityId: string + flowKey: RegistrationFlowKey + authKey: OwnerAuthKey +}> + +/** + * Build the two registration JWSs over the exact Complete body bytes. + * + * Serializes header and payload with `JSON.stringify` (DAA verifies the + * transmitted signing input and parsed claim semantics, not a reconstructed + * encoding). Each signature is 64-byte JOSE `R || S`. + */ +export async function authorizeRegistrationComplete( + request: RegistrationCompleteAuthorizationRequest, + clock: RegistrationAuthorizationClock = DEFAULT_CLOCK, +): Promise { + const idempotencyKey = idempotencyKeyFromExactBody(request.bodyBytes) + if (idempotencyKey === undefined) { + throw contractViolation( + 'Device Registration Complete body must contain idempotencyKey so both proofs bind it', + ) + } + if (!isUuid(request.clientEntityId)) { + throw contractViolation('clientEntityId must be a UUID') + } + + const iat = requireEpochSeconds(clock.nowEpochSeconds()) + const flowJti = clock.jti() + const deviceJti = clock.jti() + if (!isUuid(flowJti) || !isUuid(deviceJti)) { + throw contractViolation('jti must be a UUID') + } + + const flowSpki = fromBase64Url(await request.flowKey.publicKeySpkiBase64Url()) + const authSpki = fromBase64Url(await request.authKey.publicKeySpkiBase64Url()) + const authKeyThumbprint = p256JwkThumbprint(authSpki) + const requestClaimInputs = { bodyBytes: request.bodyBytes, idempotencyKey, iat } + + const flowJws = await compactJws({ + protectedHeader: { + alg: 'ES256', + jwk: p256PublicJwkFromSpki(flowSpki), + typ: FLOW_TYP, + }, + payload: registrationFlowClaims({ + ...requestClaimInputs, + registrationHandle: request.registrationHandle, + registrationCodeVerifier: request.registrationCodeVerifier, + clientEntityId: request.clientEntityId, + authKeyThumbprint, + jti: flowJti, + }), + sign: (bytes) => request.flowKey.signExactBytes(bytes), + }) + const deviceJws = await compactJws({ + protectedHeader: { + alg: 'ES256', + jwk: p256PublicJwkFromSpki(authSpki), + typ: DEVICE_TYP, + }, + // Request claims only — no binding claims (see the header comment). + payload: registrationDeviceClaims({ ...requestClaimInputs, jti: deviceJti }), + // Registration, not post-activation: this AuthKey has not been + // acknowledged yet, and the claim/typ shape here is the registration + // profile, not `auth/deviceAuthorization.ts`'s. Routing this through + // `signExactBytes` would sign valid bytes with the wrong native + // validator (`DaaDeviceAuthorizationSigningInput`, which pins the + // post-activation `typ` and a `kid`-only header) and fail on a real + // device. `signRegistrationDeviceAuthorization` is the distinct seam for + // this profile — see `securekey/SecureKey.ts`. + sign: (bytes) => request.authKey.signRegistrationDeviceAuthorization(bytes), + }) + return { flowJws, deviceJws } +} + +async function compactJws(args: { + protectedHeader: object + payload: object + sign: (bytes: Uint8Array) => Promise +}): Promise { + const signingInput = + toBase64Url(utf8Json(args.protectedHeader)) + '.' + toBase64Url(utf8Json(args.payload)) + let signature: Uint8Array + try { + signature = await args.sign(new TextEncoder().encode(signingInput)) + } catch (err) { + throw mapNativeError(err) + } + if (signature.length !== JOSE_SIGNATURE_LENGTH) { + throw contractViolation('registration authorization signature must be 64 bytes') + } + return signingInput + '.' + toBase64Url(signature) +} + +type RequestClaimInputs = { + bodyBytes: Uint8Array + idempotencyKey: string + jti: string + iat: number +} + +/** + * The claims that pin the request: operation, body, idempotency key, path, + * method, and audience. Both payloads open with these, in this order. + */ +function requestTargetClaims(args: RequestClaimInputs): object { + return { + discriminator: DISCRIMINATOR, + schema_version: SCHEMA_VERSION, + body_sha256: toBase64Url(sha256(args.bodyBytes)), + idempotency_key: args.idempotencyKey, + canonical_path: DEVICE_REGISTRATION_COMPLETE_PATH, + method: 'POST', + aud: AUDIENCE, + } +} + +/** Replay and lifetime claims. Both payloads close with these. */ +function lifetimeClaims(args: RequestClaimInputs): object { + return { + jti: args.jti, + iat: args.iat, + exp: args.iat + AUTHORIZATION_LIFETIME_SECONDS, + } +} + +/** Flow proof: the 10 request claims plus the four binding claims. */ +function registrationFlowClaims( + args: RequestClaimInputs & { + registrationHandle: string + registrationCodeVerifier: string + clientEntityId: string + authKeyThumbprint: string + }, +): object { + return { + ...requestTargetClaims(args), + registration_handle_sha256: toBase64Url( + sha256(new TextEncoder().encode(args.registrationHandle)), + ), + profile_id: args.clientEntityId, + auth_key_thumbprint: args.authKeyThumbprint, + code_verifier_sha256: registrationCodeChallengeS256(args.registrationCodeVerifier), + ...lifetimeClaims(args), + } +} + +/** + * Device proof: the 10 request claims only. DAA rejects any other + * field here, so the binding claims must never be added. + */ +function registrationDeviceClaims(args: RequestClaimInputs): object { + return { + ...requestTargetClaims(args), + ...lifetimeClaims(args), + } +} + +function requireEpochSeconds(value: number): number { + if (!Number.isInteger(value) || value <= 0) { + throw contractViolation('registration authorization clock must yield a positive Unix timestamp') + } + return value +} + +/** + * Read `idempotencyKey` from the already-serialized body. Parsing is observation + * only — the hashed and sent bytes are unchanged. + */ +function idempotencyKeyFromExactBody(bodyBytes: Uint8Array): string | undefined { + if (bodyBytes.length === 0) { + return undefined + } + + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bodyBytes)) + } catch { + throw contractViolation('signed request body is not UTF-8 JSON') + } + if (!isJsonObject(parsed)) { + throw contractViolation('signed request body must be a JSON object') + } + if (!Object.prototype.hasOwnProperty.call(parsed, 'idempotencyKey')) { + return undefined + } + + const value = parsed.idempotencyKey + if (typeof value !== 'string' || !isUuid(value)) { + throw contractViolation('idempotencyKey must be a UUID when present on a signed body') + } + return value +} + +function isJsonObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function utf8Json(value: object): Uint8Array { + return new TextEncoder().encode(JSON.stringify(value)) +} diff --git a/src/auth/registrationCodeVerifier.ts b/src/auth/registrationCodeVerifier.ts new file mode 100644 index 0000000..ca4b527 --- /dev/null +++ b/src/auth/registrationCodeVerifier.ts @@ -0,0 +1,76 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The PKCE-shaped handoff that binds Prepare to Device Registration Complete. +// +// Before Prepare, the SDK generates and stores a high-entropy registration +// code verifier and an ephemeral P-256 registration-flow key. Prepare sends +// only the S256 challenge and the ephemeral public key, never an AuthKey +// public key. +// +// Two values, two calls: +// +// - the **challenge** (`S256(verifier)`) goes out at Prepare, in +// `PrepareSocialLoginRequest.registrationCodeChallenge`; +// - the **verifier** itself goes out only at Device Registration Complete, in +// `CompleteDeviceRegistrationRequest.registrationCodeVerifier`, where DAA +// re-derives the digest and matches it against the prepared challenge. +// +// The verifier is therefore a secret for the life of one login attempt. It is +// never logged, never put in an error message, and never exposed on a public +// field — `PreparedSocialLogin` holds it behind a `#` private field. +// +// This is PKCE's construction, not PKCE's protocol. No authorization code is +// exchanged anywhere in this flow: the SDK supplies `idToken` directly, and no +// authorization-code exchange, PKCE, token endpoint, or provider client secret +// participates in completion. The verifier binds the SDK instance that +// prepared the attempt to the SDK instance that completes the registration; it +// does not talk to the identity provider at all. The names come from the +// contract's own fields (`registrationCode*`), which is why they read like PKCE. + +import { toBase64Url } from '../crypto/base64url' +import { randomBytes } from '../crypto/random' +import { sha256 } from '../crypto/sha256' + +/** + * 32 bytes → 43 unpadded Base64URL characters, which is both the RFC 7636 + * maximum-entropy recommendation and the contract's `minLength: 43` for + * `registrationCodeVerifier`. + */ +const VERIFIER_ENTROPY_BYTES = 32 + +/** The one challenge method the contract's enum allows. */ +export const REGISTRATION_CODE_CHALLENGE_METHOD = 'S256' + +/** Mint a fresh high-entropy registration code verifier for one login attempt. */ +export function newRegistrationCodeVerifier(): string { + return toBase64Url(randomBytes(VERIFIER_ENTROPY_BYTES)) +} + +/** + * The S256 challenge for a verifier: unpadded Base64URL of the SHA-256 digest of + * the verifier's ASCII bytes. Always 43 characters, matching the contract's + * `^[A-Za-z0-9_-]{43}$`. + * + * The digest is taken over the verifier **string**, not over the random bytes it + * was encoded from. That is what RFC 7636 specifies and what the server can + * reproduce, since the verifier string is the only form it ever receives. + */ +export function registrationCodeChallengeS256(verifier: string): string { + return toBase64Url(sha256(new TextEncoder().encode(verifier))) +} diff --git a/src/config.ts b/src/config.ts new file mode 100644 index 0000000..dc3cd21 --- /dev/null +++ b/src/config.ts @@ -0,0 +1,156 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { DaaTransport } from './transport/DaaTransport' + +/** + * Environment namespaces keys, credentials, and endpoints. The public + * environments are `sandbox` (testnet) and `production` (mainnet). With + * `sandbox`, `publicApiOrigin` overrides the API origin with another bare https + * origin on circle.com or a subdomain. + * + * Exposed as a runtime allow-list so a JS caller passing an unknown value (which + * the compile-time type cannot catch) fails fast instead of silently creating a + * separate key namespace. + */ +export const DAA_ENVIRONMENTS = ['sandbox', 'production'] as const + +export type DaaEnvironment = (typeof DAA_ENVIRONMENTS)[number] + +const PUBLIC_API_ORIGINS: Readonly> = Object.freeze({ + sandbox: 'https://api-sandbox.circle.com', + production: 'https://api.circle.com', +}) + +const CIRCLE_DOMAIN = 'circle.com' + +/** + * The closed DeviceKeyPolicy. Application code cannot request an exportable + * private key or bypass required local authentication. The only accepted value + * is this singleton. + */ +export const DEVICE_KEY_POLICY = Object.freeze({ + hardwareBacked: true, + userVerification: 'REQUIRED_FOR_EACH_SIGNATURE', +} as const) + +export type DeviceKeyPolicy = typeof DEVICE_KEY_POLICY + +export function isRecord(value: unknown): value is Record { + return value !== null && typeof value === 'object' +} + +/** True when `value` matches the closed DeviceKeyPolicy exactly. */ +export function isRequiredDeviceKeyPolicy(value: unknown): value is DeviceKeyPolicy { + return ( + isRecord(value) && + value['hardwareBacked'] === DEVICE_KEY_POLICY.hardwareBacked && + value['userVerification'] === DEVICE_KEY_POLICY.userVerification + ) +} + +/** + * Runtime allow-list for `keyPolicy`. TypeScript cannot catch a JS caller + * passing a weaker object, so construction fail-closes unless the value + * matches `DEVICE_KEY_POLICY`. Returns the canonical frozen singleton so extra + * fields on the caller's object cannot leak into stored config. + */ +export function assertDeviceKeyPolicy(value: unknown): DeviceKeyPolicy { + if (value === undefined || value === null) { + throw new Error('DAA: keyPolicy is required') + } + if (!isRequiredDeviceKeyPolicy(value)) { + throw new Error( + 'DAA: keyPolicy must be hardware-backed with REQUIRED_FOR_EACH_SIGNATURE user verification', + ) + } + return DEVICE_KEY_POLICY +} + +export type DaaSdkConfiguration = Readonly<{ + /** + * Identifies the application integration and namespaces local key storage: + * `[A-Za-z0-9._-]`, at most 41 characters. `DaaClient` refuses any other value. + */ + appId: string + environment: DaaEnvironment + /** Required. The SDK never embeds a DAA service credential. */ + transport: DaaTransport + /** Closed set; must be `DEVICE_KEY_POLICY`. */ + keyPolicy: DeviceKeyPolicy + /** + * Overrides the sandbox API origin with another bare, lowercase https origin + * on circle.com or a subdomain. Only with `sandbox`; refused for + * `production`. Replaces the environment's origin as the pagination trust + * anchor. + */ + publicApiOrigin?: string +}> + +/** SDK-owned trust anchor used to authenticate absolute pagination links. */ +export function publicApiOriginFor(environment: DaaEnvironment): string { + return PUBLIC_API_ORIGINS[environment] +} + +/** + * Validates `publicApiOrigin` against `environment`, with the rule the native + * SDKs apply to the SCA `circleOrigin` override. Production is refused first, + * so an override left in a debug configuration fails at construction instead + * of trusting another origin for production pagination. Returns the override, + * or `undefined` when none is set. + */ +export function assertPublicApiOrigin( + environment: DaaEnvironment, + publicApiOrigin: unknown, +): string | undefined { + if (publicApiOrigin === undefined) { + return undefined + } + if (environment === 'production') { + throw new Error('DAA: publicApiOrigin cannot be set for production') + } + if (typeof publicApiOrigin !== 'string' || !isCircleOrigin(publicApiOrigin)) { + throw new Error( + 'DAA: publicApiOrigin must be a bare, lowercase https origin on circle.com or a subdomain', + ) + } + return publicApiOrigin +} + +/** + * A bare, lowercase `https://` origin on `circle.com` or one of its + * subdomains: no port, path, query, fragment, or credentials. Anything that + * would need normalizing is refused rather than normalized. + */ +function isCircleOrigin(origin: string): boolean { + const prefix = 'https://' + if (!origin.startsWith(prefix)) { + return false + } + const host = origin.slice(prefix.length) + return ( + (host === CIRCLE_DOMAIN || host.endsWith(`.${CIRCLE_DOMAIN}`)) && + host.length <= 253 && + host.split('.').every(isDnsLabel) + ) +} + +/** A lowercase LDH label: 1–63 of `[a-z0-9-]`, not starting or ending with a hyphen. */ +function isDnsLabel(label: string): boolean { + return /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/.test(label) +} diff --git a/src/crypto/base64url.ts b/src/crypto/base64url.ts new file mode 100644 index 0000000..8250f83 --- /dev/null +++ b/src/crypto/base64url.ts @@ -0,0 +1,88 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Unpadded Base64URL (RFC 4648 §5) codec. Implemented without Buffer/atob/btoa +// so it behaves identically on React Native, Node, and browsers. + +const B64URL_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_' + +// Values are always masked to 0..63, so the lookup is total. +const enc = (v: number): string => B64URL_CHARS[v]! + +// Decode table, built once at module load rather than per fromBase64Url() call. +const B64URL_LOOKUP: Record = (() => { + const table: Record = {} + for (let i = 0; i < B64URL_CHARS.length; i++) { + table[B64URL_CHARS[i]!] = i + } + return table +})() + +/** Encode bytes as unpadded Base64URL. */ +export function toBase64Url(bytes: Uint8Array): string { + let out = '' + let i = 0 + for (; i + 2 < bytes.length; i += 3) { + const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) | bytes[i + 2]! + out += enc((n >>> 18) & 63) + enc((n >>> 12) & 63) + enc((n >>> 6) & 63) + enc(n & 63) + } + const rem = bytes.length - i + if (rem === 1) { + const n = bytes[i]! << 16 + out += enc((n >>> 18) & 63) + enc((n >>> 12) & 63) + } else if (rem === 2) { + const n = (bytes[i]! << 16) | (bytes[i + 1]! << 8) + out += enc((n >>> 18) & 63) + enc((n >>> 12) & 63) + enc((n >>> 6) & 63) + } + return out +} + +/** + * Decode unpadded Base64URL back to bytes. Strict: rejects invalid characters, + * an impossible length (`len % 4 === 1`), and non-canonical encodings whose + * trailing bits are non-zero. Strictness matters because this decodes SPKI and + * ES256 signatures, where malleable inputs must not silently pass. + */ +export function fromBase64Url(input: string): Uint8Array { + const len = input.length + if (len % 4 === 1) { + throw new Error('DAA: invalid Base64URL length') + } + const outLen = Math.floor((len * 6) / 8) + const out = new Uint8Array(outLen) + let bits = 0 + let acc = 0 + let p = 0 + for (let i = 0; i < len; i++) { + const v = B64URL_LOOKUP[input[i]!] + if (v === undefined) { + throw new Error('DAA: invalid Base64URL input') + } + acc = (acc << 6) | v + bits += 6 + if (bits >= 8) { + bits -= 8 + out[p++] = (acc >>> bits) & 0xff + } + } + // Leftover bits of a canonical encoding must be zero padding. + if (bits > 0 && (acc & ((1 << bits) - 1)) !== 0) { + throw new Error('DAA: non-canonical Base64URL (non-zero trailing bits)') + } + return out +} diff --git a/src/crypto/bytes.ts b/src/crypto/bytes.ts new file mode 100644 index 0000000..df64935 --- /dev/null +++ b/src/crypto/bytes.ts @@ -0,0 +1,30 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Return a standalone `ArrayBuffer` holding a copy of the view's bytes. + * + * WebCrypto's `BufferSource` parameters want an `ArrayBuffer`-backed view; under + * TypeScript's typed-array generics a plain `Uint8Array` may be + * `Uint8Array` (possibly `SharedArrayBuffer`-backed) and does + * not satisfy that. Copying to a fresh `ArrayBuffer` sidesteps the mismatch and + * keeps callers passing the exact bytes. + */ +export function toArrayBuffer(view: Uint8Array): ArrayBuffer { + return view.buffer.slice(view.byteOffset, view.byteOffset + view.byteLength) as ArrayBuffer +} diff --git a/src/crypto/es256Jws.ts b/src/crypto/es256Jws.ts new file mode 100644 index 0000000..a169804 --- /dev/null +++ b/src/crypto/es256Jws.ts @@ -0,0 +1,240 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Compact ES256 JWS verification against a pinned key set. +// +// This file does the structural work only. The signature itself is checked by +// the native SDKs' `DaaPrepareReceiptSignature` — CryptoKit on iOS, +// `java.security` on Android — through the Expo `DaaRegistration` module; +// there is no curve arithmetic in TypeScript. +// Node/Jest has no native module, so `jest.setup.js` stands in with WebCrypto, +// the same arrangement `crypto/random.ts` uses. A React Native host without the +// module fails closed. +// +// What this file enforces, and why each rule is here: +// +// - `alg` must be exactly `ES256`. It is compared against a fixed allowlist and +// never obeyed, which closes `alg: none` and algorithm confusion by +// construction. +// - `typ` must be the value the caller expects, so a JWS minted for another +// purpose under the same key does not verify as this one. +// - No key is ever taken from the token. `jwk`/`jku`/`x5u`/`x5c` are rejected +// outright, even on a token that would verify. `kid` selects among the keys +// the caller pinned and nothing else: an unknown `kid` is a rejection, not a +// fetch. +// - Any `crit` is rejected: this module understands no extension. +// - The signature must decode to exactly 64 bytes (JOSE `R || S`) before the +// platform is called. +// - The payload is parsed only after the signature verifies, so unverified +// claims never reach a caller. +// +// Rejections are a closed set of this module's own literals, so a caller can +// say why a token was refused without reflecting attacker-supplied text into a +// message a host app is likely to log. + +import { + nativeVerifyPrepareReceiptSignature, + requireDaaRegistrationNative, +} from '../auth/daaRegistrationNative' +import { contractViolation } from '../errors' +import { fromBase64Url } from './base64url' + +/** + * The one algorithm this SDK verifies. Every additional entry is another + * verification path, so the list holds only ES256. + */ +export const SUPPORTED_JWS_ALGORITHMS: readonly string[] = Object.freeze(['ES256']) + +/** JOSE `R || S` for P-256: two 32-byte big-endian scalars. */ +export const ES256_SIGNATURE_LENGTH = 64 + +/** Uncompressed SEC 1 point: `0x04 || X(32) || Y(32)`. */ +const X963_LENGTH = 65 + +/** Header members that carry or locate a key. Never honoured; always rejected. */ +const KEY_SOURCING_HEADERS: readonly string[] = Object.freeze(['jwk', 'jku', 'x5u', 'x5c']) + +/** A verification key the caller pinned, addressed by its `kid`. */ +export type PinnedEs256Key = Readonly<{ + kid: string + /** Uncompressed P-256 point. The platform validates it is on the curve. */ + publicKeyX963: Uint8Array +}> + +export type Es256JwsRejection = + | 'malformed_compact_serialization' + | 'malformed_protected_header' + | 'unsupported_algorithm' + | 'unexpected_type' + | 'header_sources_a_key' + | 'unsupported_critical_header' + | 'missing_key_id' + | 'unknown_key_id' + | 'malformed_signature' + | 'signature_mismatch' + | 'malformed_payload' + +export type Es256JwsResult = + | Readonly<{ + verified: true + protectedHeader: Readonly> + payload: Readonly> + }> + | Readonly<{ verified: false; reason: Es256JwsRejection }> + +function rejected(reason: Es256JwsRejection): Es256JwsResult { + return { verified: false, reason } +} + +/** Own-property read, so a name on `Object.prototype` never reads as a member. */ +export function ownMember(object: Readonly>, name: string): unknown { + return Object.prototype.hasOwnProperty.call(object, name) ? object[name] : undefined +} + +/** Decode one Base64URL segment as a UTF-8 JSON object, or `null`. */ +function decodeJsonObject(segment: string): Record | null { + let bytes: Uint8Array + try { + bytes = fromBase64Url(segment) + } catch { + return null + } + let parsed: unknown + try { + parsed = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) + } catch { + return null + } + if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) { + return null + } + return parsed as Record +} + +/** + * Index the pinned keys by `kid`. + * + * A malformed key set is a configuration error on this side of the boundary, + * so it throws rather than returning a rejection that would read as a bad token. + */ +function indexPinnedKeys(keys: readonly PinnedEs256Key[]): ReadonlyMap { + if (!Array.isArray(keys) || keys.length === 0) { + throw contractViolation('ES256 verification requires at least one pinned key') + } + const byKid = new Map() + for (const key of keys) { + if (typeof key.kid !== 'string' || key.kid.length === 0) { + throw contractViolation('every pinned ES256 key must have a non-empty kid') + } + if (byKid.has(key.kid)) { + throw contractViolation('pinned ES256 keys must have distinct kids') + } + if ( + !(key.publicKeyX963 instanceof Uint8Array) || + key.publicKeyX963.length !== X963_LENGTH || + key.publicKeyX963[0] !== 0x04 + ) { + throw contractViolation('every pinned ES256 key must be an uncompressed P-256 point') + } + byKid.set(key.kid, key.publicKeyX963) + } + return byKid +} + +/** + * Verify a compact JWS (`header.payload.signature`) against pinned P-256 keys. + * + * Length bounds are the caller's business: a caller with a contract bound (as + * the Prepare receipt has) applies it first. + * + * @throws DaaError `contract_violation` for a malformed pinned key set, and when + * the platform verifier is unavailable or fails — including a pinned key the + * platform does not accept as a P-256 point. A token that is merely wrong is + * a `{ verified: false }` result, not a throw. + */ +export async function verifyCompactEs256( + jws: string, + options: Readonly<{ keys: readonly PinnedEs256Key[]; expectedTyp: string }>, +): Promise { + const keysByKid = indexPinnedKeys(options.keys) + + const segments = jws.split('.') + if (segments.length !== 3) { + return rejected('malformed_compact_serialization') + } + const [encodedHeader, encodedPayload, encodedSignature] = segments as [string, string, string] + if (encodedHeader === '' || encodedPayload === '' || encodedSignature === '') { + return rejected('malformed_compact_serialization') + } + + const header = decodeJsonObject(encodedHeader) + if (header === null) { + return rejected('malformed_protected_header') + } + for (const name of KEY_SOURCING_HEADERS) { + if (Object.prototype.hasOwnProperty.call(header, name)) { + return rejected('header_sources_a_key') + } + } + if (Object.prototype.hasOwnProperty.call(header, 'crit')) { + return rejected('unsupported_critical_header') + } + const algorithm = ownMember(header, 'alg') + if (typeof algorithm !== 'string' || !SUPPORTED_JWS_ALGORITHMS.includes(algorithm)) { + return rejected('unsupported_algorithm') + } + if (ownMember(header, 'typ') !== options.expectedTyp) { + return rejected('unexpected_type') + } + const kid = ownMember(header, 'kid') + if (typeof kid !== 'string' || kid.length === 0) { + return rejected('missing_key_id') + } + const publicKeyX963 = keysByKid.get(kid) + if (publicKeyX963 === undefined) { + return rejected('unknown_key_id') + } + + let signature: Uint8Array + try { + signature = fromBase64Url(encodedSignature) + } catch { + return rejected('malformed_signature') + } + if (signature.length !== ES256_SIGNATURE_LENGTH) { + return rejected('malformed_signature') + } + + // RFC 7515 §5.2: the signing input is the ASCII of the two encoded segments + // exactly as received, never re-encoded from the parsed header. + const signingInput = new TextEncoder().encode(`${encodedHeader}.${encodedPayload}`) + const verified = await nativeVerifyPrepareReceiptSignature(requireDaaRegistrationNative(), { + publicKeyX963, + signingInput, + signature, + }) + if (!verified) { + return rejected('signature_mismatch') + } + + const payload = decodeJsonObject(encodedPayload) + if (payload === null) { + return rejected('malformed_payload') + } + return { verified: true, protectedHeader: header, payload } +} diff --git a/src/crypto/jwkThumbprint.ts b/src/crypto/jwkThumbprint.ts new file mode 100644 index 0000000..978a208 --- /dev/null +++ b/src/crypto/jwkThumbprint.ts @@ -0,0 +1,65 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { toBase64Url } from './base64url' +import { contractViolation } from '../errors' +import { sha256 } from './sha256' + +// RFC 7638 JWK thumbprint (`jkt`) of a P-256 public key, derived from its DER +// SubjectPublicKeyInfo. Deriving it in ONE place means the in-memory and native +// stores agree byte-for-byte, and — because `x`/`y` are the fixed 32-byte field +// elements sliced straight from the SPKI — the short-coordinate interop bug +// (a `jkt` computed over a leading-zero-trimmed coordinate) cannot occur. +// +// A P-256 SPKI is exactly 91 bytes and ends with a 65-byte uncompressed point +// (`0x04 || X(32) || Y(32)`) starting at offset 26. + +/** P-256 public JWK as Registration Complete embeds it (`kty`/`crv`/`x`/`y`). */ +export type P256PublicJwk = Readonly<{ + kty: 'EC' + crv: 'P-256' + x: string + y: string +}> + +/** + * Slice the uncompressed P-256 point out of a 91-byte SPKI. + * + * Used both for RFC 7638 thumbprints and for the embedded `jwk` in the + * registration dual-header JWSs. One slice, so those two cannot disagree. + */ +export function p256PublicJwkFromSpki(spki: Uint8Array): P256PublicJwk { + if (spki.length !== 91 || spki[26] !== 0x04) { + // contract_violation (not a raw Error) so callers narrowing with isDaaError + // catch this on the production thumbprint() path too. + throw contractViolation('expected a 91-byte P-256 SPKI with an uncompressed point') + } + return { + kty: 'EC', + crv: 'P-256', + x: toBase64Url(spki.subarray(27, 59)), + y: toBase64Url(spki.subarray(59, 91)), + } +} + +export function p256JwkThumbprint(spki: Uint8Array): string { + const jwk = p256PublicJwkFromSpki(spki) + // Canonical JWK: members in lexicographic order, no whitespace (RFC 7638). + const canonical = `{"crv":"P-256","kty":"EC","x":"${jwk.x}","y":"${jwk.y}"}` + return toBase64Url(sha256(new TextEncoder().encode(canonical))) +} diff --git a/src/crypto/random.ts b/src/crypto/random.ts new file mode 100644 index 0000000..df75d5b --- /dev/null +++ b/src/crypto/random.ts @@ -0,0 +1,113 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Cryptographically strong randomness. +// +// Production always goes through the Expo `DaaRegistration` module +// (`DaaSecureRandom` for verifier bytes, platform CSPRNG UUID for the attempt +// id). There is no host-WebCrypto fallback in these functions: a missing module +// is a `contract_violation`, including on a host that installed a WebCrypto +// polyfill for some other library. +// +// Node / Jest inject a fake native module in `jest.setup.js`. The explicit +// `webCryptoRandomBytes` / `webCryptoRandomUuidV4` helpers exist so tests can +// pin the stand-in; production callers never use them. +// +// randomBytes -> DaaSecureRandom.bytes +// randomUuidV4 -> platform UUID +// +// A missing or non-functional source is a `contract_violation`, never a silent +// fallback. There is no `Math.random` path: the verifier is the secret binding +// Prepare to Registration Complete, and a predictable one defeats the handoff. + +import { + nativeRandomBytes, + nativeRandomUuidV4, + requireDaaRegistrationNative, +} from '../auth/daaRegistrationNative' +import { contractViolation } from '../errors' +import { isUuidV4 } from '../validation/uuid' + +/** Fill a fresh buffer with `length` cryptographically strong random bytes. */ +export function randomBytes(length: number): Uint8Array { + if (!Number.isInteger(length) || length <= 0) { + throw contractViolation('random byte length must be a positive integer') + } + return nativeRandomBytes(requireDaaRegistrationNative(), length) +} + +/** + * A random (version 4) UUID in the canonical hyphenated form, from the Expo + * module's platform CSPRNG UUID. Re-checked so a stubbed native return fails + * where the value is minted rather than as a rejected request later. + */ +export function randomUuidV4(): string { + const uuid = nativeRandomUuidV4(requireDaaRegistrationNative()) + if (!isUuidV4(uuid)) { + throw contractViolation('native randomUuidV4 did not return an RFC 4122 version 4 UUID') + } + return uuid +} + +/** + * Node/Jest stand-in for verifier bytes. Production `randomBytes` never calls + * this; tests that pin host WebCrypto import it explicitly. + */ +export function webCryptoRandomBytes(length: number): Uint8Array { + if (!Number.isInteger(length) || length <= 0) { + throw contractViolation('random byte length must be a positive integer') + } + const getRandomValues = hostFunction('getRandomValues') + const buffer = new Uint8Array(length) + getRandomValues(buffer) + return buffer +} + +/** + * Node/Jest stand-in for the attempt UUID. Production `randomUuidV4` never + * calls this; tests that pin `crypto.randomUUID` import it explicitly. + */ +export function webCryptoRandomUuidV4(): string { + const uuid = hostFunction('randomUUID')() + if (!isUuidV4(uuid)) { + throw contractViolation('crypto.randomUUID did not return an RFC 4122 version 4 UUID') + } + return uuid +} + +// Resolve one WebCrypto function by name, or fail closed naming it. +// +// `globalThis.crypto` is read per call rather than captured at import, so a host +// that installs its polyfill after this module is first evaluated is still +// served. One message shape for every missing function, so a caller (and a test) +// can tell exactly which one the host did not supply. +// +// Bound to the host object: both functions are specified to reject a foreign +// receiver (`TypeError: Value of "this" must be of type Crypto`), so returning +// them detached would throw at the call site instead of working. +function hostFunction(name: K): NonNullable { + const host = (globalThis as { crypto?: Crypto }).crypto + if (host === undefined || typeof host[name] !== 'function') { + throw contractViolation( + `crypto.${name} is required to mint login-attempt material; ` + + 'install a WebCrypto implementation that provides it in the host app', + ) + } + const fn = host[name] as NonNullable + return fn.bind(host) as NonNullable +} diff --git a/src/crypto/serialization.ts b/src/crypto/serialization.ts new file mode 100644 index 0000000..5a12804 --- /dev/null +++ b/src/crypto/serialization.ts @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Deterministic, exact-byte body serialization. +// +// The SDK serializes a request body exactly once and then signs and sends that +// same immutable byte slice. It never canonicalizes or re-serializes the body. +// Callers must treat the returned Uint8Array as immutable. + +/** + * Serialize a JSON request body to its exact UTF-8 bytes, once. + * + * @throws if the value cannot be represented as JSON (e.g. contains only + * `undefined`, a function, or a BigInt). + */ +export function serializeBody(value: unknown): Uint8Array { + const json = JSON.stringify(value) + if (json === undefined) { + throw new Error('DAA: request body is not JSON-serializable') + } + return new TextEncoder().encode(json) +} + +/** The exact-byte representation of a body-less request: the empty byte array. */ +export function serializeEmptyBody(): Uint8Array { + return new Uint8Array(0) +} diff --git a/src/crypto/sha256.ts b/src/crypto/sha256.ts new file mode 100644 index 0000000..31b3ab0 --- /dev/null +++ b/src/crypto/sha256.ts @@ -0,0 +1,105 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Minimal SHA-256 (FIPS 180-4), dependency-free, so JWK thumbprints can be +// derived in TypeScript on React Native (Hermes has no WebCrypto by default). +// Standard algorithm; verified against known test vectors in the unit tests. + +const K = new Uint32Array([ + 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, + 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, + 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, + 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, + 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, + 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, + 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, + 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2, +]) + +function rotr(x: number, n: number): number { + return (x >>> n) | (x << (32 - n)) +} + +export function sha256(input: Uint8Array): Uint8Array { + const h = new Uint32Array([ + 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19, + ]) + + const l = input.length + const bitLen = l * 8 + // Pad to a multiple of 64 bytes: 0x80, zeros, then the 64-bit big-endian length. + const total = (((l + 8) >> 6) + 1) << 6 + const m = new Uint8Array(total) + m.set(input) + m[l] = 0x80 + const dv = new DataView(m.buffer) + dv.setUint32(total - 4, bitLen >>> 0, false) + dv.setUint32(total - 8, Math.floor(bitLen / 0x100000000), false) + + const w = new Uint32Array(64) + for (let off = 0; off < total; off += 64) { + for (let i = 0; i < 16; i++) w[i] = dv.getUint32(off + i * 4, false) + for (let i = 16; i < 64; i++) { + const a15 = w[i - 15]! + const a2 = w[i - 2]! + const s0 = rotr(a15, 7) ^ rotr(a15, 18) ^ (a15 >>> 3) + const s1 = rotr(a2, 17) ^ rotr(a2, 19) ^ (a2 >>> 10) + w[i] = (w[i - 16]! + s0 + w[i - 7]! + s1) >>> 0 + } + + let a = h[0]! + let b = h[1]! + let c = h[2]! + let d = h[3]! + let e = h[4]! + let f = h[5]! + let g = h[6]! + let hh = h[7]! + + for (let i = 0; i < 64; i++) { + const S1 = rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25) + const ch = (e & f) ^ (~e & g) + const t1 = (hh + S1 + ch + K[i]! + w[i]!) >>> 0 + const S0 = rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22) + const maj = (a & b) ^ (a & c) ^ (b & c) + const t2 = (S0 + maj) >>> 0 + hh = g + g = f + f = e + e = (d + t1) >>> 0 + d = c + c = b + b = a + a = (t1 + t2) >>> 0 + } + + h[0] = (h[0]! + a) >>> 0 + h[1] = (h[1]! + b) >>> 0 + h[2] = (h[2]! + c) >>> 0 + h[3] = (h[3]! + d) >>> 0 + h[4] = (h[4]! + e) >>> 0 + h[5] = (h[5]! + f) >>> 0 + h[6] = (h[6]! + g) >>> 0 + h[7] = (h[7]! + hh) >>> 0 + } + + const out = new Uint8Array(32) + const odv = new DataView(out.buffer) + for (let i = 0; i < 8; i++) odv.setUint32(i * 4, h[i]!, false) + return out +} diff --git a/src/errors.ts b/src/errors.ts new file mode 100644 index 0000000..fafac3a --- /dev/null +++ b/src/errors.ts @@ -0,0 +1,319 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Stable SDK error model. Unknown DAA codes remain observable as +// `api` and are never guessed retryable. Errors never expose Owner grants, JWS +// values, raw key material, native key handles, or sealed server state. +// +// `device_revoked` and `owner_binding_invalid` are reserved: DAA returns no +// code that produces them, so the SDK never throws them. They stay in the type +// so that a later DAA code does not change the public type. + +export type DaaSdkError = + | { kind: 'transport'; retryable: boolean; idempotencyKey?: string } + | { kind: 'api'; httpStatus: number; daaStatusCode?: string | number; retryable: boolean } + | { kind: 'local_user_authentication_required' } + | { kind: 'login_request_expired' } + | { kind: 'owner_grant_invalid' } + | { kind: 'owner_grant_expired' } + | { kind: 'prepare_receipt_invalid' } + | { kind: 'owner_binding_invalid' } + | { kind: 'device_not_initialized' } + | { kind: 'device_revoked' } + | { kind: 'idempotency_conflict'; idempotencyKey: string; correlationId?: string } + | { kind: 'contract_violation'; correlationId?: string } + +/** + * An Error carrying a structured `DaaSdkError`. The SDK throws this so callers + * get the stable model (`err.detail.kind`) instead of raw platform text. + */ +export class DaaError extends Error { + readonly detail: DaaSdkError + // The originating error. Kept off `message` (so it never lands in logs by + // default) but available to a host that deliberately inspects `err.cause`. + readonly cause: unknown + + constructor(detail: DaaSdkError, message: string, cause: unknown = undefined) { + super(message) + this.name = 'DaaError' + this.detail = detail + this.cause = cause + // Keep `cause` non-enumerable so JSON.stringify and crash reporters that + // walk own enumerable properties do not export the raw native error (its + // code / userInfo / native stack). It stays readable via `err.cause`. + Object.defineProperty(this, 'cause', { enumerable: false }) + } +} + +/** Narrow an unknown caught value to `DaaError` (so callers can read `.detail`). */ +export function isDaaError(err: unknown): err is DaaError { + return err instanceof DaaError +} + +/** A local boundary/contract check failed (no request was sent). */ +export function contractViolation(message: string, correlationId?: string | null): DaaError { + if (correlationId === undefined || correlationId === null) { + return new DaaError({ kind: 'contract_violation' }, `DAA: ${message}`) + } + return new DaaError( + { kind: 'contract_violation', correlationId }, + `DAA: ${message}${requestIdSuffix(correlationId)}`, + ) +} + +/** + * A correlation id is a server-supplied header value, and it reaches + * `DaaError.message` — which a consuming app is likely to log verbatim. A header + * carrying CR, LF, or other control characters could therefore forge log lines, + * so only printable ASCII is interpolated. + * + * This does not cost the value: a correlation id is printable, so the message + * carries the exact header. Only one already carrying control characters comes + * through altered, and the missing characters are the ones that made it unsafe. + * Where the error model carries the field — `contract_violation` — the detail + * still holds it exactly, for a caller reading it deliberately rather than + * logging it. + */ +function messageSafe(correlationId: string): string { + return correlationId.replace(/[^\x20-\x7e]/g, '') +} + +/** The ` (requestId=…)` message suffix, or nothing when there is no correlation id. */ +function requestIdSuffix(correlationId: string | null): string { + return correlationId === null ? '' : ` (requestId=${messageSafe(correlationId)})` +} + +/** + * A successful response could not be read as the contract's shape. + * + * The same `contract_violation` kind as a local check: the model describes a + * broken contract, not which side broke it, and a caller's recovery is the same + * either way — the call cannot be made to succeed by retrying it. What + * distinguishes this one is `correlationId`, the provider's `X-Request-Id`, which + * is what makes it diagnosable server-side. + * + * Nothing derived from the response *body* is carried. The body is the thing the + * SDK could not vouch for; a misrouted or intercepted response must not be able + * to put its own text into a consumer's logs. Not even the name of the field that + * was missing goes in. + */ +export function malformedResponse(correlationId: string | null): DaaError { + const detail: DaaSdkError = + correlationId === null + ? { kind: 'contract_violation' } + : { kind: 'contract_violation', correlationId } + return new DaaError( + detail, + `DAA: the response did not match the DAA API contract${requestIdSuffix(correlationId)}`, + ) +} + +/** + * A DAA API call returned an unexpected status. + * + * `retryable` is decided by the HTTP status alone. A caller may safely retry + * `429` and `5xx` responses; write retries must reuse the original body and + * idempotency key. Other `4xx` responses will not become successes on a second + * attempt. The DAA status code is carried for logging and support but is + * deliberately **not** consulted — an unknown DAA code stays observable and is + * never guessed retryable. + * + * `correlationId` goes in the message and **not** on the detail, because the + * `api` variant does not model one — the error model puts the field on + * `contract_violation` only, and the SDK does not widen the `api` type to carry + * it. Sanitising costs nothing here: a correlation id is printable, so the + * message copy is the exact header. Only a header already carrying control + * characters differs, and that value is not one to hand back untouched. + */ +export function apiFailure(args: { + httpStatus: number + daaStatusCode: string | number | null + correlationId: string | null +}): DaaError { + const retryable = args.httpStatus === 429 || args.httpStatus >= 500 + const detail: DaaSdkError = { + kind: 'api', + httpStatus: args.httpStatus, + retryable, + ...(args.daaStatusCode === null ? {} : { daaStatusCode: args.daaStatusCode }), + } + return new DaaError( + detail, + `DAA: API call failed (status=${args.httpStatus})${requestIdSuffix(args.correlationId)}`, + ) +} + +/** + * The consumer's transport threw instead of returning a response. + * + * The error model calls this `transport`. A throw from `DaaTransport.send` does + * not say whether the request reached DAA. Cancellation after transport + * submission remains an ambiguous result and follows the retry rules; a throw + * from the transport leaves the same unknown outcome. The retry rule is to + * retry with the same body bytes and the same idempotency key. That is why + * `retryable` is `true`, and why the idempotency key of the request handed to + * the transport, when its body has one, goes on the detail: it is the key the + * retry must reuse. + * + * The thrown value is the consumer's own error. It is kept as `cause`, not + * copied into `message`: the SDK cannot vouch for its text, and `message` is + * what crash reporters log by default. + * + * Every `DaaUserClient` operation reports a transport throw this way. The three + * login calls (Prepare, Social Session, and Device Registration Complete) do + * not: they rethrow the consumer's error unchanged, because the SDK mints their + * idempotency keys itself and does not let a caller resend the same bytes, so + * `retryable: true` would not be true for them. + */ +export function transportFailure(cause: unknown, idempotencyKey?: string): DaaError { + const detail: DaaSdkError = + idempotencyKey === undefined + ? { kind: 'transport', retryable: true } + : { kind: 'transport', retryable: true, idempotencyKey } + return new DaaError(detail, 'DAA: the transport failed before a response was received', cause) +} + +/** + * The pending login request expired (`410`). + * + * The contract's rule for the Prepare and Social Session calls: "An exact retry + * after expiry returns `410`; the SDK starts a new logical attempt with a fresh, + * permanently unused key." So the caller's recovery is a new `prepareSocialLogin`, + * not a retry, and the expired key is never reused. + * + * `correlationId`, the response's `X-Request-Id`, goes in the message only, as + * on `api`. The error model puts a correlation id on `contract_violation`; + * `idempotency_conflict` also carries it, as an optional field (see + * {@link idempotencyConflict}), and this variant does not. + */ +export function loginRequestExpired(correlationId: string | null): DaaError { + return new DaaError( + { kind: 'login_request_expired' }, + `DAA: the login request has expired${requestIdSuffix(correlationId)}`, + ) +} + +/** + * The Prepare receipt could not be verified: it is missing where one is + * required, malformed, signed by no pinned key, bound to values other than this + * attempt's, outside its validity window, or the platform verifier is missing + * or failed. + * + * On the login path this is raised only when a trust anchor is pinned for the + * environment: the SDK then verifies the receipt and fails closed on any + * mismatch, and nothing from that Prepare response reaches the application. + * With no anchor pinned, the receipt is ignored. Not retryable in place: the + * caller's recovery is a new `prepareSocialLogin`, which sends a fresh + * challenge and flow key. A failure that persists across fresh attempts points + * at the relay or at trust material that does not match the service's signer, + * not at the user. + * + * The receipt is unverified server-supplied text and never goes into the + * message; `message` here is one of the SDK's own literals. + */ +export function prepareReceiptInvalid(message: string, cause: unknown = undefined): DaaError { + return new DaaError({ kind: 'prepare_receipt_invalid' }, `DAA: ${message}`, cause) +} + +/** + * The same error with the response's `X-Request-Id` named in its message. + * + * For a check that runs on a decoded response without seeing the response + * itself — the Prepare receipt's verification has many throw sites and none of + * them holds the headers — so the caller that does hold the response adds the + * id once. The detail, the cause, and the stack of the check that threw are + * unchanged. + */ +export function withRequestId(err: DaaError, correlationId: string | null): DaaError { + if (correlationId === null) { + return err + } + const correlated = new DaaError( + err.detail, + `${err.message}${requestIdSuffix(correlationId)}`, + err.cause, + ) + if (err.stack !== undefined) { + // Keep the frame that names which receipt check failed, with the new message. + // A function replacer, so a `$` in the server's id is not a replace pattern. + correlated.stack = err.stack.replace(err.message, () => correlated.message) + } + return correlated +} + +/** + * An idempotency key was reused with different request bytes: a `409` with + * `IDEMPOTENCY_KEY_REUSED` (`420034`). Another `409` is not this error. + * + * The key goes on the detail so a caller can correlate the conflict; it stays + * out of `message` because that string is what crash reporters log by default. + * The response's `X-Request-Id` is the server's id, not the caller's, so it goes + * in both, in the shape `contract_violation` uses: a host that reports + * `err.detail` rather than the message can still trace the conflict + * server-side. The error model puts a correlation id on `contract_violation`; + * `idempotency_conflict` also carries it, as an optional field. + */ +export function idempotencyConflict( + idempotencyKey: string, + correlationId: string | null, +): DaaError { + const detail: DaaSdkError = + correlationId === null + ? { kind: 'idempotency_conflict', idempotencyKey } + : { kind: 'idempotency_conflict', idempotencyKey, correlationId } + return new DaaError( + detail, + `DAA: idempotency key was reused with a different request${requestIdSuffix(correlationId)}`, + ) +} + +/** + * Map an error thrown by the native secure-key module onto `DaaSdkError`. The + * raw native message is never propagated into `.message` — it can contain + * keystore/enclave internals that must not reach host-app logs — but is retained + * as `.cause` for deliberate inspection. + * + * An already-structured `DaaError` passes through unchanged. Otherwise a stable + * `code` on the native error maps the known custody states; anything else + * collapses to `contract_violation`. + */ +export function mapNativeError(err: unknown): DaaError { + if (err instanceof DaaError) { + return err + } + const code = (err as { code?: unknown } | null | undefined)?.code + if (code === 'USER_AUTH_REQUIRED') { + return new DaaError( + { kind: 'local_user_authentication_required' }, + 'DAA: user authentication is required', + err, + ) + } + if (code === 'NOT_INITIALIZED') { + return new DaaError( + { kind: 'device_not_initialized' }, + 'DAA: secure key is not initialized', + err, + ) + } + return new DaaError( + { kind: 'contract_violation' }, + 'DAA: native secure-key operation failed', + err, + ) +} diff --git a/src/index.ts b/src/index.ts new file mode 100644 index 0000000..5e145b9 --- /dev/null +++ b/src/index.ts @@ -0,0 +1,223 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Public surface of this package. +// +// The transport boundary, exact-byte serialization, the typed read/write clients +// (types only), and the login ceremony: Prepare, Social Session, Device +// Registration Complete, then `DaaClient.forUser` for an ACTIVE context. +// No generic signing API. Registered-device `signDeviceAuthorization` is +// bridged to native on both platforms. Device Registration Complete sends the +// two-JWS registration proof — `X-Device-Authorization` over the proposed +// AuthKey, plus `X-Registration-Flow-Authorization` over the ephemeral flow +// key committed at Prepare — and both signatures reach native, each through +// its OWN typed seam: the AuthKey signs the device proof through +// `signRegistrationDeviceAuthorization` (a different native function and +// validator from post-activation `signDeviceAuthorization` — see +// `securekey/SecureKey.ts`), and the flow key signs through +// `DaaRegistrationFlowKey.signRegistrationAuthorization`. Tests can also +// finish the ceremony with the WebCrypto flow-key provider and `./testing` +// InMemory AuthKeys. +// +// The Owner-key *interfaces* are exported (they carry no runtime capability and +// are the contract that native/production key stores implement). The concrete +// WebCrypto test double is NOT exported here — it lives behind the `./testing` +// subpath and fails closed in production builds. So raw-byte signing is +// unreachable from `.` on exports-aware resolvers, and gated by a runtime guard +// elsewhere (see SECURITY.md and the `exports` map in package.json). + +export { DaaClient } from './DaaClient' + +// Passkey SCA (native ceremony through Circle's hosted page). A runtime value +// on purpose: it is the only way to reach the DaaSca native module. +export { createScaClient, isScaError, ScaError } from './sca/ScaClient' +export type { + ScaCapabilities, + ScaClient, + ScaConfig, + ScaEnvironment, + ScaErrorCode, +} from './sca/ScaClient' + +// The typed API surface and its models are exported as **types only**. That is +// what keeps a consumer from fabricating server-attributed data: there is no +// runtime constructor for `Account`, `Money`, `BusinessPii`, or `Address` +// anywhere on this entry, and the factory that builds them +// (`api/DaaUserClient.createDaaUserClient`) is not exported either. Every +// instance a caller can hold came from a response this SDK decoded. The models +// also carry `#` private fields, so an object literal cannot be *typed* as one +// of them either. +// +// The mixed prefixing is deliberate. The SDK contract states this surface in +// TypeScript, so for this SDK those are the names rather than an idiomatic +// rendering of them: `DaaClient`, `DaaUserClient`, `DaaTransport`, +// `DaaSdkConfiguration`, `DaaUserContext`, and `DaaSdkError` carry the prefix; +// the resources and sub-clients — `Account`, `AccountsClient`, `Page` — do not. +// Names the contract does not mention (`Money`, `BusinessPii`, `Address`) +// follow its convention for resources. +// +// TypeScript has no namespace to lean on the way the natives do, so a consumer +// imports into a flat scope; every unprefixed name here is type-only, and a +// collision with an app's own `Account` is resolved at the import site with `as`. +export type { AuthClient } from './api/AuthClient' +export type { AccountListQuery, AccountsClient } from './api/AccountsClient' +export type { AccountLimitsClient, AccountLimitsUsageQuery } from './api/AccountLimitsClient' +export type { DepositAddressListQuery, DepositAddressesClient } from './api/DepositAddressesClient' +export type { DepositListQuery, DepositsClient } from './api/DepositsClient' +export type { TransactionListQuery, TransactionsClient } from './api/TransactionsClient' +export type { TransferListQuery, TransfersClient } from './api/TransfersClient' +export type { WithdrawalListQuery, WithdrawalsClient } from './api/WithdrawalsClient' +export type { FiatAccountsClient } from './api/FiatAccountsClient' +export type { + PublicAccountId, + WireFiatAccountListQuery, + WireFiatAccountsClient, + WireInstructionQuery, +} from './api/WireFiatAccountsClient' +export type { AchFiatAccountListQuery, AchFiatAccountsClient } from './api/AchFiatAccountsClient' +export type { DaaUserClient } from './api/DaaUserClient' +export type { + DaaUserContext, + DeviceContext, + DeviceRegistrationResult, +} from './models/DaaUserContext' +export type { PendingDeviceRegistration } from './models/PendingDeviceRegistration' +export type { + Account, + AccountPurpose, + AccountRendering, + AccountStatus, + AccountType, + CustodyType, +} from './models/Account' +export type { CreateAccountRequest } from './models/CreateAccountRequest' +export type { + AccountLimitsUsage, + AccountLimitsUsageItem, + AccountLimitsUsageRendering, + AccountLimitsUsageResourceType, + LimitsUsageAssetType, + LimitsUsageComparisonType, + LimitsUsageOperation, + LimitsUsageUnit, + LimitsUsageWindow, +} from './models/AccountLimitsUsage' +export type { + CreateTransferAmount, + CreateTransferDestination, + CreateTransferRequest, + CreateTransferRiskSignals, + CreateTransferSource, +} from './models/CreateTransferRequest' +export type { Address, BusinessPii } from './models/BusinessPii' +export type { AddressObject, AddressObjectRendering } from './models/AddressObject' +export type { DepositAddressChain, GenerateAddressRequest } from './models/GenerateAddressRequest' +export type { + Deposit, + DepositAccountLocation, + DepositRendering, + DepositRiskEvaluation, + DepositSourceLocation, + DepositStatus, + DepositType, +} from './models/Deposit' +export type { DepositSummary, DepositSummaryRendering } from './models/DepositSummary' +export type { Money } from './models/Money' +export type { Page } from './models/Page' +export type { PreparedSocialLogin } from './models/PreparedSocialLogin' +export type { + Transaction, + TransactionAccountLocation, + TransactionBlockchainLocation, + TransactionBlockchainLocationRendering, + TransactionFiatLocation, + TransactionLocation, + TransactionRendering, + TransactionStatus, + TransactionType, +} from './models/Transaction' +export type { + Fee, + Transfer, + TransferDestinationAccountLocation, + TransferDestinationAccountLocationRendering, + TransferDestinationBlockchainLocation, + TransferDestinationBlockchainLocationRendering, + TransferDestinationLocation, + TransferErrorCode, + TransferPolicyEvaluation, + TransferRendering, + TransferSourceLocation, + TransferStatus, +} from './models/Transfer' +export type { + WithdrawalAdjustments, + WithdrawalDestination, + WithdrawalDestinationType, + WithdrawalDetail, + WithdrawalDetailRendering, + WithdrawalErrorCode, + WithdrawalPolicyEvaluation, + WithdrawalReturn, + WithdrawalRiskEvaluation, + WithdrawalStatus, + WithdrawalSubAccountSweep, + WithdrawalSweepStatus, + WithdrawalToAmount, +} from './models/Withdrawal' +export type { + CreateWithdrawalAmount, + CreateWithdrawalDestination, + CreateWithdrawalRequest, + CreateWithdrawalRiskSignals, + CreateWithdrawalSource, + CreateWithdrawalToAmount, +} from './models/CreateWithdrawalRequest' +export type { BankAddress, BillingDetails, FiatAccountStatus } from './models/FiatAccount' +export type { + TransferTypeInfo, + Wire, + WireInstruction, + WireInstructionBeneficiary, + WireInstructionBeneficiaryBank, + WireSummary, +} from './models/Wire' +export type { + ACH, + ACHInstruction, + ACHInstructionBeneficiary, + ACHInstructionBeneficiaryBank, +} from './models/Ach' + +export { DAA_ENVIRONMENTS, DEVICE_KEY_POLICY } from './config' +export type { DaaEnvironment, DaaSdkConfiguration, DeviceKeyPolicy } from './config' +export type { DaaHttpRequest, DaaHttpResponse, DaaTransport } from './transport/DaaTransport' +export type { DaaSdkError } from './errors' +// Structured error thrown by the SDK; callers narrow with `isDaaError` and read +// `err.detail.kind`. +export { DaaError, isDaaError } from './errors' +export type { + AuthKeyResolution, + OwnerAuthKey, + OwnerKeyIdentity, + SecureKeyStore, +} from './securekey/SecureKey' + +// Exact-byte serialization utilities. +export { serializeBody, serializeEmptyBody } from './crypto/serialization' +export { toBase64Url, fromBase64Url } from './crypto/base64url' diff --git a/src/models/Account.ts b/src/models/Account.ts new file mode 100644 index 0000000..cf02d5f --- /dev/null +++ b/src/models/Account.ts @@ -0,0 +1,264 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { BusinessPii } from './BusinessPii' +import type { Money } from './Money' + +// The four closed-set fields on an account. +// +// Each is a discriminated union on `kind` — the shape `DaaSdkError` already uses +// in this SDK — rather than a string-literal union. A string-literal union has no +// room for the value the service will add next: decoding into one would either +// throw (leaving this SDK unable to read *any* account because one custody type +// was added service-side) or silently widen to `string`, which discards the +// closed set the type exists to express. +// +// An unfamiliar **present** value degrades to `unrecognized` **carrying the raw +// string**, per the SDK contract's requirement to preserve it "as an +// unknown/raw-value case instead of failing the entire response". Not failing is +// half of that; a bare `unknown` marker satisfies that half and throws away what +// arrived, leaving nobody able to answer why an account read as unknown. +// +// `rawValue` is `null` only where an absent field is tolerated, which is +// `custodyType` alone — see `Account`. + +/** + * How an account's keys are held. + * + * The OpenAPI marks `custodyType` as the discriminator for `Account` but supplies + * no `mapping`, and declares variant schemas for `omnibus` and `segregated` only + * — it omits the self-custody one entirely, so a client generated from it would + * produce a union with no arm for the custody type this SDK exists for. The + * service's responses do carry all three, including self-custody accounts, so + * the flat model here follows the service's responses rather than the schema. + */ +export type CustodyType = + | { readonly kind: 'omnibus' } + | { readonly kind: 'segregated' } + /** A non-custodial account: the device key authorizes custody changes. */ + | { readonly kind: 'self' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** What the account is for. */ +export type AccountPurpose = + | { readonly kind: 'custody' } + | { readonly kind: 'payments' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** Where the account is in its lifecycle. A created account starts `pending`. */ +export type AccountStatus = + | { readonly kind: 'active' } + | { readonly kind: 'pending' } + | { readonly kind: 'rejected' } + | { readonly kind: 'archived' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** Whether the account is held for the entity itself or on behalf of another. */ +export type AccountType = + | { readonly kind: 'first_party' } + | { readonly kind: 'third_party' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** The redacted shape `JSON.stringify(account)` produces. */ +export type AccountRendering = { + readonly accountId: string + readonly balances: string + readonly blockchain: string | null + readonly custodyType: CustodyType + readonly purpose: AccountPurpose + readonly status: AccountStatus + readonly type: AccountType +} + +/** + * A DAA account, as the service reports it. + * + * Read-only at runtime as well as in the type system: the instance is frozen and + * `balances` is a frozen array, because `readonly` is erased at compile time and + * would leave a returned account mutable through a cast. + * + * **Not constructible by a consumer.** This class is exported from `index.ts` as + * a **type only**, so no runtime constructor reaches the public entry, and the + * `#` private fields make the type nominal so an object literal cannot be typed + * as an `Account` either. Every instance a caller holds came from a response + * this SDK decoded — the same rule the error model follows, and for the same + * reason: code downstream treats these values as server-attributed. + * + * **Fields the service guarantees are non-null here.** A response missing one is + * reported as a `contract_violation` rather than decoded into an account with + * holes in it. Making everything nullable would turn a service defect into an SDK + * *success* and push the null handling onto every caller — a `200` with an empty + * body would arrive as a cheerful empty account. Tolerating unknown *additional* + * fields and preserving an unfamiliar *present* closed-set value are forward + * compatibility; accepting a missing required value is not. + * + * The guaranteed set comes from the service's own nullability contract — + * `accountId`, `balances`, `entityId`, `purpose`, `status`, and `type` are + * never null in what it serialises — and **not** from the OpenAPI's + * `required:` block. Nothing validates a response against that block, and it + * lists fields the service genuinely omits. + * + * **Balances and the receive address do not appear in any default rendering.** + * They sit behind prototype accessors rather than own properties, so + * `Object.keys`, `JSON.stringify`, `{ ...account }`, `for...in`, and the object + * inspectors behind `console.log` do not reach them; `toString` and `toJSON` + * reduce balances to a count and omit the rest. The service excludes the same + * fields from its own rendering. + * + * That is a control over *default* rendering, not a capability: an inspector + * explicitly asked to evaluate prototype accessors + * (`util.inspect(account, { showHidden: true, getters: true })`) reveals them, and + * a consumer reading `balances[0].amount` and logging it is doing so deliberately. + * What is prevented is a balance reaching a log by accident — through a crash + * reporter, a `console.log(account)`, or a `JSON.stringify` of a state tree. + */ +export class Account { + /** Service-assigned identifier. */ + readonly accountId: string + + /** + * The account's immutable home chain, as returned by the account API. + * + * A plain string because the SDK contract declares it `blockchain?: string` and + * new chains ship without an SDK release. `null` when the service sent none; + * the contract states DAA provisions on `ARC` when the field is omitted at + * creation, but that default is the service's to apply and is not invented + * here. Present on self-custody and segregated accounts. + */ + readonly blockchain: string | null + + /** Set only for a `self` custody type; identifies the entity whose keys hold the account. */ + readonly clientEntityId: string | null + + /** How the keys are held. `self` is a non-custodial account whose device key authorizes custody changes. */ + readonly custodyType: CustodyType + + /** + * Caller-supplied label, absent when none was set. + * + * Optional despite the OpenAPI listing it as required. The service treats + * this field as nullable, like `clientEntityId` and `groupId`, and the + * service creates accounts without a description. A response omitting it is + * ordinary, not malformed. + */ + readonly description: string | null + + /** The owning entity. */ + readonly entityId: string + + /** Nullable on the wire as well as absent — the contract marks it so. */ + readonly groupId: string | null + + readonly purpose: AccountPurpose + + readonly status: AccountStatus + + readonly type: AccountType + + readonly #balances: readonly Money[] + readonly #businessPii: BusinessPii | null + readonly #depositAddress: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly accountId: string + readonly balances: readonly Money[] + readonly blockchain: string | null + readonly businessPii: BusinessPii | null + readonly clientEntityId: string | null + readonly custodyType: CustodyType + readonly depositAddress: string | null + readonly description: string | null + readonly entityId: string + readonly groupId: string | null + readonly purpose: AccountPurpose + readonly status: AccountStatus + readonly type: AccountType + }) { + this.accountId = fields.accountId + this.blockchain = fields.blockchain + this.clientEntityId = fields.clientEntityId + this.custodyType = fields.custodyType + this.description = fields.description + this.entityId = fields.entityId + this.groupId = fields.groupId + this.purpose = fields.purpose + this.status = fields.status + this.type = fields.type + // The array is copied before freezing so the caller's own array is not + // frozen. The freeze itself is pinned by a test. + this.#balances = Object.freeze(fields.balances.slice()) + this.#businessPii = fields.businessPii + this.#depositAddress = fields.depositAddress + Object.freeze(this) + } + + /** Balances held, one entry per currency. Empty when the service sent none. */ + get balances(): readonly Money[] { + return this.#balances + } + + /** + * Business identity enrichment, on eligible omnibus reads only. + * + * Never present on a self-custody account. See `BusinessPii`. + */ + get businessPii(): BusinessPii | null { + return this.#businessPii + } + + /** + * The established receive address for a self-custody or segregated account. + * + * `null` until the provider mapping is active and complete, which is the + * service's own wording — an account can exist before it has a routable + * address, so absence is a state rather than an error. For a self-custody + * consumer this is the field the account is *for*. + */ + get depositAddress(): string | null { + return this.#depositAddress + } + + /** Identifiers and states render; values do not. */ + toJSON(): AccountRendering { + return { + accountId: this.accountId, + balances: `${this.#balances.length} entries`, + blockchain: this.blockchain, + custodyType: this.custodyType, + purpose: this.purpose, + status: this.status, + type: this.type, + } + } + + /** + * Identifiers and states print; values do not. + * + * `depositAddress` is excluded because it is the account's receive address, and + * balances are reduced to a count. `businessPii` is not referenced at all. + */ + toString(): string { + return ( + `Account(accountId=${this.accountId}, blockchain=${this.blockchain}, ` + + `custodyType=${this.custodyType.kind}, purpose=${this.purpose.kind}, ` + + `status=${this.status.kind}, type=${this.type.kind}, ` + + `balances=${this.#balances.length} entries)` + ) + } +} diff --git a/src/models/AccountLimitsUsage.ts b/src/models/AccountLimitsUsage.ts new file mode 100644 index 0000000..1f3c75a --- /dev/null +++ b/src/models/AccountLimitsUsage.ts @@ -0,0 +1,192 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// An account's limits and their current usage, as +// `GET /v1/accounts/{accountId}/limits/usage` reports it. +// +// The public API reference +// (https://developers.circle.com/api-reference/digital-asset-accounts/all/list-account-limits-usage) +// is this model's source of truth. +// +// Every closed-set field below follows the same discriminated-union-on-`kind` +// shape the rest of this SDK uses (`Account`'s four closed-set fields, +// `Deposit`'s status/type/rail): an unfamiliar *present* value degrades to +// `unrecognized` rather than failing the whole response, because a client +// cannot prove the service will never add a tenth `operation` or a third +// `window`. + +/** The nine operations the public reference names for `operation`. */ +export type LimitsUsageOperation = + | { readonly kind: 'deposit' } + | { readonly kind: 'withdrawal' } + | { readonly kind: 'receive' } + | { readonly kind: 'send' } + | { readonly kind: 'send_count' } + | { readonly kind: 'address_linking' } + | { readonly kind: 'fiat_linking' } + | { readonly kind: 'deposit_return_count' } + | { readonly kind: 'balance_cap' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +export type LimitsUsageAssetType = + | { readonly kind: 'fiat' } + | { readonly kind: 'crypto' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * Whether an item's `effectiveThreshold` is a per-transaction ceiling or a + * rolling-window aggregate. Only an `aggregation` item carries `window`, + * `currentAggregate`, or `usagePercent` — see `AccountLimitsUsageItem`. + */ +export type LimitsUsageComparisonType = + | { readonly kind: 'transaction' } + | { readonly kind: 'aggregation' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** The unit `effectiveThreshold`/`currentAggregate` are denominated in. */ +export type LimitsUsageUnit = + | { readonly kind: 'usd_cents' } + | { readonly kind: 'count' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** The ISO 8601 rolling-window duration an `aggregation` item's threshold applies over. */ +export type LimitsUsageWindow = + | { readonly kind: 'PT24H' } + | { readonly kind: 'P30D' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * The envelope's `type` discriminator. The public reference documents exactly + * one value (`limitsUsage`); an unfamiliar one degrades to + * `unrecognized` rather than failing the read, the same posture every other + * closed-set field on this model takes. + */ +export type AccountLimitsUsageResourceType = + | { readonly kind: 'limitsUsage' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * One limit/usage row for an `operation` x `assetType` pair. + * + * `window`, `currentAggregate`, and `usagePercent` are present **only** on a + * `comparisonType: 'aggregation'` item; a `comparisonType: 'transaction'` item + * typically omits all three, per the public reference's own example (a + * transaction-limit row carries none of them). None of the three is required + * on every item — requiring them would reject the transaction-limit rows the + * service actually sends. + * + * `effectiveThreshold` and `currentAggregate` are the documented units + * unconverted: a `usd_cents` value stays whole USD cents, and a `count` value + * stays a whole-number count. Converting `usd_cents` to dollars here would + * silently disagree with the wire value a caller can independently verify + * against the public API response. + */ +export type AccountLimitsUsageItem = Readonly<{ + operation: LimitsUsageOperation + assetType: LimitsUsageAssetType + comparisonType: LimitsUsageComparisonType + /** Present only for a rolling-window (`aggregation`) limit. */ + window: LimitsUsageWindow | null + unit: LimitsUsageUnit + /** Whole USD cents for `usd_cents`, a whole count for `count`. Never negative. */ + effectiveThreshold: number + /** Present only for an `aggregation` limit. Same unit as `effectiveThreshold`. Never negative. */ + currentAggregate: number | null + /** Present only for an `aggregation` limit. A percentage (0-100+), not a fraction. Never negative. */ + usagePercent: number | null +}> + +/** The shape `JSON.stringify(accountLimitsUsage)` produces. Nothing here is redacted — see the class note. */ +export type AccountLimitsUsageRendering = { + readonly type: AccountLimitsUsageResourceType + readonly accountId: string + readonly currency: string + readonly watermark: string + readonly items: readonly AccountLimitsUsageItem[] +} + +/** + * An account's limits and current usage, as the SDK contract's + * `AccountLimitsClient.get` result. + * + * **Not redacted.** Unlike `Money.amount`, `FiatAccount`'s `billingDetails`/ + * `bankAddress`, or a deposit's external references, nothing here falls under + * the SDK's restricted-PII redaction rules or any comparable rule: these are + * threshold/usage figures for the account's own limits, not a transaction + * amount, a balance, or bank/PII detail. So every field is an ordinary own + * property and the default `toJSON`/`toString` render all of them, the same + * posture `Page` takes for its (non-sensitive) `items`. + * + * **Every field the public reference documents on `data` is guaranteed** + * (`type`, `accountId`, `currency`, `watermark`, `items`); a response missing + * one is a `contract_violation` rather than a value with holes in it, the same + * rule every other model in this SDK applies. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#items` private field makes the type nominal. + */ +export class AccountLimitsUsage { + readonly type: AccountLimitsUsageResourceType + readonly accountId: string + readonly currency: string + /** "Freshness boundary for aggregate values" (public reference), as RFC 3339 text. */ + readonly watermark: string + + readonly #items: readonly AccountLimitsUsageItem[] + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly type: AccountLimitsUsageResourceType + readonly accountId: string + readonly currency: string + readonly watermark: string + readonly items: readonly AccountLimitsUsageItem[] + }) { + this.type = fields.type + this.accountId = fields.accountId + this.currency = fields.currency + this.watermark = fields.watermark + // Sliced before freezing, like `Account#balances`: freezing in place would + // also freeze an array the caller (the wire mapper) still holds a + // reference to. + this.#items = Object.freeze(fields.items.slice()) + Object.freeze(this) + } + + /** One row per `operation` x `assetType` pair the service reports. */ + get items(): readonly AccountLimitsUsageItem[] { + return this.#items + } + + toJSON(): AccountLimitsUsageRendering { + return { + type: this.type, + accountId: this.accountId, + currency: this.currency, + watermark: this.watermark, + items: this.#items, + } + } + + toString(): string { + return ( + `AccountLimitsUsage(accountId=${this.accountId}, currency=${this.currency}, ` + + `watermark=${this.watermark}, items=${this.#items.length} entries)` + ) + } +} diff --git a/src/models/Ach.ts b/src/models/Ach.ts new file mode 100644 index 0000000..584bb62 --- /dev/null +++ b/src/models/Ach.ts @@ -0,0 +1,269 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BankAddress, BillingDetails } from './FiatAccount' +import type { FiatAccountStatus } from './FiatAccount' +import { REDACTED } from './redaction' + +// `ACH` and `ACHInstruction` follow the component naming of the canonical +// public Accounts OpenAPI's wire schemas, not DAA-owned aliases. +// +// The public Accounts OpenAPI does not publish an ACH schema, so these field +// names are inferred: they mirror `Wire`'s own shape. The ACH beneficiary bank +// is `name`/`accountNumber`/`routingNumber`/`address`/`city`/`country`/ +// `postalCode` — no `swiftCode` or `currency`, unlike wire's beneficiary bank, +// because ACH is a domestic-only rail. The one field beyond the wire mirror, +// `ACH.routingNumber`, carries the account's routing information: fiat-account +// list and get responses contain restricted PII, including billing details +// and, **for ACH, routing information**, on the ACH resource itself and not +// only inside its instructions. Check these names against the public ACH +// schema once one is published. + +/** + * Circle's own receiving identity on an ACH instruction. Not redacted, for the + * same reason `WireInstructionBeneficiary` is not — see that type's doc. + */ +export type ACHInstructionBeneficiary = Readonly<{ + name: string | null + address1: string | null + address2: string | null +}> + +/** + * The receiving bank's own account details for an ACH instruction — + * `routingNumber` and `accountNumber` among them, which are restricted for + * ACH. Redacted the same way `WireInstructionBeneficiaryBank` is. No + * `swiftCode`/`currency`: ACH is a domestic US rail (see the file header). + */ +export class ACHInstructionBeneficiaryBank { + readonly #name: string | null + readonly #routingNumber: string | null + readonly #accountNumber: string | null + readonly #address: string | null + readonly #city: string | null + readonly #postalCode: string | null + readonly #country: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly name: string | null + readonly routingNumber: string | null + readonly accountNumber: string | null + readonly address: string | null + readonly city: string | null + readonly postalCode: string | null + readonly country: string | null + }) { + this.#name = fields.name + this.#routingNumber = fields.routingNumber + this.#accountNumber = fields.accountNumber + this.#address = fields.address + this.#city = fields.city + this.#postalCode = fields.postalCode + this.#country = fields.country + Object.freeze(this) + } + + get name(): string | null { + return this.#name + } + + get routingNumber(): string | null { + return this.#routingNumber + } + + get accountNumber(): string | null { + return this.#accountNumber + } + + get address(): string | null { + return this.#address + } + + get city(): string | null { + return this.#city + } + + get postalCode(): string | null { + return this.#postalCode + } + + get country(): string | null { + return this.#country + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `ACHInstructionBeneficiaryBank(${REDACTED})` + } +} + +/** + * Circle receiving instructions for an ACH fiat account (`GET + * /v1/banks/ach/{id}/instructions`). + * + * Deliberately a separate SDK method and response type from {@link ACH} — see + * {@link import('./Wire').WireInstruction}'s doc, which states the same rule + * for wire. Also a plain typed read of the public route for the same reason: + * no self-custody pass-through-account resolution happens here, and the ACH + * route has no public `accountId` parameter to resolve one with. + */ +export class ACHInstruction { + readonly trackingRef: string | null + readonly beneficiary: ACHInstructionBeneficiary | null + + readonly #beneficiaryBank: ACHInstructionBeneficiaryBank | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + trackingRef: string | null + beneficiary: ACHInstructionBeneficiary | null + beneficiaryBank: ACHInstructionBeneficiaryBank | null + }) { + this.trackingRef = fields.trackingRef + this.beneficiary = fields.beneficiary + this.#beneficiaryBank = fields.beneficiaryBank + Object.freeze(this) + } + + get beneficiaryBank(): ACHInstructionBeneficiaryBank | null { + return this.#beneficiaryBank + } + + toJSON(): { + trackingRef: string | null + beneficiary: ACHInstructionBeneficiary | null + beneficiaryBank: string | null + } { + return { + trackingRef: this.trackingRef, + beneficiary: this.beneficiary, + beneficiaryBank: this.#beneficiaryBank === null ? null : REDACTED, + } + } + + toString(): string { + return ( + `ACHInstruction(trackingRef=${this.trackingRef ?? 'null'}, ` + + `beneficiaryBank=${this.#beneficiaryBank === null ? 'null' : REDACTED})` + ) + } +} + +/** + * An ACH fiat account. This single type serves both `ach.list()` and + * `ach.get()`: the list returns the full `ACH` projection for consistency with + * the by-id read, unlike wire's separate `WireSummary`/`Wire` list/get pair. + * + * `billingDetails`, `bankAddress`, and `routingNumber` are private, redacted + * fields — all three are restricted for ACH. See the file header for + * `routingNumber`. + */ +export class ACH { + readonly id: string + readonly type: string | null + readonly status: FiatAccountStatus + readonly description: string + readonly trackingRef: string + readonly fingerprint: string + readonly createDate: string + readonly updateDate: string + + readonly #billingDetails: BillingDetails + readonly #bankAddress: BankAddress | null + readonly #routingNumber: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: BillingDetails + bankAddress: BankAddress | null + routingNumber: string | null + createDate: string + updateDate: string + }) { + this.id = fields.id + this.type = fields.type + this.status = fields.status + this.description = fields.description + this.trackingRef = fields.trackingRef + this.fingerprint = fields.fingerprint + this.createDate = fields.createDate + this.updateDate = fields.updateDate + this.#billingDetails = fields.billingDetails + this.#bankAddress = fields.bankAddress + this.#routingNumber = fields.routingNumber + Object.freeze(this) + } + + get billingDetails(): BillingDetails { + return this.#billingDetails + } + + get bankAddress(): BankAddress | null { + return this.#bankAddress + } + + get routingNumber(): string | null { + return this.#routingNumber + } + + toJSON(): { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: string + bankAddress: string | null + routingNumber: string | null + createDate: string + updateDate: string + } { + return { + id: this.id, + type: this.type, + status: this.status, + description: this.description, + trackingRef: this.trackingRef, + fingerprint: this.fingerprint, + billingDetails: REDACTED, + bankAddress: this.#bankAddress === null ? null : REDACTED, + routingNumber: this.#routingNumber === null ? null : REDACTED, + createDate: this.createDate, + updateDate: this.updateDate, + } + } + + toString(): string { + return ( + `ACH(id=${this.id}, status=${this.status.kind}, billingDetails=${REDACTED}, ` + + `bankAddress=${this.#bankAddress === null ? 'null' : REDACTED}, ` + + `routingNumber=${this.#routingNumber === null ? 'null' : REDACTED})` + ) + } +} diff --git a/src/models/AddressObject.ts b/src/models/AddressObject.ts new file mode 100644 index 0000000..bc924c6 --- /dev/null +++ b/src/models/AddressObject.ts @@ -0,0 +1,169 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { REDACTED } from './redaction' + +/** The redacted shape `JSON.stringify(addressObject)` produces. */ +export type AddressObjectRendering = { + readonly id: string + readonly address: string + readonly addressTag: string | null + readonly currency: string | null + readonly chain: string + readonly accountId: string | null +} + +/** + * A DAA deposit address, as the service reports it + * (`GET /v1/accounts/addresses/deposit/{depositId}`; the `AddressObject` + * response). + * + * **This model exists to carry a blockchain receive address, and that is the + * field an SDK for self-custody DAA accounts must guard hardest.** `address` + * and `addressTag` sit behind prototype accessors over `#` private fields + * rather than own properties — the same technique `Account` uses for + * `depositAddress` and `Money` uses for `amount` — so `Object.keys`, + * `JSON.stringify`, `{ ...addressObject }`, `for...in`, and the object + * inspectors behind `console.log` cannot reach them. `toJSON`/`toString` say + * the value was withheld rather than omitting it silently — the same choice + * `Money` makes, and for the same reason: a caller who logs an address object + * should see that a receive address exists and was not printed, not get back + * an object that quietly has one field fewer. + * + * **Fields the service guarantees are non-null here: `id`, `address`, and + * `chain`.** That set comes from how the service builds an address for each of + * its three custody sources — omnibus, segregated, and self — and **not** from + * the schema, which names only `addressTag` as nullable. The guarantee is + * narrower than the schema implies: + * + * - `addressTag` is genuinely optional: a real value from the omnibus source, + * always `null` from segregated and self, matching its documented role as a + * memo/destination tag. + * - **`currency` is `null` on every segregated and self-custody *read*.** Both + * sources report a real value only on `create`, which this SDK does not call + * here. Only the omnibus source ever returns a real currency from a read. A + * model that trusted the schema's silence and made `currency` required would + * fail to decode most segregated/self-custody address reads. + * - `accountId` can be `null`: the omnibus source can return an address it + * cannot attribute to an account, which is a state to tolerate, not a + * defect. + * + * A response missing `id`, `address`, or `chain` is reported as a + * `contract_violation` rather than decoded into an address with a hole in it + * — see `wire/addressObjectPayload.ts`. + * + * **`currency` and `chain` are plain strings, not closed unions,** for the + * same reason `Account.blockchain` and `Money.currency` are: both bind to the + * service's shared chain and currency types, which are large and + * grow independently of an SDK release, so modelling them as a closed set + * this SDK controls would reject a real, valid value the day the service adds + * one. This is a deliberate difference from `CustodyType`/`AccountPurpose`/ + * `AccountStatus`/`AccountType`, the small business-state enums this SDK does + * discriminate on (see `wire/wireEnums.ts`) — `AddressObject` has no field of + * that shape. + * + * **Not constructible by a consumer.** Exported from `index.ts` as a type + * only, so no runtime constructor reaches the public entry, and the `#` + * private fields make the type nominal so an object literal cannot be typed + * as an `AddressObject` either. Frozen at construction for the same reason + * `Account` is: `readonly` is erased at compile time and would leave a + * returned address mutable through a cast. + */ +export class AddressObject { + /** Service-assigned identifier for this address record. */ + readonly id: string + + /** + * Currency the address accepts. `null` on every segregated and + * self-custody read — see the class note. Not sensitive; not redacted. + */ + readonly currency: string | null + + /** Chain the address is on. Not sensitive; not redacted. */ + readonly chain: string + + /** + * The DAA account this address belongs to. `null` only when the omnibus + * source cannot attribute the address to an account — see the class note. Not sensitive; not + * redacted. + */ + readonly accountId: string | null + + readonly #address: string + readonly #addressTag: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly id: string + readonly address: string + readonly addressTag: string | null + readonly currency: string | null + readonly chain: string + readonly accountId: string | null + }) { + this.id = fields.id + this.currency = fields.currency + this.chain = fields.chain + this.accountId = fields.accountId + this.#address = fields.address + this.#addressTag = fields.addressTag + Object.freeze(this) + } + + /** + * The blockchain receive address. This is the field the SDK exists to + * report and the one it guards hardest — see the class note. + */ + get address(): string { + return this.#address + } + + /** + * Secondary on-chain identifier (e.g. a Stellar memo or destination tag). + * `null` when the chain or custody source has none — see the class note. + * Redacted the same way `address` is: it is a crypto identifier too. + */ + get addressTag(): string | null { + return this.#addressTag + } + + /** + * Identifiers and states render; the address and its tag say only that + * they were withheld — `null` renders as `null` rather than a redaction + * marker, since there is nothing to redact from an address with no tag. + */ + toJSON(): AddressObjectRendering { + return { + id: this.id, + address: REDACTED, + addressTag: this.#addressTag === null ? null : REDACTED, + currency: this.currency, + chain: this.chain, + accountId: this.accountId, + } + } + + /** Identifiers and states print; the address and its tag do not. */ + toString(): string { + return ( + `AddressObject(id=${this.id}, chain=${this.chain}, currency=${this.currency}, ` + + `accountId=${this.accountId}, address=${REDACTED}, ` + + `addressTag=${this.#addressTag === null ? null : REDACTED})` + ) + } +} diff --git a/src/models/BusinessPii.ts b/src/models/BusinessPii.ts new file mode 100644 index 0000000..5000b00 --- /dev/null +++ b/src/models/BusinessPii.ts @@ -0,0 +1,154 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { REDACTED } from './redaction' + +/** + * A postal address, as the DAA API reports it. + * + * Every field is optional. The OpenAPI marks several required, but the service + * populates them best-effort from customer records — an absent source attribute + * simply leaves the field null — and omits nulls from the JSON. Requiring any of + * them would make an account with incomplete enrichment fail to read at all. + * + * **Nothing is rendered.** Every field is identity data, so all of them sit + * behind prototype accessors rather than own properties: `Object.keys`, + * `{ ...address }`, `for...in`, and the inspectors behind `console.log` see an + * empty object, and `toJSON` returns a redaction marker so `JSON.stringify` does + * too. A rendering exists so a log line naming the type is still useful, not so + * the address travels with it. + */ +export class Address { + readonly #city: string | null + readonly #country: string | null + readonly #district: string | null + readonly #line1: string | null + readonly #line2: string | null + readonly #postalCode: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly city: string | null + readonly country: string | null + readonly district: string | null + readonly line1: string | null + readonly line2: string | null + readonly postalCode: string | null + }) { + this.#city = fields.city + this.#country = fields.country + this.#district = fields.district + this.#line1 = fields.line1 + this.#line2 = fields.line2 + this.#postalCode = fields.postalCode + Object.freeze(this) + } + + get city(): string | null { + return this.#city + } + + get country(): string | null { + return this.#country + } + + get district(): string | null { + return this.#district + } + + get line1(): string | null { + return this.#line1 + } + + get line2(): string | null { + return this.#line2 + } + + get postalCode(): string | null { + return this.#postalCode + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `Address(${REDACTED})` + } +} + +/** + * Business identity enrichment attached to an account. + * + * The service sends this only on eligible omnibus read responses — the contract + * scopes it to `first_party` attributed accounts with `payments` purpose, absent + * on create, archive, segregated, and ineligible responses. It is therefore + * never present on the self-custody accounts this SDK exists for, and a consumer + * should expect `null` in practice. + * + * It is modelled rather than discarded because the endpoint this SDK calls + * returns it, and silently dropping a field the service sent would hide it + * from the caller. + * + * Redacted the same way [Address] is, and for the same reason. The service + * excludes the same field from its own rendering. + */ +export class BusinessPii { + readonly #address: Address | null + readonly #businessName: string | null + readonly #businessUniqueIdentifier: string | null + readonly #identifierIssuingCountryCode: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly address: Address | null + readonly businessName: string | null + readonly businessUniqueIdentifier: string | null + readonly identifierIssuingCountryCode: string | null + }) { + this.#address = fields.address + this.#businessName = fields.businessName + this.#businessUniqueIdentifier = fields.businessUniqueIdentifier + this.#identifierIssuingCountryCode = fields.identifierIssuingCountryCode + Object.freeze(this) + } + + get address(): Address | null { + return this.#address + } + + get businessName(): string | null { + return this.#businessName + } + + get businessUniqueIdentifier(): string | null { + return this.#businessUniqueIdentifier + } + + get identifierIssuingCountryCode(): string | null { + return this.#identifierIssuingCountryCode + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `BusinessPii(${REDACTED})` + } +} diff --git a/src/models/CreateAccountRequest.ts b/src/models/CreateAccountRequest.ts new file mode 100644 index 0000000..5a3f644 --- /dev/null +++ b/src/models/CreateAccountRequest.ts @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The body of a signed account create. +// +// **Shaped from the Owner-authorization registry, not from the OpenAPI.** The +// digest-pinned registry is what DAA validates the signed bytes against, +// property by property, with `additionalProperties: false`; the OpenAPI +// describes what the HTTP endpoint documents. Where the two disagree the registry decides what +// may be sent, because a body the registry rejects never reaches the endpoint +// the OpenAPI describes. +// +// They do disagree here, in more than one place worth naming. The registry's +// `create_account` schema lists `clientEntityId` as an optional property, +// while the contract's `SelfCustodyAccountCreationRequest` marks it required, +// and a non-custodial account requires it outright — resolved by the consuming +// application's authenticated backend, included in the exact signed body, and +// checked against the active Owner binding before anything else persists. +// Since the registry pins `custodyType` to the single value `self`, every +// signed create is a self-custody create, which is exactly the shape the +// contract requires it on. So it is required in this type: the registry +// describes the outer bound of what DAA would accept, not what a +// conforming SDK should send, and this SDK holds itself to the stricter rule +// rather than the more permissive one. +// +// `type` and `purpose` follow the identical pattern. The registry's +// `create_account` schema types both as open strings, but the contract's +// `SelfCustodyAccountCreationRequest` narrows each to the single literal a +// self-custody create can carry — `third_party` and `custody` — and DAA rejects +// any other value outright. Since this type is exclusively the self-custody +// create body, it holds itself to the contract's single literal for each rather +// than the registry's wider set. +// +// `blockchain` is optional, and this SDK does not require it: DAA selects the +// home chain when it is omitted and provisions on `ARC`. The registry types it +// as a plain optional string, and the public API docs document it as optional. + +/** + * Body for creating a self-custody DAA account. + * + * Every field is checked before the body is serialized, and the serialized + * bytes are the ones signed and sent. An unrecognized property is rejected + * rather than dropped: the registry schema refuses additional properties, so a + * misspelled `blockChain` is a request DAA would reject, and silently + * discarding it would instead create an account on the wrong home chain. + */ +export type CreateAccountRequest = Readonly<{ + /** + * Identifies this account-creation attempt. Persist it before sending and + * never reuse it with different body bytes — the authorization JWS carries + * this same value as its `idempotency_key` claim, so a reused key with + * changed bytes is a different signed request under an old identity. + */ + idempotencyKey: string + /** + * The end-user sub-entity the account is for. Required: the registry itself + * would admit omitting it, but the public contract requires it for a + * self-custody create, and DAA checks it against the active Owner binding + * before anything persists. See the file note. + */ + clientEntityId: string + /** The registry admits one value: this is the self-custody create. */ + custodyType: 'self' + /** + * Whether the account is held for the entity itself or on behalf of + * another. The registry types this as an open string, but the contract + * narrows a self-custody create to the single literal `third_party` — + * non-custodial accounts are always end-user accounts — and DAA rejects + * any other value. See the file note. + */ + type: 'third_party' + /** + * What the account is for. The registry types this as an open string, but + * the contract narrows a self-custody create to the single literal + * `custody`, and DAA rejects any other value. See the file note. + */ + purpose: 'custody' + /** + * Caller-supplied label. Required by the registry, and so never omitted. + * The contract caps it at 255 characters; this SDK checks that bound + * locally so an oversized label fails before a device-authorization + * ceremony and idempotency key are spent on a request the service would + * reject anyway. + */ + description: string + /** + * The account's immutable home chain. Optional: DAA resolves and persists + * `ARC` when it is omitted, and that default is the service's to apply + * rather than one this SDK sends on its behalf. See the file note. A plain + * string rather than a closed set, matching `Account.blockchain`: the + * registry types it `string`, and new chains ship without an SDK release. + */ + blockchain?: string +}> diff --git a/src/models/CreateTransferRequest.ts b/src/models/CreateTransferRequest.ts new file mode 100644 index 0000000..9e59e56 --- /dev/null +++ b/src/models/CreateTransferRequest.ts @@ -0,0 +1,114 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The body of a signed transfer create. +// +// Shaped from the Owner-authorization registry rather than the OpenAPI, for the +// reason `CreateAccountRequest` sets out: the registry is what DAA +// validates the signed bytes against, so it decides what may be sent. +// +// These are **request** legs and are deliberately not the response legs in +// `models/Transfer.ts`. The two taxonomies differ, and reusing one for the +// other would be wrong in both directions: a request destination is +// `account` or `verified_blockchain`, while a decoded transfer's destination is +// `account` or `blockchain` (the service folds `verified_blockchain` into +// `blockchain` on the way out, since the public read taxonomy has no verified +// form). A request leg also carries no address, chain, or tag — it names a +// destination, it does not describe one — so nothing here needs the redaction +// the response legs are built around. + +/** + * The account a transfer draws from. + * + * The registry admits only an account source. Omitted, DAA resolves the + * effective source itself and still requires its Owner to match the registered + * credential, so leaving it out is not a way to move someone else's funds. + */ +export type CreateTransferSource = Readonly<{ + type: 'account' + /** Public account id. Account ids are strings, including numeric ones. */ + id: string +}> + +/** + * Where a transfer sends funds: another DAA account, or a verified blockchain + * address already registered with DAA. + * + * A `oneOf` in the registry, so exactly one arm must match — the two carry + * disjoint required properties (`id` against `addressId`) and neither admits + * additional ones, which is what makes "exactly one" decidable. + */ +export type CreateTransferDestination = + | Readonly<{ + type: 'account' + /** Public account id. Account ids are strings, including numeric ones. */ + id: string + }> + | Readonly<{ + type: 'verified_blockchain' + /** The registered address's id, which the registry types as a UUID. */ + addressId: string + }> + +/** + * The amount to transfer. + * + * `amount` is a decimal **string**, not a number, for the reason `Money` + * documents on the way in: JavaScript has one number type and it is an + * IEEE-754 double, so a large or long amount written as a numeric literal is + * rounded by `JSON.stringify` before anything can see it — and these are the + * exact bytes that get signed, so the rounded value is what the Owner would be + * authorizing. The registry's `decimal` type accepts a JSON string or a JSON + * number, so the string form is not a workaround. + */ +export type CreateTransferAmount = Readonly<{ + /** Exact decimal literal, e.g. `"10.25"`. */ + amount: string + /** ISO 4217 code. Not a closed set here — see `Money`. */ + currency: string +}> + +/** Optional caller-supplied risk context. The registry requires none of it. */ +export type CreateTransferRiskSignals = Readonly<{ + ipAddress?: string + sessionId?: string + deviceId?: string +}> + +/** + * Body for creating a transfer. + * + * Every field is checked before the body is serialized, and the serialized + * bytes are the ones signed and sent. An unrecognized property is rejected + * rather than dropped, at every level of the body — the registry schema + * refuses additional properties on the request and on each of its nested + * objects. + */ +export type CreateTransferRequest = Readonly<{ + /** + * Identifies this transfer attempt. Persist it before sending and never reuse + * it with different body bytes — the authorization JWS carries this same + * value as its `idempotency_key` claim. + */ + idempotencyKey: string + /** Omitted lets DAA resolve the source; see {@link CreateTransferSource}. */ + source?: CreateTransferSource + destination: CreateTransferDestination + amount: CreateTransferAmount + riskSignals?: CreateTransferRiskSignals +}> diff --git a/src/models/CreateWithdrawalRequest.ts b/src/models/CreateWithdrawalRequest.ts new file mode 100644 index 0000000..8702118 --- /dev/null +++ b/src/models/CreateWithdrawalRequest.ts @@ -0,0 +1,120 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The body of a signed withdrawal create. +// +// Shaped from the Owner-authorization registry rather than the OpenAPI, for the +// reason `CreateAccountRequest` and `CreateTransferRequest` set out: the +// digest-pinned registry is what DAA validates the signed bytes against, so it +// decides what may be sent. +// +// One place they disagree, worth naming: the public OpenAPI's +// `FiatPayoutToMoney.amount` (`toAmount.amount`) is `readOnly`, describing a +// value the service computes on read. The registry's `toAmount` schema names +// `amount` as an ordinary optional property of the signed request body, with no +// such marker. The registry wins for signed bytes — refusing it locally would +// reject a body DAA accepts, and a service that does not want a +// caller-supplied conversion amount answers on its own terms. + +/** + * The account a withdrawal draws from. + * + * The registry admits only an account source. Omitted, DAA resolves the + * effective source itself and still requires its Owner to match the registered + * credential, so leaving it out is not a way to move someone else's funds. See + * `CreateTransferSource`, which this mirrors. + */ +export type CreateWithdrawalSource = Readonly<{ + type: 'account' + /** Public account id. Account ids are strings, including numeric ones. */ + id: string +}> + +/** + * The bank destination a withdrawal pays out to: a registered wire or ACH fiat + * account. + */ +export type CreateWithdrawalDestination = Readonly<{ + type: 'wire' | 'ach' + /** The registered fiat account's id, which the registry types as a UUID. */ + id: string + /** Caller-supplied label for the destination. */ + name?: string +}> + +/** + * The amount to withdraw. + * + * `amount` is a decimal **string**, not a number, for the reason `Money` and + * `CreateTransferAmount` document: JavaScript has one number type and it is an + * IEEE-754 double, so a numeric literal is rounded by `JSON.stringify` before + * anything can see it — and these are the exact bytes that get signed, so the + * rounded value is what the Owner would be authorizing. + */ +export type CreateWithdrawalAmount = Readonly<{ + /** Exact decimal literal, e.g. `"10.25"`. */ + amount: string + /** ISO 4217 code. Not a closed set here — see `Money`. */ + currency: string +}> + +/** + * A target fiat amount for a cross-currency payout. + * + * The registry requires only `currency`; `amount` is optional and, unlike + * {@link CreateWithdrawalAmount.amount}, may be omitted to let DAA resolve the + * converted amount itself. + */ +export type CreateWithdrawalToAmount = Readonly<{ + /** Exact decimal literal. Omitted lets DAA compute the converted amount. */ + amount?: string + currency: 'USD' | 'EUR' +}> + +/** Optional caller-supplied risk context. The registry requires none of it. */ +export type CreateWithdrawalRiskSignals = Readonly<{ + ipAddress?: string + sessionId?: string + deviceId?: string +}> + +/** + * Body for creating a withdrawal. + * + * Every field is checked before the body is serialized, and the serialized + * bytes are the ones signed and sent. An unrecognized property is rejected + * rather than dropped, at every level of the body — the registry schema + * refuses additional properties on the request and on each of its nested + * objects. + */ +export type CreateWithdrawalRequest = Readonly<{ + /** + * Identifies this withdrawal attempt. Persist it before sending and never + * reuse it with different body bytes — the authorization JWS carries this + * same value as its `idempotency_key` claim. + */ + idempotencyKey: string + /** Omitted lets DAA resolve the source; see {@link CreateWithdrawalSource}. */ + source?: CreateWithdrawalSource + destination: CreateWithdrawalDestination + amount: CreateWithdrawalAmount + toAmount?: CreateWithdrawalToAmount + riskSignals?: CreateWithdrawalRiskSignals + /** Sweep the full source balance. DAA defaults this to `false` when omitted. */ + burnAll?: boolean +}> diff --git a/src/models/DaaUserContext.ts b/src/models/DaaUserContext.ts new file mode 100644 index 0000000..a53fb55 --- /dev/null +++ b/src/models/DaaUserContext.ts @@ -0,0 +1,172 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isUuid } from '../validation/uuid' +import { contractViolation } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' + +/** RFC 7638 P-256 JWK thumbprints are 32-byte unpadded Base64URL digests. */ +const JWK_THUMBPRINT = /^[A-Za-z0-9_-]{43}$/ + +/** + * Owner-bound local SDK context: `DaaUserContext`. + * + * Produced only by an `ACTIVE` Device Registration Complete. It is not a DAA + * bearer token or an application session. The `#` private field makes the type + * nominal: an object literal cannot be typed or passed as one, so `forUser` + * cannot be opened with a fabricated context. The constructor is also brand- + * gated (see `DECODER_TOKEN` below), so holding one real context does not let + * a caller reach the class through `ctx.constructor` and mint another for a + * different Owner. + * + * Not constructible by a consumer: exported from `index.ts` as a type only. + */ +export type DeviceContext = Readonly<{ + deviceCredentialStatus: 'active' + ownerBindingId: string + authKeyId: string + /** + * When the context was resolved, as ISO-8601 text. The decoder also accepts + * the epoch-millisecond form the service sends for this timestamp and + * normalises it here, so a consumer never sees the wire's disagreement. + */ + resolvedAt: string +}> + +/** + * Brands the constructor, not just the instance. `isActiveDaaUserContext`'s + * `instanceof` plus its read of `#active` stops a consumer-fabricated object + * literal, but not the class itself: any code holding one real + * `DaaUserContext` can still reach `DaaUserContext` via `ctx.constructor` and + * call it directly, with no import of this module at all. Requiring this + * exact `Symbol` as the constructor's first argument closes that path — + * `ctx.constructor` is reachable, but constructing anything with it throws + * unless the caller already holds this token, and the only two places that do + * are the decoder call sites below and in `../wire/deviceRegistrationResultPayload.ts`. + * + * Exported so those wire decoders can import it, but never re-exported from + * `index.ts` — the package's `exports` map has no entry for this module's + * path, so a consuming application cannot import it either. + */ +export const DECODER_TOKEN: unique symbol = Symbol('daa.context') + +/** Internal storage: the binding must not become part of the public context shape. */ +const AUTH_KEY_THUMBPRINTS = new WeakMap() + +export class DaaUserContext { + readonly clientEntityId: string + readonly deviceContext: DeviceContext + readonly #active: true + + /** + * @internal Constructed only by this module and the Device Registration + * Complete decoder, which are the only code paths able to supply `token`. + */ + constructor( + token: symbol, + fields: { readonly clientEntityId: string; readonly deviceContext: DeviceContext }, + /** @internal Set only after Complete pairs the response with its local AuthKey. */ + authKeyThumbprint?: string, + ) { + if (token !== DECODER_TOKEN) { + throw contractViolation('DaaUserContext must be constructed by the DAA decoder') + } + if (!isUuid(fields.clientEntityId)) { + throw contractViolation('DaaUserContext.clientEntityId must be a UUID') + } + // Re-checked here rather than only trusted from the wire decoder: this + // constructor is the sole gate the brand above funnels every caller + // through, so the invariants the decoder happens to also enforce should + // hold no matter which of its call sites reaches this point. + if (fields.deviceContext.deviceCredentialStatus !== 'active') { + throw contractViolation('DaaUserContext.deviceContext.deviceCredentialStatus must be active') + } + if (!isUuid(fields.deviceContext.authKeyId)) { + throw contractViolation('DaaUserContext.deviceContext.authKeyId must be a UUID') + } + if (authKeyThumbprint !== undefined && !JWK_THUMBPRINT.test(authKeyThumbprint)) { + throw contractViolation('DaaUserContext AuthKey thumbprint is malformed') + } + this.clientEntityId = fields.clientEntityId + this.deviceContext = Object.freeze({ + deviceCredentialStatus: fields.deviceContext.deviceCredentialStatus, + ownerBindingId: fields.deviceContext.ownerBindingId, + authKeyId: fields.deviceContext.authKeyId, + resolvedAt: fields.deviceContext.resolvedAt, + }) + this.#active = true + if (authKeyThumbprint !== undefined) { + AUTH_KEY_THUMBPRINTS.set(this, authKeyThumbprint) + } + Object.freeze(this) + } + + /** @internal */ + isActive(): boolean { + return this.#active + } +} + +/** + * Pair an ACTIVE server context with the AuthKey that authorized Complete. + * + * The server-assigned `authKeyId` remains the JWS `kid`; the thumbprint is a + * local, non-enumerable guard that prevents a later key resolution from being + * silently paired with that server identifier. The returned context is a new + * branded value because contexts are immutable once exposed to an application. + */ +export function bindAuthKeyToContext( + context: DaaUserContext, + authKeyThumbprint: string, +): DaaUserContext { + if (!isActiveDaaUserContext(context)) { + throw contractViolation('only an ACTIVE DaaUserContext can be bound to an AuthKey') + } + return new DaaUserContext( + DECODER_TOKEN, + { clientEntityId: context.clientEntityId, deviceContext: context.deviceContext }, + authKeyThumbprint, + ) +} + +/** Fail closed when the local key no longer matches the key paired at Complete. */ +export async function assertAuthKeyMatchesContext( + context: DaaUserContext, + authKey: OwnerAuthKey, +): Promise { + const expectedThumbprint = AUTH_KEY_THUMBPRINTS.get(context) + if (expectedThumbprint === undefined) { + throw contractViolation('DaaUserContext has no local AuthKey binding') + } + if ((await authKey.thumbprint()) !== expectedThumbprint) { + throw contractViolation('the resolved AuthKey does not match the ACTIVE DaaUserContext') + } +} + +/** True only for a context this SDK decoded from an ACTIVE registration. */ +export function isActiveDaaUserContext(value: unknown): value is DaaUserContext { + return value instanceof DaaUserContext && value.isActive() +} + +export type DeviceRegistrationResult = + | Readonly<{ status: 'ACTIVE'; context: DaaUserContext }> + | Readonly<{ + status: 'RECOVERY_PENDING' + recoveryReference: string + expiresAt: string + }> diff --git a/src/models/Deposit.ts b/src/models/Deposit.ts new file mode 100644 index 0000000..71b9a09 --- /dev/null +++ b/src/models/Deposit.ts @@ -0,0 +1,307 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Money } from './Money' + +// The closed-set fields on a deposit, and the two location shapes it carries. +// +// Each is a discriminated union on `kind`, the same shape `Account`'s closed-set +// fields use (see `models/Account.ts`) and for the same reason: a string-literal +// union has no room for a value the service adds next, and decoding into one +// would either throw (this SDK could no longer read *any* deposit because one +// status was added service-side) or silently widen to `string`, discarding the +// closed set the type exists to express. An unfamiliar *present* value degrades +// to `unrecognized` **carrying the raw string**, per the SDK contract's +// requirement to preserve it "as an unknown/raw-value case instead of failing +// the entire response". + +/** + * Public lifecycle status of a DAA account deposit. + * + * The service's `DepositStatus` enum has exactly three wire values — `pending`, + * `complete`, `failed` — and owns the two-way translation from the finer + * payment-processor status. Modelled as a closed set for the same + * forward-compatibility reason as `AccountStatus`. + */ +export type DepositStatus = + | { readonly kind: 'pending' } + | { readonly kind: 'complete' } + | { readonly kind: 'failed' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * The fiat rail a deposit's source account was received over. + * + * The service's `DepositType` enum lists fourteen wire values, all already + * lower_snake_case, so (unlike `AccountType`'s `first_party`/`firstParty` split) + * a `kind` here is spelled identically to its own wire value. New rails ship + * before an SDK release picks them up, which is exactly the case `unrecognized` + * exists for. + */ +export type DepositType = + | { readonly kind: 'wire' } + | { readonly kind: 'ach' } + | { readonly kind: 'cbit' } + | { readonly kind: 'rtgs' } + | { readonly kind: 'rtp' } + | { readonly kind: 'xpay' } + | { readonly kind: 'signet' } + | { readonly kind: 'sepa' } + | { readonly kind: 'sepa_instant' } + | { readonly kind: 'sen' } + | { readonly kind: 'pix' } + | { readonly kind: 'cubix' } + | { readonly kind: 'book_transfer' } + | { readonly kind: 'fed_now' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * The DAA account a deposit was credited to. + * + * The service's `DepositAccountLocation` has one `type` constant (`account`), + * but that is not a wire guarantee, and `type` is serialized as an ordinary + * string discriminator on the same location family the transfer and withdrawal + * models use for on-chain legs. + * Modelled as a closed set rather than a fixed `{ kind: 'account' }` so a future + * non-account destination degrades instead of failing the read. + */ +export type DepositAccountLocation = + | { readonly kind: 'account'; readonly accountId: string } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * The originating fiat account a deposit was received from, when the service + * can identify it. + * + * `type` and `id` are guaranteed together: the service returns a source + * location only when both are present and `type` parses, so a decoded source + * location never has one without the other. `name` is a best-effort + * display label and is not guaranteed even when the rest is. + */ +export type DepositSourceLocation = { + readonly type: DepositType + readonly id: string + readonly name: string | null +} + +/** + * A risk evaluation on a deposit. + * + * Both fields are free-form upstream strings the service does not itself + * constrain to a closed set — the schema's `allowableValues` on `decision` + * documents examples, not a contract — so neither is modelled as one here. The + * service surfaces the object whenever either field exists, so a reason-only + * evaluation has a `null` decision. + */ +export type DepositRiskEvaluation = { + readonly decision: string | null + readonly reason: string | null +} + +/** The redacted shape `JSON.stringify(deposit)` produces. Every amount is a `Money`, which self-redacts. */ +export type DepositRendering = { + readonly amount: Money + readonly createDate: string + readonly destination: DepositAccountLocation | null + readonly fee: Money | null + readonly fees: Money | null + readonly fromAmount: Money | null + readonly id: string + readonly status: DepositStatus +} + +/** + * A DAA account deposit, as the service reports it. + * + * Read-only at runtime as well as in the type system, for the same reason as + * `Account`: the instance is frozen, because `readonly` is erased at compile + * time and would leave a returned deposit mutable through a cast. + * + * **Not constructible by a consumer.** Exported from `index.ts` as a **type + * only**, so no runtime constructor reaches the public entry, and + * the `#` private fields make the type nominal so an object literal cannot be + * typed as a `Deposit` either. Every instance a caller holds came from a + * response this SDK decoded. + * + * **The guaranteed set does not follow the OpenAPI schema's required + * marking,** which covers only a few fields here and which this SDK already + * treats as non-authoritative for `Account` (see `wire/accountPayload.ts`). The + * guaranteed set here is read from what the service can actually produce + * across both the omnibus and segregated read paths: + * + * - `id`, `amount`, `status`, and `createDate` have no code path that leaves + * them absent on either source, so they are guaranteed here. + * - `destination` is marked required, but the service reports `null` whenever + * the ledger leg the deposit landed on is not a wallet location — a real code + * path, not a hypothetical one — so this SDK treats it as optional despite + * the schema. Trusting the schema would be the same defect documented for + * `Account.description`. + * - `updateDate` is **not** marked required at all, even though both read + * paths suggest it is in practice always present. It is still + * modelled optional: the risk is asymmetric, because a wrongly-required field + * rejects a valid response outright while a wrongly-optional field only + * under-promises a type. Absent a marker to settle it, the safer side wins. + * + * Everything else the service can omit is optional here. + * + * **Sensitive fields do not appear in any default rendering.** `amount`, `fee`, + * `fees`, `fromAmount`, `externalRef`, and `customerExternalRef` sit behind + * prototype accessors over `#` private fields, following `Money` and + * `BusinessPii`: `Object.keys`, `JSON.stringify`, spread, `for...in`, and the + * inspectors behind `console.log` cannot reach the fields themselves. Each + * `Money` additionally withholds its own amount text. The external references + * are bank/customer-supplied values that the service also redacts from metadata + * logging. Service-assigned identifiers, states, and locations remain visible so + * a log line naming a deposit by id and status stays useful. + */ +export class Deposit { + readonly createDate: string + + /** + * The account credited by the deposit, when the service can attribute one. + * `null` when the ledger leg the deposit landed on is not a wallet — see the + * class note. + */ + readonly destination: DepositAccountLocation | null + + /** Failure reason. Present only for a `failed` deposit. A free-form upstream code, not a closed set. */ + readonly errorCode: string | null + + /** Service-assigned identifier. */ + readonly id: string + + /** Risk evaluation; present whenever the service reports either risk field. */ + readonly riskEvaluation: DepositRiskEvaluation | null + + /** The originating fiat account, when the service can identify it. */ + readonly source: DepositSourceLocation | null + + /** Originating fiat account id the deposit was received from. */ + readonly sourceAccountId: string | null + + readonly status: DepositStatus + + /** Tracking reference. */ + readonly trackingRef: string | null + + /** + * Last-update timestamp (ISO-8601 UTC), as the service sent it. Carried as the + * exact wire string rather than parsed into a `Date` — this SDK does not + * introduce a second representation of a value it does not compute over. + * `null` only out of caution; see the class note. + */ + readonly updateDate: string | null + + readonly #amount: Money + readonly #customerExternalRef: string | null + readonly #externalRef: string | null + readonly #fee: Money | null + readonly #fees: Money | null + readonly #fromAmount: Money | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly amount: Money + readonly createDate: string + readonly customerExternalRef: string | null + readonly destination: DepositAccountLocation | null + readonly errorCode: string | null + readonly externalRef: string | null + readonly fee: Money | null + readonly fees: Money | null + readonly fromAmount: Money | null + readonly id: string + readonly riskEvaluation: DepositRiskEvaluation | null + readonly source: DepositSourceLocation | null + readonly sourceAccountId: string | null + readonly status: DepositStatus + readonly trackingRef: string | null + readonly updateDate: string | null + }) { + this.createDate = fields.createDate + this.destination = fields.destination + this.errorCode = fields.errorCode + this.id = fields.id + this.riskEvaluation = fields.riskEvaluation + this.source = fields.source + this.sourceAccountId = fields.sourceAccountId + this.status = fields.status + this.trackingRef = fields.trackingRef + this.updateDate = fields.updateDate + this.#amount = fields.amount + this.#customerExternalRef = fields.customerExternalRef + this.#externalRef = fields.externalRef + this.#fee = fields.fee + this.#fees = fields.fees + this.#fromAmount = fields.fromAmount + Object.freeze(this) + } + + /** Settled deposit amount. Guaranteed by the service; see the class note. */ + get amount(): Money { + return this.#amount + } + + /** Customer-supplied reference (for example, a wire memo). Withheld from default renderings. */ + get customerExternalRef(): string | null { + return this.#customerExternalRef + } + + /** External bank reference. Withheld from default renderings. */ + get externalRef(): string | null { + return this.#externalRef + } + + /** Legacy singular fee field; populated only when the source projection supplies `fee`. */ + get fee(): Money | null { + return this.#fee + } + + /** Detail fee field; populated only when the source projection supplies `fees`. */ + get fees(): Money | null { + return this.#fees + } + + /** Pre-conversion amount, present only when a currency conversion applied. */ + get fromAmount(): Money | null { + return this.#fromAmount + } + + /** Identifiers, states, and locations render; amounts do not. */ + toJSON(): DepositRendering { + return { + amount: this.#amount, + createDate: this.createDate, + destination: this.destination, + fee: this.#fee, + fees: this.#fees, + fromAmount: this.#fromAmount, + id: this.id, + status: this.status, + } + } + + /** Identifiers and states print; amounts do not — each `Money` withholds its own. */ + toString(): string { + return ( + `Deposit(id=${this.id}, status=${this.status.kind}, ` + + `destination=${this.destination === null ? 'null' : this.destination.kind}, ` + + `amount=${String(this.#amount)}, fee=${String(this.#fee)}, fees=${String(this.#fees)})` + ) + } +} diff --git a/src/models/DepositSummary.ts b/src/models/DepositSummary.ts new file mode 100644 index 0000000..1f94597 --- /dev/null +++ b/src/models/DepositSummary.ts @@ -0,0 +1,142 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { DepositAccountLocation, DepositRiskEvaluation, DepositStatus } from './Deposit' +import type { Money } from './Money' + +/** The redacted shape `JSON.stringify(depositSummary)` produces. Every amount is a `Money`, which self-redacts. */ +export type DepositSummaryRendering = { + readonly amount: Money + readonly createDate: string + readonly destination: DepositAccountLocation | null + readonly fee: Money | null + readonly id: string + readonly status: DepositStatus +} + +/** + * The compact deposit projection the collection endpoint returns, as the SDK + * contract's `DepositListQuery` result element + * (`list(): Promise>`). + * + * This is deliberately not `Deposit`, and not merely `Deposit` with fields + * omitted at the type level: the service's `DepositSummary` response has no + * `source`, `fees`, `fromAmount`, or `trackingRef` property at all, so a + * decoder that read them off a summary response would either throw on every + * page or silently invent absence for a field the wire never carries. `fee` on + * a summary is the coalesced value (`fee` if the source projection supplied + * one, else `fees`) — the summary has the one fee field, unlike the detail + * read's separate legacy and detail fee fields. + * + * Requiredness mirrors `Deposit`'s class note, because both wire records come + * from the same two read paths (omnibus and segregated): `id`, `amount`, + * `status`, and `createDate` are guaranteed; `destination` is optional despite + * the schema marking it required, because the omnibus path reports `null` + * whenever the ledger leg is not a wallet — a real code path, not a + * hypothetical one; `updateDate` is optional and not marked required at all, + * for the same asymmetric-risk reason `Deposit` gives. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#` private fields make the type nominal. + */ +export class DepositSummary { + readonly createDate: string + readonly destination: DepositAccountLocation | null + readonly errorCode: string | null + readonly id: string + readonly riskEvaluation: DepositRiskEvaluation | null + readonly sourceAccountId: string | null + readonly status: DepositStatus + readonly updateDate: string | null + + readonly #amount: Money + readonly #customerExternalRef: string | null + readonly #externalRef: string | null + readonly #fee: Money | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly amount: Money + readonly createDate: string + readonly customerExternalRef: string | null + readonly destination: DepositAccountLocation | null + readonly errorCode: string | null + readonly externalRef: string | null + readonly fee: Money | null + readonly id: string + readonly riskEvaluation: DepositRiskEvaluation | null + readonly sourceAccountId: string | null + readonly status: DepositStatus + readonly updateDate: string | null + }) { + this.createDate = fields.createDate + this.destination = fields.destination + this.errorCode = fields.errorCode + this.id = fields.id + this.riskEvaluation = fields.riskEvaluation + this.sourceAccountId = fields.sourceAccountId + this.status = fields.status + this.updateDate = fields.updateDate + this.#amount = fields.amount + this.#customerExternalRef = fields.customerExternalRef + this.#externalRef = fields.externalRef + this.#fee = fields.fee + Object.freeze(this) + } + + /** Settled deposit amount. Guaranteed by the service; see the class note. */ + get amount(): Money { + return this.#amount + } + + /** Customer-supplied reference (for example, a wire memo). Withheld from default renderings. */ + get customerExternalRef(): string | null { + return this.#customerExternalRef + } + + /** External bank reference. Withheld from default renderings. */ + get externalRef(): string | null { + return this.#externalRef + } + + /** The one fee field a summary carries — see the class note on how it is coalesced. */ + get fee(): Money | null { + return this.#fee + } + + /** Identifiers, states, and locations render; amounts do not. */ + toJSON(): DepositSummaryRendering { + return { + amount: this.#amount, + createDate: this.createDate, + destination: this.destination, + fee: this.#fee, + id: this.id, + status: this.status, + } + } + + /** Identifiers and states print; amounts do not — each `Money` withholds its own. */ + toString(): string { + return ( + `DepositSummary(id=${this.id}, status=${this.status.kind}, ` + + `destination=${this.destination === null ? 'null' : this.destination.kind}, ` + + `amount=${String(this.#amount)}, fee=${String(this.#fee)})` + ) + } +} diff --git a/src/models/FiatAccount.ts b/src/models/FiatAccount.ts new file mode 100644 index 0000000..7591742 --- /dev/null +++ b/src/models/FiatAccount.ts @@ -0,0 +1,195 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { REDACTED } from './redaction' + +// Shapes shared by the two fiat-account rails (`Wire`/`WireSummary` and `ACH`), +// per the canonical public Accounts OpenAPI's `WireSummary`/`Wire` schemas. +// `WireSummary`, `Wire`, `WireInstruction`, `ACH`, and `ACHInstruction` follow +// the canonical public Accounts OpenAPI's component naming, not DAA-owned +// aliases — but the status enum and the two nested address/billing shapes below +// are not themselves named by that public surface, so they follow this SDK's +// own naming convention for an unnamed nested shape (the same latitude +// `WithdrawalStatus` and `WithdrawalDestinationType` take in +// `models/Withdrawal.ts`). + +/** + * Lifecycle status of a fiat account, decoded from the service's + * `ExternalFiatAccountStatus` wire enum (`pending` | `complete` | `failed`). + * + * Closed set for the same forward-compatibility reason as `DepositStatus` + * (`models/Deposit.ts`): an unfamiliar *present* value degrades to + * `unrecognized` rather than failing the whole response. + */ +export type FiatAccountStatus = + | { readonly kind: 'pending' } + | { readonly kind: 'complete' } + | { readonly kind: 'failed' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * The fiat-account holder's billing address, as the service's `BillingDetails` + * schema reports it (`name`, `city`, `country`, `line1`, `line2`, `district`, + * `postalCode`, `valid`). + * + * Fiat-account `billingDetails`, `bankAddress`, and `routingNumber` must never + * enter logs, traces, crash reports, or analytics. This follows + * `BusinessPii`/`Address`'s pattern (`models/BusinessPii.ts`) rather than + * `WithdrawalDetail`'s: every field is held behind a prototype accessor over a + * `#` private field, so `Object.keys`, spread, `for...in`, and the inspectors + * behind `console.log` see an empty object, and `toJSON`/`toString` render only + * a redaction marker. + */ +export class BillingDetails { + readonly #name: string + readonly #city: string + readonly #country: string + readonly #line1: string + readonly #line2: string | null + readonly #district: string | null + readonly #postalCode: string + readonly #valid: boolean | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly name: string + readonly city: string + readonly country: string + readonly line1: string + readonly line2: string | null + readonly district: string | null + readonly postalCode: string + readonly valid: boolean | null + }) { + this.#name = fields.name + this.#city = fields.city + this.#country = fields.country + this.#line1 = fields.line1 + this.#line2 = fields.line2 + this.#district = fields.district + this.#postalCode = fields.postalCode + this.#valid = fields.valid + Object.freeze(this) + } + + get name(): string { + return this.#name + } + + get city(): string { + return this.#city + } + + get country(): string { + return this.#country + } + + get line1(): string { + return this.#line1 + } + + get line2(): string | null { + return this.#line2 + } + + get district(): string | null { + return this.#district + } + + get postalCode(): string { + return this.#postalCode + } + + get valid(): boolean | null { + return this.#valid + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `BillingDetails(${REDACTED})` + } +} + +/** + * The receiving bank's address, as the service's `BankAddress` schema reports + * it, and provided during bank-account creation. + * + * Redacted the same way {@link BillingDetails} is, and for the same reason: + * `bankAddress` is restricted alongside `billingDetails` and `routingNumber`. + */ +export class BankAddress { + readonly #bankName: string | null + readonly #city: string | null + readonly #country: string + readonly #line1: string | null + readonly #line2: string | null + readonly #district: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly bankName: string | null + readonly city: string | null + readonly country: string + readonly line1: string | null + readonly line2: string | null + readonly district: string | null + }) { + this.#bankName = fields.bankName + this.#city = fields.city + this.#country = fields.country + this.#line1 = fields.line1 + this.#line2 = fields.line2 + this.#district = fields.district + Object.freeze(this) + } + + get bankName(): string | null { + return this.#bankName + } + + get city(): string | null { + return this.#city + } + + get country(): string { + return this.#country + } + + get line1(): string | null { + return this.#line1 + } + + get line2(): string | null { + return this.#line2 + } + + get district(): string | null { + return this.#district + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `BankAddress(${REDACTED})` + } +} diff --git a/src/models/GenerateAddressRequest.ts b/src/models/GenerateAddressRequest.ts new file mode 100644 index 0000000..bc51e45 --- /dev/null +++ b/src/models/GenerateAddressRequest.ts @@ -0,0 +1,101 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Chain names recognized at author time, mirrored from the public Accounts + * API reference's `chain` enum for deposit-address generation, for editor + * autocomplete and typo protection only. + * + * This is **not** a runtime allowlist. That enum is a server-owned, + * externally-growing catalog — Circle onboards new blockchains on its own + * release cadence, and each onboarding is a doc/contract update on that side, + * not a business-vocabulary change on this one. A closed local allowlist would + * make every already-published SDK version reject a newly onboarded chain with + * `contract_violation` before the request ever reaches the network, until a + * new SDK release reaches every integrator through mobile app-store review — + * a multi-week gap in the worst case. `DepositAddressesClient.create` therefore + * only checks that a supplied `chain` is a plausible non-empty string and lets + * the server be the sole authority (it 400s on a genuinely invalid value). + */ +export const DEPOSIT_ADDRESS_CHAINS = Object.freeze([ + 'ALGO', + 'APTOS', + 'ARB', + 'AVAX', + 'BASE', + 'BTC', + 'CELO', + 'CODEX', + 'ETH', + 'HBAR', + 'HYPEREVM', + 'INK', + 'LINEA', + 'NEAR', + 'NOBLE', + 'OP', + 'PAH', + 'PLUME', + 'POLY', + 'SEI', + 'SOL', + 'SONIC', + 'SUI', + 'UNI', + 'WORLDCHAIN', + 'XDC', + 'XLM', + 'XRP', + 'ZKS', + 'ZKSYNC', +] as const) + +export type DepositAddressChain = (typeof DEPOSIT_ADDRESS_CHAINS)[number] + +/** + * Body for creating or resolving a deposit address. + * + * This SDK's typed client only supports account-scoped requests: `accountId` is + * always required. DAA derives custody from the supplied `accountId`, so any + * account the caller names is reachable, an omnibus account included. The + * broader public Accounts API additionally permits omitting `accountId` to + * select the caller's omnibus master account. That omission is deliberately + * not exposed here: this SDK's operations are bound to an authenticated + * device/Owner context, and a caller who forgot `accountId` would silently get + * the master account's address rather than their own. + * + * `chain` is optional: per the service's `GenerateAddressRequest` contract, it + * is required for an omnibus `accountId`, where DAA creates the address, and + * optional for segregated/self-custody accounts, where an omitted `chain` + * resolves to the account's immutable home blockchain. An omnibus request + * without `chain` is the service's to reject, not this SDK's. + */ +export type GenerateAddressRequest = Readonly<{ + /** Caller-generated UUID v4, durably reused for retries of this operation. */ + idempotencyKey: string + /** The account to create or resolve a deposit address for. */ + accountId: string + /** Currency accepted by the public Accounts request contract. */ + currency: 'USD' | 'EUR' + /** + * Blockchain to generate the address on. Optional — when omitted, resolves + * to the account's immutable home blockchain. See {@link DEPOSIT_ADDRESS_CHAINS} + * for why an unrecognized value is not rejected locally. + */ + chain?: DepositAddressChain +}> diff --git a/src/models/Money.ts b/src/models/Money.ts new file mode 100644 index 0000000..3c79216 --- /dev/null +++ b/src/models/Money.ts @@ -0,0 +1,91 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { REDACTED } from './redaction' + +/** + * An amount in a currency, as the DAA API reports it (`Money`). + * + * `currency` is a `string`, not a closed union, deliberately. The OpenAPI + * schema types it as an enum of twenty-two currencies — BIF, BYR, CLP, + * CNH, EUR, IDR, IQD, IRR, JOD, KPW, LAK, LBP, MKD, MMK, MNT, MUR, NOK, PKR, + * RSD, SLL, SYP, UGX — which does **not** include USD. That enum does not list + * every currency the service returns, and a client that turned it into a + * closed type would reject the balance this SDK exists to report. + * + * `amount` is the **exact decimal literal the service sent**, carried as a + * string. JavaScript has one number type and it is an IEEE-754 double, so a + * balance sent as `1234567890123456.78` comes back a different value with + * nothing to indicate it changed — the same reason the Kotlin model refuses a + * `Double`. `JSON.parse` performs that conversion before any code here can see + * the token, so there is no way to recover an exact value from a JSON number + * after the fact. + * + * The SDK does not try to. The service sends this field as a plain decimal JSON + * **string**, so the exact decimal arrives untouched. An `amount` that ever + * arrives as a JSON number is **rejected** as a malformed response rather than + * coerced: by then it has already been rounded, and reporting it would mean + * handing back a balance the service never sent. Its + * grammar is checked on the way in (`wire/jsonNumber.ts`), since nothing else + * verifies that a string field holds a number. + * + * A caller doing arithmetic should hand `amount` to a decimal library; + * `Number(amount)` reintroduces exactly the rounding this avoids. + * + * Not constructible by a consumer: this class is exported from `index.ts` as a + * **type only**, so no runtime constructor reaches the public entry, and the + * private `#amount` field makes the type nominal so an object literal cannot be + * typed as a `Money` either. Every instance a caller holds came from a + * response this SDK decoded. + * + * **No default rendering prints the amount.** `Account` reduces its balances + * to a count precisely so a logged account does not carry holdings, and that is + * worth nothing if logging one balance prints it anyway. `amount` is reached + * through a prototype accessor rather than an own property, so it is absent from + * `Object.keys`, `JSON.stringify`, `{ ...money }`, `for...in`, and the object + * inspectors that drive `console.log`. The service excludes the same class of + * value from its own rendering. + */ +export class Money { + /** ISO 4217 code. Not constrained to a known set — see the class note. */ + readonly currency: string + + readonly #amount: string + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(amount: string, currency: string) { + this.#amount = amount + this.currency = currency + Object.freeze(this) + } + + /** The amount, exactly as the service sent it. See the class note. */ + get amount(): string { + return this.#amount + } + + /** `JSON.stringify` renders the currency and says the amount was withheld. */ + toJSON(): { readonly amount: string; readonly currency: string } { + return { amount: REDACTED, currency: this.currency } + } + + /** The currency is not sensitive; the amount is. */ + toString(): string { + return `Money(amount=${REDACTED}, currency=${this.currency})` + } +} diff --git a/src/models/Page.ts b/src/models/Page.ts new file mode 100644 index 0000000..6fcdb2c --- /dev/null +++ b/src/models/Page.ts @@ -0,0 +1,48 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +type PageLoader = () => Promise> + +/** A frozen collection page with trusted navigation to adjacent pages. */ +export class Page { + readonly items: readonly T[] + readonly #next: PageLoader | null + readonly #previous: PageLoader | null + + /** @internal Constructed only by a typed collection client. */ + constructor(items: readonly T[], next: PageLoader | null, previous: PageLoader | null) { + this.items = Object.freeze([...items]) + this.#next = next + this.#previous = previous + Object.freeze(this) + } + + /** Load the following page, or return `null` when the API supplied no link. */ + async next(): Promise | null> { + return this.#next === null ? null : this.#next() + } + + /** Load the preceding page, or return `null` when the API supplied no link. */ + async previous(): Promise | null> { + return this.#previous === null ? null : this.#previous() + } + + toJSON(): Readonly<{ items: readonly T[] }> { + return Object.freeze({ items: this.items }) + } +} diff --git a/src/models/PendingDeviceRegistration.ts b/src/models/PendingDeviceRegistration.ts new file mode 100644 index 0000000..7b54b8c --- /dev/null +++ b/src/models/PendingDeviceRegistration.ts @@ -0,0 +1,197 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + authorizeRegistrationComplete, + DEVICE_REGISTRATION_COMPLETE_PATH, + REGISTRATION_DEVICE_AUTHORIZATION_HEADER, + REGISTRATION_FLOW_AUTHORIZATION_HEADER, +} from '../auth/registrationAuthorization' +import { releaseQuietly, type RegistrationFlowKey } from '../auth/RegistrationFlowKey' +import { randomUuidV4 } from '../crypto/random' +import { serializeBody } from '../crypto/serialization' +import { contractViolation } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import type { DaaTransport } from '../transport/DaaTransport' +import { loginStepFailure } from '../api/loginFailure' +import { decodeResourceResponse } from '../api/resourceRequest' +import { toDeviceRegistrationResult } from '../wire/deviceRegistrationResultPayload' +import { bindAuthKeyToContext, type DeviceRegistrationResult } from './DaaUserContext' + +const AUTH_KEY_PUBLIC_KEY = /^[A-Za-z0-9_-]{122}$/ + +/** + * Pending device registration after Social Session. + * + * `complete()` is Device Registration Complete: the four-field body + * (`idempotencyKey`, `registrationHandle`, `registrationCodeVerifier`, + * `authKeyPublicKey`), including the registration code verifier minted before + * Prepare and redeemed here against the challenge Prepare sent. Two JWSs + * authorize it — `X-Device-Authorization` (signed by the proposed AuthKey) and + * `X-Registration-Flow-Authorization` (signed by the per-attempt flow key from + * Prepare) — both over the exact body bytes. Both carry the same request claims + * bar `jti`; only the flow proof also carries the binding claims (registration + * handle, profile, AuthKey thumbprint, code verifier). Building and signing + * those proofs is `authorizeRegistrationComplete`. + * + * Every device takes this same path, first or additional. A new device on an + * existing Owner does social login and then this same registration, with the + * same body; there is no approval from an already-registered device and + * no mode to select. DAA adds the new AuthKey next to the Owner's existing + * keys (additive registration). + * + * There is no `abandon()`. If the caller backs out after Session without + * calling `complete()`, the native flow-key cache is held until the process + * exits; `complete()` releases it in `finally`. The API has no cancel call for + * a pending registration. + * + * Not constructible by a consumer: exported from `index.ts` as a type only. + */ +export class PendingDeviceRegistration { + readonly registrationHandle: string + readonly clientEntityId: string + /** + * When the registration handle expires, as ISO-8601 text. The decoder also + * accepts the epoch-millisecond form the service sends for this timestamp + * and normalises it here, so a consumer never sees the wire's disagreement. + */ + readonly expiresAt: string + + readonly #transport: DaaTransport + readonly #registrationCodeVerifier: string + readonly #registrationFlowKey: RegistrationFlowKey + readonly #authKey: OwnerAuthKey + #consumed = false + + /** @internal Constructed only by `PreparedSocialLogin.completeSocialSession`. */ + constructor(fields: { + readonly registrationHandle: string + readonly clientEntityId: string + readonly expiresAt: string + readonly transport: DaaTransport + readonly registrationCodeVerifier: string + readonly registrationFlowKey: RegistrationFlowKey + readonly authKey: OwnerAuthKey + }) { + this.registrationHandle = fields.registrationHandle + this.clientEntityId = fields.clientEntityId + this.expiresAt = fields.expiresAt + this.#transport = fields.transport + this.#registrationCodeVerifier = fields.registrationCodeVerifier + this.#registrationFlowKey = fields.registrationFlowKey + this.#authKey = fields.authKey + Object.freeze(this) + } + + /** + * Finish the ceremony: `POST /v1/accounts/auth/deviceKeyRegistration` with + * both `X-Device-Authorization` and `X-Registration-Flow-Authorization` + * bound to the exact body bytes. + * + * Takes no input: the body is the same four fields for every device — see + * the class doc. + * + * The service returns a flat `DeviceContext`. A `{ status, context }` / + * `RECOVERY_PENDING` payload is also decoded. On `ACTIVE`, acknowledges + * the AuthKey so later `resolveOrCreate` returns `existing`. + * + * @throws DaaError with `detail.kind === 'login_request_expired'` for `410`; + * `idempotency_conflict` for a `409` with `IDEMPOTENCY_KEY_REUSED` + * (`420034`); `contract_violation` for `LOGIN_REQUEST_CONSUMED` (`420039`), + * for a second call, for unusable key material, and for a response the SDK + * cannot read; and `api` for any other status besides the documented + * `200`, including the `409` that DAA sends with `AUTH_KEY_BINDING_CONFLICT` + * (`420038`). + */ + async complete(): Promise { + if (this.#consumed) { + throw contractViolation('this pending device registration has already been consumed') + } + this.#consumed = true + + try { + const authKeyPublicKey = await this.#authKey.publicKeySpkiBase64Url() + if (!AUTH_KEY_PUBLIC_KEY.test(authKeyPublicKey)) { + throw contractViolation( + 'AuthKey public key must be a 122-character unpadded Base64URL P-256 SPKI', + ) + } + + const idempotencyKey = randomUuidV4() + const bodyBytes = serializeBody({ + idempotencyKey, + registrationHandle: this.registrationHandle, + registrationCodeVerifier: this.#registrationCodeVerifier, + authKeyPublicKey, + }) + const { deviceJws, flowJws } = await authorizeRegistrationComplete({ + bodyBytes, + registrationHandle: this.registrationHandle, + registrationCodeVerifier: this.#registrationCodeVerifier, + clientEntityId: this.clientEntityId, + flowKey: this.#registrationFlowKey, + authKey: this.#authKey, + }) + + const response = await this.#transport.send({ + method: 'POST', + path: DEVICE_REGISTRATION_COMPLETE_PATH, + query: null, + headers: { + 'Content-Type': 'application/json', + [REGISTRATION_DEVICE_AUTHORIZATION_HEADER]: deviceJws, + [REGISTRATION_FLOW_AUTHORIZATION_HEADER]: flowJws, + }, + bodyBytes, + }) + + const failure = loginStepFailure(response, idempotencyKey) + if (failure !== null) { + throw failure + } + + const result = decodeResourceResponse({ + response, + expectedStatus: 200, + decode: (value) => toDeviceRegistrationResult(value, this.clientEntityId), + }) + return await this.#finish(result) + } finally { + await releaseQuietly(this.#registrationFlowKey) + } + } + + async #finish(result: DeviceRegistrationResult): Promise { + switch (result.status) { + case 'ACTIVE': + // Keep the server-assigned authKeyId as the JWS kid, but retain the + // local key's thumbprint alongside it. `DaaClient.forUser` checks this + // pairing every time it resolves the key for a signed operation. + const boundContext = bindAuthKeyToContext(result.context, await this.#authKey.thumbprint()) + await this.#authKey.acknowledgeRegistration() + return Object.freeze({ ...result, context: boundContext }) + case 'RECOVERY_PENDING': + return result + default: { + const exhaustive: never = result + void exhaustive + throw contractViolation('device registration status is not in the closed set') + } + } + } +} diff --git a/src/models/PreparedSocialLogin.ts b/src/models/PreparedSocialLogin.ts new file mode 100644 index 0000000..780fbd0 --- /dev/null +++ b/src/models/PreparedSocialLogin.ts @@ -0,0 +1,287 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOwnerGrantFlowKeyThumbprint } from '../auth/ownerGrant' +import { releaseQuietly, type RegistrationFlowKey } from '../auth/RegistrationFlowKey' +import { fromBase64Url } from '../crypto/base64url' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { randomUuidV4 } from '../crypto/random' +import { serializeBody } from '../crypto/serialization' +import { contractViolation } from '../errors' +import type { OwnerAuthKey } from '../securekey/SecureKey' +import type { DaaTransport } from '../transport/DaaTransport' +import { headerValueIgnoringCase } from '../transport/headers' +import { isUuid } from '../validation/uuid' +import { loginStepFailure } from '../api/loginFailure' +import { decodeResourceResponse } from '../api/resourceRequest' +import { toPendingRegistration } from '../wire/pendingRegistrationPayload' +import { PendingDeviceRegistration } from './PendingDeviceRegistration' + +/** + * `POST /v1/accounts/auth/sessions` — the contract's `completeSocialLogin` + * operation, on the public path. + */ +export const SOCIAL_SESSION_PATH = '/v1/accounts/auth/sessions' + +const ID_TOKEN_MAX_LENGTH = 16384 + +/** + * A prepared social login: `PreparedSocialLogin`. + * + * The five public fields are what the consuming application carries through its + * own provider login. There is deliberately no AuthKey field of any kind — no + * `authKeyId`, no thumbprint — because AuthKey selection happens *after* the + * Social Session response, so at this point in the flow no AuthKey has been + * chosen and naming one would be fiction. + * + * Held privately, for one attempt only: + * + * - the **registration code verifier**, whose S256 challenge went out at Prepare + * and whose digest is redeemed in the Complete flow-proof claim set; + * - the **ephemeral registration-flow key**. It signs the + * `X-Registration-Flow-Authorization` proof sent on Complete. Not an + * AuthKey — see `auth/RegistrationFlowKey.ts`; + * - the Prepare **`idempotencyKey`**, so an ambiguous retry can resend identical + * bytes rather than starting a second logical attempt. + * + * All three are `#` private fields. The verifier in particular is the secret that + * binds the two halves of the handoff; it is never a public field, never in an + * error message, and never logged. + * + * **This state lives in memory, for the life of this object.** It is not + * persisted across a process restart. A login attempt that does not + * survive to `completeSocialSession` is abandoned, and a new Prepare starts a + * new attempt with fresh material — the fail-closed behaviour. Call + * {@link PreparedSocialLogin.abandon} when the user backs out so the native + * flow-key cache is dropped; dropping this object alone does not. + * + * `AuthClient.prepareSocialLogin` checks the Prepare receipt before it + * constructs this object (`auth/prepareReceipt.ts`, `checkPrepareReceipt`), so + * an instance only exists for a response that passed that check. Session does + * not consume receipt claims: it sends `loginRequestId` plus the application's + * `idToken` and `clientEntityId`. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, and + * the `#` private fields make the type nominal. + */ +export class PreparedSocialLogin { + /** Opaque, single-use DAA correlation for this pending registration attempt. */ + readonly loginRequestId: string + + /** + * Single-use nonce the application supplies to the social provider. Only a + * verified receipt's `nonce` claim binds it to `loginRequestId`, and no + * receipt trust anchor is pinned in this release, so it is unauthenticated + * relay output. Do not treat it as proof that the login request came from + * Circle: bind the login with the application's own OAuth `state` and its + * authenticated session with its backend. + */ + readonly oidcNonce: string + + /** + * DAA correlation to bind inside or alongside the application's own OAuth + * CSRF state. Per the contract it "must not replace app-owned redirect + * protection". The receipt does not bind it: DAA signs no state claim, so it + * is unauthenticated whether or not a trust anchor is pinned. The + * application's own `state` is the primary binding for the provider redirect. + */ + readonly oidcState: string + + /** + * The DAA-signed Prepare receipt, verified before this object exists. Null + * when no trust anchor is pinned for the environment, which is every + * environment in this release: the SDK then ignores any receipt the service + * sends, and does not hand on one it has not checked. + */ + readonly prepareReceiptJws: string | null + + /** + * When the login request expires, as ISO-8601 text. The contract declares that + * string form and the running service sends epoch milliseconds, so the decoder + * accepts both and normalises the number to this one representation — a + * consumer never sees the wire's disagreement. + */ + readonly expiresAt: string + + readonly #registrationCodeVerifier: string + readonly #registrationFlowKey: RegistrationFlowKey + readonly #idempotencyKey: string + readonly #transport: DaaTransport + readonly #resolveAuthKey: (clientEntityId: string) => Promise + #sessionConsumed = false + + /** @internal Constructed only by `AuthClient.prepareSocialLogin`. */ + constructor(fields: { + readonly loginRequestId: string + readonly oidcNonce: string + readonly oidcState: string + readonly prepareReceiptJws: string | null + readonly expiresAt: string + readonly registrationCodeVerifier: string + readonly registrationFlowKey: RegistrationFlowKey + readonly idempotencyKey: string + readonly transport: DaaTransport + readonly resolveAuthKey: (clientEntityId: string) => Promise + }) { + this.loginRequestId = fields.loginRequestId + this.oidcNonce = fields.oidcNonce + this.oidcState = fields.oidcState + this.prepareReceiptJws = fields.prepareReceiptJws + this.expiresAt = fields.expiresAt + this.#registrationCodeVerifier = fields.registrationCodeVerifier + this.#registrationFlowKey = fields.registrationFlowKey + this.#idempotencyKey = fields.idempotencyKey + this.#transport = fields.transport + this.#resolveAuthKey = fields.resolveAuthKey + Object.freeze(this) + } + + /** + * Exchange the provider ID token for a pending device registration: + * `POST /v1/accounts/auth/sessions` (the Social Session call). + * + * AuthKey selection happens only after a successful response, then the + * returned `PendingDeviceRegistration` can call Device Registration Complete. + * + * `clientEntityId` is required, and there is no resolve-or-create fallback + * behind it: the service refuses a Session that omits it. The value names an + * end user the application's own backend has already onboarded to an active + * account — Circle never creates one here. The service checks that the entity + * belongs to the authenticated parent and then binds this end user to it + * permanently, so a wrong id is not a mistake a later call can undo. + * + * It is taken on this method because this is the call that carries it. Taking + * it at client construction would pin one end user to a whole `DaaClient`, and + * taking it at Prepare would pin it to an attempt that has not yet named one. + * + * The `idToken` is sent in the exact body bytes and is never logged, stored on + * this object, or interpolated into errors. + * + * @throws DaaError with `detail.kind === 'login_request_expired'` for `410`; + * `idempotency_conflict` for a `409` with `IDEMPOTENCY_KEY_REUSED` + * (`420034`); `contract_violation` for invalid input, a second call, + * `LOGIN_REQUEST_CONSUMED` (`420039`), a response the SDK cannot read, and + * an Owner grant that is not bound to this attempt's flow key; and `api` + * for any other status besides the documented `200`, including any other + * `409`. + */ + async completeSocialSession(input: { + idToken: string + clientEntityId: string + }): Promise { + if (typeof input !== 'object' || input === null || Array.isArray(input)) { + throw contractViolation('completeSocialSession input must be an object') + } + if ( + typeof input.idToken !== 'string' || + input.idToken.length < 1 || + input.idToken.length > ID_TOKEN_MAX_LENGTH + ) { + throw contractViolation('idToken must be a provider token of at most 16384 characters') + } + if (typeof input.clientEntityId !== 'string' || !isUuid(input.clientEntityId)) { + throw contractViolation('clientEntityId must be a UUID') + } + if (this.#sessionConsumed) { + throw contractViolation('this prepared social login has already been consumed') + } + + const idToken = input.idToken + const clientEntityId = input.clientEntityId + // One-shot on this object: latch before send. A dropped connection still + // consumes the attempt; recovery is a new `prepareSocialLogin`, not a retry + // of `completeSocialSession` (the verifier and flow key are bound here). + this.#sessionConsumed = true + try { + // Prepare's idempotency key is for Prepare retries only. Session is a + // distinct operation and owns its own key. + void this.#idempotencyKey + const idempotencyKey = randomUuidV4() + // Serialized once. These are the bytes that go on the wire; nothing + // downstream re-serializes them. The four members are the service's four + // required properties, in the order it declares them. + const bodyBytes = serializeBody({ + idempotencyKey, + loginRequestId: this.loginRequestId, + idToken, + clientEntityId, + }) + const response = await this.#transport.send({ + method: 'POST', + path: SOCIAL_SESSION_PATH, + query: null, + headers: { 'Content-Type': 'application/json' }, + bodyBytes, + }) + + const failure = loginStepFailure(response, idempotencyKey) + if (failure !== null) { + throw failure + } + + const pending = decodeResourceResponse({ + response, + expectedStatus: 200, + decode: toPendingRegistration, + }) + + if (pending.ownerGrant !== null) { + const flowSpki = fromBase64Url(await this.#registrationFlowKey.publicKeySpkiBase64Url()) + requireOwnerGrantFlowKeyThumbprint( + pending.ownerGrant, + p256JwkThumbprint(flowSpki), + headerValueIgnoringCase(response.headers, 'X-Request-Id'), + ) + } + + // Select or create the AuthKey only after the Social Session response. + // Namespaced to `pending.clientEntityId` — the response's OWN echo of the + // bound entity — and NOT `clientEntityId` (this method's argument), + // because the service is what validates and binds that value; it is the + // server-confirmed identity the rest of the ceremony, and every later + // `forUser` re-resolution, is checked against. + const authKey = await this.#resolveAuthKey(pending.clientEntityId) + return new PendingDeviceRegistration({ + registrationHandle: pending.registrationHandle, + // The service's own echo of the bound entity, decoded from the response, + // not the argument this method was handed. The response field is what the + // rest of the ceremony is checked against, so it stays the one source. + clientEntityId: pending.clientEntityId, + expiresAt: pending.expiresAt, + transport: this.#transport, + registrationCodeVerifier: this.#registrationCodeVerifier, + registrationFlowKey: this.#registrationFlowKey, + authKey, + }) + } catch (error) { + await releaseQuietly(this.#registrationFlowKey) + throw error + } + } + + /** + * Drop the native registration-flow key for this attempt. + * + * Call this when the user backs out of provider login. The JS handle going out + * of scope does not clear the native process cache. Safe to call more than + * once. After this, the attempt cannot proceed to Registration Complete. + */ + async abandon(): Promise { + await this.#registrationFlowKey.release() + } +} diff --git a/src/models/Transaction.ts b/src/models/Transaction.ts new file mode 100644 index 0000000..37c7e32 --- /dev/null +++ b/src/models/Transaction.ts @@ -0,0 +1,247 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Money } from './Money' +import { REDACTED } from './redaction' + +// A DAA transaction's closed-set fields and its polymorphic source/destination +// legs. Same posture as `Transfer`: a discriminated union on `kind` rather than +// a string-literal union, so a value the service adds later degrades to +// `unrecognized` instead of failing the whole row. +// +// This is the unified activity row (OpenAPI `Transaction`) returned by +// `GET /v1/accounts/transactions`. Unlike `Transfer`, a transaction leg may be +// a fiat rail (`wire`/`ach`), and both `source` and `destination` are optional +// ("present when available"). `status` adds `returned` over the transfer set. + +/** + * Where a transaction is in its lifecycle (OpenAPI `TransactionStatus`). + * + * A superset of `TransferStatus`: unified account activity adds `returned` + * (e.g. a returned deposit). + */ +export type TransactionStatus = + | { readonly kind: 'pending' } + | { readonly kind: 'complete' } + | { readonly kind: 'failed' } + | { readonly kind: 'returned' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * Coarse activity kind (OpenAPI `TransactionType`). + * + * This is the user-facing taxonomy the service already collapses its internal + * types onto. An unmapped present value degrades to `unrecognized` here; the service + * itself folds unknown upstream types to `other` before they reach the wire. + */ +export type TransactionType = + | { readonly kind: 'deposit' } + | { readonly kind: 'withdrawal' } + | { readonly kind: 'transfer' } + | { readonly kind: 'fx' } + | { readonly kind: 'fee' } + | { readonly kind: 'credit' } + | { readonly kind: 'other' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * An account transaction leg (OpenAPI `TransactionDestinationAccountLocation` + * / `TransferSourceAccountLocation`). Named `accountId` so it is not confused + * with the transaction's own `id`. + * + * The service always reports an account leg here with only its id, so the + * crypto `address`/`addressTag` a transfer destination can carry are not part + * of this shape. Unknown extra fields are ignored on the way in. + */ +export type TransactionAccountLocation = { + readonly kind: 'account' + readonly accountId: string +} + +/** The redacted shape `JSON.stringify`/`toString` produce for a blockchain leg. */ +export type TransactionBlockchainLocationRendering = { + readonly kind: 'blockchain' + readonly chain: string | null + readonly address: string | null + readonly addressTag: string | null +} + +/** + * An on-chain transaction leg (the runtime `BlockchainLocation` class). + * + * OpenAPI splits this: a source is `TransferSourceBlockchainLocation` (chain + * only) and a destination is `TransferDestinationBlockchainLocation` (chain + + * address). The service does not: it copies the recorded + * `chain`/`address`/`addressTag` onto **both** legs and omits whichever of + * those is unset. So this SDK decodes one shape for both sides, with every + * field optional, rather than requiring an address that a source leg — or an + * on-chain leg whose metadata has not backfilled — will not have. + * + * `address`/`addressTag` are redacted the same way `Money.amount` is. + */ +export class TransactionBlockchainLocation { + readonly kind = 'blockchain' as const + readonly chain: string | null + readonly #address: string | null + readonly #addressTag: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { chain: string | null; address: string | null; addressTag: string | null }) { + this.chain = fields.chain + this.#address = fields.address + this.#addressTag = fields.addressTag + Object.freeze(this) + } + + get address(): string | null { + return this.#address + } + + get addressTag(): string | null { + return this.#addressTag + } + + toJSON(): TransactionBlockchainLocationRendering { + return { + kind: this.kind, + chain: this.chain, + address: this.#address === null ? null : REDACTED, + addressTag: this.#addressTag === null ? null : REDACTED, + } + } + + toString(): string { + return ( + `TransactionBlockchainLocation(kind=blockchain, chain=${this.chain}, ` + + `address=${this.#address === null ? 'null' : REDACTED}, ` + + `addressTag=${this.#addressTag === null ? 'null' : REDACTED})` + ) + } +} + +/** + * A fiat transaction leg (OpenAPI `TransactionFiatLocation`). `wire` and `ach` + * are the discriminator values, so they are `kind` rather than a nested type + * field. `name` is the human-readable bank or rail label when available; it is + * not redacted, matching `WithdrawalDestination.name`. + */ +export type TransactionFiatLocation = { + readonly kind: 'wire' | 'ach' + readonly fiatAccountId: string + readonly name: string | null +} + +/** + * A transaction source or destination leg. The service uses one location type + * on both sides; OpenAPI documents two `oneOf`s that this union + * is the product of. A `verified_blockchain` leaking through, or a kind not + * yet invented, degrades to `unrecognized`. + */ +export type TransactionLocation = + | TransactionAccountLocation + | TransactionBlockchainLocation + | TransactionFiatLocation + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** The redacted shape `JSON.stringify(transaction)` produces. */ +export type TransactionRendering = { + readonly id: string + readonly type: TransactionType + readonly status: TransactionStatus + readonly amount: { readonly amount: string; readonly currency: string } + readonly source: TransactionLocation | null + readonly destination: TransactionLocation | null + readonly createDate: string + readonly updateDate: string +} + +/** + * A DAA unified activity row (OpenAPI `Transaction`), as + * `GET /v1/accounts/transactions` reports it. + * + * There is no by-id read: the API is list-only for transactions. + * + * **Guaranteed fields** are `id`, `type`, `status`, `amount`, `createDate`, and + * `updateDate`. Those six are marked required, and every service path that + * produces a transaction always sets them. `source` and `destination` are + * documented "when available", and the service omits an absent leg rather than + * sending JSON `null`. + * + * **`amount` does not appear in any default rendering.** It sits behind a + * prototype accessor, so `Object.keys`, `JSON.stringify`, spread, `for...in`, + * and `console.log` do not reach it. A blockchain leg redacts its own address. + * + * Not constructible by a consumer: exported from `index.ts` as a type only, + * and the `#amount` field makes the type nominal. + */ +export class Transaction { + readonly id: string + readonly type: TransactionType + readonly status: TransactionStatus + readonly source: TransactionLocation | null + readonly destination: TransactionLocation | null + readonly createDate: string + readonly updateDate: string + readonly #amount: Money + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly id: string + readonly type: TransactionType + readonly status: TransactionStatus + readonly amount: Money + readonly source: TransactionLocation | null + readonly destination: TransactionLocation | null + readonly createDate: string + readonly updateDate: string + }) { + this.id = fields.id + this.type = fields.type + this.status = fields.status + this.source = fields.source + this.destination = fields.destination + this.createDate = fields.createDate + this.updateDate = fields.updateDate + this.#amount = fields.amount + Object.freeze(this) + } + + get amount(): Money { + return this.#amount + } + + toJSON(): TransactionRendering { + return { + id: this.id, + type: this.type, + status: this.status, + amount: this.#amount.toJSON(), + source: this.source, + destination: this.destination, + createDate: this.createDate, + updateDate: this.updateDate, + } + } + + toString(): string { + return ( + `Transaction(id=${this.id}, type=${this.type.kind}, status=${this.status.kind}, ` + + `amount=${this.#amount.toString()}, createDate=${this.createDate}, updateDate=${this.updateDate})` + ) + } +} diff --git a/src/models/Transfer.ts b/src/models/Transfer.ts new file mode 100644 index 0000000..12471be --- /dev/null +++ b/src/models/Transfer.ts @@ -0,0 +1,459 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Money } from './Money' +import { REDACTED } from './redaction' + +// A DAA transfer's closed-set fields and its polymorphic source/destination legs. +// +// Same posture as `Account`'s closed-set fields (see `models/Account.ts`): a +// discriminated union on `kind` rather than a string-literal union, because a +// string-literal union has no room for a value the service adds later — decoding +// into one would either throw (making the whole transfer unreadable because one +// status or location kind was unfamiliar) or silently widen to `string`, which +// throws away the closed set the type exists to express. An unfamiliar *present* +// value degrades to `unrecognized`, carrying the raw string so a caller — or +// support, reading a bug report — can answer "why did this read as unknown" +// rather than just "it did". +// +// **A general note on how requiredness is decided in this file**: a response +// field marked required in the service's OpenAPI schema is a hint that it is +// *usually* present — never proof. The only evidence that settles it is whether +// a code path in the service can produce the value absent. The service's +// mapping of transfer legs is that evidence for `source`, `destination`, and +// the blockchain leg's `chain`/`address` — each is marked required and each has +// a real path to `null`, documented per-field below. Treating them as required +// would reject perfectly ordinary transfers (a fiat onramp/offramp leg, or a +// blockchain leg recorded before its chain/address metadata backfilled) — the +// same class of defect `Account.description` shows. + +/** + * Where a transfer is in its lifecycle (OpenAPI `TransferStatus`, wire values + * are the enum constant names verbatim). + * + * `pending` also covers any asynchronous processing before settlement: the + * public contract has no intermediate state, so that phase folds into + * `pending` before this SDK ever sees it. + */ +export type TransferStatus = + | { readonly kind: 'pending' } + /** Terminal: successfully settled. */ + | { readonly kind: 'complete' } + /** Terminal: failed or denied — see {@link TransferErrorCode}. */ + | { readonly kind: 'failed' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * Why a transfer failed (OpenAPI `TransferErrorCode`), present only when + * {@link TransferStatus} is `failed`. + * + * This is the service's own public subset: internal failure reasons fold into + * `transfer_failed` before they reach the wire. + * Still modeled as an open set here rather than trusted to stay exactly five + * values — the public enum can grow without this SDK's say-so, and a value it has + * not shipped for must read as `unrecognized`, not fail the transfer. + */ +export type TransferErrorCode = + | { readonly kind: 'transfer_failed' } + | { readonly kind: 'transfer_denied' } + | { readonly kind: 'blockchain_error' } + | { readonly kind: 'insufficient_funds' } + | { readonly kind: 'invalid_crypto_address' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * A transfer's source leg (OpenAPI `TransferSourceLocation`, a `oneOf` of + * `TransferSourceAccountLocation` and `TransferSourceBlockchainLocation`). + * + * Neither source shape ever carries an address: `TransferSourceAccountLocation` + * has only `id`, and `TransferSourceBlockchainLocation` has only `chain` — a + * transfer's origin address is not part of the public contract. Both are safe as + * plain frozen literals, unlike the destination union below, because neither + * carries a value this SDK must redact. + * + * The wire discriminator is the location's shared `type` property, keyed here + * to `account` / `blockchain` — the only two location types the contract + * allows for a transfer leg (`verified_blockchain`, `wire`, and `ach` are + * `Transaction`-only). A transfer that ever carries one of those, or a location + * kind not yet invented, degrades to `unrecognized` with the raw `type` string + * rather than failing the whole read — the same forward-compatibility contract as + * every other closed set here. + */ +export type TransferSourceLocation = + | { + readonly kind: 'account' + /** The account id. Named `accountId` here (the wire spells it `id`) so it + * is not confused with the transfer's own `id` at `transfer.source.id`. */ + readonly accountId: string + } + | { + readonly kind: 'blockchain' + /** + * Chain of the on-chain leg, as a plain string rather than a closed set — + * same reasoning as `Account.blockchain`: new chains ship without an SDK + * release, and the service's own chain type is the thing that would have + * to grow, not this union. + * + * **Nullable**, despite the OpenAPI schema marking + * `TransferSourceBlockchainLocation.chain` required: the service builds a + * blockchain source leg with no chain when the leg was recorded before its + * blockchain metadata backfilled, and the schema does not prevent it from + * sending that leg anyway. + */ + readonly chain: string | null + } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** The redacted shape `JSON.stringify`/`toString` produce for a destination account leg. */ +export type TransferDestinationAccountLocationRendering = { + readonly kind: 'account' + readonly accountId: string + readonly address: string | null + readonly addressTag: string | null +} + +/** + * A transfer destination that is a DAA account (OpenAPI + * `TransferDestinationAccountLocation`). + * + * Unlike the source shape, a destination account leg can carry the on-chain + * `address`/`addressTag` funds arrived at — present only when this account leg + * received a crypto deposit. A crypto address is treated as sensitive data, so + * it is held the same way `Money` holds `amount`: behind a `#` private field + * and a prototype accessor, with `toJSON`/`toString` reporting only *whether* + * one is present. The service redacts it from its own logs but still sends it + * in the JSON body; this SDK redacts the JSON rendering too. + */ +export class TransferDestinationAccountLocation { + readonly kind = 'account' as const + readonly accountId: string + readonly #address: string | null + readonly #addressTag: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { accountId: string; address: string | null; addressTag: string | null }) { + this.accountId = fields.accountId + this.#address = fields.address + this.#addressTag = fields.addressTag + Object.freeze(this) + } + + /** The on-chain address this account leg received a deposit at, or `null` if it did not. */ + get address(): string | null { + return this.#address + } + + /** Secondary on-chain identifier (e.g. a Stellar memo) paired with {@link address}; nullable. */ + get addressTag(): string | null { + return this.#addressTag + } + + toJSON(): TransferDestinationAccountLocationRendering { + return { + kind: this.kind, + accountId: this.accountId, + address: this.#address === null ? null : REDACTED, + addressTag: this.#addressTag === null ? null : REDACTED, + } + } + + toString(): string { + return ( + `TransferDestinationAccountLocation(kind=account, accountId=${this.accountId}, ` + + `address=${this.#address === null ? 'null' : REDACTED}, ` + + `addressTag=${this.#addressTag === null ? 'null' : REDACTED})` + ) + } +} + +/** The redacted shape `JSON.stringify`/`toString` produce for a destination blockchain leg. */ +export type TransferDestinationBlockchainLocationRendering = { + readonly kind: 'blockchain' + readonly chain: string | null + readonly address: string | null + readonly addressTag: string | null +} + +/** + * A transfer destination that is an on-chain address (OpenAPI + * `TransferDestinationBlockchainLocation`). + * + * **Both `chain` and `address` are nullable here, despite the OpenAPI schema + * marking both required.** The wire's `type: "blockchain"` comes from two + * different kinds of leg that this SDK cannot tell apart from the JSON alone: + * a verified-blockchain leg folds into it, because the public transfer + * taxonomy has no verified form on a read. + * + * - A plain blockchain leg always resolves `address` (the service falls back + * to the stored leg id when metadata is absent), so that path alone would + * justify treating it as required. + * - A folded verified-blockchain leg does **not** fall back — one with no + * recorded metadata yet genuinely has no address to report. + * - Both kinds report `chain` only once their blockchain metadata is + * recorded. + * + * Since either path can produce the wire shape this SDK decodes, and one of + * them can leave `address` absent, `address` has to be modeled as optional — + * requiring it would reject a real, un-backfilled verified-blockchain + * destination. Both fields are redacted the same way `Money.amount` is: behind + * a `#` private field, never an own enumerable property; `chain` is public + * because it is not sensitive. + */ +export class TransferDestinationBlockchainLocation { + readonly kind = 'blockchain' as const + readonly chain: string | null + readonly #address: string | null + readonly #addressTag: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { chain: string | null; address: string | null; addressTag: string | null }) { + this.chain = fields.chain + this.#address = fields.address + this.#addressTag = fields.addressTag + Object.freeze(this) + } + + /** The destination on-chain address, or `null` for an un-backfilled verified-blockchain leg. See the class note. */ + get address(): string | null { + return this.#address + } + + /** Secondary on-chain identifier (e.g. a Stellar memo) paired with {@link address}; nullable. */ + get addressTag(): string | null { + return this.#addressTag + } + + toJSON(): TransferDestinationBlockchainLocationRendering { + return { + kind: this.kind, + chain: this.chain, + address: this.#address === null ? null : REDACTED, + addressTag: this.#addressTag === null ? null : REDACTED, + } + } + + toString(): string { + return ( + `TransferDestinationBlockchainLocation(kind=blockchain, chain=${this.chain}, ` + + `address=${this.#address === null ? 'null' : REDACTED}, ` + + `addressTag=${this.#addressTag === null ? 'null' : REDACTED})` + ) + } +} + +/** + * A transfer's destination leg (OpenAPI `TransferDestinationLocation`, a `oneOf` + * of `TransferDestinationBlockchainLocation` and `TransferDestinationAccountLocation`). + * + * See {@link TransferSourceLocation} for the shared discriminator and the + * forward-compatibility contract for a `type` this SDK does not recognise. + */ +export type TransferDestinationLocation = + | TransferDestinationAccountLocation + | TransferDestinationBlockchainLocation + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +/** + * A single fee applied to a transfer (OpenAPI `Fee`). + * + * `amount` reuses `Money` rather than carrying its own decimal string — the exact + * problem `Money` already solves (the service serializes `Fee.amount` the same + * way, as a plain decimal string) and redacts the same way. `type` is a plain + * `string`: the service does not constrain it to an enum (the schema's + * `network` value is documentation only, not a runtime constraint), so there is + * no closed set to model or to get wrong. + */ +export type Fee = { + readonly amount: Money + readonly type: string +} + +/** + * Policy-engine evaluation attached to a transfer when one is available (OpenAPI + * `PolicyEvaluation`). + * + * `status` is a plain `string`, matching the service: `PolicyEvaluation.status` + * is a free-form string, not an enum, so — unlike `TransferStatus`/ + * `TransferErrorCode` — there is no closed set to widen or to fall back from. + */ +export type TransferPolicyEvaluation = { + readonly status: string +} + +/** The redacted shape `JSON.stringify(transfer)` produces. */ +export type TransferRendering = { + readonly id: string + readonly source: TransferSourceLocation | null + readonly destination: TransferDestinationLocation | null + readonly amount: { readonly amount: string; readonly currency: string } + readonly fees: string + readonly transactionHash: string | null + readonly destinationTransactionHash: string | null + readonly status: TransferStatus + readonly errorCode: TransferErrorCode | null + readonly policyEvaluation: TransferPolicyEvaluation | null + readonly createDate: string | null +} + +/** + * A DAA transfer, as the service reports it (OpenAPI `Transfer`, the response + * contract for `POST /v1/accounts/transfers`, each element of + * `GET /v1/accounts/transfers`, and `GET /v1/accounts/transfers/{transferId}`). + * + * Read-only at runtime as well as in the type system, for the same reason as + * `Account`: `readonly` is erased at compile time and would leave a returned + * transfer mutable through a cast. The instance is frozen and the fee list is a + * frozen array. + * + * **Not constructible by a consumer.** Exported from `index.ts` as a type only, + * and the `#` private fields make the type nominal so an object literal cannot + * be typed as a `Transfer`. + * + * **Only `id`, `amount`, and `status` are guaranteed non-null here — `source` + * and `destination` are not, despite the OpenAPI schema marking all five + * required.** That marking is a hint, not proof; the only evidence that + * settles requiredness is whether a service code path can produce the value + * absent, and for `source`/`destination` one does: the service reports no leg + * at all for a fiat source or destination, and no source leg for a + * verified-blockchain source. A transfer with a fiat leg — an ordinary onramp + * or offramp — is real, and the service omits null locations, so that leg is + * simply **absent** from the JSON body, not `null`; requiring it would reject + * an otherwise-readable transfer. `fees`, `transactionHash`, + * `destinationTransactionHash`, `errorCode`, and `policyEvaluation` are each + * documented as present only in some cases (a non-zero fee exists; a leg is + * blockchain; the CCTP destination leg has minted; status is `failed`; one is + * available) and decode to empty/`null` when absent, exactly as documented. + * + * **`createDate` is treated as optional despite looking mandatory**, and that is + * a deliberate hedge rather than an oversight: the OpenAPI schema does not mark + * it required at all (unlike `id`/`amount`/`status`) — the same kind of gap + * as `Account.description`, which the service can omit. This SDK reports it + * as it finds it rather than rejecting a transfer that is otherwise perfectly + * readable. + * + * **`amount` and `fees` do not appear in any default rendering.** Like `Account`'s + * `balances`, they sit behind prototype accessors rather than own properties, so + * `Object.keys`, `JSON.stringify`, `{ ...transfer }`, `for...in`, and the object + * inspectors behind `console.log` do not reach them; `toJSON`/`toString` reduce + * `fees` to a count and delegate `amount` to `Money`'s own redacted rendering. + * `source`/`destination` are plain own properties — safe, because a location that + * can carry an address redacts it itself (see + * {@link TransferDestinationAccountLocation}/{@link TransferDestinationBlockchainLocation}). + */ +export class Transfer { + /** Transfer id. */ + readonly id: string + + /** `null` for a fiat leg (an onramp) or a stray `verified_blockchain` source — see the class note. */ + readonly source: TransferSourceLocation | null + + /** `null` for a fiat leg (an offramp) — see the class note. */ + readonly destination: TransferDestinationLocation | null + + readonly status: TransferStatus + + /** Present only when {@link status} is `failed`. */ + readonly errorCode: TransferErrorCode | null + + /** On-chain transaction hash; present only when a leg is blockchain. */ + readonly transactionHash: string | null + + /** + * CCTP destination-mint hash — the transaction hash of the destination leg + * minting on the receiving chain. Present only for a CCTP transfer once + * that leg has minted; `null` otherwise. + */ + readonly destinationTransactionHash: string | null + + /** Policy-evaluation; absent until one is available. */ + readonly policyEvaluation: TransferPolicyEvaluation | null + + /** Creation timestamp, exactly as the service sent it (ISO-8601 UTC). See the class note on why this is optional. */ + readonly createDate: string | null + + readonly #amount: Money + readonly #fees: readonly Fee[] + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly id: string + readonly source: TransferSourceLocation | null + readonly destination: TransferDestinationLocation | null + readonly amount: Money + readonly fees: readonly Fee[] + readonly transactionHash: string | null + readonly destinationTransactionHash: string | null + readonly status: TransferStatus + readonly errorCode: TransferErrorCode | null + readonly policyEvaluation: TransferPolicyEvaluation | null + readonly createDate: string | null + }) { + this.id = fields.id + this.source = fields.source + this.destination = fields.destination + this.status = fields.status + this.errorCode = fields.errorCode + this.transactionHash = fields.transactionHash + this.destinationTransactionHash = fields.destinationTransactionHash + this.policyEvaluation = fields.policyEvaluation + this.createDate = fields.createDate + this.#amount = fields.amount + // Same reasoning as `Account#balances`: freezing a copy rather than the + // caller's own array, so this construction cannot reach back and freeze an + // argument the caller still holds a reference to. + this.#fees = Object.freeze(fields.fees.slice()) + Object.freeze(this) + } + + /** The transferred amount. Reuses `Money`, which redacts its own `amount` field. */ + get amount(): Money { + return this.#amount + } + + /** Applied fees. Empty when the service sent none (no non-zero fee exists). */ + get fees(): readonly Fee[] { + return this.#fees + } + + /** Identifiers and states render; the amount and fee amounts do not. */ + toJSON(): TransferRendering { + return { + id: this.id, + source: this.source, + destination: this.destination, + amount: this.#amount.toJSON(), + fees: `${this.#fees.length} entries`, + transactionHash: this.transactionHash, + destinationTransactionHash: this.destinationTransactionHash, + status: this.status, + errorCode: this.errorCode, + policyEvaluation: this.policyEvaluation, + createDate: this.createDate, + } + } + + /** Identifiers and states print; the amount and fee amounts do not. */ + toString(): string { + return ( + `Transfer(id=${this.id}, status=${this.status.kind}, ` + + `errorCode=${this.errorCode === null ? 'null' : this.errorCode.kind}, ` + + `amount=${this.#amount.toString()}, fees=${this.#fees.length} entries, ` + + `transactionHash=${this.transactionHash}, createDate=${this.createDate})` + ) + } +} diff --git a/src/models/Wire.ts b/src/models/Wire.ts new file mode 100644 index 0000000..96efde5 --- /dev/null +++ b/src/models/Wire.ts @@ -0,0 +1,405 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { BankAddress, BillingDetails } from './FiatAccount' +import type { FiatAccountStatus } from './FiatAccount' +import { REDACTED } from './redaction' + +// `WireSummary`, `Wire`, and `WireInstruction` are the exact component names +// the canonical public Accounts OpenAPI uses, not DAA-owned aliases. +// `WireInstructionBeneficiary` and `WireInstructionBeneficiaryBank` are that +// same schema's own nested type names for `WireInstruction`'s +// `beneficiary`/`beneficiaryBank` properties. + +/** One `transferTypesInfo` entry: the currencies a supported transfer type accepts. */ +export type TransferTypeInfo = Readonly<{ + currencies: readonly string[] +}> + +/** + * Circle's own receiving identity on a wire instruction — who the wire is + * addressed to, not the fiat-account holder. Not redacted: this is Circle's + * published receiving name and address, the same information the wire + * reference text itself carries, not the restricted PII this SDK redacts + * (`billingDetails`, `bankAddress`, `routingNumber`). + */ +export type WireInstructionBeneficiary = Readonly<{ + name: string | null + address1: string | null + address2: string | null +}> + +/** + * The receiving bank's own account details for a wire instruction — + * `routingNumber` and `accountNumber` among them, which are restricted PII. + * Redacted the same way + * `models/FiatAccount.ts`'s `BillingDetails`/`BankAddress` are. + */ +export class WireInstructionBeneficiaryBank { + readonly #name: string | null + readonly #swiftCode: string | null + readonly #routingNumber: string | null + readonly #accountNumber: string | null + readonly #currency: string | null + readonly #address: string | null + readonly #city: string | null + readonly #postalCode: string | null + readonly #country: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + readonly name: string | null + readonly swiftCode: string | null + readonly routingNumber: string | null + readonly accountNumber: string | null + readonly currency: string | null + readonly address: string | null + readonly city: string | null + readonly postalCode: string | null + readonly country: string | null + }) { + this.#name = fields.name + this.#swiftCode = fields.swiftCode + this.#routingNumber = fields.routingNumber + this.#accountNumber = fields.accountNumber + this.#currency = fields.currency + this.#address = fields.address + this.#city = fields.city + this.#postalCode = fields.postalCode + this.#country = fields.country + Object.freeze(this) + } + + get name(): string | null { + return this.#name + } + + get swiftCode(): string | null { + return this.#swiftCode + } + + get routingNumber(): string | null { + return this.#routingNumber + } + + get accountNumber(): string | null { + return this.#accountNumber + } + + get currency(): string | null { + return this.#currency + } + + get address(): string | null { + return this.#address + } + + get city(): string | null { + return this.#city + } + + get postalCode(): string | null { + return this.#postalCode + } + + get country(): string | null { + return this.#country + } + + toJSON(): string { + return this.toString() + } + + toString(): string { + return `WireInstructionBeneficiaryBank(${REDACTED})` + } +} + +/** + * Circle receiving instructions for a wire fiat account (`GET + * /v1/banks/wires/{id}/instructions`). + * + * Deliberately a separate SDK method and response type from {@link Wire}: the + * account resource and its funding instructions are separate. This is a plain + * typed read of the public instruction route, which returns Circle's receiving + * instructions; it does not resolve a self-custody pass-through account. + */ +export class WireInstruction { + readonly trackingRef: string | null + readonly beneficiary: WireInstructionBeneficiary | null + readonly virtualAccountEnabled: boolean | null + + readonly #beneficiaryBank: WireInstructionBeneficiaryBank | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + trackingRef: string | null + beneficiary: WireInstructionBeneficiary | null + beneficiaryBank: WireInstructionBeneficiaryBank | null + virtualAccountEnabled: boolean | null + }) { + this.trackingRef = fields.trackingRef + this.beneficiary = fields.beneficiary + this.virtualAccountEnabled = fields.virtualAccountEnabled + this.#beneficiaryBank = fields.beneficiaryBank + Object.freeze(this) + } + + get beneficiaryBank(): WireInstructionBeneficiaryBank | null { + return this.#beneficiaryBank + } + + toJSON(): { + trackingRef: string | null + beneficiary: WireInstructionBeneficiary | null + beneficiaryBank: string | null + virtualAccountEnabled: boolean | null + } { + return { + trackingRef: this.trackingRef, + beneficiary: this.beneficiary, + beneficiaryBank: this.#beneficiaryBank === null ? null : REDACTED, + virtualAccountEnabled: this.virtualAccountEnabled, + } + } + + toString(): string { + return ( + `WireInstruction(trackingRef=${this.trackingRef ?? 'null'}, ` + + `beneficiaryBank=${this.#beneficiaryBank === null ? 'null' : REDACTED})` + ) + } +} + +/** + * A wire bank account summary (`GET /v1/banks/wires` collection entry). + * + * `billingDetails` and `bankAddress` are private, redacted fields — see + * `models/FiatAccount.ts`. `ffcMemo` is private and redacted the same way: it + * is not one of the named restricted fields, but a for-further-credit memo can + * carry the end beneficiary's name, which is the same personal data + * `billingDetails.name` holds. Every other field is public: + * `id`/`status`/`description` (bank name plus last four + * digits)/`trackingRef`/`fingerprint` are what a caller needs to identify and + * select a fiat account without exposing the underlying bank details. + */ +export class WireSummary { + readonly id: string + readonly type: string | null + readonly status: FiatAccountStatus + readonly description: string + readonly trackingRef: string + readonly fingerprint: string + readonly virtualAccountEnabled: boolean | null + readonly createDate: string + readonly updateDate: string + + readonly #billingDetails: BillingDetails + readonly #bankAddress: BankAddress | null + readonly #ffcMemo: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: BillingDetails + bankAddress: BankAddress | null + virtualAccountEnabled: boolean | null + ffcMemo: string | null + createDate: string + updateDate: string + }) { + this.id = fields.id + this.type = fields.type + this.status = fields.status + this.description = fields.description + this.trackingRef = fields.trackingRef + this.fingerprint = fields.fingerprint + this.virtualAccountEnabled = fields.virtualAccountEnabled + this.createDate = fields.createDate + this.updateDate = fields.updateDate + this.#billingDetails = fields.billingDetails + this.#bankAddress = fields.bankAddress + this.#ffcMemo = fields.ffcMemo + Object.freeze(this) + } + + get billingDetails(): BillingDetails { + return this.#billingDetails + } + + get bankAddress(): BankAddress | null { + return this.#bankAddress + } + + get ffcMemo(): string | null { + return this.#ffcMemo + } + + toJSON(): { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: string + bankAddress: string | null + virtualAccountEnabled: boolean | null + ffcMemo: string | null + createDate: string + updateDate: string + } { + return { + id: this.id, + type: this.type, + status: this.status, + description: this.description, + trackingRef: this.trackingRef, + fingerprint: this.fingerprint, + billingDetails: REDACTED, + bankAddress: this.#bankAddress === null ? null : REDACTED, + virtualAccountEnabled: this.virtualAccountEnabled, + ffcMemo: this.#ffcMemo === null ? null : REDACTED, + createDate: this.createDate, + updateDate: this.updateDate, + } + } + + toString(): string { + return ( + `WireSummary(id=${this.id}, status=${this.status.kind}, ` + + `billingDetails=${REDACTED}, bankAddress=${this.#bankAddress === null ? 'null' : REDACTED})` + ) + } +} + +/** + * A wire bank account (`GET /v1/banks/wires/{id}`). + * + * Carries every {@link WireSummary} field plus `transferTypesInfo`, which the + * list projection omits, and redacts `billingDetails`, `bankAddress`, and + * `ffcMemo` the same way. Deliberately a distinct SDK type from `WireSummary` + * rather than a subtype — fiat-account resources are distinct SDK methods and + * response types, and the two + * projections diverge only in this one additional field, not in a + * specialization relationship. + */ +export class Wire { + readonly id: string + readonly type: string | null + readonly status: FiatAccountStatus + readonly description: string + readonly trackingRef: string + readonly fingerprint: string + readonly virtualAccountEnabled: boolean | null + readonly transferTypesInfo: Readonly> | null + readonly createDate: string + readonly updateDate: string + + readonly #billingDetails: BillingDetails + readonly #bankAddress: BankAddress | null + readonly #ffcMemo: string | null + + /** @internal Constructed only by the SDK's response decoder. */ + constructor(fields: { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: BillingDetails + bankAddress: BankAddress | null + virtualAccountEnabled: boolean | null + ffcMemo: string | null + transferTypesInfo: Readonly> | null + createDate: string + updateDate: string + }) { + this.id = fields.id + this.type = fields.type + this.status = fields.status + this.description = fields.description + this.trackingRef = fields.trackingRef + this.fingerprint = fields.fingerprint + this.virtualAccountEnabled = fields.virtualAccountEnabled + this.transferTypesInfo = fields.transferTypesInfo + this.createDate = fields.createDate + this.updateDate = fields.updateDate + this.#billingDetails = fields.billingDetails + this.#bankAddress = fields.bankAddress + this.#ffcMemo = fields.ffcMemo + Object.freeze(this) + } + + get billingDetails(): BillingDetails { + return this.#billingDetails + } + + get bankAddress(): BankAddress | null { + return this.#bankAddress + } + + get ffcMemo(): string | null { + return this.#ffcMemo + } + + toJSON(): { + id: string + type: string | null + status: FiatAccountStatus + description: string + trackingRef: string + fingerprint: string + billingDetails: string + bankAddress: string | null + virtualAccountEnabled: boolean | null + ffcMemo: string | null + transferTypesInfo: Readonly> | null + createDate: string + updateDate: string + } { + return { + id: this.id, + type: this.type, + status: this.status, + description: this.description, + trackingRef: this.trackingRef, + fingerprint: this.fingerprint, + billingDetails: REDACTED, + bankAddress: this.#bankAddress === null ? null : REDACTED, + virtualAccountEnabled: this.virtualAccountEnabled, + ffcMemo: this.#ffcMemo === null ? null : REDACTED, + transferTypesInfo: this.transferTypesInfo, + createDate: this.createDate, + updateDate: this.updateDate, + } + } + + toString(): string { + return ( + `Wire(id=${this.id}, status=${this.status.kind}, ` + + `billingDetails=${REDACTED}, bankAddress=${this.#bankAddress === null ? 'null' : REDACTED})` + ) + } +} diff --git a/src/models/Withdrawal.ts b/src/models/Withdrawal.ts new file mode 100644 index 0000000..6c8b47b --- /dev/null +++ b/src/models/Withdrawal.ts @@ -0,0 +1,283 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { Money } from './Money' +import { REDACTED } from './redaction' + +export type WithdrawalStatus = + | { readonly kind: 'pending' } + | { readonly kind: 'complete' } + | { readonly kind: 'failed' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +export type WithdrawalErrorCode = + | { readonly kind: 'insufficient_funds' } + | { readonly kind: 'transaction_denied' } + | { readonly kind: 'transaction_failed' } + | { readonly kind: 'transaction_returned' } + | { readonly kind: 'bank_transaction_error' } + | { readonly kind: 'fiat_account_limit_exceeded' } + | { readonly kind: 'invalid_bank_account_number' } + | { readonly kind: 'invalid_ach_rtn' } + | { readonly kind: 'invalid_wire_rtn' } + | { readonly kind: 'vendor_inactive' } + | { readonly kind: 'payout_canceled' } + | { readonly kind: 'invalid_travel_rule_identity' } + | { readonly kind: 'intermediary_bank_required' } + | { readonly kind: 'sen_not_supported' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +export type WithdrawalDestinationType = + | { readonly kind: 'wire' } + | { readonly kind: 'ach' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +export type WithdrawalDestination = Readonly<{ + type: WithdrawalDestinationType + id: string + name: string | null +}> + +export type WithdrawalRiskEvaluation = Readonly<{ + decision: string | null + reason: string | null +}> + +export type WithdrawalPolicyEvaluation = Readonly<{ status: string }> + +/** Target fiat amount. Unlike `Money`, its service-side amount is deliberately optional. */ +export class WithdrawalToAmount { + readonly currency: string | null + readonly #amount: string | null + + /** @internal Constructed only by the response decoder. */ + constructor(amount: string | null, currency: string | null) { + this.#amount = amount + this.currency = currency + Object.freeze(this) + } + + get amount(): string | null { + return this.#amount + } + + toJSON(): { readonly amount: string | null; readonly currency: string | null } { + return { amount: this.#amount === null ? null : REDACTED, currency: this.currency } + } + + toString(): string { + return `WithdrawalToAmount(amount=${this.#amount === null ? 'null' : REDACTED}, currency=${this.currency})` + } +} + +export type WithdrawalAdjustments = Readonly<{ + fxCredit: Money | null + fxDebit: Money | null +}> + +export type WithdrawalReturn = Readonly<{ + id: string | null + payoutId: string | null + amount: Money | null + fees: Money | null + reason: string | null + status: WithdrawalStatus | null + createDate: string | null + updateDate: string | null +}> + +export type WithdrawalSweepStatus = + | { readonly kind: 'pending' } + | { readonly kind: 'complete' } + | { readonly kind: 'failed' } + | { readonly kind: 'skipped' } + | { readonly kind: 'unrecognized'; readonly rawValue: string | null } + +export type WithdrawalSubAccountSweep = Readonly<{ + subAccountId: string | null + amount: Money | null + status: WithdrawalSweepStatus | null +}> + +export type WithdrawalDetailRendering = Readonly<{ + id: string + sourceAccountId: string + destination: WithdrawalDestination + amount: ReturnType + toAmount: WithdrawalToAmount | null + fees: ReturnType | null + status: WithdrawalStatus + trackingRef: string | null + errorCode: WithdrawalErrorCode | null + externalRef: string | null + riskEvaluation: WithdrawalRiskEvaluation | null + adjustments: string + return: string + customerExternalRef: string | null + burnAll: boolean | null + subAccountSweeps: string + createDate: string + updateDate: string | null + policyEvaluation: WithdrawalPolicyEvaluation | null +}> + +/** + * GET-only DAA withdrawal projection. + * + * The guaranteed core follows the service's two read paths, not the generated + * schema: `id`, `sourceAccountId`, `destination`, `amount`, `status`, and + * `createDate` are produced by both payout-backed and stored-withdrawal reads. + * Enrichment is omitted from the response whenever unavailable. Amounts plus + * bank/customer references are private so object inspection, spread, and + * enumeration cannot disclose them. + */ +export class WithdrawalDetail { + readonly id: string + readonly sourceAccountId: string + readonly destination: WithdrawalDestination + readonly status: WithdrawalStatus + readonly trackingRef: string | null + readonly errorCode: WithdrawalErrorCode | null + readonly riskEvaluation: WithdrawalRiskEvaluation | null + readonly burnAll: boolean | null + readonly createDate: string + readonly updateDate: string | null + readonly policyEvaluation: WithdrawalPolicyEvaluation | null + + readonly #amount: Money + readonly #toAmount: WithdrawalToAmount | null + readonly #fees: Money | null + readonly #externalRef: string | null + readonly #adjustments: WithdrawalAdjustments | null + readonly #returnObject: WithdrawalReturn | null + readonly #customerExternalRef: string | null + readonly #subAccountSweeps: readonly WithdrawalSubAccountSweep[] + + /** @internal Constructed only by the response decoder. */ + constructor(fields: { + id: string + sourceAccountId: string + destination: WithdrawalDestination + amount: Money + toAmount: WithdrawalToAmount | null + fees: Money | null + status: WithdrawalStatus + trackingRef: string | null + errorCode: WithdrawalErrorCode | null + externalRef: string | null + riskEvaluation: WithdrawalRiskEvaluation | null + adjustments: WithdrawalAdjustments | null + returnObject: WithdrawalReturn | null + customerExternalRef: string | null + burnAll: boolean | null + subAccountSweeps: readonly WithdrawalSubAccountSweep[] + createDate: string + updateDate: string | null + policyEvaluation: WithdrawalPolicyEvaluation | null + }) { + this.id = fields.id + this.sourceAccountId = fields.sourceAccountId + this.destination = fields.destination + this.status = fields.status + this.trackingRef = fields.trackingRef + this.errorCode = fields.errorCode + this.riskEvaluation = fields.riskEvaluation + this.burnAll = fields.burnAll + this.createDate = fields.createDate + this.updateDate = fields.updateDate + this.policyEvaluation = fields.policyEvaluation + this.#amount = fields.amount + this.#toAmount = fields.toAmount + this.#fees = fields.fees + this.#externalRef = fields.externalRef + this.#adjustments = fields.adjustments + this.#returnObject = fields.returnObject + this.#customerExternalRef = fields.customerExternalRef + this.#subAccountSweeps = Object.freeze(fields.subAccountSweeps.slice()) + Object.freeze(this) + } + + get amount(): Money { + return this.#amount + } + + get toAmount(): WithdrawalToAmount | null { + return this.#toAmount + } + + get fees(): Money | null { + return this.#fees + } + + get externalRef(): string | null { + return this.#externalRef + } + + get adjustments(): WithdrawalAdjustments | null { + return this.#adjustments + } + + get returnObject(): WithdrawalReturn | null { + return this.#returnObject + } + + get customerExternalRef(): string | null { + return this.#customerExternalRef + } + + get subAccountSweeps(): readonly WithdrawalSubAccountSweep[] { + return this.#subAccountSweeps + } + + toJSON(): WithdrawalDetailRendering { + return { + id: this.id, + sourceAccountId: this.sourceAccountId, + destination: this.destination, + amount: this.#amount.toJSON(), + toAmount: this.#toAmount, + fees: this.#fees?.toJSON() ?? null, + status: this.status, + trackingRef: this.trackingRef, + errorCode: this.errorCode, + externalRef: this.#externalRef === null ? null : REDACTED, + riskEvaluation: this.riskEvaluation, + adjustments: `${this.#adjustments === null ? 0 : 1} entry`, + return: `${this.#returnObject === null ? 0 : 1} entry`, + customerExternalRef: this.#customerExternalRef === null ? null : REDACTED, + burnAll: this.burnAll, + subAccountSweeps: `${this.#subAccountSweeps.length} entries`, + createDate: this.createDate, + updateDate: this.updateDate, + policyEvaluation: this.policyEvaluation, + } + } + + toString(): string { + return ( + `WithdrawalDetail(id=${this.id}, sourceAccountId=${this.sourceAccountId}, ` + + `status=${this.status.kind}, amount=${this.#amount.toString()}, ` + + `fees=${this.#fees === null ? 'null' : this.#fees.toString()}, ` + + `externalRef=${this.#externalRef === null ? 'null' : REDACTED}, ` + + `customerExternalRef=${this.#customerExternalRef === null ? 'null' : REDACTED}, ` + + `adjustments=${this.#adjustments === null ? 0 : 1} entry, ` + + `return=${this.#returnObject === null ? 0 : 1} entry, ` + + `subAccountSweeps=${this.#subAccountSweeps.length} entries)` + ) + } +} diff --git a/src/models/redaction.ts b/src/models/redaction.ts new file mode 100644 index 0000000..993f8bf --- /dev/null +++ b/src/models/redaction.ts @@ -0,0 +1,22 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The one spelling of a redacted value, so a model cannot half-redact and a test +// cannot pass against a different placeholder than the one production renders. + +export const REDACTED = '' diff --git a/src/sca/ScaClient.ts b/src/sca/ScaClient.ts new file mode 100644 index 0000000..14c1970 --- /dev/null +++ b/src/sca/ScaClient.ts @@ -0,0 +1,289 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' + +/** + * Passkey strong customer authentication (SCA) through Circle's hosted + * ceremony page, run by the native iOS / Android SDKs. + * + * The flow: your backend opens a challenge (or registration) with your app's + * `redirectUri` and keeps the returned id; it hands the app only the + * `frameToken`. The app calls {@link ScaClient.approve} (or `enroll`) and sends + * the returned string, unmodified, back to the backend, which retries the + * gated request with `X-Sca-Challenge-Id` and `X-Sca-Assertion`. + */ + +/** Public environments only; reach another Circle host with `circleOrigin`. */ +export type ScaEnvironment = 'sandbox' | 'production' + +export interface ScaConfig { + environment: ScaEnvironment + /** + * The callback URI registered with Circle for your app, exactly as + * registered. Android requires an `https` App Link for `approve`. + */ + redirectUri: string + /** + * Another Circle ceremony origin (bare `https://*.circle.com`). Only with + * `sandbox`; refused for `production`. + */ + circleOrigin?: string + /** Deadline for an approval, ms. Default 300 000, range 30 000–3 600 000. */ + approveTimeoutMs?: number + /** Deadline for an enrollment, ms. Default 600 000, range 30 000–3 600 000. */ + enrollTimeoutMs?: number +} + +export type ScaErrorCode = + | 'Cancelled' + | 'Expired' + | 'Unsupported' + | 'AlreadyEnrolled' + | 'Protocol' + | 'Transport' + | 'InvalidConfiguration' + | 'CeremonyInProgress' + | 'NativeModuleUnavailable' + +/** + * A failed ceremony. `code` is the stable vocabulary to branch on; `reason` + * narrows `Unsupported` and `Protocol` where the platform can tell (for + * example `NoAllowedBrowser`, `CallbackNotRouted`, `SessionUnavailable`, + * `StateMismatch`, `InvalidFrameToken`). `Protocol` is an integration bug, + * never a reason to offer a different authentication method. + * + * The SDK always sets `message` to one of its own literals, never to text from + * the native SDKs: it is what crash reporters log by default. For a failure that + * came from native, the native rejection is kept as `cause` for deliberate + * inspection. + */ +export class ScaError extends Error { + readonly code: ScaErrorCode + readonly reason: string | null + // The native rejection this error was mapped from, if any. Kept off + // `message` (so it never lands in logs by default) but available to a host + // that deliberately inspects `err.cause`. + readonly cause: unknown + + constructor( + code: ScaErrorCode, + message: string, + reason: string | null = null, + cause: unknown = undefined, + ) { + super(message) + this.name = 'ScaError' + this.code = code + this.reason = reason + this.cause = cause + // Keep `cause` non-enumerable so JSON.stringify and crash reporters that + // walk own enumerable properties do not export the native rejection (its + // message, code, or native stack). It stays readable via `err.cause`. + Object.defineProperty(this, 'cause', { enumerable: false }) + } +} + +export function isScaError(err: unknown): err is ScaError { + return err instanceof ScaError +} + +export interface ScaCapabilities { + protocolVersion: number + /** `webAuthenticationSession` (iOS), `authTab` / `customTab` (Android), or `none`. */ + surface: string + /** The redirect URI reaches this app's callback (Android: an exported, routed activity). */ + callbackReady: boolean + /** Android API 31+: whether the App Link is verified; otherwise `null`. */ + callbackVerified: boolean | null + /** Android: whether the callback activity is task-isolated; otherwise `null`. */ + callbackTaskIsolated: boolean | null + platformPasskeys: boolean +} + +export interface ScaClient { + readonly config: Readonly + /** Returns the exact `X-Sca-Assertion` value. Send it unmodified. */ + approve(frameToken: string): Promise + /** Returns the registration response JSON text for your backend. */ + enroll(frameToken: string): Promise + capabilities(): Promise +} + +interface DaaScaNativeModule { + approve(config: ScaConfig, frameToken: string): Promise + enroll(config: ScaConfig, frameToken: string): Promise + capabilities(config: ScaConfig): Promise> +} + +const NATIVE_CODES: Readonly> = { + SCA_CANCELLED: 'Cancelled', + SCA_EXPIRED: 'Expired', + SCA_UNSUPPORTED: 'Unsupported', + SCA_ALREADY_ENROLLED: 'AlreadyEnrolled', + SCA_PROTOCOL: 'Protocol', + SCA_TRANSPORT: 'Transport', + SCA_INVALID_CONFIGURATION: 'InvalidConfiguration', + SCA_CEREMONY_IN_PROGRESS: 'CeremonyInProgress', +} + +// The `message` for each code. The native rejection's own text never reaches +// `ScaError.message`: it can carry platform or internal detail, and `message` +// is what crash reporters log by default. The native rejection stays on the +// non-enumerable `cause`. +const MESSAGES: Readonly> = { + Cancelled: 'The SCA ceremony was cancelled', + Expired: 'The SCA ceremony deadline passed', + Unsupported: 'This device or app cannot run the SCA ceremony', + AlreadyEnrolled: 'A passkey is already enrolled on this authenticator', + Protocol: 'The SCA ceremony failed with a protocol error', + Transport: 'The SCA ceremony failed on a transport error', + InvalidConfiguration: 'The SCA configuration was rejected', + CeremonyInProgress: 'Another SCA ceremony is still open', + NativeModuleUnavailable: 'The DaaSca native module is not linked in this build', +} + +// Expo prefixes an async function's message ("Calling the 'approve' function +// has failed\n→ Caused by: …"), so the tag is read from the innermost cause. +// Android passes the native exception's code through; iOS does not (the +// rejection reaches JS without a code), so both bridges also tag the innermost +// message with the code ("[SCA_UNSUPPORTED:NoAllowedBrowser] …"). A known +// `code` wins; otherwise the tag is used; otherwise it is a Protocol failure. +// The message itself is read only for that tag. +const CAUSE_SEPARATOR = '→ Caused by: ' +const CODE_TAG = /^\[(SCA_[A-Z_]+(?::[A-Za-z]+)?)\] ?/ +// A reason is a name from the platform's vocabulary. One with any other shape +// is native text, not a reason, and is dropped rather than passed on. +const REASON = /^[A-Za-z]+$/ + +function innermostMessage(message: string): string { + const at = message.lastIndexOf(CAUSE_SEPARATOR) + return at < 0 ? message : message.slice(at + CAUSE_SEPARATOR.length) +} + +function knownCode(base: string): ScaErrorCode | undefined { + return Object.prototype.hasOwnProperty.call(NATIVE_CODES, base) ? NATIVE_CODES[base] : undefined +} + +function splitCode(nativeCode: string): [string, string | null] { + const separator = nativeCode.indexOf(':') + if (separator < 0) { + return [nativeCode, null] + } + const reason = nativeCode.slice(separator + 1) + return [nativeCode.slice(0, separator), REASON.test(reason) ? reason : null] +} + +/** + * Translates a native rejection into a {@link ScaError}. The result's + * `message` is the fixed text for its code; the rejection itself is kept as + * the non-enumerable `cause`. + */ +export function mapNativeScaError(err: unknown): ScaError { + if (err instanceof ScaError) { + return err + } + const rawCode = + typeof (err as { code?: unknown })?.code === 'string' ? (err as { code: string }).code : '' + const rawMessage = + typeof (err as { message?: unknown })?.message === 'string' + ? (err as { message: string }).message + : '' + const tag = CODE_TAG.exec(innermostMessage(rawMessage)) + const fromCode = splitCode(rawCode) + const [base, reason] = knownCode(fromCode[0]) + ? fromCode + : tag + ? splitCode(tag[1] ?? '') + : fromCode + const code = knownCode(base) ?? 'Protocol' + return new ScaError(code, MESSAGES[code], reason, err) +} + +function validated(config: ScaConfig): Readonly { + if (config.environment !== 'sandbox' && config.environment !== 'production') { + throw new ScaError('InvalidConfiguration', "environment must be 'sandbox' or 'production'") + } + if (typeof config.redirectUri !== 'string' || config.redirectUri.length === 0) { + throw new ScaError('InvalidConfiguration', 'redirectUri is required') + } + // The native SDKs re-validate everything (URI rules, origin, timeout range). + return Object.freeze({ ...config }) +} + +/** + * Creates an SCA client. One ceremony runs at a time across the app: a second + * `approve` or `enroll` while one is open rejects with `CeremonyInProgress` + * and leaves the open one alone. Disable the control that starts a ceremony + * until the call settles. + */ +export function createScaClient( + config: ScaConfig, + native: DaaScaNativeModule | null = requireOptionalNativeModule('DaaSca'), +): ScaClient { + const frozen = validated(config) + const module = (): DaaScaNativeModule => { + if (native === null) { + throw new ScaError('NativeModuleUnavailable', MESSAGES.NativeModuleUnavailable) + } + return native + } + let inFlight = false + + const ceremony = async ( + run: (n: DaaScaNativeModule) => Promise, + frameToken: string, + ): Promise => { + if (typeof frameToken !== 'string' || frameToken.length === 0) { + throw new ScaError('InvalidConfiguration', 'frameToken is required') + } + if (inFlight) { + throw new ScaError('CeremonyInProgress', MESSAGES.CeremonyInProgress) + } + inFlight = true + try { + return await run(module()) + } catch (err) { + throw mapNativeScaError(err) + } finally { + inFlight = false + } + } + + return { + config: frozen, + approve: (frameToken) => ceremony((n) => n.approve(frozen, frameToken), frameToken), + enroll: (frameToken) => ceremony((n) => n.enroll(frozen, frameToken), frameToken), + async capabilities() { + try { + const raw = await module().capabilities(frozen) + return { + protocolVersion: Number(raw.protocolVersion), + surface: String(raw.surface), + callbackReady: raw.callbackReady === true, + callbackVerified: typeof raw.callbackVerified === 'boolean' ? raw.callbackVerified : null, + callbackTaskIsolated: + typeof raw.callbackTaskIsolated === 'boolean' ? raw.callbackTaskIsolated : null, + platformPasskeys: raw.platformPasskeys === true, + } + } catch (err) { + throw mapNativeScaError(err) + } + }, + } +} diff --git a/src/securekey/InMemorySecureKey.ts b/src/securekey/InMemorySecureKey.ts new file mode 100644 index 0000000..0e8293c --- /dev/null +++ b/src/securekey/InMemorySecureKey.ts @@ -0,0 +1,138 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { toBase64Url } from '../crypto/base64url' +import { toArrayBuffer } from '../crypto/bytes' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { secureKeyAlias } from './alias' +import type { AuthKeyResolution, OwnerAuthKey, OwnerKeyIdentity, SecureKeyStore } from './SecureKey' + +// A WebCrypto-backed, in-memory implementation of the DAA Owner-key API. It +// produces real P-256/ES256 signatures so it can drive golden vectors and unit +// tests WITHOUT native hardware. It is NOT a production secure-key +// implementation: keys live in process memory, not a secure enclave/keystore. + +function getSubtle(): SubtleCrypto { + const c = (globalThis as { crypto?: Crypto }).crypto + if (!c || !c.subtle) { + throw new Error('DAA: WebCrypto (crypto.subtle) is not available') + } + return c.subtle +} + +function assertDevelopmentEnvironment(): void { + const g = globalThis as { __DEV__?: boolean; process?: { env?: { NODE_ENV?: string } } } + const nodeEnvironment = g.process?.env?.NODE_ENV + const explicitlyProduction = g.__DEV__ === false || nodeEnvironment === 'production' + const explicitlyDevelopment = + g.__DEV__ === true || nodeEnvironment === 'development' || nodeEnvironment === 'test' + if (explicitlyProduction) { + throw new Error( + 'DAA: InMemorySecureKeyStore is a test double and must not be used in ' + + 'production; wire the native secure-key store instead.', + ) + } + if (!explicitlyDevelopment) { + throw new Error( + 'DAA: InMemorySecureKeyStore requires an explicit development or test ' + + 'environment marker (__DEV__ or NODE_ENV).', + ) + } +} + +class InMemoryOwnerAuthKey implements OwnerAuthKey { + // There is no durable store behind this double, so a handle always starts + // unacknowledged and the state lives only as long as the handle does. The + // native store persists the equivalent state in the OS keystore. + #acknowledged = false + readonly #keyPair: CryptoKeyPair + + constructor(keyPair: CryptoKeyPair) { + this.#keyPair = keyPair + } + + resolution(): AuthKeyResolution { + return this.#acknowledged ? 'existing' : 'created' + } + + async acknowledgeRegistration(): Promise { + this.#acknowledged = true + } + + async publicKeySpkiBase64Url(): Promise { + const spki = await getSubtle().exportKey('spki', this.#keyPair.publicKey) + return toBase64Url(new Uint8Array(spki)) + } + + async thumbprint(): Promise { + // Same one-place RFC 7638 derivation the native store uses. + const spki = await getSubtle().exportKey('spki', this.#keyPair.publicKey) + return p256JwkThumbprint(new Uint8Array(spki)) + } + + async signExactBytes(message: Uint8Array): Promise { + const sig = await getSubtle().sign( + { name: 'ECDSA', hash: 'SHA-256' }, + this.#keyPair.privateKey, + toArrayBuffer(message), + ) + return new Uint8Array(sig) // JOSE R || S, 64 bytes. + } + + async signRegistrationDeviceAuthorization(message: Uint8Array): Promise { + // This test double has no separate native validators to route between — + // it is one WebCrypto key signing whatever exact bytes it is given + // either way. The two methods exist here only so this class satisfies + // OwnerAuthKey and a test can assert on WHICH method the production + // caller reached; native's two validators are what actually diverge. + return this.signExactBytes(message) + } +} + +export class InMemorySecureKeyStore implements SecureKeyStore { + readonly #keys = new Map>() + + constructor() { + assertDevelopmentEnvironment() + } + + async resolveOrCreate(identity: OwnerKeyIdentity): Promise { + const id = secureKeyAlias(identity) + let existing = this.#keys.get(id) + if (!existing) { + // Evict on failure so a transient error (e.g. crypto.subtle not yet + // available) is not memoized permanently for this identity. + existing = this.#generate().catch((err: unknown) => { + this.#keys.delete(id) + throw err + }) + this.#keys.set(id, existing) + } + return existing + } + + async #generate(): Promise { + const keyPair = (await getSubtle().generateKey( + { name: 'ECDSA', namedCurve: 'P-256' }, + // Non-exportable private key; the public key is still exportable. + false, + ['sign', 'verify'], + )) as CryptoKeyPair + return new InMemoryOwnerAuthKey(keyPair) + } +} diff --git a/src/securekey/NativeSecureKey.ts b/src/securekey/NativeSecureKey.ts new file mode 100644 index 0000000..6ed5037 --- /dev/null +++ b/src/securekey/NativeSecureKey.ts @@ -0,0 +1,179 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { fromBase64Url, toBase64Url } from '../crypto/base64url' +import { p256JwkThumbprint } from '../crypto/jwkThumbprint' +import { contractViolation, mapNativeError } from '../errors' +import { secureKeyAlias } from './alias' +import type { NativeSecureKeyBridge } from './NativeSecureKeyBridge' +import type { AuthKeyResolution, OwnerAuthKey, OwnerKeyIdentity, SecureKeyStore } from './SecureKey' + +// Production DAA Owner-key store backed by the platform secure-key module. It +// holds no key material itself — every operation delegates to the native bridge, +// which keeps the non-exportable private key behind the OS keystore/enclave. +// +// The bridge is injected so this class is unit-testable without native hardware +// (see src/__test__/nativeSecureKey.test.ts). Production wiring resolves the +// real native module via resolveNativeBridge(). +// +// The `'created' | 'existing'` discriminant native returns from resolveOrCreate +// is retained on the handle rather than discarded, so a caller can tell an +// AuthKey still awaiting Circle's registration acknowledgement from one that +// already has it. It is deliberately NOT flattened at this seam. + +// The alias namespaces one key per `{appId, environment, clientEntityId}` — +// per Owner, not per installation (see secureKeyAlias). +// The Expo module parses that alias in TypeScript, then constructs native +// `DaaAuthKeyIdentity` with a durable per-install UUID it owns (app-container +// file excluded from backup on iOS, app-private no-backup storage on Android; +// both are deleted on uninstall). Native key tags therefore include the +// installation UUID. + +// Run a native bridge call, mapping any rejection onto DaaSdkError so raw +// keystore/enclave text never reaches the caller. +async function guardNative(op: () => Promise): Promise { + try { + return await op() + } catch (err) { + throw mapNativeError(err) + } +} + +// Decode a Base64URL value the native module returned and assert its exact byte +// length — the seam is the last place to enforce the OwnerAuthKey contract +// before these values reach the wire or pin an Owner key. +function decodeExact(value: string, expected: number, what: string): Uint8Array { + let bytes: Uint8Array + try { + bytes = fromBase64Url(value) + } catch { + throw contractViolation(`native ${what} is not valid Base64URL`) + } + if (bytes.length !== expected) { + throw contractViolation(`native ${what} must be ${expected} bytes; got ${bytes.length}`) + } + return bytes +} + +// Re-validate the discriminant at the store seam. resolveNativeBridge() already +// checks it for the production module, but an injected stand-in is untyped at +// runtime, so a third value must fail closed here too rather than being pinned +// onto a handle and read back later as if it were meaningful. +function parseNativeResolution(value: unknown): AuthKeyResolution { + if (value === 'created' || value === 'existing') { + return value + } + throw contractViolation('native resolveOrCreate must return created or existing') +} + +class NativeOwnerAuthKey implements OwnerAuthKey { + #resolution: AuthKeyResolution + #acknowledging: Promise | null = null + readonly #bridge: NativeSecureKeyBridge + readonly #alias: string + + constructor(bridge: NativeSecureKeyBridge, alias: string, resolution: AuthKeyResolution) { + this.#bridge = bridge + this.#alias = alias + this.#resolution = resolution + } + + resolution(): AuthKeyResolution { + return this.#resolution + } + + async acknowledgeRegistration(): Promise { + if (this.#resolution === 'existing') { + return + } + if (this.#acknowledging === null) { + // De-duplicate concurrent callers on one handle to a single native round + // trip, the same way NativeSecureKeyStore.resolveOrCreate does. The + // `existing` check above cannot do it alone: it is synchronous, so two + // callers that do not await between them both observe `created`. + // + // Cleared on failure so a transient native error stays retryable and is + // not memoized as a permanently poisoned acknowledgement. + this.#acknowledging = guardNative(() => this.#bridge.acknowledgeRegistration(this.#alias)) + .then(() => { + this.#resolution = 'existing' + }) + .catch((err: unknown) => { + this.#acknowledging = null + throw err + }) + } + return this.#acknowledging + } + + async publicKeySpkiBase64Url(): Promise { + const spki = await guardNative(() => this.#bridge.publicKeySpkiBase64Url(this.#alias)) + decodeExact(spki, 91, 'public key (P-256 SPKI)') // P-256 SPKI is exactly 91 DER bytes + return spki + } + + async thumbprint(): Promise { + // Derived in TS from the (length-checked) SPKI — one RFC 7638 implementation + // shared with the in-memory store; no native thumbprint to drift. + const spki = await this.publicKeySpkiBase64Url() + return p256JwkThumbprint(fromBase64Url(spki)) + } + + async signExactBytes(message: Uint8Array): Promise { + const raw = await guardNative(() => this.#bridge.sign(this.#alias, toBase64Url(message))) + // A native module that forgets DER -> R||S returns ~70 bytes that decode + // cleanly; the exact-length check catches it here, before the wire. + return decodeExact(raw, 64, 'signature (JOSE R||S; convert DER ECDSA to R||S)') + } + + async signRegistrationDeviceAuthorization(message: Uint8Array): Promise { + // A DIFFERENT bridge call from signExactBytes/sign above — see + // SecureKey.ts and NativeSecureKeyBridge.ts for why the registration + // device proof cannot share the post-activation seam. + const raw = await guardNative(() => + this.#bridge.signRegistrationDeviceAuthorization(this.#alias, toBase64Url(message)), + ) + return decodeExact(raw, 64, 'registration signature (JOSE R||S; convert DER ECDSA to R||S)') + } +} + +export class NativeSecureKeyStore implements SecureKeyStore { + readonly #keys = new Map>() + readonly #bridge: NativeSecureKeyBridge + + constructor(bridge: NativeSecureKeyBridge) { + this.#bridge = bridge + } + + async resolveOrCreate(identity: OwnerKeyIdentity): Promise { + const alias = secureKeyAlias(identity) + let existing = this.#keys.get(alias) + if (!existing) { + // Evict on failure so a transient native error is not memoized forever; + // map the native rejection onto DaaSdkError. + existing = guardNative(() => this.#bridge.resolveOrCreate(alias)) + .then((raw) => new NativeOwnerAuthKey(this.#bridge, alias, parseNativeResolution(raw))) + .catch((err: unknown) => { + this.#keys.delete(alias) + throw err + }) + this.#keys.set(alias, existing) + } + return existing + } +} diff --git a/src/securekey/NativeSecureKeyBridge.ts b/src/securekey/NativeSecureKeyBridge.ts new file mode 100644 index 0000000..05fa94c --- /dev/null +++ b/src/securekey/NativeSecureKeyBridge.ts @@ -0,0 +1,109 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The JS <-> native contract implemented by the platform secure-key module +// (iOS Keychain / Secure Enclave, Android Keystore). +// +// Keys are non-exportable and referenced by an opaque `alias`. Private key bytes +// never cross this boundary. All byte-valued arguments and results are unpadded +// Base64URL strings so the contract is uniform across the RN bridge. +// +// The Expo `DaaSecureKey` module under ios/ and android/ implements this +// contract by delegating to daa-ios-sdk / daa-android-sdk. Production apps +// resolve it via resolveNativeBridge(); tests inject a stand-in. +// +// Every method here takes the RN `alias`; resolveNativeBridge() parses it into +// the structured `{appId, environment}` pair the Expo module accepts. +import type { AuthKeyResolution } from './SecureKey' + +// The bridge-side name for the public `AuthKeyResolution`. +export type NativeAuthKeyResolution = AuthKeyResolution + +export interface NativeSecureKeyBridge { + /** + * Ensure a non-exportable P-256 key exists for `alias`, creating it only when + * absent. Idempotent. + * + * Returns the native SDKs' resolution discriminant, which is about + * REGISTRATION state, not merely whether this call minted the key: + * `'created'` when the key was just minted OR when an existing key carries no + * durable registration acknowledgement; `'existing'` only for a key Circle is + * durably recorded as having registered. `acknowledgeRegistration` is what + * moves a key from the former to the latter. + */ + resolveOrCreate(alias: string): Promise + + /** Unpadded Base64URL DER SubjectPublicKeyInfo of the public key. */ + publicKeySpkiBase64Url(alias: string): Promise + + /** + * Persist that Circle registered the public key for `alias`. Idempotent — + * native no-ops when the key is already acknowledged. After it succeeds, + * later `resolveOrCreate` calls return `'existing'`. + */ + acknowledgeRegistration(alias: string): Promise + + // The RFC 7638 thumbprint is derived in TypeScript from the SPKI above (see + // crypto/jwkThumbprint), so the native module does not implement it — one + // canonicalization, no cross-platform drift. Native thumbprint() is not + // called at this seam. + + /** + * ES256 signature over the exact message bytes. + * + * Production `resolveNativeBridge()` sends those bytes to Expo + * `signDeviceAuthorization` (native `DaaSecureKey.signDeviceAuthorization` + * + `DaaDeviceAuthorizationSigningInput`). There is no native generic + * `sign(bytes)` Expo method. Compact JWS construction lives in + * `auth/deviceAuthorization.ts` and signs through `OwnerAuthKey.signExactBytes`. + * Native validates the compact signing input and signs that same slice. + * The header carries the published `typ` as-is. + * + * Injectable test stand-ins may still implement this for NativeSecureKeyStore + * unit tests (including arbitrary bytes the native validator would reject). + * + * @param messageBase64Url unpadded Base64URL of the exact bytes to sign. + * @returns unpadded Base64URL of the 64-byte JOSE `R || S` signature. + */ + sign(alias: string, messageBase64Url: string): Promise + + /** + * ES256 signature over the exact Device Registration Complete device-proof + * signing input. + * + * A DISTINCT method from {@link sign}, not an overload or a shared code + * path: production `resolveNativeBridge()` sends these bytes to Expo + * `signRegistrationDeviceAuthorization` (native + * `DaaSecureKey.signRegistrationDeviceAuthorization` + + * `DaaRegistrationAuthorizationSigningInput`), which is a different native + * function with a different validator than `signDeviceAuthorization` + + * `DaaDeviceAuthorizationSigningInput` behind {@link sign}. The registration + * profile is built in `auth/registrationAuthorization.ts` and signs through + * `OwnerAuthKey.signRegistrationDeviceAuthorization`. Native validates the + * compact signing input and signs that same slice; it does not require a + * durably acknowledged key, because Complete runs before + * `acknowledgeRegistration`. + * + * Injectable test stand-ins may still implement this for NativeSecureKeyStore + * unit tests (including arbitrary bytes the native validator would reject). + * + * @param messageBase64Url unpadded Base64URL of the exact bytes to sign. + * @returns unpadded Base64URL of the 64-byte JOSE `R || S` signature. + */ + signRegistrationDeviceAuthorization(alias: string, messageBase64Url: string): Promise +} diff --git a/src/securekey/SecureKey.ts b/src/securekey/SecureKey.ts new file mode 100644 index 0000000..ec47568 --- /dev/null +++ b/src/securekey/SecureKey.ts @@ -0,0 +1,149 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { DaaEnvironment } from '../config' + +/** + * The consumer's application-level identity: `appId` and `environment`, known + * at `DaaClient`/`AuthClient` construction, before any Owner is known. + * + * Combined with a per-Owner `clientEntityId` — available only after the + * Social Session response — to form the full {@link OwnerKeyIdentity} the + * secure-key store resolves. Kept as its own type so the two are + * never silently conflated: an app-level identity cannot select an AuthKey by + * itself, and code that only has one cannot pretend otherwise. + */ +export type AppKeyIdentity = Readonly<{ + appId: string + environment: DaaEnvironment +}> + +/** + * Identity that namespaces the installation AuthKey: one non-exportable + * P-256/ES256 key per `{appId, environment, clientEntityId (Owner), + * installation}`. + * + * `clientEntityId` must be the SERVER-CONFIRMED value the Social Session + * response echoed back — never a caller-supplied value the SDK has not + * validated. See `models/PreparedSocialLogin.ts#completeSocialSession`. + * + * The raw value never reaches native or the alias in the clear: `alias.ts` + * only ever folds it into `deriveKeyScope`'s SHA-256 digest. + */ +export type OwnerKeyIdentity = AppKeyIdentity & + Readonly<{ + clientEntityId: string + }> + +/** + * Result of resolving the installation AuthKey. Same name and same two cases as + * the native SDKs' `AuthKeyResolution` (`daa-ios-sdk`, `daa-android-sdk`), so + * the discriminant is not renamed or re-interpreted as it crosses the bridge. + * + * This is about REGISTRATION state, not about which call minted the key: + * + * - `created` — the key was just minted, OR a key already exists but carries no + * durable registration acknowledgement. Per the native SDK contract, passcode + * removal, Keychain reset, device restore, or a crash before acknowledgement + * all resolve to `created` rather than silently presenting an unregistered + * key as registered. + * - `existing` — returned only for a key with a durable acknowledgement, i.e. + * after {@link OwnerAuthKey.acknowledgeRegistration} has succeeded. + */ +export type AuthKeyResolution = 'created' | 'existing' + +/** + * The DAA Owner AuthKey. + * + * The private key never leaves the secure key handle. There is deliberately NO + * generic `sign(bytes)` at the SDK surface — signing is reachable only through + * this DAA-specific API, for defined DAA operations (login completion, protected + * writes, signed context refresh). See SECURITY.md. + * + * **Not the ephemeral registration-flow key.** The login contract has two + * P-256 keys, and this is the durable, namespaced, enclave-held one. The other — + * per login attempt, anonymous, process memory only, exported at Prepare — is + * `auth/RegistrationFlowKey.ts`, which never comes from this store and carries a + * comparison table for the difference. + */ +export interface OwnerAuthKey { + /** Unpadded Base64URL DER SubjectPublicKeyInfo of the public key. */ + publicKeySpkiBase64Url(): Promise + + /** RFC 7638 JWK thumbprint (`jkt`) of the P-256 public key. */ + thumbprint(): Promise + + /** + * Registration state of this handle: `created` while Circle's acknowledgement + * is still outstanding, `existing` once it is durably recorded. Read from the + * value the store observed when it resolved the key, and refreshed locally by + * {@link acknowledgeRegistration}. + */ + resolution(): AuthKeyResolution + + /** + * Persist that Circle registered this public key, moving the handle from + * `created` to `existing`. Idempotent: a no-op once the handle is `existing`. + * + * Per the native SDK contract the caller invokes this only AFTER Circle has + * successfully registered the exported SPKI. Device Registration Complete + * calls it on an `ACTIVE` result. `RECOVERY_PENDING` must not. + */ + acknowledgeRegistration(): Promise + + /** + * Produce an ES256 signature (JOSE `R || S`, 64 bytes) over the exact message + * bytes. The caller passes the already-serialized signing input; this method + * does not reserialize or canonicalize. + * + * This seam does NOT gate on {@link resolution}. Registered-device + * authorization (`auth/deviceAuthorization.ts`) requires `existing` before it + * calls this. Production `NativeSecureKeyStore` reaches native + * `signDeviceAuthorization`, which rejects with `authKeyRegistrationRequired` + * until acknowledgement succeeds (except native-allowed login completion). + * There is no public generic `sign(bytes)`. + * + * **Post-activation only.** Do not call this for the Device Registration + * Complete device proof — see {@link signRegistrationDeviceAuthorization}. + */ + signExactBytes(message: Uint8Array): Promise + + /** + * Produce an ES256 signature (JOSE `R || S`, 64 bytes) over the exact + * Device Registration Complete device-proof signing input + * (`auth/registrationAuthorization.ts`'s `X-Device-Authorization`, the + * registration profile's claim/header shape, not the post-activation one + * of the same header name). + * + * A DIFFERENT native seam from {@link signExactBytes}, on purpose: this key + * has typically not been acknowledged yet (Complete runs before + * `acknowledgeRegistration`), and the registration profile's claim set and + * embedded-JWK header are validated by native's registration validator, not + * `DaaDeviceAuthorizationSigningInput`. Production `NativeSecureKeyStore` + * reaches native `signRegistrationDeviceAuthorization`. Routing this proof + * through `signExactBytes` instead would sign valid bytes against the wrong + * native validator and fail on a real device even though it looks correct + * in this SDK's own JWS construction. + */ + signRegistrationDeviceAuthorization(message: Uint8Array): Promise +} + +export interface SecureKeyStore { + /** Resolve the installation AuthKey, creating it only when absent. */ + resolveOrCreate(identity: OwnerKeyIdentity): Promise +} diff --git a/src/securekey/alias.ts b/src/securekey/alias.ts new file mode 100644 index 0000000..0930015 --- /dev/null +++ b/src/securekey/alias.ts @@ -0,0 +1,204 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { DAA_ENVIRONMENTS } from '../config' +import type { DaaEnvironment } from '../config' +import { toBase64Url } from '../crypto/base64url' +import { sha256 } from '../crypto/sha256' +import { contractViolation } from '../errors' +import { isUuid } from '../validation/uuid' +import type { OwnerKeyIdentity } from './SecureKey' + +// The installation key namespace. This value is interpolated into an OS keystore +// identifier (iOS `kSecAttrApplicationTag`, Android KeyStore alias), so ALL +// THREE inputs are validated — it is a custody-key namespace, not free text, +// and a store can be constructed without going through DaaClient's checks. +// +// Validating `environment` against the allow-list is what keeps the alias +// injective on that axis: no allowed environment contains `.`, so splitting +// from the right always recovers it (see `parseSecureKeyAlias`). +// +// The per-Owner component is a SHA-256 digest, never the raw +// `clientEntityId` — see `deriveKeyScope`. Hashing also keeps a +// string-concatenation collision out of the `clientEntityId` axis: recovering +// two different `(appId, environment, clientEntityId)` triples from one alias +// would require a SHA-256 preimage or collision, not a parsing ambiguity. +const APP_ID_CHARSET = /^[A-Za-z0-9._-]+$/ + +// 128 bits of digest is enough collision resistance for a per-installation, +// per-Owner namespace while leaving room in native's 64-character appId slot +// for a real-world appId. Base64URL length is computed rather than hardcoded +// so it can never drift from KEY_SCOPE_DIGEST_BYTES. +const KEY_SCOPE_DIGEST_BYTES = 16 +const KEY_SCOPE_LENGTH = Math.ceil((KEY_SCOPE_DIGEST_BYTES * 8) / 6) // 22 + +// Native's hard cap on the appId slot (`isValidNamespace` in daa-ios-sdk's +// DaaSecureKey.swift: `[A-Za-z0-9._-]{1,64}`). The value that actually reaches +// it is `${appId}.${keyScope}` (see `secureKeyAlias`), so this cap applies to +// the COMPOSED value, and only `parseSecureKeyAlias` — which recovers that +// composed value — validates against it. +const MAX_NATIVE_APP_ID_LENGTH = 64 + +// What a consumer may actually configure as `appId`: native's slot minus the +// per-Owner scope and its separator. Derived from the two constants above +// rather than written as 41, so the limit enforced at the door can never drift +// from the composed value's real budget. +// +// Enforcing this in `assertAppId` is what keeps the two checks from +// disagreeing: an over-long appId is rejected up front, naming the limit the +// consumer controls, instead of passing validation and failing later during +// key resolution with a budget the caller never saw. +const MAX_APP_ID_LENGTH = MAX_NATIVE_APP_ID_LENGTH - 1 - KEY_SCOPE_LENGTH // 41 + +/** + * The per-Owner key-scope component: unpadded Base64URL of the + * first 128 bits of SHA-256 over `appId`, `environment`, and `clientEntityId`. + * + * The preimage deliberately includes `appId` and `environment`, not + * `clientEntityId` alone, so the digest cannot be correlated across + * applications or environments for the same Owner. + * + * `appId`, `environment`, and `clientEntityId` are joined with a NUL (`\0`) + * separator. NUL cannot appear in any of the three — `APP_ID_CHARSET` excludes + * control characters, `environment` is one of the fixed `DAA_ENVIRONMENTS` + * strings, and `clientEntityId` is validated as a hyphenated UUID — so the + * join cannot map two different triples onto the same preimage bytes. + */ +export function deriveKeyScope(identity: OwnerKeyIdentity): string { + const preimage = `${identity.appId}\u0000${identity.environment}\u0000${identity.clientEntityId}` + const digest = sha256(new TextEncoder().encode(preimage)) + return toBase64Url(digest.subarray(0, KEY_SCOPE_DIGEST_BYTES)) +} + +/** + * What actually reaches the native module's `appId` parameter once + * `parseSecureKeyAlias` recovers it: the consumer's configured `appId` + * composed with the derived per-Owner {@link deriveKeyScope} digest — NOT + * `OwnerKeyIdentity.appId` alone. + * + * Kept as its own type, rather than reusing or widening `OwnerKeyIdentity`, + * so the consumer's raw `appId` and the opaque scoped value native receives + * are never silently conflated. `environment` is unchanged, since + * it is not namespaced by Owner. + */ +export type NativeKeyIdentity = Readonly<{ + appId: string + environment: DaaEnvironment +}> + +/** + * Build the RN secure-key alias: `{appId}.{keyScope}.{environment}`, where + * `keyScope` is {@link deriveKeyScope}'s digest of `identity`. + * + * `keyScope` is composed with `appId` in the slot native validates and stores + * against — the derived scope, not `identity.clientEntityId` and not + * `identity.appId` by itself, is what reaches the native module (see + * {@link NativeKeyIdentity}). Two different Owners (`clientEntityId`) on the + * same `{appId, environment}` therefore resolve to two different aliases, and + * so to two different native keys. A returning Owner reproduces the same + * digest and so the same alias, and therefore resolves the SAME native key. + */ +export function secureKeyAlias(identity: OwnerKeyIdentity): string { + assertAppId(identity.appId) + const environment = parseEnvironment(identity.environment) + assertClientEntityId(identity.clientEntityId) + const keyScope = deriveKeyScope(identity) + // No length check is needed here: `assertAppId` caps `appId` at + // MAX_APP_ID_LENGTH, which is defined as exactly the room left once the + // separator and the fixed-width `keyScope` are accounted for, so the + // composed value cannot exceed MAX_NATIVE_APP_ID_LENGTH. + const nativeAppId = `${identity.appId}.${keyScope}` + return `${nativeAppId}.${environment}` +} + +/** + * Inverse of `secureKeyAlias`'s environment split — NOT a full inverse of + * `secureKeyAlias`, because {@link deriveKeyScope} is one-way. Splits from the + * right so the composed `{appId}.{keyScope}` prefix may itself contain dots + * (an `appId` always could). The Expo module then constructs native + * `DaaAuthKeyIdentity` from these fields plus a per-install UUID the native + * module owns. + * + * Returns {@link NativeKeyIdentity}, not `OwnerKeyIdentity`: what this + * recovers is the value native's `appId` parameter needs — the composed + * scope — not the consumer's original `appId` and not the `clientEntityId` + * that fed into it. That information is exactly what the hash discards, by + * design. + */ +export function parseSecureKeyAlias(alias: string): NativeKeyIdentity { + const separator = alias.lastIndexOf('.') + if (separator <= 0 || separator === alias.length - 1) { + throw contractViolation( + `secure-key alias must be {appId}.{environment} (got a ${alias.length}-char value)`, + ) + } + const appId = alias.slice(0, separator) + const environment = parseEnvironment(alias.slice(separator + 1)) + assertNativeAppId(appId) + return { appId, environment } +} + +/** + * Validates the consumer-supplied `appId`, before the per-Owner scope is + * folded in — so the cap is MAX_APP_ID_LENGTH, not native's slot size. + * + * Exported for `DaaClient`'s constructor, so an `appId` no key can be stored + * under is refused before any request is sent, not on the first key + * resolution — which comes after Social Session has already bound the end + * user. `secureKeyAlias` still checks it, because a store can be reached + * without a `DaaClient`. + */ +export function assertAppId(appId: string): void { + assertAppIdWithin(appId, MAX_APP_ID_LENGTH) +} + +/** + * Validates the composed `{appId}.{keyScope}` recovered from an alias, which + * is what native's appId slot actually receives — so the cap here is native's + * full MAX_NATIVE_APP_ID_LENGTH. Applying assertAppId's tighter consumer cap + * would reject legitimate aliases, since the scope alone is 22 characters. + */ +function assertNativeAppId(nativeAppId: string): void { + assertAppIdWithin(nativeAppId, MAX_NATIVE_APP_ID_LENGTH) +} + +function assertAppIdWithin(value: string, maxLength: number): void { + // Report only the length, never the (untrusted) value, so it cannot forge log + // lines when the error surfaces. + if (!APP_ID_CHARSET.test(value) || value.length > maxLength) { + throw contractViolation( + `appId must match ${String(APP_ID_CHARSET)} and be at most ${maxLength} ` + + `characters to namespace the secure key (got a ${value.length}-char value)`, + ) + } +} + +function assertClientEntityId(clientEntityId: string): void { + if (!isUuid(clientEntityId)) { + throw contractViolation('clientEntityId must be a UUID to namespace the secure key') + } +} + +function parseEnvironment(value: string): DaaEnvironment { + for (const environment of DAA_ENVIRONMENTS) { + if (environment === value) { + return environment + } + } + throw contractViolation(`unknown environment; expected one of ${DAA_ENVIRONMENTS.join(', ')}`) +} diff --git a/src/securekey/ownerAuthKeyResolver.ts b/src/securekey/ownerAuthKeyResolver.ts new file mode 100644 index 0000000..9a4a50f --- /dev/null +++ b/src/securekey/ownerAuthKeyResolver.ts @@ -0,0 +1,96 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Resolving the installation AuthKey by alias, in one place. +// +// Two call sites need the same key: the login ceremony selects it after Social +// Session (`AuthClient`), and the authenticated operations surface signs writes +// with it (`DaaClient.forUser`). The key is not carried on `DaaUserContext` — +// that context is a decoded server result, not a handle to enclave-held key +// material — so `forUser` re-resolves by the same `{appId, environment}` alias +// login used, together with the SAME context's `clientEntityId`. +// `DeviceContext.authKeyId` supplies the JWS `kid` alongside it. +// +// The lazy `NativeSecureKeyStore` is why this is a factory rather than a free +// function. Constructing the store requires the Expo `DaaSecureKey` module, and +// `DaaClient` construction deliberately does not; the store is therefore built +// on first resolution and then reused, so login and every later signed write +// share one store — and so share its in-flight `resolveOrCreate` map rather +// than racing two independent handles for the same alias. + +import { contractViolation } from '../errors' +import { NativeSecureKeyStore } from './NativeSecureKey' +import { resolveNativeBridge } from './resolveNativeBridge' +import type { AppKeyIdentity, OwnerAuthKey, SecureKeyStore } from './SecureKey' + +/** + * Resolves the installation AuthKey for one already-known Owner. + * + * Deliberately a zero-arg function rather than the store itself: a holder can + * obtain the one key its identity namespaces and nothing else — no alias of + * its choosing, and no store to resolve a different one from. This is the + * shape `DaaUserSigning.resolveAuthKey` (`api/signedResource.ts`) needs, + * because by the time `forUser` builds one it already knows which Owner it is + * signing for. It is NOT the shape {@link createOwnerAuthKeyResolver} returns + * — see {@link AppAuthKeyResolver}. + */ +export type OwnerAuthKeyResolver = () => Promise + +/** + * Resolves the installation AuthKey for a given Owner, by `clientEntityId`. + * + * `clientEntityId` is a per-call parameter rather than baked into the + * resolver at construction: it is not known when `DaaClient` + * builds this resolver (only the Social Session response names an Owner), and + * one long-lived `DaaClient` may serve more than one Owner over its lifetime + * — sign-out, then sign back in as someone else. Each call site binds the + * `clientEntityId` it already has (Social Session's response for login; + * `DaaUserContext.clientEntityId` for `forUser`) and, for `forUser`, wraps the + * result down to an {@link OwnerAuthKeyResolver} before handing it to a + * resource client — a resource client has no Owner concept of its own. + */ +export type AppAuthKeyResolver = (clientEntityId: string) => Promise + +/** + * Build the resolver for one application identity. + * + * @param identity App-level identity (`appId`, `environment`); `null` when + * the SDK has no application identity to select a key with, which fails + * closed at the first resolution rather than at construction — + * `AuthClient` is built for Prepare, and Prepare never touches an + * AuthKey. + * @param secureKeys Injected store, which tests substitute. Absent, the native + * store is constructed on first use and reused. + */ +export function createOwnerAuthKeyResolver( + identity: AppKeyIdentity | null, + secureKeys: SecureKeyStore | null, +): AppAuthKeyResolver { + // The mutable slot the lazily-constructed native store fills. A closure + // variable rather than a field because the clients holding this resolver are + // sealed with `Object.freeze`. + let nativeStore: NativeSecureKeyStore | null = null + + return async (clientEntityId: string) => { + if (identity === null) { + throw contractViolation('AuthKey selection requires the DaaClient application identity') + } + const store = secureKeys ?? (nativeStore ??= new NativeSecureKeyStore(resolveNativeBridge())) + return store.resolveOrCreate({ ...identity, clientEntityId }) + } +} diff --git a/src/securekey/resolveNativeBridge.ts b/src/securekey/resolveNativeBridge.ts new file mode 100644 index 0000000..39045d6 --- /dev/null +++ b/src/securekey/resolveNativeBridge.ts @@ -0,0 +1,185 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { requireOptionalNativeModule } from 'expo-modules-core' +import { DEVICE_KEY_POLICY, isRecord } from '../config' +import type { DeviceKeyPolicy } from '../config' +import { contractViolation } from '../errors' +import { parseSecureKeyAlias } from './alias' +import type { NativeAuthKeyResolution, NativeSecureKeyBridge } from './NativeSecureKeyBridge' + +// JS shape of the Expo `DaaSecureKey` native module. Identity is passed as +// structured `{appId, environment}` fields after TypeScript parses the RN +// alias; the native module owns the per-install UUID and constructs +// `DaaAuthKeyIdentity`. +interface DaaSecureKeyNativeModule { + /** + * The DeviceKeyPolicy this native module was built to enforce. This is a + * version-skew guard, not a live capability readback: it is a compiled-in + * constant on both sides of the bridge (mirrors `DEVICE_KEY_POLICY`), so a + * mismatch means the JS and native module versions disagree about the + * closed set, not that a specific key's real hardware/OS protection was + * measured and found wanting. Neither native SDK exposes a public API for + * that. + */ + declaredKeyPolicy?: () => unknown + resolveOrCreate(appId: string, environment: string): Promise + publicKeySpkiBase64Url(appId: string, environment: string): Promise + acknowledgeRegistration(appId: string, environment: string): Promise + signDeviceAuthorization( + appId: string, + environment: string, + signingInputBase64Url: string, + ): Promise + /** + * The registration-profile counterpart of {@link signDeviceAuthorization}. + * A separate native function with a separate validator + * (`DaaRegistrationAuthorizationSigningInput`), not an overload — see + * `NativeSecureKeyBridge.signRegistrationDeviceAuthorization`. + */ + signRegistrationDeviceAuthorization( + appId: string, + environment: string, + signingInputBase64Url: string, + ): Promise +} + +/** + * When the Expo `DaaSecureKey` module is loaded, require that its declared + * policy matches the configured closed set. No-ops when the module is absent + * (Node / Jest) so Prepare can still construct a client. + * + * This is a version-skew guard between the JS and native module, not a live + * attestation of a specific key's real protection level — see + * `declaredKeyPolicy` on `DaaSecureKeyNativeModule` above. + */ +export function assertNativeModuleKeyPolicyIfPresent(configured: DeviceKeyPolicy): void { + const native = requireOptionalNativeModule('DaaSecureKey') + if (native === null) { + return + } + assertNativeDeclaredKeyPolicy(native, configured) +} + +function assertNativeDeclaredKeyPolicy( + native: DaaSecureKeyNativeModule, + configured: DeviceKeyPolicy, +): void { + const query = native.declaredKeyPolicy + if (typeof query !== 'function') { + throw contractViolation('native DaaSecureKey module did not declare a DeviceKeyPolicy') + } + const declared = query.call(native) + if ( + !isRecord(declared) || + declared['hardwareBacked'] !== configured.hardwareBacked || + declared['userVerification'] !== configured.userVerification + ) { + throw contractViolation( + 'native DaaSecureKey declared keyPolicy does not match the configured DeviceKeyPolicy', + ) + } +} + +// Production wiring to the platform native module (Swift under ios/, Kotlin +// under android/), resolved via expo-modules-core. +// +// Node / Jest have no native module: fail closed rather than silently no-op. +// Tests inject a NativeSecureKeyBridge explicitly. +export function resolveNativeBridge(): NativeSecureKeyBridge { + const native = requireOptionalNativeModule('DaaSecureKey') + if (native === null) { + throw contractViolation( + 'native DaaSecureKey module is not available. Provide a NativeSecureKeyBridge ' + + 'explicitly, or run inside a React Native app that includes the DaaSecureKey Expo ' + + 'module.', + ) + } + assertNativeDeclaredKeyPolicy(native, DEVICE_KEY_POLICY) + return wrapNativeModule(native) +} + +function wrapNativeModule(native: DaaSecureKeyNativeModule): NativeSecureKeyBridge { + return { + async resolveOrCreate(alias: string): Promise { + const identity = parseSecureKeyAlias(alias) + const resolution = await native.resolveOrCreate(identity.appId, identity.environment) + if (resolution === 'created' || resolution === 'existing') { + return resolution + } + throw contractViolation('native resolveOrCreate returned an unknown resolution') + }, + + async publicKeySpkiBase64Url(alias: string): Promise { + const identity = parseSecureKeyAlias(alias) + return await native.publicKeySpkiBase64Url(identity.appId, identity.environment) + }, + + async acknowledgeRegistration(alias: string): Promise { + // Calls the acknowledgeRegistration the Expo module already exposes on + // both platforms; no parallel native API is introduced. Native owns + // idempotence and persistence (Data Protection Keychain on iOS, + // app-private storage on Android). + const identity = parseSecureKeyAlias(alias) + await native.acknowledgeRegistration(identity.appId, identity.environment) + }, + + async sign(alias: string, messageBase64Url: string): Promise { + // Typed native signDeviceAuthorization — not a generic sign(bytes) Expo + // method. `messageBase64Url` is the exact compact-JWS signing input + // `deviceAuthorization.ts` already constructed. Native wraps those bytes + // in DaaDeviceAuthorizationSigningInput (validates, does not re-encode) + // and returns 64-byte JOSE R||S as unpadded Base64URL. + if (typeof native.signDeviceAuthorization !== 'function') { + throw contractViolation('native DaaSecureKey.signDeviceAuthorization is required') + } + const identity = parseSecureKeyAlias(alias) + return await native.signDeviceAuthorization( + identity.appId, + identity.environment, + messageBase64Url, + ) + }, + + async signRegistrationDeviceAuthorization( + alias: string, + messageBase64Url: string, + ): Promise { + // Typed native signRegistrationDeviceAuthorization — the registration + // counterpart of `sign` above, NOT the same native call. `messageBase64Url` + // is the exact compact-JWS signing input `registrationAuthorization.ts` + // already constructed. Native wraps those bytes in + // DaaRegistrationAuthorizationSigningInput (a different validator from + // DaaDeviceAuthorizationSigningInput: registration `typ`s, an embedded + // JWK header, and the 14-claim registration payload) and returns the + // 64-byte JOSE R||S signature as unpadded Base64URL. Unlike `sign`, this + // does not require a durably acknowledged key. + if (typeof native.signRegistrationDeviceAuthorization !== 'function') { + throw contractViolation( + 'native DaaSecureKey.signRegistrationDeviceAuthorization is required', + ) + } + const identity = parseSecureKeyAlias(alias) + return await native.signRegistrationDeviceAuthorization( + identity.appId, + identity.environment, + messageBase64Url, + ) + }, + } +} diff --git a/src/testing.ts b/src/testing.ts new file mode 100644 index 0000000..8c403fd --- /dev/null +++ b/src/testing.ts @@ -0,0 +1,32 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Test-only entry point: the package's `./testing` subpath. +// +// Exposes the DAA Owner-key interfaces and a WebCrypto-backed in-memory store so +// consumers and golden vectors can exercise signing WITHOUT device hardware. +// +// NOT for production: the in-memory store holds a P-256 private key in process +// memory. It fails closed when constructed in a production build. +// +// The Owner-key interfaces (OwnerAuthKey / OwnerKeyIdentity / SecureKeyStore) +// are exported from the main entry (`.`) since they are the contract a +// production/native store implements. This subpath adds only the concrete +// test double. + +export { InMemorySecureKeyStore } from './securekey/InMemorySecureKey' diff --git a/src/transport/DaaTransport.ts b/src/transport/DaaTransport.ts new file mode 100644 index 0000000..4ce0860 --- /dev/null +++ b/src/transport/DaaTransport.ts @@ -0,0 +1,42 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Injected transport boundary. The SDK never embeds a DAA service credential; a +// consumer supplies transport that carries exact request bytes to the DAA public +// API (directly, or through a consumer backend relay). + +export type DaaHttpRequest = Readonly<{ + method: string + /** Signed public API path beginning `/v1` — not a consumer-backend route. */ + path: string + /** Exact percent-encoded query without the leading `?`, or null. */ + query: string | null + headers: Readonly> + /** Immutable body bytes. The SDK signs and sends this same slice. */ + bodyBytes: Uint8Array | null +}> + +export type DaaHttpResponse = Readonly<{ + status: number + headers: Readonly> + bodyBytes: Uint8Array | null +}> + +export interface DaaTransport { + send(request: DaaHttpRequest): Promise +} diff --git a/src/transport/headers.ts b/src/transport/headers.ts new file mode 100644 index 0000000..bc8d35a --- /dev/null +++ b/src/transport/headers.ts @@ -0,0 +1,46 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Look a response header up without assuming its casing. + * + * HTTP field names are case-insensitive and HTTP/2 mandates lowercase on the + * wire, so a `fetch`-based transport may surface `x-request-id` where another + * surfaces `X-Request-Id`. `DaaHttpResponse` deliberately does not normalize — + * the transport is the consumer's — so the typed client, which is the first thing + * that reads a response header, owns the lookup. + * + * Returns `null` for an absent header. Absence is reported as absence rather than + * as an empty string, which a provider could also legitimately send. + */ +export function headerValueIgnoringCase( + headers: Readonly>, + name: string, +): string | null { + const exact = headers[name] + if (exact !== undefined) { + return exact + } + const wanted = name.toLowerCase() + for (const key of Object.keys(headers)) { + if (key.toLowerCase() === wanted) { + return headers[key] ?? null + } + } + return null +} diff --git a/src/validation/requestBody.ts b/src/validation/requestBody.ts new file mode 100644 index 0000000..ae0c9b4 --- /dev/null +++ b/src/validation/requestBody.ts @@ -0,0 +1,60 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Local checks on a request body before it is serialized, signed, and sent. +// +// These exist because the Owner-authorization registry declares every signed +// operation's schema `additionalProperties: false`, and DAA enforces it +// property by property. A body carrying a property the schema does not name is +// refused there, so the SDK refuses it here — where the caller still has the +// stack that produced it, and before an Owner signature has been spent on bytes +// that cannot succeed. +// +// Rejecting is deliberate, and it is not the same as projecting the known +// properties and dropping the rest. A dropped property is a silent change of +// meaning: `blockChain` for `blockchain` would create an account on the default +// home chain rather than the requested one, and the caller would have no way to +// tell from the result that the field it set was never sent. + +import { contractViolation } from '../errors' + +/** Refuse anything that is not a plain JSON object, including an array or null. */ +export function requireBodyObject(value: unknown, label: string): void { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throw contractViolation(`${label} must be an object`) + } +} + +/** + * Refuse a property the operation's registry schema does not name. + * + * `Object.keys` reports own enumerable string keys, which is exactly the set + * `JSON.stringify` would serialize — so this checks the properties that would + * actually reach the wire rather than a structural approximation of them. + */ +export function requireKnownProperties( + value: object, + allowed: readonly string[], + label: string, +): void { + for (const key of Object.keys(value)) { + if (!allowed.includes(key)) { + throw contractViolation(`${label} does not accept the property "${key}"`) + } + } +} diff --git a/src/validation/uuid.ts b/src/validation/uuid.ts new file mode 100644 index 0000000..98b4852 --- /dev/null +++ b/src/validation/uuid.ts @@ -0,0 +1,31 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Whether a value uses the hyphenated UUID form accepted by DAA path + * parameters. UUIDs are strings at the TypeScript boundary, so this is the + * runtime guard before one becomes part of a request path. + */ +export function isUuid(value: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value) +} + +/** Whether a value is an RFC 4122 UUID v4, including a valid variant nibble. */ +export function isUuidV4(value: string): boolean { + return /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value) +} diff --git a/src/wire/accountLimitsUsagePayload.ts b/src/wire/accountLimitsUsagePayload.ts new file mode 100644 index 0000000..aef5937 --- /dev/null +++ b/src/wire/accountLimitsUsagePayload.ts @@ -0,0 +1,182 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { + AccountLimitsUsageItem, + AccountLimitsUsageResourceType, + LimitsUsageAssetType, + LimitsUsageComparisonType, + LimitsUsageOperation, + LimitsUsageUnit, + LimitsUsageWindow, +} from '../models/AccountLimitsUsage' +import { AccountLimitsUsage } from '../models/AccountLimitsUsage' +import { + asObject, + MalformedPayloadError, + optionalNonNegativeInteger, + optionalNonNegativeNumber, + optionalString, + requiredNonNegativeInteger, + requiredString, + unrecognized, +} from './payload' + +// Wire-string to public-type mapping, one `Map` per closed-set field — the +// same `Object.prototype` hazard `wireEnums.ts` guards against, kept local to +// this endpoint the same way `depositPayload.ts` keeps `DEPOSIT_STATUSES` and +// `DEPOSIT_TYPES` local rather than exporting them off the model. + +const RESOURCE_TYPES = new Map([ + ['limitsUsage', Object.freeze({ kind: 'limitsUsage' as const })], +]) + +const OPERATIONS = new Map([ + ['deposit', Object.freeze({ kind: 'deposit' as const })], + ['withdrawal', Object.freeze({ kind: 'withdrawal' as const })], + ['receive', Object.freeze({ kind: 'receive' as const })], + ['send', Object.freeze({ kind: 'send' as const })], + ['send_count', Object.freeze({ kind: 'send_count' as const })], + ['address_linking', Object.freeze({ kind: 'address_linking' as const })], + ['fiat_linking', Object.freeze({ kind: 'fiat_linking' as const })], + ['deposit_return_count', Object.freeze({ kind: 'deposit_return_count' as const })], + ['balance_cap', Object.freeze({ kind: 'balance_cap' as const })], +]) + +const ASSET_TYPES = new Map([ + ['fiat', Object.freeze({ kind: 'fiat' as const })], + ['crypto', Object.freeze({ kind: 'crypto' as const })], +]) + +const COMPARISON_TYPES = new Map([ + ['transaction', Object.freeze({ kind: 'transaction' as const })], + ['aggregation', Object.freeze({ kind: 'aggregation' as const })], +]) + +const UNITS = new Map([ + ['usd_cents', Object.freeze({ kind: 'usd_cents' as const })], + ['count', Object.freeze({ kind: 'count' as const })], +]) + +const WINDOWS = new Map([ + ['PT24H', Object.freeze({ kind: 'PT24H' as const })], + ['P30D', Object.freeze({ kind: 'P30D' as const })], +]) + +function toResourceType(raw: string): AccountLimitsUsageResourceType { + return RESOURCE_TYPES.get(raw) ?? unrecognized(raw) +} + +function toOperation(raw: string): LimitsUsageOperation { + return OPERATIONS.get(raw) ?? unrecognized(raw) +} + +function toAssetType(raw: string): LimitsUsageAssetType { + return ASSET_TYPES.get(raw) ?? unrecognized(raw) +} + +function toComparisonType(raw: string): LimitsUsageComparisonType { + return COMPARISON_TYPES.get(raw) ?? unrecognized(raw) +} + +function toUnit(raw: string): LimitsUsageUnit { + return UNITS.get(raw) ?? unrecognized(raw) +} + +function toWindow(raw: string): LimitsUsageWindow { + return WINDOWS.get(raw) ?? unrecognized(raw) +} + +/** + * Map one decoded `items[]` element onto the public shape. + * + * `window`, `currentAggregate`, and `usagePercent` are read as optional + * unconditionally — there is no `comparisonType` branch that requires them. + * The public reference's own example shows a `transaction` item omitting all + * three and an `aggregation` item carrying all three, but nothing here + * enforces that correlation: a service that sent an `aggregation` item + * without, say, `usagePercent` would still decode rather than fail the whole + * read, which is the same latitude this SDK gives every other + * service-guarantees-in-practice-but-not-by-schema field (see `Deposit`'s + * class note on `destination`). + * + * @throws MalformedPayloadError + */ +function toAccountLimitsUsageItem(value: unknown): AccountLimitsUsageItem { + const payload = asObject(value, 'accountLimitsUsage.items[]') + + const window = optionalString(payload, 'window') + return Object.freeze({ + operation: toOperation( + requiredString(payload, 'operation', 'accountLimitsUsage.items[].operation'), + ), + assetType: toAssetType( + requiredString(payload, 'assetType', 'accountLimitsUsage.items[].assetType'), + ), + comparisonType: toComparisonType( + requiredString(payload, 'comparisonType', 'accountLimitsUsage.items[].comparisonType'), + ), + window: window === null ? null : toWindow(window), + unit: toUnit(requiredString(payload, 'unit', 'accountLimitsUsage.items[].unit')), + effectiveThreshold: requiredNonNegativeInteger( + payload, + 'effectiveThreshold', + 'accountLimitsUsage.items[].effectiveThreshold', + ), + currentAggregate: optionalNonNegativeInteger( + payload, + 'currentAggregate', + 'accountLimitsUsage.items[].currentAggregate', + ), + usagePercent: optionalNonNegativeNumber( + payload, + 'usagePercent', + 'accountLimitsUsage.items[].usagePercent', + ), + }) +} + +function toAccountLimitsUsageItems(value: unknown): readonly AccountLimitsUsageItem[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('accountLimitsUsage.items') + } + return Object.freeze(value.map(toAccountLimitsUsageItem)) +} + +/** + * Map a decoded `GET /v1/accounts/{accountId}/limits/usage` payload onto the + * public model. + * + * `type`, `accountId`, `currency`, `watermark`, and `items` are all required — + * the public reference marks every one of them required on `data`, and this is + * a single-object envelope (see `AccountLimitsClient.get`), not a page, so + * there is no separate list-projection type the way `deposits.list` has one. + * + * @throws MalformedPayloadError + */ +export function toAccountLimitsUsage(value: unknown): AccountLimitsUsage { + const payload = asObject(value, 'accountLimitsUsage') + + return new AccountLimitsUsage({ + type: toResourceType(requiredString(payload, 'type', 'accountLimitsUsage.type')), + accountId: requiredString(payload, 'accountId'), + currency: requiredString(payload, 'currency'), + watermark: requiredString(payload, 'watermark'), + items: toAccountLimitsUsageItems(payload['items']), + }) +} diff --git a/src/wire/accountPayload.ts b/src/wire/accountPayload.ts new file mode 100644 index 0000000..95b46fe --- /dev/null +++ b/src/wire/accountPayload.ts @@ -0,0 +1,108 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Account } from '../models/Account' +import { Address, BusinessPii } from '../models/BusinessPii' +import { toMoney } from './moneyPayload' +import { + asObject, + MalformedPayloadError, + optionalObject, + optionalString, + requiredString, +} from './payload' +import { toAccountPurpose, toAccountStatus, toAccountType, toCustodyType } from './wireEnums' + +export { MalformedPayloadError } from './payload' + +function requiredArray(payload: Record, name: string): unknown[] { + const value = payload[name] + if (!Array.isArray(value)) { + throw new MalformedPayloadError(name) + } + return value +} + +function toAddress(payload: Record): Address { + return new Address({ + city: optionalString(payload, 'city'), + country: optionalString(payload, 'country'), + district: optionalString(payload, 'district'), + line1: optionalString(payload, 'line1'), + line2: optionalString(payload, 'line2'), + postalCode: optionalString(payload, 'postalCode'), + }) +} + +function toBusinessPii(payload: Record): BusinessPii { + const address = optionalObject(payload, 'address') + return new BusinessPii({ + address: address === null ? null : toAddress(address), + businessName: optionalString(payload, 'businessName'), + businessUniqueIdentifier: optionalString(payload, 'businessUniqueIdentifier'), + identifierIssuingCountryCode: optionalString(payload, 'identifierIssuingCountryCode'), + }) +} + +/** + * Map a decoded `Account` payload onto the public model. + * + * Unknown *additional* fields are ignored and an unfamiliar *present* closed-set + * value degrades to `unrecognized`; a missing guaranteed field throws. That is the + * line between forward compatibility and accepting a hole. + * + * `depositAddress` and `businessPii` are read because the service's responses + * carry them: self-custody and segregated accounts add `blockchain` and + * `depositAddress`. The OpenAPI schema shows none of the three, so the decoder + * follows the service's responses. For a self-custody consumer, + * `depositAddress` is the field the account exists for. + * + * @throws MalformedPayloadError + */ +export function toAccount(value: unknown): Account { + const payload = asObject(value, 'account') + const businessPii = optionalObject(payload, 'businessPii') + + return new Account({ + accountId: requiredString(payload, 'accountId'), + balances: requiredArray(payload, 'balances').map((balance) => toMoney(balance, 'balances[]')), + blockchain: optionalString(payload, 'blockchain'), + businessPii: businessPii === null ? null : toBusinessPii(businessPii), + clientEntityId: optionalString(payload, 'clientEntityId'), + // Outside the guaranteed set, unlike the three below, so an absent one is + // tolerated and is the only way to reach `unrecognized` with a null raw + // value. + custodyType: toCustodyType(optionalString(payload, 'custodyType')), + depositAddress: optionalString(payload, 'depositAddress'), + description: optionalString(payload, 'description'), + entityId: requiredString(payload, 'entityId'), + groupId: optionalString(payload, 'groupId'), + // Guaranteed, so an absent one is malformed. Only an unfamiliar *present* + // value becomes `unrecognized`. + purpose: toAccountPurpose(requiredString(payload, 'purpose')), + status: toAccountStatus(requiredString(payload, 'status')), + type: toAccountType(requiredString(payload, 'type')), + }) +} + +export function toAccounts(value: unknown): readonly Account[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('accounts') + } + return Object.freeze(value.map(toAccount)) +} diff --git a/src/wire/achPayload.ts b/src/wire/achPayload.ts new file mode 100644 index 0000000..d7b1d4d --- /dev/null +++ b/src/wire/achPayload.ts @@ -0,0 +1,98 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { ACH, ACHInstruction, ACHInstructionBeneficiaryBank } from '../models/Ach' +import type { ACHInstructionBeneficiary } from '../models/Ach' +import { + optionalBankAddress, + requiredBillingDetails, + toFiatAccountStatus, +} from './fiatAccountPayload' +import { + MalformedPayloadError, + asObject, + optionalObject, + optionalString, + requiredString, +} from './payload' + +// See `models/Ach.ts`'s file header: this decoder mirrors `wirePayload.ts` +// field-for-field wherever `Wire`/`WireInstruction` and `ACH`/`ACHInstruction` +// share a shape, and the model file explains the one extra field +// (`ACH.routingNumber`). + +function toAchInstructionBeneficiary(payload: Record): ACHInstructionBeneficiary { + return Object.freeze({ + name: optionalString(payload, 'name', 'beneficiary.name'), + address1: optionalString(payload, 'address1', 'beneficiary.address1'), + address2: optionalString(payload, 'address2', 'beneficiary.address2'), + }) +} + +function toAchInstructionBeneficiaryBank( + payload: Record, +): ACHInstructionBeneficiaryBank { + return new ACHInstructionBeneficiaryBank({ + name: optionalString(payload, 'name', 'beneficiaryBank.name'), + routingNumber: optionalString(payload, 'routingNumber', 'beneficiaryBank.routingNumber'), + accountNumber: optionalString(payload, 'accountNumber', 'beneficiaryBank.accountNumber'), + address: optionalString(payload, 'address', 'beneficiaryBank.address'), + city: optionalString(payload, 'city', 'beneficiaryBank.city'), + postalCode: optionalString(payload, 'postalCode', 'beneficiaryBank.postalCode'), + country: optionalString(payload, 'country', 'beneficiaryBank.country'), + }) +} + +/** Decode one `ACH` fiat account, for both list entries and the by-id read. */ +export function toAch(value: unknown): ACH { + const payload = asObject(value, 'ach') + return new ACH({ + id: requiredString(payload, 'id'), + type: optionalString(payload, 'type'), + status: toFiatAccountStatus(requiredString(payload, 'status')), + description: requiredString(payload, 'description'), + trackingRef: requiredString(payload, 'trackingRef'), + fingerprint: requiredString(payload, 'fingerprint'), + billingDetails: requiredBillingDetails(payload, 'billingDetails'), + bankAddress: optionalBankAddress(payload, 'bankAddress'), + routingNumber: optionalString(payload, 'routingNumber'), + createDate: requiredString(payload, 'createDate'), + updateDate: requiredString(payload, 'updateDate'), + }) +} + +/** Decode the ACH collection's unpaginated `data` array. */ +export function toAchList(value: unknown): readonly ACH[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('ach') + } + return Object.freeze(value.map(toAch)) +} + +/** Decode an `ACHInstruction` (`GET /v1/banks/ach/{id}/instructions`). */ +export function toAchInstruction(value: unknown): ACHInstruction { + const payload = asObject(value, 'achInstruction') + const beneficiary = optionalObject(payload, 'beneficiary') + const beneficiaryBank = optionalObject(payload, 'beneficiaryBank') + return new ACHInstruction({ + trackingRef: optionalString(payload, 'trackingRef'), + beneficiary: beneficiary === null ? null : toAchInstructionBeneficiary(beneficiary), + beneficiaryBank: + beneficiaryBank === null ? null : toAchInstructionBeneficiaryBank(beneficiaryBank), + }) +} diff --git a/src/wire/addressObjectPayload.ts b/src/wire/addressObjectPayload.ts new file mode 100644 index 0000000..a775d68 --- /dev/null +++ b/src/wire/addressObjectPayload.ts @@ -0,0 +1,64 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { AddressObject } from '../models/AddressObject' +import { MalformedPayloadError, asObject, optionalString, requiredString } from './payload' + +/** + * Map a decoded `AddressObject` payload onto the public model. + * + * `id`, `address`, and `chain` are guaranteed by every custody source a + * by-id read can return from; `addressTag`, `currency`, and `accountId` are + * not — see the class note on `AddressObject` for the source-by-source + * evidence, which disagrees with the schema (it names only `addressTag` as + * nullable). + * + * Unknown *additional* fields are ignored, matching the service's own + * tolerance for unknown fields — see `addressObjectPayload.test.ts`'s + * forward-compatibility case. + * + * `currency` and `chain` are carried as plain strings rather than a + * closed-set union: the service adds chains and currencies independently of an + * SDK release, the same reasoning `models/Account.ts` and `models/Money.ts` + * give for `Account.blockchain` and `Money.currency`. Neither needs the + * `wireEnums.ts`-style unrecognized-with-raw-value treatment `custodyType`, + * `purpose`, `status`, and `type` need, because neither is modelled as a + * small closed set this SDK discriminates on. + * + * @throws MalformedPayloadError + */ +export function toAddressObject(value: unknown): AddressObject { + const payload = asObject(value, 'addressObject') + + return new AddressObject({ + id: requiredString(payload, 'id'), + address: requiredString(payload, 'address'), + addressTag: optionalString(payload, 'addressTag'), + currency: optionalString(payload, 'currency'), + chain: requiredString(payload, 'chain'), + accountId: optionalString(payload, 'accountId'), + }) +} + +/** Decode the `data` array returned by the deposit-address collection. */ +export function toAddressObjects(value: unknown): readonly AddressObject[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('depositAddresses') + } + return Object.freeze(value.map(toAddressObject)) +} diff --git a/src/wire/daaStatusCodes.ts b/src/wire/daaStatusCodes.ts new file mode 100644 index 0000000..426a842 --- /dev/null +++ b/src/wire/daaStatusCodes.ts @@ -0,0 +1,69 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * The DAA status codes this SDK classifies, keyed by a symbolic name for each + * row. The names are labels for this code. DAA never sends them: it sends only + * the numeric code, and {@link isDaaStatus} matches only that number. This + * table is the one place a number appears; every mapping goes through {@link + * isDaaStatus}. + * + * Only rows with a numeric code are here. Some conditions have no distinct DAA + * code, such as `DEVICE_AUTHORIZATION_EXPIRED`, + * `DEVICE_AUTHORIZATION_MISSING` and `DEVICE_CREDENTIAL_REVOKED`. DAA reports + * those with another code, and the SDK must not infer the condition from it. + * A non-numeric string `code` matches nothing and classifies as `api`, whether + * it is the name of a row in this table, the name of a condition with no code, + * or a name that is not a DAA status code at all, such as + * `OWNER_AUTHORIZATION_INVALID`. + * + * The signed-request mapping (`api/signedResource.ts`) matches + * `DEVICE_AUTHORIZATION_INVALID`, `IDEMPOTENCY_KEY_REUSED`, + * `DEVICE_AUTHORIZATION_REQUEST_MISMATCH` and `DEVICE_AUTHORIZATION_REPLAYED`. + * The login mapping (`api/loginFailure.ts`) matches `IDEMPOTENCY_KEY_REUSED` + * and `LOGIN_REQUEST_CONSUMED`. The unsigned deposit-address create + * (`api/DepositAddressesClient.ts`) matches `IDEMPOTENCY_KEY_REUSED`. + * `AUTH_KEY_BINDING_CONFLICT` is in the table because DAA returns it with `409` + * from Device Registration Complete. It classifies as `api`, so no mapping + * matches it, and the login mapping does not let its `409` become + * `idempotency_conflict`. The numbers are stable: DAA retires a code rather than + * reusing it. + */ +export const DAA_STATUS_CODES = Object.freeze({ + DEVICE_AUTHORIZATION_INVALID: 420031, + IDEMPOTENCY_KEY_REUSED: 420034, + DEVICE_AUTHORIZATION_REQUEST_MISMATCH: 420036, + AUTH_KEY_BINDING_CONFLICT: 420038, + LOGIN_REQUEST_CONSUMED: 420039, + DEVICE_AUTHORIZATION_REPLAYED: 420043, +} as const satisfies Readonly>) + +export type DaaStatusName = keyof typeof DAA_STATUS_CODES + +/** + * Whether a code read by `readDaaStatusCode` is the named DAA status. + * + * The matching rule: a DAA error is classified on its numeric code only. + * `name` selects the row; the code matches only when it is that row's number. + * A decimal string such as `"420034"` already arrives here as the number. Any + * other string, including the row's own name, is not a match, so it falls + * through to `api`. `null` (no readable code) is not a match either. + */ +export function isDaaStatus(code: string | number | null, name: DaaStatusName): boolean { + return typeof code === 'number' && code === DAA_STATUS_CODES[name] +} diff --git a/src/wire/dataEnvelope.ts b/src/wire/dataEnvelope.ts new file mode 100644 index 0000000..ea4879f --- /dev/null +++ b/src/wire/dataEnvelope.ts @@ -0,0 +1,80 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { malformedResponse } from '../errors' + +/** + * The DAA service wraps every **public** success response in `data`, and there is + * exactly one envelope. + * + * Every public resource wraps its payload under that key: accounts, + * transfers, withdrawals, deposits, deposit addresses, transactions, and the + * bank instruction reads. + * + * The OpenAPI schema does not show the wrapper, so a client generated + * from the schema decodes the wrong root and reads every field as absent. + */ +const ENVELOPE_KEY = 'data' + +/** + * Decode a DAA public success body: validate UTF-8, unwrap the `data` envelope, + * and hand back the value under it. + * + * Everything that can go wrong — a body that is not UTF-8, a body that is not + * JSON, a body whose payload sits at the root, an envelope present but empty — + * becomes the one `contract_violation` carrying the correlation id, and nothing + * else. An envelope present but empty is malformed rather than an absent value: + * the wrapper is not optional on a successful response. + * + * The decoder's own message is never attached. `JSON.parse` quotes the offending + * input, and the SDK cannot know what a misrouted or intercepted response + * contains. + * + * UTF-8 validation is strict (`fatal: true`) rather than replacing a bad sequence + * with U+FFFD: a replacement character is a legal JSON string character, so + * lenient decoding would accept bytes the contract does not describe and hand the + * caller a field the service never sent. That only bites for bytes inside a field + * the payload does not read — an invalid byte in a declared field usually breaks + * the JSON as well — which is exactly why the guard has to be here rather than + * left to the parser. + */ +export function decodeDataEnvelope(bytes: Uint8Array, correlationId: string | null): unknown { + let text: string + try { + text = new TextDecoder('utf-8', { fatal: true }).decode(bytes) + } catch { + throw malformedResponse(correlationId) + } + + let root: unknown + try { + root = JSON.parse(text) + } catch { + throw malformedResponse(correlationId) + } + + if (typeof root !== 'object' || root === null || Array.isArray(root)) { + throw malformedResponse(correlationId) + } + + const data = (root as Record)[ENVELOPE_KEY] + if (data === undefined || data === null) { + throw malformedResponse(correlationId) + } + return data +} diff --git a/src/wire/depositPayload.ts b/src/wire/depositPayload.ts new file mode 100644 index 0000000..8ac3458 --- /dev/null +++ b/src/wire/depositPayload.ts @@ -0,0 +1,186 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { + DepositAccountLocation, + DepositRiskEvaluation, + DepositSourceLocation, + DepositStatus, + DepositType, +} from '../models/Deposit' +import { Deposit } from '../models/Deposit' +import { DepositSummary } from '../models/DepositSummary' +import { optionalMoney, requiredMoney } from './moneyPayload' +import { + asObject, + MalformedPayloadError, + optionalObject, + optionalString, + requiredString, + unrecognized, +} from './payload' + +// Wire-string to public-type mapping. A `Map`, not an object literal — the same +// `Object.prototype` hazard `wireEnums.ts` guards against, where +// `lookup['constructor']` would "recognise" a hostile value as something that is +// not a status at all. + +const DEPOSIT_STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' as const })], + ['complete', Object.freeze({ kind: 'complete' as const })], + ['failed', Object.freeze({ kind: 'failed' as const })], +]) + +const DEPOSIT_TYPES = new Map([ + ['wire', Object.freeze({ kind: 'wire' as const })], + ['ach', Object.freeze({ kind: 'ach' as const })], + ['cbit', Object.freeze({ kind: 'cbit' as const })], + ['rtgs', Object.freeze({ kind: 'rtgs' as const })], + ['rtp', Object.freeze({ kind: 'rtp' as const })], + ['xpay', Object.freeze({ kind: 'xpay' as const })], + ['signet', Object.freeze({ kind: 'signet' as const })], + ['sepa', Object.freeze({ kind: 'sepa' as const })], + ['sepa_instant', Object.freeze({ kind: 'sepa_instant' as const })], + ['sen', Object.freeze({ kind: 'sen' as const })], + ['pix', Object.freeze({ kind: 'pix' as const })], + ['cubix', Object.freeze({ kind: 'cubix' as const })], + ['book_transfer', Object.freeze({ kind: 'book_transfer' as const })], + ['fed_now', Object.freeze({ kind: 'fed_now' as const })], +]) + +function toDepositStatus(raw: string): DepositStatus { + return DEPOSIT_STATUSES.get(raw) ?? unrecognized(raw) +} + +function toDepositType(raw: string): DepositType { + return DEPOSIT_TYPES.get(raw) ?? unrecognized(raw) +} + +/** + * The destination location has one `type` constant (`account`), but `type` is + * an ordinary string discriminator rather than something this SDK can prove + * closed — see the type's doc comment in `models/Deposit.ts`. + */ +function toDepositAccountLocation(payload: Record): DepositAccountLocation { + const type = requiredString(payload, 'type', 'destination.type') + if (type !== 'account') { + return unrecognized(type) + } + return Object.freeze({ + kind: 'account' as const, + accountId: requiredString(payload, 'id', 'destination.id'), + }) +} + +/** + * `type` and `id` are guaranteed together here: the service returns a source + * location only when both parse, so a decoded source location + * never has one without the other. + */ +function toDepositSourceLocation(payload: Record): DepositSourceLocation { + return Object.freeze({ + type: toDepositType(requiredString(payload, 'type', 'source.type')), + id: requiredString(payload, 'id', 'source.id'), + name: optionalString(payload, 'name'), + }) +} + +function toDepositRiskEvaluation(payload: Record): DepositRiskEvaluation { + return Object.freeze({ + decision: optionalString(payload, 'decision', 'riskEvaluation.decision'), + reason: optionalString(payload, 'reason'), + }) +} + +/** + * Map a decoded deposit payload onto the public model. + * + * Unknown *additional* fields are ignored and an unfamiliar *present* closed-set + * value degrades to `unrecognized`; a missing guaranteed field throws. See the + * class note on `Deposit` for exactly which fields are guaranteed and why that + * set does not follow the OpenAPI schema's required marking. + * + * @throws MalformedPayloadError + */ +export function toDeposit(value: unknown): Deposit { + const payload = asObject(value, 'deposit') + + const destinationPayload = optionalObject(payload, 'destination') + const sourcePayload = optionalObject(payload, 'source') + const riskEvaluationPayload = optionalObject(payload, 'riskEvaluation') + + return new Deposit({ + amount: requiredMoney(payload, 'amount'), + createDate: requiredString(payload, 'createDate'), + customerExternalRef: optionalString(payload, 'customerExternalRef'), + destination: destinationPayload === null ? null : toDepositAccountLocation(destinationPayload), + errorCode: optionalString(payload, 'errorCode'), + externalRef: optionalString(payload, 'externalRef'), + fee: optionalMoney(payload, 'fee'), + fees: optionalMoney(payload, 'fees'), + fromAmount: optionalMoney(payload, 'fromAmount'), + id: requiredString(payload, 'id'), + riskEvaluation: + riskEvaluationPayload === null ? null : toDepositRiskEvaluation(riskEvaluationPayload), + source: sourcePayload === null ? null : toDepositSourceLocation(sourcePayload), + sourceAccountId: optionalString(payload, 'sourceAccountId'), + status: toDepositStatus(requiredString(payload, 'status')), + trackingRef: optionalString(payload, 'trackingRef'), + updateDate: optionalString(payload, 'updateDate'), + }) +} + +/** + * Map a decoded deposit-collection element onto the public `DepositSummary`. + * + * Same required/optional line as {@link toDeposit} — see `models/DepositSummary.ts`'s + * class note for why the service's `DepositSummary` response has no `source`, + * `fees`, `fromAmount`, or `trackingRef` at all, rather than merely omitting + * them from this projection. + * + * @throws MalformedPayloadError + */ +export function toDepositSummary(value: unknown): DepositSummary { + const payload = asObject(value, 'deposit') + + const destinationPayload = optionalObject(payload, 'destination') + const riskEvaluationPayload = optionalObject(payload, 'riskEvaluation') + + return new DepositSummary({ + amount: requiredMoney(payload, 'amount'), + createDate: requiredString(payload, 'createDate'), + customerExternalRef: optionalString(payload, 'customerExternalRef'), + destination: destinationPayload === null ? null : toDepositAccountLocation(destinationPayload), + errorCode: optionalString(payload, 'errorCode'), + externalRef: optionalString(payload, 'externalRef'), + fee: optionalMoney(payload, 'fee'), + id: requiredString(payload, 'id'), + riskEvaluation: + riskEvaluationPayload === null ? null : toDepositRiskEvaluation(riskEvaluationPayload), + sourceAccountId: optionalString(payload, 'sourceAccountId'), + status: toDepositStatus(requiredString(payload, 'status')), + updateDate: optionalString(payload, 'updateDate'), + }) +} + +export function toDepositSummaries(value: unknown): readonly DepositSummary[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('deposits') + } + return Object.freeze(value.map(toDepositSummary)) +} diff --git a/src/wire/deviceContextPayload.ts b/src/wire/deviceContextPayload.ts new file mode 100644 index 0000000..910dcaf --- /dev/null +++ b/src/wire/deviceContextPayload.ts @@ -0,0 +1,58 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { DeviceContext } from '../models/DaaUserContext' +import { isUuid } from '../validation/uuid' +import { requiredDateTime } from './instant' +import { asObject, MalformedPayloadError, requiredString } from './payload' + +function requiredUuidField(payload: Record, name: string): string { + const value = requiredString(payload, name) + if (!isUuid(value)) { + throw new MalformedPayloadError(name) + } + return value +} + +/** + * Decode the wire `DeviceContext`: the shape Device Registration + * Complete's `context` carries and `get_device_context` + * (`GET /v1/accounts/auth/context`, `DaaUserClient.refreshContext`) returns. + * + * One decoder for both, rather than two copies: they are the same + * `DeviceContext` response type, so a divergence between "the shape Complete + * returns" and "the shape refresh returns" would be a service defect, not + * something two independent decoders should each get to interpret. + * + * `DeviceContext.resolvedAt` is one of the timestamps the service sends in its + * default number form, the same as `PreparedSocialLogin.expiresAt`, so the + * epoch-millisecond form is accepted here. See `wire/instant.ts`. + */ +export function toDeviceContext(value: unknown): DeviceContext { + const payload = asObject(value, 'deviceContext') + const status = requiredString(payload, 'deviceCredentialStatus') + if (status !== 'active') { + throw new MalformedPayloadError('deviceCredentialStatus') + } + return { + deviceCredentialStatus: 'active', + ownerBindingId: requiredUuidField(payload, 'ownerBindingId'), + authKeyId: requiredUuidField(payload, 'authKeyId'), + resolvedAt: requiredDateTime(payload, 'resolvedAt'), + } +} diff --git a/src/wire/deviceRegistrationResultPayload.ts b/src/wire/deviceRegistrationResultPayload.ts new file mode 100644 index 0000000..b26a09f --- /dev/null +++ b/src/wire/deviceRegistrationResultPayload.ts @@ -0,0 +1,153 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + DaaUserContext, + DECODER_TOKEN, + type DeviceRegistrationResult, +} from '../models/DaaUserContext' +import { toDeviceContext } from './deviceContextPayload' +import { requiredDateTime } from './instant' +import { + asObject, + MalformedPayloadError, + optionalObject, + optionalString, + requiredString, +} from './payload' + +const RECOVERY_REF_MIN = 16 +const RECOVERY_REF_MAX = 512 + +function toActiveContext( + payload: Record, + sessionClientEntityId: string, +): DaaUserContext { + return new DaaUserContext(DECODER_TOKEN, { + clientEntityId: sessionClientEntityId, + deviceContext: toDeviceContext(payload), + }) +} + +/** + * The DeviceContext-shaped object Complete returns: a flat payload, or + * nested `context.deviceContext` / `context` when `status: "ACTIVE"`. + */ +function deviceContextPayloadFromComplete( + payload: Record, +): Record { + if (optionalString(payload, 'status') !== 'ACTIVE') { + return payload + } + const contextPayload = optionalObject(payload, 'context') + if (contextPayload === null) { + throw new MalformedPayloadError('context') + } + return optionalObject(contextPayload, 'deviceContext') ?? contextPayload +} + +/** + * Map Complete's `data` payload. + * + * The service returns a flat `DeviceContext`. The wrapped `{ status, context }` + * shape and `RECOVERY_PENDING` are also decoded when present. An absent + * `status` is read as that flat shape only on a positive signal: it still needs + * `deviceCredentialStatus === 'active'` (enforced by `toDeviceContext`), and + * it must carry neither `recoveryReference` nor `expiresAt` — the fields that + * belong to the `RECOVERY_PENDING` shape. A payload carrying either alongside + * an absent `status` is ambiguous and is rejected rather than resolved toward + * the more privileged `ACTIVE` outcome. Extra members are otherwise ignored. + * `clientEntityId` comes from Social Session, not this payload. + */ +export function toDeviceRegistrationResult( + value: unknown, + sessionClientEntityId: string, +): DeviceRegistrationResult { + const payload = asObject(value, 'payload') + const status = optionalString(payload, 'status') + if (status === 'RECOVERY_PENDING') { + if (optionalObject(payload, 'context') !== null) { + throw new MalformedPayloadError('context') + } + const recoveryReference = requiredString(payload, 'recoveryReference') + if ( + recoveryReference.length < RECOVERY_REF_MIN || + recoveryReference.length > RECOVERY_REF_MAX + ) { + throw new MalformedPayloadError('recoveryReference') + } + const result: DeviceRegistrationResult = Object.freeze({ + status: 'RECOVERY_PENDING', + recoveryReference, + // `expiresAt` accepts both timestamp forms, like the other login-flow + // timestamps on this response. + expiresAt: requiredDateTime(payload, 'expiresAt'), + }) + return result + } + if (status === 'ACTIVE') { + const contextPayload = optionalObject(payload, 'context') + if (contextPayload === null) { + throw new MalformedPayloadError('context') + } + const nestedClient = optionalString(contextPayload, 'clientEntityId') + if (nestedClient !== null && nestedClient !== sessionClientEntityId) { + throw new MalformedPayloadError('clientEntityId') + } + const devicePayload = deviceContextPayloadFromComplete(payload) + const result: DeviceRegistrationResult = Object.freeze({ + status: 'ACTIVE', + context: new DaaUserContext(DECODER_TOKEN, { + clientEntityId: sessionClientEntityId, + deviceContext: toDeviceContext(devicePayload), + }), + }) + return result + } + if (status !== null) { + throw new MalformedPayloadError('status') + } + + // Flat shape: only decodable on a positive ACTIVE signal, never on + // the mere absence of `status`. `toActiveContext` still requires + // `deviceCredentialStatus === 'active'`; this additionally refuses a + // payload that also carries a `RECOVERY_PENDING` field, rather than + // silently preferring the more privileged outcome. The error names + // whichever `RECOVERY_PENDING` field is actually present — `status` itself + // is absent here, not malformed. + const conflictingRecoveryField = hasPresentField(payload, 'recoveryReference') + ? 'recoveryReference' + : hasPresentField(payload, 'expiresAt') + ? 'expiresAt' + : null + if (conflictingRecoveryField !== null) { + throw new MalformedPayloadError(conflictingRecoveryField) + } + + const result: DeviceRegistrationResult = Object.freeze({ + status: 'ACTIVE', + context: toActiveContext(payload, sessionClientEntityId), + }) + return result +} + +/** JSON `null` is treated as absence, matching `optionalString`/`optionalObject`. */ +function hasPresentField(payload: Record, name: string): boolean { + const value = payload[name] + return value !== undefined && value !== null +} diff --git a/src/wire/errorEnvelope.ts b/src/wire/errorEnvelope.ts new file mode 100644 index 0000000..cac4e12 --- /dev/null +++ b/src/wire/errorEnvelope.ts @@ -0,0 +1,87 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { JSON_NUMBER } from './jsonNumber' + +/** + * The DAA status code from an error body, when the body carries a readable one. + * + * Best-effort by design: a failed call must still surface its HTTP status and + * correlation id when the provider returned an empty body, a proxy's HTML error + * page, or a shape the contract does not describe. Losing the whole error because + * its detail did not parse would be worse than losing the detail, so every failure + * here is `null`. + * + * Only the code is lifted. The envelope's `message` and `externalMessage` are + * provider-authored text from a response the SDK cannot vouch for, and the SDK + * error model has nowhere to put them that is not a log line. + * + * DAA sends the flat platform error body, with the code at the **root**: + * `{"code":420034,"message":"…","externalMessage":"…"}`. The SDK also + * accepts the code at `status.code`, but only when the root `code` is absent. + * A root `code` that is present decides alone, even when it is unreadable or + * unknown and `status.code` is a known code. Present means the key exists with + * a value other than `null`. Neither is under `data`: the `data` success + * wrapper is never applied to an error response. + * + * A decimal-string code comes back as the number. Any other string comes back + * unchanged so that an `api` error can still show it, but it classifies + * nothing: `isDaaStatus` matches numbers only. + */ +export function readDaaStatusCode(bytes: Uint8Array | null): string | number | null { + if (bytes === null || bytes.length === 0) { + return null + } + + let root: unknown + try { + root = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as unknown + } catch { + return null + } + + if (!isObject(root)) { + return null + } + const flat = root['code'] + if (flat !== undefined && flat !== null) { + return codeValue(flat) + } + const status = root['status'] + return isObject(status) ? codeValue(status['code']) : null +} + +function isObject(value: unknown): value is Record { + return typeof value === 'object' && value !== null && !Array.isArray(value) +} + +function codeValue(code: unknown): string | number | null { + // A numeric code arrives as a number from `JSON.parse`. A status code is + // small enough that no rounding question arises, so it is handed back as it + // came. + if (typeof code === 'number') { + return Number.isFinite(code) ? code : null + } + if (typeof code !== 'string' || code.length === 0) { + return null + } + // A code the service quoted is handed back as a number when it is one, so a + // consumer can compare it without knowing which shape arrived. A string that + // is not a number is kept only for diagnostics on the `api` error. + return JSON_NUMBER.test(code) ? Number(code) : code +} diff --git a/src/wire/fiatAccountPayload.ts b/src/wire/fiatAccountPayload.ts new file mode 100644 index 0000000..efee639 --- /dev/null +++ b/src/wire/fiatAccountPayload.ts @@ -0,0 +1,112 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { FiatAccountStatus } from '../models/FiatAccount' +import { BankAddress, BillingDetails } from '../models/FiatAccount' +import { + MalformedPayloadError, + asObject, + optionalObject, + optionalString, + requiredString, + unrecognized, +} from './payload' + +/** Decoders shared by the wire and ACH fiat-account payloads (`wirePayload.ts`, `achPayload.ts`). */ + +const STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' as const })], + ['complete', Object.freeze({ kind: 'complete' as const })], + ['failed', Object.freeze({ kind: 'failed' as const })], +]) + +export function toFiatAccountStatus(raw: string): FiatAccountStatus { + return STATUSES.get(raw) ?? unrecognized(raw) +} + +export function optionalBoolean( + payload: Record, + name: string, + label = name, +): boolean | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + if (typeof value !== 'boolean') { + throw new MalformedPayloadError(label) + } + return value +} + +/** + * Decode the guaranteed `BillingDetails` shape. + * + * The service requires `name`, `city`, `country`, `line1`, and `postalCode` on + * every wire/ACH fiat account, unlike `Account`'s optional `BusinessPii` + * enrichment — so a fiat account missing one of these is a broken contract, + * not a partially-enriched record. + */ +export function toBillingDetails(value: unknown, label: string): BillingDetails { + const payload = asObject(value, label) + return new BillingDetails({ + name: requiredString(payload, 'name', `${label}.name`), + city: requiredString(payload, 'city', `${label}.city`), + country: requiredString(payload, 'country', `${label}.country`), + line1: requiredString(payload, 'line1', `${label}.line1`), + line2: optionalString(payload, 'line2', `${label}.line2`), + district: optionalString(payload, 'district', `${label}.district`), + postalCode: requiredString(payload, 'postalCode', `${label}.postalCode`), + valid: optionalBoolean(payload, 'valid', `${label}.valid`), + }) +} + +export function requiredBillingDetails( + payload: Record, + name: string, +): BillingDetails { + const value = payload[name] + if (value === undefined || value === null) { + throw new MalformedPayloadError(name) + } + return toBillingDetails(value, name) +} + +/** + * Decode the optional `BankAddress` shape. Only `country` is guaranteed when + * the object is present at all. + */ +export function toBankAddress(value: unknown, label: string): BankAddress { + const payload = asObject(value, label) + return new BankAddress({ + bankName: optionalString(payload, 'bankName', `${label}.bankName`), + city: optionalString(payload, 'city', `${label}.city`), + country: requiredString(payload, 'country', `${label}.country`), + line1: optionalString(payload, 'line1', `${label}.line1`), + line2: optionalString(payload, 'line2', `${label}.line2`), + district: optionalString(payload, 'district', `${label}.district`), + }) +} + +export function optionalBankAddress( + payload: Record, + name: string, +): BankAddress | null { + const value = optionalObject(payload, name) + return value === null ? null : toBankAddress(value, name) +} diff --git a/src/wire/instant.ts b/src/wire/instant.ts new file mode 100644 index 0000000..3ac2d1d --- /dev/null +++ b/src/wire/instant.ts @@ -0,0 +1,93 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { MalformedPayloadError, requiredString } from './payload' + +// The two wire forms a login-flow timestamp arrives in, and the single form +// the login decoders hand on. +// +// By default the service serialises a timestamp as a JSON number: an integral +// count of epoch milliseconds, not fractional seconds. Most timestamps opt out +// and are sent as ISO-8601 strings: every response carrying a `createDate` / +// `updateDate` does. Exactly three responses do not — Prepare +// (`PreparedSocialLogin`), Session and the device context — and those three are +// the login flow's three responses. The number form is therefore not a +// service-wide habit but a property of precisely the fields these decoders +// read, which is why this lives on its own rather than in `payload.ts` beside +// `requiredString`: a resource `createDate` arriving as a number would be a real +// contract violation, and `deposit`/`transfer`/`withdrawal` must keep rejecting +// it. +// +// The three fields are `PreparedSocialLogin.expiresAt`, +// `SocialSession.expiresAt` and `DeviceContext.resolvedAt`. They are the same +// kind of field, serialised the same way, so all three accept both forms. + +/** + * The ISO-8601 form the contract declares for an `Instant`, with a `T` + * separator. The service does not always send this form — see `requiredDateTime` + * — but it is the single form these decoders hand on. + */ +const DATE_TIME = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d+)?(Z|[+-]\d{2}:\d{2})$/ + +/** + * Render epoch milliseconds as the same ISO-8601 text the string form carries. + * + * Three checks, no coercions. A fractional, non-finite, or beyond-safe-integer + * value is not a count of milliseconds, and zero or below is a field that + * arrived as a number without being a timestamp. What survives that can still be + * outside the range `Date` represents, so the instant is checked before it is + * rendered. The rendered text then has to satisfy `DATE_TIME` exactly as the + * string form does — which is what bounds the year, rather than an invented + * constant: an epoch rendering `'+275760-09-13T00:00:00.000Z'` is rejected here + * for the same reason that string would be. + */ +function fromEpochMillis(value: number, name: string): string { + if (!Number.isSafeInteger(value) || value <= 0) { + throw new MalformedPayloadError(name) + } + const instant = new Date(value) + if (Number.isNaN(instant.getTime())) { + throw new MalformedPayloadError(name) + } + const text = instant.toISOString() + if (!DATE_TIME.test(text)) { + throw new MalformedPayloadError(name) + } + return text +} + +/** + * A login-flow timestamp the service guarantees, in either form it sends. + * + * The contract OpenAPI declares an ISO-8601 string and the running service + * sends a JSON number of epoch milliseconds, so the SDK accepts both. A number + * is normalised to the string form at this boundary, so every public timestamp + * stays one stable type no matter which form arrived. Anything that is neither + * form still fails closed. + */ +export function requiredDateTime(payload: Record, name: string): string { + const raw = payload[name] + if (typeof raw === 'number') { + return fromEpochMillis(raw, name) + } + const value = requiredString(payload, name) + if (!DATE_TIME.test(value)) { + throw new MalformedPayloadError(name) + } + return value +} diff --git a/src/wire/jsonNumber.ts b/src/wire/jsonNumber.ts new file mode 100644 index 0000000..b7ae417 --- /dev/null +++ b/src/wire/jsonNumber.ts @@ -0,0 +1,33 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// The JSON number grammar, applied to values that arrive as text. + +/** + * RFC 8259's number grammar. + * + * The service sends `Money.amount` as a plain decimal JSON **string**, not a + * number. So the exact decimal survives + * `JSON.parse` untouched, and nothing on the way in checks that the text is a + * number at all — the OpenAPI's `type: number` describes the schema, not the + * wire. + * + * That makes this the **only** check on an amount rather than a second one, which + * is why it lives on its own rather than beside a decoder. + */ +export const JSON_NUMBER = /^-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?$/ diff --git a/src/wire/moneyPayload.ts b/src/wire/moneyPayload.ts new file mode 100644 index 0000000..62428bd --- /dev/null +++ b/src/wire/moneyPayload.ts @@ -0,0 +1,55 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { Money } from '../models/Money' +import { JSON_NUMBER } from './jsonNumber' +import { asObject, MalformedPayloadError, requiredString } from './payload' + +/** + * Decode the shared `Money` wire shape without coercing its decimal. + * + * The service serializes `amount` as a plain decimal JSON string. Accepting a JSON number would lose precision in + * `JSON.parse` before this decoder could inspect it, so only an RFC 8259 + * number-shaped string is accepted. `Money` owns redaction of the amount. + */ +export function toMoney(value: unknown, label: string): Money { + const payload = asObject(value, label) + const amount = requiredString(payload, 'amount', `${label}.amount`) + if (!JSON_NUMBER.test(amount)) { + throw new MalformedPayloadError(`${label}.amount`) + } + return new Money(amount, requiredString(payload, 'currency', `${label}.currency`)) +} + +/** Decode a guaranteed money field. */ +export function requiredMoney(payload: Record, name: string): Money { + const value = payload[name] + if (value === undefined || value === null) { + throw new MalformedPayloadError(name) + } + return toMoney(value, name) +} + +/** Decode a money field the service may omit. JSON `null` is absence. */ +export function optionalMoney(payload: Record, name: string): Money | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + return toMoney(value, name) +} diff --git a/src/wire/paginationLinks.ts b/src/wire/paginationLinks.ts new file mode 100644 index 0000000..c356837 --- /dev/null +++ b/src/wire/paginationLinks.ts @@ -0,0 +1,204 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { contractViolation } from '../errors' +import type { DaaHttpResponse } from '../transport/DaaTransport' + +type TrustedTarget = Readonly<{ query: string | null }> + +export type TrustedPaginationTargets = Readonly<{ + next: TrustedTarget | null + previous: TrustedTarget | null +}> + +type LinkValue = Readonly<{ + target: string + relation: string +}> + +// RFC 3986 query = *( pchar / "/" / "?" ). Percent escapes are checked +// separately so the opaque substring can be forwarded without normalizing it. +const RAW_QUERY_CHARACTERS = /^[A-Za-z0-9._~!$&'()*+,;=:@/?%-]*$/ + +/** Parse and trust-check navigation metadata from an untrusted API response. */ +export function trustedPaginationTargets( + response: DaaHttpResponse, + publicApiOrigin: string, + expectedPath: string, +): TrustedPaginationTargets { + const matchingHeaders = Object.keys(response.headers).filter( + (name) => name.toLowerCase() === 'link', + ) + if (matchingHeaders.length === 0) { + return { next: null, previous: null } + } + if (matchingHeaders.length !== 1) { + throw contractViolation('the response contains ambiguous pagination metadata') + } + + const header = response.headers[matchingHeaders[0] as string] + if (header === undefined) { + throw contractViolation('the response contains malformed pagination metadata') + } + + let nextTarget: string | null = null + let previousTarget: string | null = null + for (const link of parseLinkHeader(header)) { + if (link.relation === 'next') { + if (nextTarget !== null) { + throw contractViolation('the response contains ambiguous pagination metadata') + } + nextTarget = link.target + } else if (link.relation === 'prev') { + if (previousTarget !== null) { + throw contractViolation('the response contains ambiguous pagination metadata') + } + previousTarget = link.target + } + } + + return { + next: nextTarget === null ? null : trustedTarget(nextTarget, publicApiOrigin, expectedPath), + previous: + previousTarget === null ? null : trustedTarget(previousTarget, publicApiOrigin, expectedPath), + } +} + +/** Accept only DAA's `; rel="value"` shape, plus HTTP comma folding. */ +function parseLinkHeader(value: string): readonly LinkValue[] { + if (value.length === 0 || /[\u0000-\u0008\u000a-\u001f\u007f]/.test(value)) { + throw contractViolation('the response contains malformed pagination metadata') + } + + const links: LinkValue[] = [] + let position = 0 + while (position < value.length) { + position = skipOptionalWhitespace(value, position) + if (value[position] !== '<') { + throw contractViolation('the response contains malformed pagination metadata') + } + const targetEnd = value.indexOf('>', position + 1) + if (targetEnd < 0) { + throw contractViolation('the response contains malformed pagination metadata') + } + const target = value.slice(position + 1, targetEnd) + position = skipOptionalWhitespace(value, targetEnd + 1) + if (value[position] !== ';') { + throw contractViolation('the response contains malformed pagination metadata') + } + + position = skipOptionalWhitespace(value, position + 1) + const relationMatch = /^rel="([!#$%&'*+.^_`|~0-9A-Za-z-]+)"/i.exec(value.slice(position)) + if (relationMatch === null) { + throw contractViolation('the response contains malformed pagination metadata') + } + const relation = (relationMatch[1] as string).toLowerCase() + position += relationMatch[0].length + position = skipOptionalWhitespace(value, position) + + links.push({ target, relation }) + if (position === value.length) { + break + } + if (value[position] !== ',') { + throw contractViolation('the response contains malformed pagination metadata') + } + position = skipOptionalWhitespace(value, position + 1) + if (position >= value.length) { + throw contractViolation('the response contains malformed pagination metadata') + } + } + return Object.freeze(links) +} + +function skipOptionalWhitespace(value: string, start: number): number { + let position = start + while (value[position] === ' ' || value[position] === '\t') position += 1 + return position +} + +function trustedTarget( + target: string, + publicApiOrigin: string, + expectedPath: string, +): TrustedTarget { + if ( + target.length === 0 || + target !== target.trim() || + /[\u0000-\u001f\u007f\\]/.test(target) || + /%(?![0-9A-Fa-f]{2})/.test(target) + ) { + throw contractViolation('the response contains an untrusted pagination link') + } + + const raw = /^https:\/\/([^/?#]+)(\/[^?#]*)?(\?[^#]*)?$/i.exec(target) + if (raw === null) { + throw contractViolation('the response contains an untrusted pagination link') + } + + const targetOrigin = canonicalHttpsOrigin(raw[1] as string) + const trustedOrigin = canonicalTrustedOrigin(publicApiOrigin) + if (targetOrigin === null || trustedOrigin === null || targetOrigin !== trustedOrigin) { + throw contractViolation('the response contains an untrusted pagination link') + } + + const rawPath = raw[2] ?? '/' + if ( + rawPath !== expectedPath || + !rawPath.startsWith('/v1/') || + rawPath.includes('%') || + rawPath.includes('//') + ) { + throw contractViolation('the response contains an untrusted pagination link') + } + + const rawQuery = raw[3] + const query = rawQuery === undefined ? null : rawQuery.slice(1) + if (query !== null && !RAW_QUERY_CHARACTERS.test(query)) { + throw contractViolation('the response contains an untrusted pagination link') + } + return Object.freeze({ query }) +} + +/** + * Canonicalize only the HTTPS authority accepted by the pagination grammar. + * + * URL parsing is deliberately not used here: React Native hosts do not all + * expose the same WHATWG URL implementation as Node. The raw target/path + * checks above already reject URL syntax we do not forward, so the trust + * decision only needs a small deterministic host/port canonicalizer. + */ +function canonicalHttpsOrigin(authority: string): string | null { + if (authority.includes('@') || authority.includes('%')) return null + const match = /^([A-Za-z0-9.-]+)(?::([0-9]{1,5}))?$/.exec(authority) + if (match === null) return null + const host = match[1] as string + const rawPort = match[2] + if (rawPort !== undefined) { + const port = Number(rawPort) + if (!Number.isInteger(port) || port < 1 || port > 65535) return null + if (port === 443) return `https://${host.toLowerCase()}` + return `https://${host.toLowerCase()}:${port}` + } + return `https://${host.toLowerCase()}` +} + +function canonicalTrustedOrigin(origin: string): string | null { + const match = /^https:\/\/([^/?#]+)$/i.exec(origin) + return match === null ? null : canonicalHttpsOrigin(match[1] as string) +} diff --git a/src/wire/payload.ts b/src/wire/payload.ts new file mode 100644 index 0000000..53d26ac --- /dev/null +++ b/src/wire/payload.ts @@ -0,0 +1,146 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +/** + * Raised when a response is missing something the service guarantees, or carries + * it in a shape the contract does not describe. + * + * Internal, and caught at the client boundary where it becomes the one + * `contract_violation` carrying the correlation id. `fieldName` exists so a + * decoder test can say which field it rejected; it is deliberately **not** + * propagated into the error a consumer sees, because it names a field in a + * response the SDK cannot vouch for. + */ +export class MalformedPayloadError extends Error { + readonly fieldName: string + + constructor(fieldName: string) { + super(`DAA: response field is missing or not the expected shape: ${fieldName}`) + this.name = 'MalformedPayloadError' + this.fieldName = fieldName + } +} + +/** Preserve an unfamiliar closed-set wire value without failing its resource. */ +export function unrecognized(rawValue: string | null): { + readonly kind: 'unrecognized' + readonly rawValue: string | null +} { + return Object.freeze({ kind: 'unrecognized' as const, rawValue }) +} + +export function asObject(value: unknown, field: string): Record { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + throw new MalformedPayloadError(field) + } + return value as Record +} + +/** An object field the service may omit. JSON `null` is treated as absence. */ +export function optionalObject( + payload: Record, + name: string, +): Record | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + return asObject(value, name) +} + +/** A field the service may omit. JSON `null` is treated as absence. */ +export function optionalString( + payload: Record, + name: string, + label = name, +): string | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + if (typeof value !== 'string') { + throw new MalformedPayloadError(label) + } + return value +} + +/** A field the service guarantees. Absent, null, or not a string is malformed. */ +export function requiredString( + payload: Record, + name: string, + label = name, +): string { + const value = optionalString(payload, name, label) + if (value === null) { + throw new MalformedPayloadError(label) + } + return value +} + +/** + * A non-negative integer field the service guarantees, sent as a JSON number + * rather than a string. + * + * Unlike `Money.amount` (a decimal serialized as a string to survive + * `JSON.parse` exactly), an int64 count or a `usd_cents` threshold is sent as + * an ordinary JSON number, so there is no second encoding to unwrap here — only + * the grammar (integer, non-negative) to check. + */ +export function requiredNonNegativeInteger( + payload: Record, + name: string, + label = name, +): number { + const value = payload[name] + if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) { + throw new MalformedPayloadError(label) + } + return value +} + +/** A non-negative integer field the service may omit. JSON `null` is treated as absence. */ +export function optionalNonNegativeInteger( + payload: Record, + name: string, + label = name, +): number | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + return requiredNonNegativeInteger(payload, name, label) +} + +/** + * A non-negative decimal field the service may omit (for example a usage + * percentage), sent as a JSON number. JSON `null` is treated as absence. + */ +export function optionalNonNegativeNumber( + payload: Record, + name: string, + label = name, +): number | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + if (typeof value !== 'number' || !Number.isFinite(value) || value < 0) { + throw new MalformedPayloadError(label) + } + return value +} diff --git a/src/wire/pendingRegistrationPayload.ts b/src/wire/pendingRegistrationPayload.ts new file mode 100644 index 0000000..d4f780f --- /dev/null +++ b/src/wire/pendingRegistrationPayload.ts @@ -0,0 +1,75 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isUuid } from '../validation/uuid' +import { requiredDateTime } from './instant' +import { asObject, MalformedPayloadError, optionalString, requiredString } from './payload' + +/** The service caps `SocialSession.registrationHandle` at 200 characters. */ +const HANDLE_MIN = 1 +const HANDLE_MAX = 200 + +export type PendingRegistrationPayload = Readonly<{ + registrationHandle: string + clientEntityId: string + /** ISO-8601, normalised when the service sends epoch milliseconds instead. */ + expiresAt: string + /** + * Not part of the documented `SocialSession` response. When present, the SDK + * checks it for a `registrationFlowKeyThumbprint` bound to this attempt's + * flow key and fails closed if that is missing or does not match. Null when + * the response does not carry it. + */ + ownerGrant: string | null +}> + +function requiredBounded( + payload: Record, + name: string, + min: number, + max: number, +): string { + const value = requiredString(payload, name) + if (value.length < min || value.length > max) { + throw new MalformedPayloadError(name) + } + return value +} + +function requiredUuid(payload: Record, name: string): string { + const value = requiredString(payload, name) + if (!isUuid(value)) { + throw new MalformedPayloadError(name) + } + return value +} + +/** Map the `SocialSession` body onto the fields the SDK keeps. */ +export function toPendingRegistration(value: unknown): PendingRegistrationPayload { + const payload = asObject(value, 'payload') + const ownerGrant = optionalString(payload, 'ownerGrant') + return { + registrationHandle: requiredBounded(payload, 'registrationHandle', HANDLE_MIN, HANDLE_MAX), + clientEntityId: requiredUuid(payload, 'clientEntityId'), + // `SocialSession.expiresAt` is one of the timestamps the service sends in + // its default number form, like Prepare's `expiresAt`, so the epoch form + // is accepted here. + expiresAt: requiredDateTime(payload, 'expiresAt'), + ownerGrant, + } +} diff --git a/src/wire/socialLoginRequestPayload.ts b/src/wire/socialLoginRequestPayload.ts new file mode 100644 index 0000000..0252a6e --- /dev/null +++ b/src/wire/socialLoginRequestPayload.ts @@ -0,0 +1,89 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { isUuid } from '../validation/uuid' +import { requiredDateTime } from './instant' +import { asObject, MalformedPayloadError, requiredString } from './payload' + +// Decoder for Prepare's `201` `data` payload. +// +// The `PreparedSocialLogin` body is loginRequestId, oidcNonce, oidcState, +// expiresAt, and `prepareReceiptJws` when the service signs a receipt. Extra +// response members are ignored. +// +// The receipt is carried through raw and not examined here: not its presence, +// its type, or its shape. What to do with it is decided per environment by +// `auth/prepareReceipt.ts`'s `checkPrepareReceipt`, which `prepareSocialLogin` +// calls right after this decoder. With no trust anchor pinned the receipt is +// ignored, so a receipt the SDK cannot use must not fail the response here; +// with an anchor pinned, a missing or malformed receipt is +// `prepare_receipt_invalid` there rather than a malformed response here. + +const OIDC_VALUE_MIN = 32 +const OIDC_VALUE_MAX = 256 + +export type SocialLoginRequestPayload = Readonly<{ + loginRequestId: string + oidcNonce: string + oidcState: string + /** ISO-8601, normalised when the service sends epoch milliseconds instead. */ + expiresAt: string + /** + * The raw `prepareReceiptJws` member, unvalidated: `null` when absent. Only + * `checkPrepareReceipt` reads it. + */ + prepareReceiptJws: unknown +}> + +function requiredUuid(payload: Record, name: string): string { + const value = requiredString(payload, name) + if (!isUuid(value)) { + throw new MalformedPayloadError(name) + } + return value +} + +function requiredOidcValue(payload: Record, name: string): string { + const value = requiredString(payload, name) + if (value.length < OIDC_VALUE_MIN || value.length > OIDC_VALUE_MAX) { + throw new MalformedPayloadError(name) + } + return value +} + +/** The raw receipt member: `null` when absent or JSON `null`, else whatever was sent. */ +function rawPrepareReceipt(payload: Record): unknown { + const value = Object.prototype.hasOwnProperty.call(payload, 'prepareReceiptJws') + ? payload['prepareReceiptJws'] + : undefined + return value === undefined ? null : value +} + +/** Map a Prepare success payload onto the fields the SDK keeps. */ +export function toSocialLoginRequest(value: unknown): SocialLoginRequestPayload { + const payload = asObject(value, 'payload') + return { + loginRequestId: requiredUuid(payload, 'loginRequestId'), + oidcNonce: requiredOidcValue(payload, 'oidcNonce'), + oidcState: requiredOidcValue(payload, 'oidcState'), + // The service sends this as epoch milliseconds; the decoder also accepts + // ISO-8601. See `instant.ts`. + expiresAt: requiredDateTime(payload, 'expiresAt'), + prepareReceiptJws: rawPrepareReceipt(payload), + } +} diff --git a/src/wire/transactionPayload.ts b/src/wire/transactionPayload.ts new file mode 100644 index 0000000..3289935 --- /dev/null +++ b/src/wire/transactionPayload.ts @@ -0,0 +1,145 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Transaction, + TransactionBlockchainLocation, + TransactionLocation, + TransactionStatus, + TransactionType, +} from '../models/Transaction' +import { requiredMoney } from './moneyPayload' +import { + asObject, + MalformedPayloadError, + optionalString, + requiredString, + unrecognized, +} from './payload' + +/** + * Wire payload -> public `Transaction` model, and the required/optional line. + * + * Generic object and string readers come from `wire/payload`; shared money + * decoding comes from `wire/moneyPayload`. Transaction-specific enum and + * location decoding remains here. + */ + +const TRANSACTION_TYPES = new Map([ + ['deposit', Object.freeze({ kind: 'deposit' })], + ['withdrawal', Object.freeze({ kind: 'withdrawal' })], + ['transfer', Object.freeze({ kind: 'transfer' })], + ['fx', Object.freeze({ kind: 'fx' })], + ['fee', Object.freeze({ kind: 'fee' })], + ['credit', Object.freeze({ kind: 'credit' })], + ['other', Object.freeze({ kind: 'other' })], +]) + +const TRANSACTION_STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' })], + ['complete', Object.freeze({ kind: 'complete' })], + ['failed', Object.freeze({ kind: 'failed' })], + ['returned', Object.freeze({ kind: 'returned' })], +]) + +function toTransactionType(raw: string): TransactionType { + return TRANSACTION_TYPES.get(raw) ?? unrecognized(raw) +} + +function toTransactionStatus(raw: string): TransactionStatus { + return TRANSACTION_STATUSES.get(raw) ?? unrecognized(raw) +} + +/** + * Decode one `Location` hierarchy member. + * + * The discriminator is the wire `type` field. `account` and `blockchain` are shared with `Transfer`; + * `wire`/`ach` are transaction-only. Anything else — including + * `verified_blockchain`, which the service maps away before serializing — is + * `unrecognized` rather than a thrown error. + * + * Fiat `id` is a UUID on the service; it is still read as a string here, + * the same way every other response id is. Requiring UUID form on the way in + * would reject a row the service actually sent. + */ +function toTransactionLocation(value: unknown, field: string): TransactionLocation { + const payload = asObject(value, field) + const type = requiredString(payload, 'type', `${field}.type`) + switch (type) { + case 'account': + return Object.freeze({ + kind: 'account' as const, + accountId: requiredString(payload, 'id', `${field}.id`), + }) + case 'blockchain': + return new TransactionBlockchainLocation({ + chain: optionalString(payload, 'chain'), + address: optionalString(payload, 'address'), + addressTag: optionalString(payload, 'addressTag'), + }) + case 'wire': + case 'ach': + return Object.freeze({ + kind: type, + fiatAccountId: requiredString(payload, 'id', `${field}.id`), + name: optionalString(payload, 'name'), + }) + default: + return unrecognized(type) + } +} + +function toOptionalTransactionLocation(value: unknown, field: string): TransactionLocation | null { + if (value === undefined || value === null) { + return null + } + return toTransactionLocation(value, field) +} + +/** + * Map a decoded `Transaction` payload onto the public model. + * + * Unknown additional fields are ignored and an unfamiliar present closed-set + * or location value degrades to `unrecognized`; a missing guaranteed field + * throws. Guaranteed fields are `id`, `type`, `status`, `amount`, `createDate`, + * and `updateDate` — see `models/Transaction.ts`. `source` and `destination` + * decode to `null` when absent. + * + * @throws MalformedPayloadError + */ +export function toTransaction(value: unknown): Transaction { + const payload = asObject(value, 'transaction') + + return new Transaction({ + id: requiredString(payload, 'id'), + type: toTransactionType(requiredString(payload, 'type')), + status: toTransactionStatus(requiredString(payload, 'status')), + amount: requiredMoney(payload, 'amount'), + source: toOptionalTransactionLocation(payload['source'], 'source'), + destination: toOptionalTransactionLocation(payload['destination'], 'destination'), + createDate: requiredString(payload, 'createDate'), + updateDate: requiredString(payload, 'updateDate'), + }) +} + +export function toTransactions(value: unknown): readonly Transaction[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('transactions') + } + return Object.freeze(value.map(toTransaction)) +} diff --git a/src/wire/transferPayload.ts b/src/wire/transferPayload.ts new file mode 100644 index 0000000..44d91e8 --- /dev/null +++ b/src/wire/transferPayload.ts @@ -0,0 +1,249 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import { + Fee, + Transfer, + TransferDestinationAccountLocation, + TransferDestinationBlockchainLocation, + TransferDestinationLocation, + TransferErrorCode, + TransferPolicyEvaluation, + TransferSourceLocation, + TransferStatus, +} from '../models/Transfer' +import { requiredMoney, toMoney } from './moneyPayload' +import { + asObject, + MalformedPayloadError, + optionalObject, + optionalString, + requiredString, + unrecognized, +} from './payload' + +/** + * Wire payload -> public `Transfer` model, and the required/optional line. + * + * Generic object and string readers come from `wire/payload`; shared money + * decoding comes from `wire/moneyPayload`; transfer-specific fee, enum, and + * location decoding remains here. + */ + +// ---- Closed-set tables, one per field, mirroring wire/wireEnums.ts's pattern ---- +// +// These tables remain resource-specific because their public unions do; they use +// the same `Map` construction as the account tables. An object literal inherits +// from `Object.prototype`, so +// `lookup['constructor']` returns a function instead of `undefined`, and a wire +// value spelled like a prototype member would be "recognised" as something it +// is not. Pinned by test, same as the account tables. + +const TRANSFER_STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' })], + ['complete', Object.freeze({ kind: 'complete' })], + ['failed', Object.freeze({ kind: 'failed' })], +]) + +const TRANSFER_ERROR_CODES = new Map([ + ['transfer_failed', Object.freeze({ kind: 'transfer_failed' })], + ['transfer_denied', Object.freeze({ kind: 'transfer_denied' })], + ['blockchain_error', Object.freeze({ kind: 'blockchain_error' })], + ['insufficient_funds', Object.freeze({ kind: 'insufficient_funds' })], + ['invalid_crypto_address', Object.freeze({ kind: 'invalid_crypto_address' })], +]) + +function toTransferStatus(raw: string): TransferStatus { + return TRANSFER_STATUSES.get(raw) ?? unrecognized(raw) +} + +/** `errorCode` is optional (present only when `status = failed`); absent is `null`, not `unrecognized`. */ +function toTransferErrorCode(raw: string | null): TransferErrorCode | null { + if (raw === null) { + return null + } + return TRANSFER_ERROR_CODES.get(raw) ?? unrecognized(raw) +} + +// ---- Locations ---- +// +// The discriminator is the wire `type` field shared by every location. A +// transfer leg is documented as only ever `account` or `blockchain` (`wire` is +// not valid on a transfer), but the decoder still has to tolerate anything +// else — a `verified_blockchain`/`wire`/`ach` leaking through, or a kind +// invented after this SDK shipped — as `unrecognized` rather than a thrown +// error. +// +// `chain` (both legs) and `address` (destination only) are read with +// `optionalString`, not `requiredString`, even though the OpenAPI schema marks +// both required. That marking is a hint, not proof: the service sends no +// `chain` on any blockchain leg whose metadata has not backfilled, and no +// `address` on a destination verified-blockchain leg in the same state (a plain +// destination `blockchain` leg falls back to the leg id, so it never actually +// sends a null address). Since the wire's `type: "blockchain"` cannot +// distinguish which kind of leg produced it, this decoder has to accept the +// nullable case both fields actually have. + +function toTransferSourceLocation(value: unknown): TransferSourceLocation { + const payload = asObject(value, 'source') + const type = requiredString(payload, 'type', 'source.type') + switch (type) { + case 'account': + return Object.freeze({ + kind: 'account' as const, + accountId: requiredString(payload, 'id', 'source.id'), + }) + case 'blockchain': + return Object.freeze({ + kind: 'blockchain' as const, + // See the note above `toTransferSourceLocation`: nullable, not required. + chain: optionalString(payload, 'chain'), + }) + default: + return unrecognized(type) + } +} + +/** + * `source` itself is optional on `Transfer` (see `models/Transfer.ts`'s class + * note): a fiat leg or a stray `verified_blockchain` source both map to a + * service-side `null`, which the service sends as an absent key rather than an + * explicit JSON `null` — so both are treated as absence here, + * consistent with every other optional field in this file. + */ +function toOptionalTransferSourceLocation(value: unknown): TransferSourceLocation | null { + if (value === undefined || value === null) { + return null + } + return toTransferSourceLocation(value) +} + +function toTransferDestinationLocation(value: unknown): TransferDestinationLocation { + const payload = asObject(value, 'destination') + const type = requiredString(payload, 'type', 'destination.type') + switch (type) { + case 'account': + return new TransferDestinationAccountLocation({ + accountId: requiredString(payload, 'id', 'destination.id'), + address: optionalString(payload, 'address'), + addressTag: optionalString(payload, 'addressTag'), + }) + case 'blockchain': + return new TransferDestinationBlockchainLocation({ + // See the note above `toTransferSourceLocation`: nullable, not required. + chain: optionalString(payload, 'chain'), + address: optionalString(payload, 'address'), + addressTag: optionalString(payload, 'addressTag'), + }) + default: + return unrecognized(type) + } +} + +/** `destination` itself is optional on `Transfer` — see `toOptionalTransferSourceLocation`; same reasoning, a fiat destination leg. */ +function toOptionalTransferDestinationLocation(value: unknown): TransferDestinationLocation | null { + if (value === undefined || value === null) { + return null + } + return toTransferDestinationLocation(value) +} + +/** + * A single fee entry. All three fields are guaranteed on a `Fee` that is + * present at all (the OpenAPI schema marks `amount`/`currency`/`type` each + * required) — it is the `fees` array itself that is + * optional on `Transfer`, not any field within an entry that does appear. + */ +function toFee(value: unknown): Fee { + const payload = asObject(value, 'fees[]') + return Object.freeze({ + amount: toMoney(payload, 'fees[]'), + type: requiredString(payload, 'type', 'fees[].type'), + }) +} + +/** + * `fees` is present only when at least one non-zero fee exists (per the API + * contract); absent or `null` decodes to an empty list rather + * than `null`, since "no fees" and "an empty fee list" are the same fact. + */ +function toFees(payload: Record): Fee[] { + const value = payload['fees'] + if (value === undefined || value === null) { + return [] + } + if (!Array.isArray(value)) { + throw new MalformedPayloadError('fees') + } + return value.map(toFee) +} + +function toPolicyEvaluation(payload: Record): TransferPolicyEvaluation { + return Object.freeze({ status: requiredString(payload, 'status', 'policyEvaluation.status') }) +} + +/** + * Map a decoded `Transfer` payload onto the public model. + * + * Unknown *additional* fields are ignored and an unfamiliar *present* + * closed-set or location value degrades to `unrecognized`; a missing guaranteed + * field throws. **Guaranteed fields are only `id`, `amount`, and `status`** — + * the OpenAPI schema's required marking is a hint, not proof (see + * `models/Transfer.ts`'s file-level note), and `source`/`destination` both have + * a real service code path to absent (a fiat leg), so they decode to `null` + * rather than throwing when missing. `fees`, `transactionHash`, `errorCode`, + * and `policyEvaluation` are documented as present only in some cases and + * decode to empty/`null` when absent. `createDate` is not marked required at + * all — the same kind of gap as `Account.description`, which the service can + * omit — so it is treated as optional here rather than rejecting an + * otherwise-readable transfer on a guess. + * + * `destinationTransactionHash` follows the same "present only when …" pattern + * as `transactionHash`: it is the CCTP destination-mint hash, present only + * once the destination leg of a cross-chain transfer has minted, and decodes + * to `null` when absent. + * + * @throws MalformedPayloadError + */ +export function toTransfer(value: unknown): Transfer { + const payload = asObject(value, 'transfer') + + return new Transfer({ + id: requiredString(payload, 'id'), + source: toOptionalTransferSourceLocation(payload['source']), + destination: toOptionalTransferDestinationLocation(payload['destination']), + amount: requiredMoney(payload, 'amount'), + fees: toFees(payload), + transactionHash: optionalString(payload, 'transactionHash'), + destinationTransactionHash: optionalString(payload, 'destinationTransactionHash'), + status: toTransferStatus(requiredString(payload, 'status')), + errorCode: toTransferErrorCode(optionalString(payload, 'errorCode')), + policyEvaluation: (() => { + const policyEvaluation = optionalObject(payload, 'policyEvaluation') + return policyEvaluation === null ? null : toPolicyEvaluation(policyEvaluation) + })(), + createDate: optionalString(payload, 'createDate'), + }) +} + +export function toTransfers(value: unknown): readonly Transfer[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('transfers') + } + return Object.freeze(value.map(toTransfer)) +} diff --git a/src/wire/wireEnums.ts b/src/wire/wireEnums.ts new file mode 100644 index 0000000..63319f4 --- /dev/null +++ b/src/wire/wireEnums.ts @@ -0,0 +1,74 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { AccountPurpose, AccountStatus, AccountType, CustodyType } from '../models/Account' +import { unrecognized } from './payload' + +// Wire-string to public-type mapping, in one table per type. +// +// One table rather than a `switch` per field, so a wire spelling appears in +// exactly one place and adding a value is one line here plus one arm on the +// public type. The spellings are lower snake_case and none of them matches the +// public `kind` for the multi-word cases, so a mapper written from the type +// instead of the wire would look right and match nothing. +// +// A `Map` rather than an object literal, deliberately: an object literal inherits +// from `Object.prototype`, so `lookup['constructor']` and `lookup['toString']` +// return functions instead of `undefined` and a service value spelled like an +// `Object.prototype` member would be "recognised" as something that is not even a +// custody type. This is a JavaScript hazard with no Kotlin or Swift equivalent, +// and it is pinned by test. + +const CUSTODY_TYPES = new Map([ + ['omnibus', Object.freeze({ kind: 'omnibus' })], + ['segregated', Object.freeze({ kind: 'segregated' })], + ['self', Object.freeze({ kind: 'self' })], +]) + +const ACCOUNT_PURPOSES = new Map([ + ['custody', Object.freeze({ kind: 'custody' })], + ['payments', Object.freeze({ kind: 'payments' })], +]) + +const ACCOUNT_STATUSES = new Map([ + ['active', Object.freeze({ kind: 'active' })], + ['pending', Object.freeze({ kind: 'pending' })], + ['rejected', Object.freeze({ kind: 'rejected' })], + ['archived', Object.freeze({ kind: 'archived' })], +]) + +const ACCOUNT_TYPES = new Map([ + ['first_party', Object.freeze({ kind: 'first_party' })], + ['third_party', Object.freeze({ kind: 'third_party' })], +]) + +export function toCustodyType(raw: string | null): CustodyType { + return (raw === null ? undefined : CUSTODY_TYPES.get(raw)) ?? unrecognized(raw) +} + +export function toAccountPurpose(raw: string | null): AccountPurpose { + return (raw === null ? undefined : ACCOUNT_PURPOSES.get(raw)) ?? unrecognized(raw) +} + +export function toAccountStatus(raw: string | null): AccountStatus { + return (raw === null ? undefined : ACCOUNT_STATUSES.get(raw)) ?? unrecognized(raw) +} + +export function toAccountType(raw: string | null): AccountType { + return (raw === null ? undefined : ACCOUNT_TYPES.get(raw)) ?? unrecognized(raw) +} diff --git a/src/wire/wirePayload.ts b/src/wire/wirePayload.ts new file mode 100644 index 0000000..b6cdde4 --- /dev/null +++ b/src/wire/wirePayload.ts @@ -0,0 +1,160 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { TransferTypeInfo, WireInstructionBeneficiary } from '../models/Wire' +import { Wire, WireInstruction, WireInstructionBeneficiaryBank, WireSummary } from '../models/Wire' +import { + optionalBankAddress, + optionalBoolean, + requiredBillingDetails, + toFiatAccountStatus, +} from './fiatAccountPayload' +import { + MalformedPayloadError, + asObject, + optionalObject, + optionalString, + requiredString, +} from './payload' + +function toWireInstructionBeneficiary( + payload: Record, +): WireInstructionBeneficiary { + return Object.freeze({ + name: optionalString(payload, 'name', 'beneficiary.name'), + address1: optionalString(payload, 'address1', 'beneficiary.address1'), + address2: optionalString(payload, 'address2', 'beneficiary.address2'), + }) +} + +function toWireInstructionBeneficiaryBank( + payload: Record, +): WireInstructionBeneficiaryBank { + return new WireInstructionBeneficiaryBank({ + name: optionalString(payload, 'name', 'beneficiaryBank.name'), + swiftCode: optionalString(payload, 'swiftCode', 'beneficiaryBank.swiftCode'), + routingNumber: optionalString(payload, 'routingNumber', 'beneficiaryBank.routingNumber'), + accountNumber: optionalString(payload, 'accountNumber', 'beneficiaryBank.accountNumber'), + currency: optionalString(payload, 'currency', 'beneficiaryBank.currency'), + address: optionalString(payload, 'address', 'beneficiaryBank.address'), + city: optionalString(payload, 'city', 'beneficiaryBank.city'), + postalCode: optionalString(payload, 'postalCode', 'beneficiaryBank.postalCode'), + country: optionalString(payload, 'country', 'beneficiaryBank.country'), + }) +} + +/** + * A `transferTypesInfo` entry the service does not describe is ignored rather + * than rejected — the SDK does not act on this field, only relays it, and a + * relayed field gets that tolerance throughout. + */ +function toTransferTypeInfo(value: unknown, label: string): TransferTypeInfo | null { + if (typeof value !== 'object' || value === null || Array.isArray(value)) { + return null + } + const payload = value as Record + const currencies = payload.currencies + if (!Array.isArray(currencies) || !currencies.every((entry) => typeof entry === 'string')) { + throw new MalformedPayloadError(`${label}.currencies`) + } + return Object.freeze({ currencies: Object.freeze(currencies.slice()) }) +} + +function toTransferTypesInfo( + payload: Record, +): Readonly> | null { + const value = payload.transferTypesInfo + if (value === undefined || value === null) { + return null + } + if (typeof value !== 'object' || Array.isArray(value)) { + throw new MalformedPayloadError('transferTypesInfo') + } + const result = Object.create(null) as Record + for (const [key, entry] of Object.entries(value as Record)) { + const info = toTransferTypeInfo(entry, `transferTypesInfo.${key}`) + if (info !== null) { + result[key] = info + } + } + return Object.freeze(result) +} + +/** Decode one `WireSummary` (`GET /v1/banks/wires` collection entry). */ +export function toWireSummary(value: unknown): WireSummary { + const payload = asObject(value, 'wire') + return new WireSummary({ + id: requiredString(payload, 'id'), + type: optionalString(payload, 'type'), + status: toFiatAccountStatus(requiredString(payload, 'status')), + description: requiredString(payload, 'description'), + trackingRef: requiredString(payload, 'trackingRef'), + fingerprint: requiredString(payload, 'fingerprint'), + billingDetails: requiredBillingDetails(payload, 'billingDetails'), + bankAddress: optionalBankAddress(payload, 'bankAddress'), + virtualAccountEnabled: optionalBoolean(payload, 'virtualAccountEnabled'), + ffcMemo: optionalString(payload, 'ffcMemo'), + createDate: requiredString(payload, 'createDate'), + updateDate: requiredString(payload, 'updateDate'), + }) +} + +/** Decode the wire collection's unpaginated `data` array. */ +export function toWireSummaries(value: unknown): readonly WireSummary[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('wires') + } + return Object.freeze(value.map(toWireSummary)) +} + +/** Decode one `Wire` (`GET /v1/banks/wires/{id}`). */ +export function toWire(value: unknown): Wire { + const payload = asObject(value, 'wire') + return new Wire({ + id: requiredString(payload, 'id'), + type: optionalString(payload, 'type'), + status: toFiatAccountStatus(requiredString(payload, 'status')), + description: requiredString(payload, 'description'), + trackingRef: requiredString(payload, 'trackingRef'), + fingerprint: requiredString(payload, 'fingerprint'), + billingDetails: requiredBillingDetails(payload, 'billingDetails'), + bankAddress: optionalBankAddress(payload, 'bankAddress'), + virtualAccountEnabled: optionalBoolean(payload, 'virtualAccountEnabled'), + ffcMemo: optionalString(payload, 'ffcMemo'), + transferTypesInfo: toTransferTypesInfo(payload), + createDate: requiredString(payload, 'createDate'), + updateDate: requiredString(payload, 'updateDate'), + }) +} + +/** + * Decode a `WireInstruction` (`GET /v1/banks/wires/{id}/instructions`). Every + * field is optional in the service's own schema. + */ +export function toWireInstruction(value: unknown): WireInstruction { + const payload = asObject(value, 'wireInstruction') + const beneficiary = optionalObject(payload, 'beneficiary') + const beneficiaryBank = optionalObject(payload, 'beneficiaryBank') + return new WireInstruction({ + trackingRef: optionalString(payload, 'trackingRef'), + beneficiary: beneficiary === null ? null : toWireInstructionBeneficiary(beneficiary), + beneficiaryBank: + beneficiaryBank === null ? null : toWireInstructionBeneficiaryBank(beneficiaryBank), + virtualAccountEnabled: optionalBoolean(payload, 'virtualAccountEnabled'), + }) +} diff --git a/src/wire/withdrawalPayload.ts b/src/wire/withdrawalPayload.ts new file mode 100644 index 0000000..2500a7f --- /dev/null +++ b/src/wire/withdrawalPayload.ts @@ -0,0 +1,219 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import type { + WithdrawalAdjustments, + WithdrawalDestination, + WithdrawalDestinationType, + WithdrawalErrorCode, + WithdrawalPolicyEvaluation, + WithdrawalReturn, + WithdrawalRiskEvaluation, + WithdrawalStatus, + WithdrawalSubAccountSweep, + WithdrawalSweepStatus, +} from '../models/Withdrawal' +import { WithdrawalDetail, WithdrawalToAmount } from '../models/Withdrawal' +import { JSON_NUMBER } from './jsonNumber' +import { optionalMoney, requiredMoney } from './moneyPayload' +import { + MalformedPayloadError, + asObject, + optionalObject, + optionalString, + requiredString, + unrecognized, +} from './payload' + +const STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' as const })], + ['complete', Object.freeze({ kind: 'complete' as const })], + ['failed', Object.freeze({ kind: 'failed' as const })], +]) + +const ERROR_CODES = new Map( + [ + 'insufficient_funds', + 'transaction_denied', + 'transaction_failed', + 'transaction_returned', + 'bank_transaction_error', + 'fiat_account_limit_exceeded', + 'invalid_bank_account_number', + 'invalid_ach_rtn', + 'invalid_wire_rtn', + 'vendor_inactive', + 'payout_canceled', + 'invalid_travel_rule_identity', + 'intermediary_bank_required', + 'sen_not_supported', + ].map((kind) => [kind, Object.freeze({ kind }) as WithdrawalErrorCode]), +) + +const DESTINATION_TYPES = new Map([ + ['wire', Object.freeze({ kind: 'wire' as const })], + ['ach', Object.freeze({ kind: 'ach' as const })], +]) + +const SWEEP_STATUSES = new Map([ + ['pending', Object.freeze({ kind: 'pending' as const })], + ['complete', Object.freeze({ kind: 'complete' as const })], + ['failed', Object.freeze({ kind: 'failed' as const })], + ['skipped', Object.freeze({ kind: 'skipped' as const })], +]) + +function optionalBoolean(payload: Record, name: string): boolean | null { + const value = payload[name] + if (value === undefined || value === null) { + return null + } + if (typeof value !== 'boolean') { + throw new MalformedPayloadError(name) + } + return value +} + +function toDestination(payload: Record): WithdrawalDestination { + const rawType = requiredString(payload, 'type', 'destination.type') + return Object.freeze({ + type: DESTINATION_TYPES.get(rawType) ?? unrecognized(rawType), + id: requiredString(payload, 'id', 'destination.id'), + name: optionalString(payload, 'name', 'destination.name'), + }) +} + +function toRiskEvaluation(payload: Record): WithdrawalRiskEvaluation { + return Object.freeze({ + decision: optionalString(payload, 'decision', 'riskEvaluation.decision'), + reason: optionalString(payload, 'reason', 'riskEvaluation.reason'), + }) +} + +function toPolicyEvaluation(payload: Record): WithdrawalPolicyEvaluation { + return Object.freeze({ status: requiredString(payload, 'status', 'policyEvaluation.status') }) +} + +function toToAmount(payload: Record): WithdrawalToAmount { + const amount = optionalString(payload, 'amount', 'toAmount.amount') + if (amount !== null && !JSON_NUMBER.test(amount)) { + throw new MalformedPayloadError('toAmount.amount') + } + return new WithdrawalToAmount(amount, optionalString(payload, 'currency', 'toAmount.currency')) +} + +function toAdjustments(payload: Record): WithdrawalAdjustments { + return Object.freeze({ + fxCredit: optionalMoney(payload, 'fxCredit'), + fxDebit: optionalMoney(payload, 'fxDebit'), + }) +} + +function optionalStatus(payload: Record, name: string): WithdrawalStatus | null { + const raw = optionalString(payload, name, `return.${name}`) + return raw === null ? null : (STATUSES.get(raw) ?? unrecognized(raw)) +} + +function toReturn(payload: Record): WithdrawalReturn { + return Object.freeze({ + id: optionalString(payload, 'id', 'return.id'), + payoutId: optionalString(payload, 'payoutId', 'return.payoutId'), + amount: optionalMoney(payload, 'amount'), + fees: optionalMoney(payload, 'fees'), + reason: optionalString(payload, 'reason', 'return.reason'), + status: optionalStatus(payload, 'status'), + createDate: optionalString(payload, 'createDate', 'return.createDate'), + updateDate: optionalString(payload, 'updateDate', 'return.updateDate'), + }) +} + +function toSweep(value: unknown, index: number): WithdrawalSubAccountSweep { + const payload = asObject(value, `subAccountSweeps[${index}]`) + const rawStatus = optionalString(payload, 'status', `subAccountSweeps[${index}].status`) + return Object.freeze({ + subAccountId: optionalString( + payload, + 'subAccountId', + `subAccountSweeps[${index}].subAccountId`, + ), + amount: optionalMoney(payload, 'amount'), + status: rawStatus === null ? null : (SWEEP_STATUSES.get(rawStatus) ?? unrecognized(rawStatus)), + }) +} + +function toSweeps(payload: Record): readonly WithdrawalSubAccountSweep[] { + const value = payload.subAccountSweeps + if (value === undefined || value === null) { + return Object.freeze([]) + } + if (!Array.isArray(value)) { + throw new MalformedPayloadError('subAccountSweeps') + } + return Object.freeze(value.map(toSweep)) +} + +/** Decode the GET-only withdrawal detail payload from the standard data envelope. */ +export function toWithdrawalDetail(value: unknown): WithdrawalDetail { + const payload = asObject(value, 'withdrawal') + const destination = optionalObject(payload, 'destination') + if (destination === null) { + throw new MalformedPayloadError('destination') + } + const rawStatus = requiredString(payload, 'status') + const rawErrorCode = optionalString(payload, 'errorCode') + const toAmount = optionalObject(payload, 'toAmount') + const riskEvaluation = optionalObject(payload, 'riskEvaluation') + const adjustments = optionalObject(payload, 'adjustments') + const returnObject = optionalObject(payload, 'return') + const policyEvaluation = optionalObject(payload, 'policyEvaluation') + + return new WithdrawalDetail({ + id: requiredString(payload, 'id'), + sourceAccountId: requiredString(payload, 'sourceAccountId'), + destination: toDestination(destination), + amount: requiredMoney(payload, 'amount'), + toAmount: toAmount === null ? null : toToAmount(toAmount), + fees: optionalMoney(payload, 'fees'), + status: STATUSES.get(rawStatus) ?? unrecognized(rawStatus), + trackingRef: optionalString(payload, 'trackingRef'), + errorCode: + rawErrorCode === null ? null : (ERROR_CODES.get(rawErrorCode) ?? unrecognized(rawErrorCode)), + externalRef: optionalString(payload, 'externalRef'), + riskEvaluation: riskEvaluation === null ? null : toRiskEvaluation(riskEvaluation), + adjustments: adjustments === null ? null : toAdjustments(adjustments), + returnObject: returnObject === null ? null : toReturn(returnObject), + customerExternalRef: optionalString(payload, 'customerExternalRef'), + burnAll: optionalBoolean(payload, 'burnAll'), + subAccountSweeps: toSweeps(payload), + createDate: requiredString(payload, 'createDate'), + updateDate: optionalString(payload, 'updateDate'), + policyEvaluation: policyEvaluation === null ? null : toPolicyEvaluation(policyEvaluation), + }) +} + +/** + * Decode a withdrawal list page's `data` array. + * + * Each row is decoded by {@link toWithdrawalDetail}, so `policyEvaluation` is + * decoded when a row carries it and is `null` when the row omits it. + */ +export function toWithdrawalDetails(value: unknown): readonly WithdrawalDetail[] { + if (!Array.isArray(value)) { + throw new MalformedPayloadError('withdrawals') + } + return Object.freeze(value.map(toWithdrawalDetail)) +} diff --git a/testing.d.ts b/testing.d.ts new file mode 100644 index 0000000..1e00f39 --- /dev/null +++ b/testing.d.ts @@ -0,0 +1,19 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +export * from './build/testing' diff --git a/testing.js b/testing.js new file mode 100644 index 0000000..38e4a1a --- /dev/null +++ b/testing.js @@ -0,0 +1,25 @@ +/** + * Copyright (c) 2026, Circle Internet Group, Inc. All rights reserved. + * + * SPDX-License-Identifier: Apache-2.0 + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +// Legacy-resolver fallback for the package's `./testing` subpath. +// +// Exports-aware resolvers use the `exports` map in package.json +// (-> ./build/testing.js). This stub is for resolvers that ignore `exports` +// (e.g. Metro without `unstable_enablePackageExports` on RN < 0.79), so the +// subpath resolves everywhere. +module.exports = require('./build/testing.js') diff --git a/tsconfig.build.json b/tsconfig.build.json new file mode 100644 index 0000000..d8c1807 --- /dev/null +++ b/tsconfig.build.json @@ -0,0 +1,4 @@ +{ + "extends": "./tsconfig.json", + "exclude": ["build", "node_modules", "**/__test__", "**/*.test.ts"] +} diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..f1355ac --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,21 @@ +{ + "compilerOptions": { + "target": "ES2020", + "module": "CommonJS", + "moduleResolution": "node", + "jsx": "react-jsx", + "lib": ["ES2021", "DOM"], + "declaration": true, + "outDir": "build", + "rootDir": "src", + "strict": true, + "noUncheckedIndexedAccess": true, + "exactOptionalPropertyTypes": true, + "esModuleInterop": true, + "skipLibCheck": true, + "forceConsistentCasingInFileNames": true, + "types": ["jest"] + }, + "include": ["src"], + "exclude": ["build", "node_modules"] +} diff --git a/yarn.lock b/yarn.lock new file mode 100644 index 0000000..273056b --- /dev/null +++ b/yarn.lock @@ -0,0 +1,5175 @@ +# THIS IS AN AUTOGENERATED FILE. DO NOT EDIT THIS FILE DIRECTLY. +# yarn lockfile v1 + + +"@babel/code-frame@^7.0.0", "@babel/code-frame@^7.12.13", "@babel/code-frame@^7.29.0", "@babel/code-frame@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/code-frame/-/code-frame-7.29.7.tgz#f2fbbfea87c44a21590ec515b778b2c26d8866e7" + integrity sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw== + dependencies: + "@babel/helper-validator-identifier" "^7.29.7" + js-tokens "^4.0.0" + picocolors "^1.1.1" + +"@babel/compat-data@^7.28.6", "@babel/compat-data@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/compat-data/-/compat-data-7.29.7.tgz#6f0237f0f36d2e51c0570a636faed9d2d0efe629" + integrity sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg== + +"@babel/core@^7.11.6", "@babel/core@^7.12.3", "@babel/core@^7.23.9", "@babel/core@^7.24.4", "@babel/core@^7.25.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/core/-/core-7.29.7.tgz#80c10b17248082968b57a857b91640971f2070f7" + integrity sha512-RgHBCvtjbOK2gXSNBNIkNoEc9qoVEtau3hj8gEqKQuL3HZAibKarWFEI3Lfm6EYKkLalOh8eSrj9b+ch9H/VBA== + dependencies: + "@babel/code-frame" "^7.29.7" + "@babel/generator" "^7.29.7" + "@babel/helper-compilation-targets" "^7.29.7" + "@babel/helper-module-transforms" "^7.29.7" + "@babel/helpers" "^7.29.7" + "@babel/parser" "^7.29.7" + "@babel/template" "^7.29.7" + "@babel/traverse" "^7.29.7" + "@babel/types" "^7.29.7" + "@jridgewell/remapping" "^2.3.5" + convert-source-map "^2.0.0" + debug "^4.1.0" + gensync "^1.0.0-beta.2" + json5 "^2.2.3" + semver "^6.3.1" + +"@babel/generator@^7.29.1", "@babel/generator@^7.29.7", "@babel/generator@^7.29.8", "@babel/generator@^7.7.2": + version "7.29.8" + resolved "https://registry.yarnpkg.com/@babel/generator/-/generator-7.29.8.tgz#4b0b887885422643339e09022148a4c4ebaa4979" + integrity sha512-gZbepsdh3WDtgZKWL+vTPh71LSBrm/Y4/QDZBVCcYfmeTEEuoOYwlSy+G1StfJg+/Zy550u/3TATbm7qDbbMtg== + dependencies: + "@babel/parser" "^7.29.8" + "@babel/types" "^7.29.8" + "@jridgewell/gen-mapping" "^0.3.12" + "@jridgewell/trace-mapping" "^0.3.28" + jsesc "^3.0.2" + +"@babel/helper-annotate-as-pure@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-annotate-as-pure/-/helper-annotate-as-pure-7.29.7.tgz#c70fe3c6ecbdc3fd2dd1b0f498428b88b82ce47f" + integrity sha512-OoK6239jHPuSQOoS0kfTVKn0b/rVTk0seKq4Gd2UMLtmOVLjDC0ki3e+c90Trqv2gMfvJFqkiljrr568+qddiw== + dependencies: + "@babel/types" "^7.29.7" + +"@babel/helper-compilation-targets@^7.28.6", "@babel/helper-compilation-targets@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-compilation-targets/-/helper-compilation-targets-7.29.7.tgz#7a1def704302401c47f64fa85589e974ae217042" + integrity sha512-wem6WaBj4NaVYVdNhLPPVacES6ZJ+KBBfSkTMD3YZxbP3rm3Di85tJU5ljaUNhaOynt+Aj0xruhYuzQBt8n71g== + dependencies: + "@babel/compat-data" "^7.29.7" + "@babel/helper-validator-option" "^7.29.7" + browserslist "^4.24.0" + lru-cache "^5.1.1" + semver "^6.3.1" + +"@babel/helper-create-class-features-plugin@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-create-class-features-plugin/-/helper-create-class-features-plugin-7.29.7.tgz#6eddf286f2ec418f740c91d60a83347c55838ddd" + integrity sha512-IY3ZD9Tmooqr3TUhc3DUWxiuo8xx1DWLhd5M7hQ+ZWJamqM2BbalrBJb2MisSLoYorOj75U03qULCxQTY9r3hg== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-member-expression-to-functions" "^7.29.7" + "@babel/helper-optimise-call-expression" "^7.29.7" + "@babel/helper-replace-supers" "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers" "^7.29.7" + "@babel/traverse" "^7.29.7" + semver "^6.3.1" + +"@babel/helper-create-regexp-features-plugin@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-create-regexp-features-plugin/-/helper-create-regexp-features-plugin-7.29.7.tgz#5d4c3f928f315cf6c4184ea2fc3b5b38745b2430" + integrity sha512-907Uymvqgg1dwUA+7IGwFAOSYzQOuzPXKNJ1yxzwPffzkYFg2q2eHi1fIOs6sXkG9NbIUMunnUlkYsfRFNvomg== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + regexpu-core "^6.3.1" + semver "^6.3.1" + +"@babel/helper-define-polyfill-provider@^0.6.5", "@babel/helper-define-polyfill-provider@^0.6.8": + version "0.6.8" + resolved "https://registry.yarnpkg.com/@babel/helper-define-polyfill-provider/-/helper-define-polyfill-provider-0.6.8.tgz#cf1e4462b613f2b54c41e6ff758d5dfcaa2c85d1" + integrity sha512-47UwBLPpQi1NoWzLuHNjRoHlYXMwIJoBf7MFou6viC/sIHWYygpvr0B6IAyh5sBdA2nr2LPIRww8lfaUVQINBA== + dependencies: + "@babel/helper-compilation-targets" "^7.28.6" + "@babel/helper-plugin-utils" "^7.28.6" + debug "^4.4.3" + lodash.debounce "^4.0.8" + resolve "^1.22.11" + +"@babel/helper-globals@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-globals/-/helper-globals-7.29.7.tgz#f04a96fbd8473241b1079243f5b3f03a3010ab7b" + integrity sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA== + +"@babel/helper-member-expression-to-functions@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-member-expression-to-functions/-/helper-member-expression-to-functions-7.29.7.tgz#8dbdb3ce0b5c487e1aec10e13c9a43a500814df8" + integrity sha512-j+7JYmk1JYDtACIGj0QJqqWZjoUpMoEikQGADMaHgCMCSDqd2+P32rfcibUNrGOMWrlzK1WJBdxrB3JJQZwWtg== + dependencies: + "@babel/traverse" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/helper-module-imports@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-module-imports/-/helper-module-imports-7.29.7.tgz#ef25048a518e828d7393fac5882ddd73921d7396" + integrity sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g== + dependencies: + "@babel/traverse" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/helper-module-transforms@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-module-transforms/-/helper-module-transforms-7.29.7.tgz#b062747a5997ba138637201328bbff77960574ae" + integrity sha512-UPUVSyXbOh627KiCIGQSgwWzGeBKLkaJ9PJEdrngIwMSzxLR4jS4+f1f1jb7VzBbg8nFLaYotvVPFCTqdrmTAg== + dependencies: + "@babel/helper-module-imports" "^7.29.7" + "@babel/helper-validator-identifier" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/helper-optimise-call-expression@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-optimise-call-expression/-/helper-optimise-call-expression-7.29.7.tgz#77b0b5b94f1997fa9d6e3125f445227b1faf9d85" + integrity sha512-+kmGVjcT9RGYzoDwdwEqEvGgKe3BYq+O1iGzjFubaNgZHwYHP6lsF2Yghf4kEuv9BV7tYDZ913aBW9am6YKong== + dependencies: + "@babel/types" "^7.29.7" + +"@babel/helper-plugin-utils@^7.0.0", "@babel/helper-plugin-utils@^7.10.4", "@babel/helper-plugin-utils@^7.12.13", "@babel/helper-plugin-utils@^7.14.5", "@babel/helper-plugin-utils@^7.28.6", "@babel/helper-plugin-utils@^7.29.7", "@babel/helper-plugin-utils@^7.8.0": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-plugin-utils/-/helper-plugin-utils-7.29.7.tgz#c0a0766f1a13617d8a17407d7ab8f9d486225ea4" + integrity sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw== + +"@babel/helper-remap-async-to-generator@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-remap-async-to-generator/-/helper-remap-async-to-generator-7.29.7.tgz#34b1f68dd75b86d31df781a29c3ff2df88da82e6" + integrity sha512-16AMiW26DbXWBbr3B8wNozKM0ydMLB892vaOaJW/fPJdnT8vJk5sdkQcU/isqUxyCE0cEoa8wZOcbgDuC4b6Og== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-wrap-function" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/helper-replace-supers@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-replace-supers/-/helper-replace-supers-7.29.7.tgz#bc3c3964329043c79112e513c1b198f16589ac21" + integrity sha512-atfGXWSeCiF4DnKZIfmJfQRkSw9b9gNNXR1kqKjbhG4pGYCOnkp8OcTB8E3NXjBu8NpheSnOeNKz8KT7UNFTmQ== + dependencies: + "@babel/helper-member-expression-to-functions" "^7.29.7" + "@babel/helper-optimise-call-expression" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/helper-skip-transparent-expression-wrappers@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-skip-transparent-expression-wrappers/-/helper-skip-transparent-expression-wrappers-7.29.7.tgz#50c95c7e4c4f54936cfa0116428edc559862d551" + integrity sha512-brcMGQaVzIeUb+6/bs1Av0f8YuNNjKY2JyvfRCsFuFsdKccEQ5Ges2y74D74NZ1Rz8lKJ9ksJkfqwQFJ/iNEyQ== + dependencies: + "@babel/traverse" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/helper-string-parser@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-string-parser/-/helper-string-parser-7.29.7.tgz#7f0871d99824d23137d60f86fcf6130fd5a1b51f" + integrity sha512-Pb5ijPrZ89GDH8223L4UP8i6QApWxs04RbPQJTeWDV0/keR2E36MeKnyr6LYmUUvqRRI+Iv87SuF1W6ErINzYw== + +"@babel/helper-validator-identifier@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-identifier/-/helper-validator-identifier-7.29.7.tgz#bd87084ced0c796ec46bda492de6e83d29e89fc2" + integrity sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg== + +"@babel/helper-validator-option@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-validator-option/-/helper-validator-option-7.29.7.tgz#cf315be940213b354eb4abcc0bd01ebe3f73bc2a" + integrity sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw== + +"@babel/helper-wrap-function@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helper-wrap-function/-/helper-wrap-function-7.29.7.tgz#eec72163044548a0935e9d182bf2d547ec5ff483" + integrity sha512-iES0Skag9ERIF68aXadpO6dbXa03mNWK3sEqJaMnLNs/eC3l0lkImdfoy6Y09/SfkpawdAB4RjQ7PVA7TcVGdw== + dependencies: + "@babel/template" "^7.29.7" + "@babel/traverse" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/helpers@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/helpers/-/helpers-7.29.7.tgz#45abfde7548997e34376c3e69feb475cffb4a607" + integrity sha512-1k2lAGRMfHTcwuNYcCNUmaUffmQv8KWMfh2iJUUeRlwlwH4FdNG7mfPI10NPfLHJFThE4Tyr4mv7kTNZOiPuBg== + dependencies: + "@babel/template" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/parser@^7.1.0", "@babel/parser@^7.14.7", "@babel/parser@^7.20.7", "@babel/parser@^7.23.9", "@babel/parser@^7.24.4", "@babel/parser@^7.29.0", "@babel/parser@^7.29.7", "@babel/parser@^7.29.8": + version "7.29.8" + resolved "https://registry.yarnpkg.com/@babel/parser/-/parser-7.29.8.tgz#9653716a2f10c677b98fbc63d4bfb000c302cf17" + integrity sha512-E8lTAYNB1KW+FH+VGJuZM1ioAx2E6oVlvQFRrf5P8ZZmsiJXYAD9vTFV7yyEURNzgh1dFqMZuO6tUwcARbqFCA== + dependencies: + "@babel/types" "^7.29.8" + +"@babel/plugin-proposal-export-default-from@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-proposal-export-default-from/-/plugin-proposal-export-default-from-7.29.7.tgz#73bd63e538a050def0f5341c42439630b4923da9" + integrity sha512-p+G5BNXDcy3bOXplhY4HybQ1GxH3i2Tppmdm/3epyRu2VgJJZuUlZ61MqRTg582Q7ZLBdP7fePYvsumSEkMxcQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-syntax-async-generators@^7.8.4": + version "7.8.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-async-generators/-/plugin-syntax-async-generators-7.8.4.tgz#a983fb1aeb2ec3f6ed042a210f640e90e786fe0d" + integrity sha512-tycmZxkGfZaxhMRbXlPXuVFpdWlXpir2W4AMhSJgRKzk/eDlIXOhb2LHWoLpDF7TEHylV5zNhykX6KAgHJmTNw== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-bigint@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-bigint/-/plugin-syntax-bigint-7.8.3.tgz#4c9a6f669f5d0cdf1b90a1671e9a146be5300cea" + integrity sha512-wnTnFlG+YxQm3vDxpGE57Pj0srRU4sHE/mDkt1qv2YJJSeUAec2ma4WLUnUPeKjyrfntVwe/N6dCXpU+zL3Npg== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-class-properties@^7.12.13": + version "7.12.13" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-properties/-/plugin-syntax-class-properties-7.12.13.tgz#b5c987274c4a3a82b89714796931a6b53544ae10" + integrity sha512-fm4idjKla0YahUNgFNLCB0qySdsoPiZP3iQE3rky0mBUtMZ23yDJ9SJdg6dXTSDnulOVqiF3Hgr9nbXvXTQZYA== + dependencies: + "@babel/helper-plugin-utils" "^7.12.13" + +"@babel/plugin-syntax-class-static-block@^7.14.5": + version "7.14.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-class-static-block/-/plugin-syntax-class-static-block-7.14.5.tgz#195df89b146b4b78b3bf897fd7a257c84659d406" + integrity sha512-b+YyPmr6ldyNnM6sqYeMWE+bgJcJpO6yS4QD7ymxgH34GBPNDM/THBh8iunyvKIZztiwLH4CJZ0RxTk9emgpjw== + dependencies: + "@babel/helper-plugin-utils" "^7.14.5" + +"@babel/plugin-syntax-dynamic-import@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-dynamic-import/-/plugin-syntax-dynamic-import-7.8.3.tgz#62bf98b2da3cd21d626154fc96ee5b3cb68eacb3" + integrity sha512-5gdGbFon+PszYzqs83S3E5mpi7/y/8M9eC90MRTZfduQOYW76ig6SOSPNe41IG5LoP3FGBn2N0RjVDSQiS94kQ== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-export-default-from@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-export-default-from/-/plugin-syntax-export-default-from-7.29.7.tgz#52402c74fbd5d684ca63784bde4bb6d7af1e9e37" + integrity sha512-foag0BB37ROhdeIX9O8G0jX7hw0UekJc04cHMrYLOnrErsnBKqJGHJ8eDRpoCFZBvEPPygmmtw4qyU97qa4oOw== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-syntax-flow@^7.12.1", "@babel/plugin-syntax-flow@^7.29.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-flow/-/plugin-syntax-flow-7.29.7.tgz#3f3278c11c896c43bf8098250819785fd1231881" + integrity sha512-ajMX6QPcyomotqwpzhkYGxcK2i/us0rs1Qo9QvUpa+Fca0FTmqrzKrctoIYLMxcOhGZldGT/BAVkRGTWBiR8gQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-syntax-import-attributes@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-attributes/-/plugin-syntax-import-attributes-7.29.7.tgz#6115264516e95ead0f35a41710906612e447f605" + integrity sha512-zGYcYfq/WmZ4V+kBIXQon9dSSc8ircGZqw9ZaNhhGj9nZkeBu1jHLBDQqYYi5WA9uawvA2sIMbry2nCFhf5Djg== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-syntax-import-meta@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-import-meta/-/plugin-syntax-import-meta-7.10.4.tgz#ee601348c370fa334d2207be158777496521fd51" + integrity sha512-Yqfm+XDx0+Prh3VSeEQCPU81yC+JWZ2pDPFSS4ZdpfZhp4MkFMaDC1UqseovEKwSUpnIL7+vK+Clp7bfh0iD7g== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + +"@babel/plugin-syntax-json-strings@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-json-strings/-/plugin-syntax-json-strings-7.8.3.tgz#01ca21b668cd8218c9e640cb6dd88c5412b2c96a" + integrity sha512-lY6kdGpWHvjoe2vk4WrAapEuBR69EMxZl+RoGRhrFGNYVK8mOPAW8VfbT/ZgrFbXlDNiiaxQnAtgVCZ6jv30EA== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-jsx@^7.29.7", "@babel/plugin-syntax-jsx@^7.7.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-jsx/-/plugin-syntax-jsx-7.29.7.tgz#622c16f9ad63782fe6e83dadc7e40330744b7f1e" + integrity sha512-TSu8+mHCoEaaCDEZ0I3+6mvTBYR4PCxQwf2z9/r5Tbztv6NaLR3B9thGTTxX2WGuGHJqRiAbKPeGTJ5XWXVg6A== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-syntax-logical-assignment-operators@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-logical-assignment-operators/-/plugin-syntax-logical-assignment-operators-7.10.4.tgz#ca91ef46303530448b906652bac2e9fe9941f699" + integrity sha512-d8waShlpFDinQ5MtvGU9xDAOzKH47+FFoney2baFIoMr952hKOLp1HR7VszoZvOsV/4+RRszNY7D17ba0te0ig== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + +"@babel/plugin-syntax-nullish-coalescing-operator@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-nullish-coalescing-operator/-/plugin-syntax-nullish-coalescing-operator-7.8.3.tgz#167ed70368886081f74b5c36c65a88c03b66d1a9" + integrity sha512-aSff4zPII1u2QD7y+F8oDsz19ew4IGEJg9SVW+bqwpwtfFleiQDMdzA/R+UlWDzfnHFCxxleFT0PMIrR36XLNQ== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-numeric-separator@^7.10.4": + version "7.10.4" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-numeric-separator/-/plugin-syntax-numeric-separator-7.10.4.tgz#b9b070b3e33570cd9fd07ba7fa91c0dd37b9af97" + integrity sha512-9H6YdfkcK/uOnY/K7/aA2xpzaAgkQn37yzWUMRK7OaPOqOpGS1+n0H5hxT9AUw9EsSjPW8SVyMJwYRtWs3X3ug== + dependencies: + "@babel/helper-plugin-utils" "^7.10.4" + +"@babel/plugin-syntax-object-rest-spread@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-object-rest-spread/-/plugin-syntax-object-rest-spread-7.8.3.tgz#60e225edcbd98a640332a2e72dd3e66f1af55871" + integrity sha512-XoqMijGZb9y3y2XskN+P1wUGiVwWZ5JmoDRwx5+3GmEplNyVM2s2Dg8ILFQm8rWM48orGy5YpI5Bl8U1y7ydlA== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-optional-catch-binding@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-catch-binding/-/plugin-syntax-optional-catch-binding-7.8.3.tgz#6111a265bcfb020eb9efd0fdfd7d26402b9ed6c1" + integrity sha512-6VPD0Pc1lpTqw0aKoeRTMiB+kWhAoT24PA+ksWSBrFtl5SIRVpZlwN3NNPQjehA2E/91FV3RjLWoVTglWcSV3Q== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-optional-chaining@^7.8.3": + version "7.8.3" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-optional-chaining/-/plugin-syntax-optional-chaining-7.8.3.tgz#4f69c2ab95167e0180cd5336613f8c5788f7d48a" + integrity sha512-KoK9ErH1MBlCPxV0VANkXW2/dw4vlbGDrFgz8bmUsBGYkFRcbRwMh6cIJubdPrkxRwuGdtCk0v/wPTKbQgBjkg== + dependencies: + "@babel/helper-plugin-utils" "^7.8.0" + +"@babel/plugin-syntax-private-property-in-object@^7.14.5": + version "7.14.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-private-property-in-object/-/plugin-syntax-private-property-in-object-7.14.5.tgz#0dc6671ec0ea22b6e94a1114f857970cd39de1ad" + integrity sha512-0wVnp9dxJ72ZUJDV27ZfbSj6iHLoytYZmh3rFcxNnvsJF3ktkzLDZPy/mA17HGsaQT3/DQsWYX1f1QGWkCoVUg== + dependencies: + "@babel/helper-plugin-utils" "^7.14.5" + +"@babel/plugin-syntax-top-level-await@^7.14.5": + version "7.14.5" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-top-level-await/-/plugin-syntax-top-level-await-7.14.5.tgz#c1cfdadc35a646240001f06138247b741c34d94c" + integrity sha512-hx++upLv5U1rgYfwe1xBQUhRmU41NEvpUvrp8jkrSCdvGSnM5/qdRMtylJ6PG5OFkBaHkbTAKTnd3/YyESRHFw== + dependencies: + "@babel/helper-plugin-utils" "^7.14.5" + +"@babel/plugin-syntax-typescript@^7.29.7", "@babel/plugin-syntax-typescript@^7.7.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-syntax-typescript/-/plugin-syntax-typescript-7.29.7.tgz#7c29388932313ed58413a0343048d75d92fb5b24" + integrity sha512-ngr+82Sh0xMz25TPCZi+nC2iTzjfCdWS2ONXTp/PtSCHCgaCNBpdMqgvJ2ccdLlClVZ7sisIgB914j/JFe+RZA== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-async-generator-functions@^7.25.4": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-generator-functions/-/plugin-transform-async-generator-functions-7.29.7.tgz#a5365617921d82a1fee33124a1102bb38a1e677d" + integrity sha512-d98gXZkgswvkyohMBABkhm3GeXhYj8psWfwQ2C7gtfrKGTykQa/iOIi+JJhwMjPlZ6Vm2XN+DCf3Es1EoG4ZLA== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-remap-async-to-generator" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/plugin-transform-async-to-generator@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-async-to-generator/-/plugin-transform-async-to-generator-7.29.7.tgz#3b5e8f1fb58133cf701bcf0baaf6f01bfd1a8889" + integrity sha512-pcUb2SS+RMo9TWVBwKGI5ShtoG7R+zBsFmCKDa6fe8c+hPr3XJlZgoE5j6i8W7gDjhyvy+85vmYexanvXh3d1w== + dependencies: + "@babel/helper-module-imports" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-remap-async-to-generator" "^7.29.7" + +"@babel/plugin-transform-block-scoping@^7.25.0": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-block-scoping/-/plugin-transform-block-scoping-7.29.7.tgz#baa376691ae16244cd14335422fca6900f54e17d" + integrity sha512-ONyr4+AZhKh8yKWInVxU9AXA9EbsyeLcL6V0dJy6M2/62vuvpGm29zzuymbTpdc451GEpDIdAyPLP3r+P61yKQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-class-properties@^7.25.4": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-class-properties/-/plugin-transform-class-properties-7.29.7.tgz#034897b8a21beec163332fac2de235b14409abdf" + integrity sha512-GtcpjFvanPfzNQi3eTitsCqtRRmmqzpy/A+yhTR1HaZo1Ly3EA8ZXxlPyHdR8/IuRMYc3E4wdGBewB2QKQjAaA== + dependencies: + "@babel/helper-create-class-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-classes@^7.25.4": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-classes/-/plugin-transform-classes-7.29.7.tgz#61d3e5aaae0c838acc3204d9db7c8dc05c25815b" + integrity sha512-qV0OGGBVacduzQHE649JyCneOFI/maT+YKsO+K4Yi3xv2wTPNjM/W2o2gdzMwEAZz7fXNTHAe0NcSg30bIN69g== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-compilation-targets" "^7.29.7" + "@babel/helper-globals" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-replace-supers" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/plugin-transform-destructuring@^7.24.8": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-destructuring/-/plugin-transform-destructuring-7.29.7.tgz#5781ec6947852e27b64c1165f0db431f408090e4" + integrity sha512-iPX8aD6H9zV5s7ZsqTdNocPN/MGQ5sSMnElKrktxjJRMnB2jN/1p2+R7GkfD6CAYoVFqy5A4XnSIUeGgJzIWpg== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/traverse" "^7.29.7" + +"@babel/plugin-transform-flow-strip-types@^7.25.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-flow-strip-types/-/plugin-transform-flow-strip-types-7.29.7.tgz#911bcb31608c3576510d7e0c95ccf64f9e1812d0" + integrity sha512-wRHeUjUjCZnMHmiO5bRgjFLcoEh7JyTdByOW11ahhwNa4V0bmeGEaIvt51yq0zQp2yWIpqfxXXPyUP6GFJZHOQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/plugin-syntax-flow" "^7.29.7" + +"@babel/plugin-transform-for-of@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-for-of/-/plugin-transform-for-of-7.29.7.tgz#c65a678592117717aacdb10c1b73a9cb85e830be" + integrity sha512-zeSIHh0+E1Um1WJRXCFlHQYu2ieJNdivLLjlBEp+dIBu3S51n+SZZmIXjxnItw6pz56Cn+KvK68BIBVsxq2JiQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers" "^7.29.7" + +"@babel/plugin-transform-modules-commonjs@^7.24.8": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-modules-commonjs/-/plugin-transform-modules-commonjs-7.29.7.tgz#70e6835abf2663dafbe94b8ef1f51de7351ef135" + integrity sha512-j0vCldybPC5b5dwCQOJ21uKtHzt7hxLygJTg9eF1ScfaikEDNfzn94XoW5Fi+seBR0nCyL23xaBFFkq7dTM8XQ== + dependencies: + "@babel/helper-module-transforms" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-named-capturing-groups-regex@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-named-capturing-groups-regex/-/plugin-transform-named-capturing-groups-regex-7.29.7.tgz#21e75d847b31189842fa7a77703722ed4b43d27d" + integrity sha512-vuFoLwr4qnv2xbZ16SQd6uPcH5FNrLHhk/Jzo++0XJFcaDsr4gjJVg6j398oMHiC+83k/GiBzviwF5KBJkPUtQ== + dependencies: + "@babel/helper-create-regexp-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-nullish-coalescing-operator@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-nullish-coalescing-operator/-/plugin-transform-nullish-coalescing-operator-7.29.7.tgz#8a54cdf88c3f50433a6173117a286195b67714cc" + integrity sha512-idmp1dFaekP9GbcMvG24Kvw2BfhFZjHnNJCkV4WuIY4PskJzwI3f1N5OdgYke38T7rftO6ERulFRn2cFeZwRkg== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-optional-catch-binding@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-optional-catch-binding/-/plugin-transform-optional-catch-binding-7.29.7.tgz#729664f79985be504eba112c51de9f71d009030b" + integrity sha512-sLsyndxK2VwX6yNUOakMb7Sh553ZTe/vVM1XJ+9Z5aW1ytsc8xOIwmyk05NNjN60vkc5/KqoTH6hB4V41LJhng== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-optional-chaining@^7.24.8": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-optional-chaining/-/plugin-transform-optional-chaining-7.29.7.tgz#b84a1b574b3c73001023092567e16c492b720e51" + integrity sha512-6GM1dhvK3gNODkXcEcMCOLEDCLSoZ/sBbro2Ax8HURyasQ4NshagQixkRFdh5niI6E4gmA/jYI/4aT7rRos3ZQ== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers" "^7.29.7" + +"@babel/plugin-transform-private-methods@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-private-methods/-/plugin-transform-private-methods-7.29.7.tgz#cea8bd3ab99533892897a02999d5b752584ad145" + integrity sha512-/6Rz4DK1ETDEM/bWHsPHcaEe7ZaT1EqSXjtSP/L0DijOYuaUhiRiOKcwpZ8P7zR4xXEHc2ITdiCgBm9Tpyv9ug== + dependencies: + "@babel/helper-create-class-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-private-property-in-object@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-private-property-in-object/-/plugin-transform-private-property-in-object-7.29.7.tgz#4a2f6be5aba47be7afbdb4cd7903c46edf3a7661" + integrity sha512-+BNo06dnrzdNNqCm1X6YUaVv0DKk8Q+JYcoZfOkLhYWNCXzlwTSRq8zGWayT1csjcpNXV9CQTBRRbmTLZac5cA== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-create-class-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-react-display-name@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-display-name/-/plugin-transform-react-display-name-7.29.7.tgz#bf161a6d750267b79db7ff6f8fb89c3369b02df3" + integrity sha512-+1wdDMGNb4UPeY3Q4L5yLiYe6TXPXubs4NjrgRFw13hPRLJfEMw2Q5OXkee6/IfdqePIeW4Jjwe3aBh7SdKz4Q== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-react-jsx-self@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-self/-/plugin-transform-react-jsx-self-7.29.7.tgz#c24424527858220624fd59a5b1eab4fa413c803a" + integrity sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-react-jsx-source@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx-source/-/plugin-transform-react-jsx-source-7.29.7.tgz#5cf25a3689906b58e2f0a2f2b374789e6627b15f" + integrity sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-react-jsx@^7.25.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-react-jsx/-/plugin-transform-react-jsx-7.29.7.tgz#3d16a0e5773f079400a8c82a190709cdf92ee204" + integrity sha512-WsZulLVBUHXVj2cUcPVx6UE21TpalB6bHbSFErKT0Ib++ax24jjXe73FqlWvdylFOjiuPHYi6VCcgRad1ItN+A== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-module-imports" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/plugin-syntax-jsx" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/plugin-transform-regenerator@^7.24.7": + version "7.29.8" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-regenerator/-/plugin-transform-regenerator-7.29.8.tgz#3a4a4dd7214af9d524f0503bb97c99af5f4abf26" + integrity sha512-0UpIXPtdDtMXfnV2OJAVMLpj3H/92vmkA6lpSRakmycJvj3VUy6Xs1dM8tXRugupykr5WB+LpiVl0J8LMVg2mg== + dependencies: + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/plugin-transform-runtime@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-runtime/-/plugin-transform-runtime-7.29.7.tgz#7c7fb6e2a46dce67e278b6cc84421c1d16da5695" + integrity sha512-xmAscdE/AsqRW7vutbPNoUmu/nF5SrLKPs7aoJgEjo35lLKA/Bc0i2rMv/hr1+Y0o1bQCiVtith3u2vdgRL39Q== + dependencies: + "@babel/helper-module-imports" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + babel-plugin-polyfill-corejs2 "^0.4.14" + babel-plugin-polyfill-corejs3 "^0.13.0" + babel-plugin-polyfill-regenerator "^0.6.5" + semver "^6.3.1" + +"@babel/plugin-transform-typescript@^7.25.2": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-typescript/-/plugin-transform-typescript-7.29.7.tgz#f0449c3df7037bbe232043476851c38f5e4a7615" + integrity sha512-jK52h8LaLc7JarhQV2ofeFMts4H7vnOXnqZNA6fYglBTZewRBE51KWt3BUltW1P+KoPsYkHoJeXePuz4zo2LMw== + dependencies: + "@babel/helper-annotate-as-pure" "^7.29.7" + "@babel/helper-create-class-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + "@babel/helper-skip-transparent-expression-wrappers" "^7.29.7" + "@babel/plugin-syntax-typescript" "^7.29.7" + +"@babel/plugin-transform-unicode-regex@^7.24.7": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/plugin-transform-unicode-regex/-/plugin-transform-unicode-regex-7.29.7.tgz#c3064b293ff7f1794b71f7650eec8db9896d3e59" + integrity sha512-7D/x/23/d/3VqZ0QA+LGbZMlGwZjztBygSWWWsfTPoQ1oQ6Q1P6Mr3d0kk42XabyUVw+fha3LqdRsFqeKqvCyA== + dependencies: + "@babel/helper-create-regexp-features-plugin" "^7.29.7" + "@babel/helper-plugin-utils" "^7.29.7" + +"@babel/runtime@^7.25.0": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/runtime/-/runtime-7.29.7.tgz#12022450c45a4da6d8d8287b18a4ff2ddb23f768" + integrity sha512-Nq8OhGWiZIZGV6hLHoyAKLLcJihP/xFeBMGJoUrxTX2psI8dCifzLhZISFb+VWS3wFMRDmCGw5R+dOySCqPLhw== + +"@babel/template@^7.28.6", "@babel/template@^7.29.7", "@babel/template@^7.3.3": + version "7.29.7" + resolved "https://registry.yarnpkg.com/@babel/template/-/template-7.29.7.tgz#4d9d4004f645cdd304de958c725162784ecac700" + integrity sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg== + dependencies: + "@babel/code-frame" "^7.29.7" + "@babel/parser" "^7.29.7" + "@babel/types" "^7.29.7" + +"@babel/traverse@^7.29.0", "@babel/traverse@^7.29.7": + version "7.29.8" + resolved "https://registry.yarnpkg.com/@babel/traverse/-/traverse-7.29.8.tgz#4111014cdc71a0f95d9471907590baa0b8a6b28a" + integrity sha512-I5z7H3bf/41ktsNVLtpN0wAa336HkqIHQ5BuPLEhTkt1jVSyZpeNKIzTgEWmlxjdg81R0IgUCcaE+Ok3NvrfZg== + dependencies: + "@babel/code-frame" "^7.29.7" + "@babel/generator" "^7.29.8" + "@babel/helper-globals" "^7.29.7" + "@babel/parser" "^7.29.8" + "@babel/template" "^7.29.7" + "@babel/types" "^7.29.8" + debug "^4.3.1" + +"@babel/types@^7.0.0", "@babel/types@^7.20.7", "@babel/types@^7.28.2", "@babel/types@^7.29.0", "@babel/types@^7.29.7", "@babel/types@^7.29.8", "@babel/types@^7.3.3": + version "7.29.8" + resolved "https://registry.yarnpkg.com/@babel/types/-/types-7.29.8.tgz#1229eef31d85156d70fa3f4cd859376d0eaf6863" + integrity sha512-Vj1jF3cPfxg7OAfoI7QnVKLoILlm2JF9pnVHrX8qx7AHMiYWT+NDAA7jChlNgRS4WTLc/fD1lXLmPixluj+3Gg== + dependencies: + "@babel/helper-string-parser" "^7.29.7" + "@babel/helper-validator-identifier" "^7.29.7" + +"@bcoe/v8-coverage@^0.2.3": + version "0.2.3" + resolved "https://registry.yarnpkg.com/@bcoe/v8-coverage/-/v8-coverage-0.2.3.tgz#75a2e8b51cb758a7553d6804a5932d7aace75c39" + integrity sha512-0hYQ8SB4Db5zvZB4axdMHGwEaQjkZzFjQiN9LVYvIFB2nSUHW9tYpxWriPrWDASIxiaXax83REcLxuSdnGPZtw== + +"@cyclonedx/cyclonedx-library@^10.0.0": + version "10.2.0" + resolved "https://registry.yarnpkg.com/@cyclonedx/cyclonedx-library/-/cyclonedx-library-10.2.0.tgz#c5af3ba8c0614561e87e0ec4b89d5782f022075e" + integrity sha512-hGeo1XXM0zuIeTyzJihxPxnEOeNBmgZkuPRmTR28RktlAqF9xLneonHRCzahZHLgCq/LOmtCs5vyojJlnmJ87w== + +"@cyclonedx/cyclonedx-npm@6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/@cyclonedx/cyclonedx-npm/-/cyclonedx-npm-6.0.1.tgz#269085c8d52880e81697918dbc8ae8a43735727d" + integrity sha512-/aU3bBC6qP6cV/qQ5SfUSygE/+2hQhwgg6sJML31/gZ96NyMvIUuwdk637H4z+LS/NryRT2kjR2wtD0qBEVVHQ== + dependencies: + "@cyclonedx/cyclonedx-library" "^10.0.0" + commander "^14.0.0" + normalize-package-data "^7.0.0 || ^8.0.0" + packageurl-js "^2.0.1" + spdx-expression-parse "^3.0.1 || ^4.0.0" + xmlbuilder2 "^3.0.2 || ^4.0.3" + optionalDependencies: + ajv "^8.12.0" + ajv-formats "^3.0.1" + ajv-formats-draft2019 "^1.6.1" + libxmljs2 "^0.35||^0.37" + +"@eslint-community/eslint-utils@^4.8.0", "@eslint-community/eslint-utils@^4.9.1": + version "4.10.1" + resolved "https://registry.yarnpkg.com/@eslint-community/eslint-utils/-/eslint-utils-4.10.1.tgz#8911bd72b2c3640a543609e0400b8c4d2e7e7cb6" + integrity sha512-cuadcxVFE8sDK6iWJbs8Sn0av2Nrh2QSGQhVlBW9AaAHqHwjWsZHT8LJ4hFGPh7ASBV2deFdM7H/DPjulmh8rg== + dependencies: + eslint-visitor-keys "^3.4.3" + +"@eslint-community/regexpp@^4.12.1", "@eslint-community/regexpp@^4.12.2": + version "4.12.2" + resolved "https://registry.yarnpkg.com/@eslint-community/regexpp/-/regexpp-4.12.2.tgz#bccdf615bcf7b6e8db830ec0b8d21c9a25de597b" + integrity sha512-EriSTlt5OC9/7SXkRSCAhfSxxoSUgBm33OH+IkwbdpgoqsSsUg7y3uh+IICI/Qg4BBWr3U2i39RpmycbxMq4ew== + +"@eslint/config-array@^0.21.2": + version "0.21.2" + resolved "https://registry.yarnpkg.com/@eslint/config-array/-/config-array-0.21.2.tgz#f29e22057ad5316cf23836cee9a34c81fffcb7e6" + integrity sha512-nJl2KGTlrf9GjLimgIru+V/mzgSK0ABCDQRvxw5BjURL7WfH5uoWmizbH7QB6MmnMBd8cIC9uceWnezL1VZWWw== + dependencies: + "@eslint/object-schema" "^2.1.7" + debug "^4.3.1" + minimatch "^3.1.5" + +"@eslint/config-helpers@^0.4.2": + version "0.4.2" + resolved "https://registry.yarnpkg.com/@eslint/config-helpers/-/config-helpers-0.4.2.tgz#1bd006ceeb7e2e55b2b773ab318d300e1a66aeda" + integrity sha512-gBrxN88gOIf3R7ja5K9slwNayVcZgK6SOUORm2uBzTeIEfeVaIhOpCtTox3P6R7o2jLFwLFTLnC7kU/RGcYEgw== + dependencies: + "@eslint/core" "^0.17.0" + +"@eslint/core@^0.17.0": + version "0.17.0" + resolved "https://registry.yarnpkg.com/@eslint/core/-/core-0.17.0.tgz#77225820413d9617509da9342190a2019e78761c" + integrity sha512-yL/sLrpmtDaFEiUj1osRP4TI2MDz1AddJL+jZ7KSqvBuliN4xqYY54IfdN8qD8Toa6g1iloph1fxQNkjOxrrpQ== + dependencies: + "@types/json-schema" "^7.0.15" + +"@eslint/eslintrc@^3.3.6": + version "3.3.6" + resolved "https://registry.yarnpkg.com/@eslint/eslintrc/-/eslintrc-3.3.6.tgz#d22bfd6b3a7d8e1f2c0b2f2e6de111b53ec6e13e" + integrity sha512-l2Ul9PrHsPCKcEY/ac7VgFj9D80C7S68sOKc618SyHDPK36s1XcFebXY0iTzUVn4Yq+YbwvSnDmCz9yxjX+QrA== + dependencies: + ajv "^6.14.0" + debug "^4.3.2" + espree "^10.0.1" + globals "^14.0.0" + ignore "^5.2.0" + import-fresh "^3.2.1" + js-yaml "^4.3.0" + minimatch "^3.1.5" + strip-json-comments "^3.1.1" + +"@eslint/js@9.39.5": + version "9.39.5" + resolved "https://registry.yarnpkg.com/@eslint/js/-/js-9.39.5.tgz#6f2fbcff75500d229d535e0a949ae13472c84787" + integrity sha512-QywQuszQh77pIXCsq998c8hbhSTI/azTty1Z6N53dmAudKHhy573j3yvRLsX2BSp8YpLtoCEG8E9DJe+8zUh4A== + +"@eslint/object-schema@^2.1.7": + version "2.1.7" + resolved "https://registry.yarnpkg.com/@eslint/object-schema/-/object-schema-2.1.7.tgz#6e2126a1347e86a4dedf8706ec67ff8e107ebbad" + integrity sha512-VtAOaymWVfZcmZbp6E2mympDIHvyjXs/12LqWYjVw6qjrfF+VK+fyG33kChz3nnK+SU5/NeHOqrTEHS8sXO3OA== + +"@eslint/plugin-kit@^0.4.1": + version "0.4.1" + resolved "https://registry.yarnpkg.com/@eslint/plugin-kit/-/plugin-kit-0.4.1.tgz#9779e3fd9b7ee33571a57435cf4335a1794a6cb2" + integrity sha512-43/qtrDUokr7LJqoF2c3+RInu/t4zfrpYdoSDfYyhg52rwLV6TnOvdG4fXm7IkSB3wErkcmJS9iEhjVtOSEjjA== + dependencies: + "@eslint/core" "^0.17.0" + levn "^0.4.1" + +"@humanfs/core@^0.19.2": + version "0.19.2" + resolved "https://registry.yarnpkg.com/@humanfs/core/-/core-0.19.2.tgz#a8272ca03b2acf492670222b2320b6c421bfde60" + integrity sha512-UhXNm+CFMWcbChXywFwkmhqjs3PRCmcSa/hfBgLIb7oQ5HNb1wS0icWsGtSAUNgefHeI+eBrA8I1fxmbHsGdvA== + dependencies: + "@humanfs/types" "^0.15.0" + +"@humanfs/node@^0.16.6": + version "0.16.8" + resolved "https://registry.yarnpkg.com/@humanfs/node/-/node-0.16.8.tgz#8f800cccc13f4f8cd3116e2d9c0a94939da3e3ed" + integrity sha512-gE1eQNZ3R++kTzFUpdGlpmy8kDZD/MLyHqDwqjkVQI0JMdI1D51sy1H958PNXYkM2rAac7e5/CnIKZrHtPh3BQ== + dependencies: + "@humanfs/core" "^0.19.2" + "@humanfs/types" "^0.15.0" + "@humanwhocodes/retry" "^0.4.0" + +"@humanfs/types@^0.15.0": + version "0.15.0" + resolved "https://registry.yarnpkg.com/@humanfs/types/-/types-0.15.0.tgz#f2a09f62012390b2bff3fc6fb248ddec8c09a090" + integrity sha512-ZZ1w0aoQkwuUuC7Yf+7sdeaNfqQiiLcSRbfI08oAxqLtpXQr9AIVX7Ay7HLDuiLYAaFPu8oBYNq/QIi9URHJ3Q== + +"@humanwhocodes/module-importer@^1.0.1": + version "1.0.1" + resolved "https://registry.yarnpkg.com/@humanwhocodes/module-importer/-/module-importer-1.0.1.tgz#af5b2691a22b44be847b0ca81641c5fb6ad0172c" + integrity sha512-bxveV4V8v5Yb4ncFTT3rPSgZBOpCkjfK0y4oVVVJwIuDVBRMDXrPyXRL988i5ap9m9bnyEEjWfm5WkBmtffLfA== + +"@humanwhocodes/retry@^0.4.0", "@humanwhocodes/retry@^0.4.2": + version "0.4.3" + resolved "https://registry.yarnpkg.com/@humanwhocodes/retry/-/retry-0.4.3.tgz#c2b9d2e374ee62c586d3adbea87199b1d7a7a6ba" + integrity sha512-bV0Tgo9K4hfPCek+aMAn81RppFKv2ySDQeMoSZuvTASywNTnVJCArCZE2FWqpvIatKu7VMRLWlR1EazvVhDyhQ== + +"@isaacs/cliui@^8.0.2": + version "8.0.2" + resolved "https://registry.yarnpkg.com/@isaacs/cliui/-/cliui-8.0.2.tgz#b37667b7bc181c168782259bab42474fbf52b550" + integrity sha512-O8jcjabXaleOG9DQ0+ARXWZBTfnP4WNAqzuiJK7ll44AmxGKv/J2M4TPjxjY3znBCfvBXFzucm1twdyFybFqEA== + dependencies: + string-width "^5.1.2" + string-width-cjs "npm:string-width@^4.2.0" + strip-ansi "^7.0.1" + strip-ansi-cjs "npm:strip-ansi@^6.0.1" + wrap-ansi "^8.1.0" + wrap-ansi-cjs "npm:wrap-ansi@^7.0.0" + +"@isaacs/fs-minipass@^4.0.0": + version "4.0.1" + resolved "https://registry.yarnpkg.com/@isaacs/fs-minipass/-/fs-minipass-4.0.1.tgz#2d59ae3ab4b38fb4270bfa23d30f8e2e86c7fe32" + integrity sha512-wgm9Ehl2jpeqP3zw/7mo3kRHFp5MEDhqAdwy1fTGkHAwnkGOVsgpvQhL8B5n1qlb01jV3n/bI0ZfZp5lWA1k4w== + dependencies: + minipass "^7.0.4" + +"@isaacs/ttlcache@^1.4.1": + version "1.4.1" + resolved "https://registry.yarnpkg.com/@isaacs/ttlcache/-/ttlcache-1.4.1.tgz#21fb23db34e9b6220c6ba023a0118a2dd3461ea2" + integrity sha512-RQgQ4uQ+pLbqXfOmieB91ejmLwvSgv9nLx6sT6sD83s7umBypgg+OIBOBbEUiJXrfpnp9j0mRhYYdzp9uqq3lA== + +"@istanbuljs/load-nyc-config@^1.0.0": + version "1.1.0" + resolved "https://registry.yarnpkg.com/@istanbuljs/load-nyc-config/-/load-nyc-config-1.1.0.tgz#fd3db1d59ecf7cf121e80650bb86712f9b55eced" + integrity sha512-VjeHSlIzpv/NyD3N0YuHfXOPDIixcA1q2ZV98wsMqcYlPmv2n3Yb2lYP9XMElnaFVXg5A7YLTeLu6V84uQDjmQ== + dependencies: + camelcase "^5.3.1" + find-up "^4.1.0" + get-package-type "^0.1.0" + js-yaml "^3.13.1" + resolve-from "^5.0.0" + +"@istanbuljs/schema@^0.1.2", "@istanbuljs/schema@^0.1.3": + version "0.1.6" + resolved "https://registry.yarnpkg.com/@istanbuljs/schema/-/schema-0.1.6.tgz#8dc9afa2ac1506cb1a58f89940f1c124446c8df3" + integrity sha512-+Sg6GCR/wy1oSmQDFq4LQDAhm3ETKnorxN+y5nbLULOR3P0c14f2Wurzj3/xqPXtasLFfHd5iRFQ7AJt4KH2cw== + +"@jest/console@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/console/-/console-29.7.0.tgz#cd4822dbdb84529265c5a2bdb529a3c9cc950ffc" + integrity sha512-5Ni4CU7XHQi32IJ398EEP4RrB8eV09sXP2ROqD4bksHrnTree52PsxvX8tpL8LvTZ3pFzXyPbNQReSN41CAhOg== + dependencies: + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + slash "^3.0.0" + +"@jest/core@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/core/-/core-29.7.0.tgz#b6cccc239f30ff36609658c5a5e2291757ce448f" + integrity sha512-n7aeXWKMnGtDA48y8TLWJPJmLmmZ642Ceo78cYWEpiD7FzDgmNDV/GCVRorPABdXLJZ/9wzzgZAlHjXjxDHGsg== + dependencies: + "@jest/console" "^29.7.0" + "@jest/reporters" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + ansi-escapes "^4.2.1" + chalk "^4.0.0" + ci-info "^3.2.0" + exit "^0.1.2" + graceful-fs "^4.2.9" + jest-changed-files "^29.7.0" + jest-config "^29.7.0" + jest-haste-map "^29.7.0" + jest-message-util "^29.7.0" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-resolve-dependencies "^29.7.0" + jest-runner "^29.7.0" + jest-runtime "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" + jest-watcher "^29.7.0" + micromatch "^4.0.4" + pretty-format "^29.7.0" + slash "^3.0.0" + strip-ansi "^6.0.0" + +"@jest/create-cache-key-function@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/create-cache-key-function/-/create-cache-key-function-29.7.0.tgz#793be38148fab78e65f40ae30c36785f4ad859f0" + integrity sha512-4QqS3LY5PBmTRHj9sAg1HLoPzqAI0uOX6wI/TRqHIcOxlFidy6YEmCQJk6FSZjNLGCeubDMfmkWL+qaLKhSGQA== + dependencies: + "@jest/types" "^29.6.3" + +"@jest/diff-sequences@30.4.0": + version "30.4.0" + resolved "https://registry.yarnpkg.com/@jest/diff-sequences/-/diff-sequences-30.4.0.tgz#8be2d260e6241d6cddddd102c304fe13b4fc8e3e" + integrity sha512-zOpzlfUs45l6u7jm39qr87JCHUDsaeCtvL+kQe/Vn9jSnRB4/5IPXISm0h9I1vZW/o00Kn4UTJ2MOlhnUGwv3g== + +"@jest/environment@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/environment/-/environment-29.7.0.tgz#24d61f54ff1f786f3cd4073b4b94416383baf2a7" + integrity sha512-aQIfHDq33ExsN4jP1NWGXhxgQ/wixs60gDiKO+XVMd8Mn0NWPWgc34ZQDTb2jKaUWQ7MuwoitXAsN2XVXNMpAw== + dependencies: + "@jest/fake-timers" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + jest-mock "^29.7.0" + +"@jest/expect-utils@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/expect-utils/-/expect-utils-29.7.0.tgz#023efe5d26a8a70f21677d0a1afc0f0a44e3a1c6" + integrity sha512-GlsNBWiFQFCVi9QVSx7f5AgMeLxe9YCCs5PuP2O2LdjDAA8Jh9eX7lA1Jq/xdXw3Wb3hyvlFNfZIfcRetSzYcA== + dependencies: + jest-get-type "^29.6.3" + +"@jest/expect@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/expect/-/expect-29.7.0.tgz#76a3edb0cb753b70dfbfe23283510d3d45432bf2" + integrity sha512-8uMeAMycttpva3P1lBHB8VciS9V0XAr3GymPpipdyQXbBcuhkLQOSe8E/p92RyAdToS6ZD1tFkX+CkhoECE0dQ== + dependencies: + expect "^29.7.0" + jest-snapshot "^29.7.0" + +"@jest/fake-timers@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/fake-timers/-/fake-timers-29.7.0.tgz#fd91bf1fffb16d7d0d24a426ab1a47a49881a565" + integrity sha512-q4DH1Ha4TTFPdxLsqDXK1d3+ioSL7yL5oCMJZgDYm6i+6CygW5E5xVr/D1HdsGxjt1ZWSfUAs9OxSB/BNelWrQ== + dependencies: + "@jest/types" "^29.6.3" + "@sinonjs/fake-timers" "^10.0.2" + "@types/node" "*" + jest-message-util "^29.7.0" + jest-mock "^29.7.0" + jest-util "^29.7.0" + +"@jest/get-type@30.1.0": + version "30.1.0" + resolved "https://registry.yarnpkg.com/@jest/get-type/-/get-type-30.1.0.tgz#4fcb4dc2ebcf0811be1c04fd1cb79c2dba431cbc" + integrity sha512-eMbZE2hUnx1WV0pmURZY9XoXPkUYjpc55mb0CrhtdWLtzMQPFvu/rZkTLZFTsdaVQa+Tr4eWAteqcUzoawq/uA== + +"@jest/globals@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/globals/-/globals-29.7.0.tgz#8d9290f9ec47ff772607fa864ca1d5a2efae1d4d" + integrity sha512-mpiz3dutLbkW2MNFubUGUEVLkTGiqW6yLVTA+JbP6fI6J5iL9Y0Nlg8k95pcF8ctKwCS7WVxteBs29hhfAotzQ== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/expect" "^29.7.0" + "@jest/types" "^29.6.3" + jest-mock "^29.7.0" + +"@jest/reporters@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/reporters/-/reporters-29.7.0.tgz#04b262ecb3b8faa83b0b3d321623972393e8f4c7" + integrity sha512-DApq0KJbJOEzAFYjHADNNxAE3KbhxQB1y5Kplb5Waqw6zVbuWatSnMjE5gs8FUgEPmNsnZA3NCWl9NG0ia04Pg== + dependencies: + "@bcoe/v8-coverage" "^0.2.3" + "@jest/console" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + "@jridgewell/trace-mapping" "^0.3.18" + "@types/node" "*" + chalk "^4.0.0" + collect-v8-coverage "^1.0.0" + exit "^0.1.2" + glob "^7.1.3" + graceful-fs "^4.2.9" + istanbul-lib-coverage "^3.0.0" + istanbul-lib-instrument "^6.0.0" + istanbul-lib-report "^3.0.0" + istanbul-lib-source-maps "^4.0.0" + istanbul-reports "^3.1.3" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + jest-worker "^29.7.0" + slash "^3.0.0" + string-length "^4.0.1" + strip-ansi "^6.0.0" + v8-to-istanbul "^9.0.1" + +"@jest/schemas@30.4.1": + version "30.4.1" + resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-30.4.1.tgz#c3703fdd71357e2c83aa59bd38469e60a11529c6" + integrity sha512-i6b4qw5qnP8c5FEeBJg/uZQ4ddrkN6Ca8qISJh0pr7a5hfn3h3v5x60BEbOC7OYAGZNMs1LfFLwnW2CuK8F57Q== + dependencies: + "@sinclair/typebox" "^0.34.0" + +"@jest/schemas@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/schemas/-/schemas-29.6.3.tgz#430b5ce8a4e0044a7e3819663305a7b3091c8e03" + integrity sha512-mo5j5X+jIZmJQveBKeS/clAueipV7KgiX1vMgCxam1RNYiqE1w62n0/tJJnHtjW8ZHcQco5gY85jA3mi0L+nSA== + dependencies: + "@sinclair/typebox" "^0.27.8" + +"@jest/source-map@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/source-map/-/source-map-29.6.3.tgz#d90ba772095cf37a34a5eb9413f1b562a08554c4" + integrity sha512-MHjT95QuipcPrpLM+8JMSzFx6eHp5Bm+4XeFDJlwsvVBjmKNiIAvasGK2fxz2WbGRlnvqehFbh07MMa7n3YJnw== + dependencies: + "@jridgewell/trace-mapping" "^0.3.18" + callsites "^3.0.0" + graceful-fs "^4.2.9" + +"@jest/test-result@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/test-result/-/test-result-29.7.0.tgz#8db9a80aa1a097bb2262572686734baed9b1657c" + integrity sha512-Fdx+tv6x1zlkJPcWXmMDAG2HBnaR9XPSd5aDWQVsfrZmLVT3lU1cwyxLgRmXR9yrq4NBoEm9BMsfgFzTQAbJYA== + dependencies: + "@jest/console" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/istanbul-lib-coverage" "^2.0.0" + collect-v8-coverage "^1.0.0" + +"@jest/test-sequencer@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/test-sequencer/-/test-sequencer-29.7.0.tgz#6cef977ce1d39834a3aea887a1726628a6f072ce" + integrity sha512-GQwJ5WZVrKnOJuiYiAF52UNUJXgTZx1NHjFSEB0qEMmSZKAkdMoIzw/Cj6x6NF4AvV23AUqDpFzQkN/eYCYTxw== + dependencies: + "@jest/test-result" "^29.7.0" + graceful-fs "^4.2.9" + jest-haste-map "^29.7.0" + slash "^3.0.0" + +"@jest/transform@^29.7.0": + version "29.7.0" + resolved "https://registry.yarnpkg.com/@jest/transform/-/transform-29.7.0.tgz#df2dd9c346c7d7768b8a06639994640c642e284c" + integrity sha512-ok/BTPFzFKVMwO5eOHRrvnBVHdRy9IrsrW1GpMaQ9MCnilNLXQKmAX8s1YXDFaai9xJpac2ySzV0YeRRECr2Vw== + dependencies: + "@babel/core" "^7.11.6" + "@jest/types" "^29.6.3" + "@jridgewell/trace-mapping" "^0.3.18" + babel-plugin-istanbul "^6.1.1" + chalk "^4.0.0" + convert-source-map "^2.0.0" + fast-json-stable-stringify "^2.1.0" + graceful-fs "^4.2.9" + jest-haste-map "^29.7.0" + jest-regex-util "^29.6.3" + jest-util "^29.7.0" + micromatch "^4.0.4" + pirates "^4.0.4" + slash "^3.0.0" + write-file-atomic "^4.0.2" + +"@jest/types@^29.6.3": + version "29.6.3" + resolved "https://registry.yarnpkg.com/@jest/types/-/types-29.6.3.tgz#1131f8cf634e7e84c5e77bab12f052af585fba59" + integrity sha512-u3UPsIilWKOM3F9CXtrG8LEJmNxwoCQC/XVj4IKYXvvpx7QIi/Kg1LI5uDmDpKlac62NUtX7eLjRh+jVZcLOzw== + dependencies: + "@jest/schemas" "^29.6.3" + "@types/istanbul-lib-coverage" "^2.0.0" + "@types/istanbul-reports" "^3.0.0" + "@types/node" "*" + "@types/yargs" "^17.0.8" + chalk "^4.0.0" + +"@jridgewell/gen-mapping@^0.3.12", "@jridgewell/gen-mapping@^0.3.5": + version "0.3.13" + resolved "https://registry.yarnpkg.com/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz#6342a19f44347518c93e43b1ac69deb3c4656a1f" + integrity sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA== + dependencies: + "@jridgewell/sourcemap-codec" "^1.5.0" + "@jridgewell/trace-mapping" "^0.3.24" + +"@jridgewell/remapping@^2.3.5": + version "2.3.5" + resolved "https://registry.yarnpkg.com/@jridgewell/remapping/-/remapping-2.3.5.tgz#375c476d1972947851ba1e15ae8f123047445aa1" + integrity sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ== + dependencies: + "@jridgewell/gen-mapping" "^0.3.5" + "@jridgewell/trace-mapping" "^0.3.24" + +"@jridgewell/resolve-uri@^3.1.0": + version "3.1.2" + resolved "https://registry.yarnpkg.com/@jridgewell/resolve-uri/-/resolve-uri-3.1.2.tgz#7a0ee601f60f99a20c7c7c5ff0c80388c1189bd6" + integrity sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw== + +"@jridgewell/source-map@^0.3.3": + version "0.3.11" + resolved "https://registry.yarnpkg.com/@jridgewell/source-map/-/source-map-0.3.11.tgz#b21835cbd36db656b857c2ad02ebd413cc13a9ba" + integrity sha512-ZMp1V8ZFcPG5dIWnQLr3NSI1MiCU7UETdS/A0G8V/XWHvJv3ZsFqutJn1Y5RPmAPX6F3BiE397OqveU/9NCuIA== + dependencies: + "@jridgewell/gen-mapping" "^0.3.5" + "@jridgewell/trace-mapping" "^0.3.25" + +"@jridgewell/sourcemap-codec@^1.4.14", "@jridgewell/sourcemap-codec@^1.5.0": + version "1.5.5" + resolved "https://registry.yarnpkg.com/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.5.5.tgz#6912b00d2c631c0d15ce1a7ab57cd657f2a8f8ba" + integrity sha512-cYQ9310grqxueWbl+WuIUIaiUaDcj7WOq5fVhEljNVgRfOUhY9fy2zTvfoqWsnebh8Sl70VScFbICvJnLKB0Og== + +"@jridgewell/trace-mapping@^0.3.12", "@jridgewell/trace-mapping@^0.3.18", "@jridgewell/trace-mapping@^0.3.24", "@jridgewell/trace-mapping@^0.3.25", "@jridgewell/trace-mapping@^0.3.28": + version "0.3.31" + resolved "https://registry.yarnpkg.com/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz#db15d6781c931f3a251a3dac39501c98a6082fd0" + integrity sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw== + dependencies: + "@jridgewell/resolve-uri" "^3.1.0" + "@jridgewell/sourcemap-codec" "^1.4.14" + +"@npmcli/agent@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/agent/-/agent-3.0.0.tgz#1685b1fbd4a1b7bb4f930cbb68ce801edfe7aa44" + integrity sha512-S79NdEgDQd/NGCay6TCoVzXSj74skRZIKJcpJjC5lOq34SZzyI6MqtiiWoiVWoVrTcGjNeC4ipbh1VIHlpfF5Q== + dependencies: + agent-base "^7.1.0" + http-proxy-agent "^7.0.0" + https-proxy-agent "^7.0.1" + lru-cache "^10.0.1" + socks-proxy-agent "^8.0.3" + +"@npmcli/fs@^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/@npmcli/fs/-/fs-4.0.0.tgz#a1eb1aeddefd2a4a347eca0fab30bc62c0e1c0f2" + integrity sha512-/xGlezI6xfGO9NwuJlnwz/K14qD1kCSAGtacBHnGzeAIuJGazcp45KP5NuyARXoKb7cwulAGWVsbeSxdG/cb0Q== + dependencies: + semver "^7.3.5" + +"@oozcitak/dom@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@oozcitak/dom/-/dom-2.0.2.tgz#0f447f0b736aa6f36c5556ba811a44e56c71c26c" + integrity sha512-GjpKhkSYC3Mj4+lfwEyI1dqnsKTgwGy48ytZEhm4A/xnH/8z9M3ZVXKr/YGQi3uCLs1AEBS+x5T2JPiueEDW8w== + dependencies: + "@oozcitak/infra" "^2.0.2" + "@oozcitak/url" "^3.0.0" + "@oozcitak/util" "^10.0.0" + +"@oozcitak/infra@^2.0.2": + version "2.0.2" + resolved "https://registry.yarnpkg.com/@oozcitak/infra/-/infra-2.0.2.tgz#e2f1cc0eeca3ac5cd551f0326a5f66f00cf1138b" + integrity sha512-2g+E7hoE2dgCz/APPOEK5s3rMhJvNxSMBrP+U+j1OWsIbtSpWxxlUjq1lU8RIsFJNYv7NMlnVsCuHcUzJW+8vA== + dependencies: + "@oozcitak/util" "^10.0.0" + +"@oozcitak/url@^3.0.0": + version "3.0.0" + resolved "https://registry.yarnpkg.com/@oozcitak/url/-/url-3.0.0.tgz#a03c959c67e28aba9e29b2d35cd50d26cb5f2cc4" + integrity sha512-ZKfET8Ak1wsLAiLWNfFkZc/BraDccuTJKR6svTYc7sVjbR+Iu0vtXdiDMY4o6jaFl5TW2TlS7jbLl4VovtAJWQ== + dependencies: + "@oozcitak/infra" "^2.0.2" + "@oozcitak/util" "^10.0.0" + +"@oozcitak/util@^10.0.0": + version "10.0.0" + resolved "https://registry.yarnpkg.com/@oozcitak/util/-/util-10.0.0.tgz#f6b40472d96c210094a556ee5ccb8e77f1bd30af" + integrity sha512-hAX0pT/73190NLqBPPWSdBVGtbY6VOhWYK3qqHqtXQ1gK7kS2yz4+ivsN07hpJ6I3aeMtKP6J6npsEKOAzuTLA== + +"@pkgjs/parseargs@^0.11.0": + version "0.11.0" + resolved "https://registry.yarnpkg.com/@pkgjs/parseargs/-/parseargs-0.11.0.tgz#a77ea742fab25775145434eb1d2328cf5013ac33" + integrity sha512-+1VkjdD0QBLPodGrJUeqarH8VAIvQODIbwh9XpP5Syisf7YoQgsJKPNFoqqLQlu+VQ/tVSshMR6loPMn8U+dPg== + +"@react-native/assets-registry@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/assets-registry/-/assets-registry-0.85.3.tgz#e28da0d296120b9677c3cb9f4ebc92b636ac987e" + integrity sha512-u9ZiYP23vA2IFtdFQFmetzSmk6SM0xgKIoiOsr1hXNHjHaLhOm+/Ph1ud57wX6+Dbwdzx8coJgnzSKL3W21PCg== + +"@react-native/babel-plugin-codegen@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/babel-plugin-codegen/-/babel-plugin-codegen-0.85.3.tgz#85584812e08e04b0b8f443ee732f787017eaf254" + integrity sha512-Wc94zGfeFG8Njf9SHMPfYZP04kjigkOps6F1TYTvd7ZVXuGxqseCDgxc50LWcOhOCLypI9n3oVVqz81C3p44ZA== + dependencies: + "@babel/traverse" "^7.29.0" + "@react-native/codegen" "0.85.3" + +"@react-native/babel-preset@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/babel-preset/-/babel-preset-0.85.3.tgz#b4e226c9b996e38cee51bdc1055d4a2ba24a733b" + integrity sha512-fD7fxEhkJB/aF57tWoXjaAWpklfrExYZS3k6aXPP3BQ77DZY7gvf/b7dbirwjID6NVnP1JDRJyTuPBGr0K/vlw== + dependencies: + "@babel/core" "^7.25.2" + "@babel/plugin-proposal-export-default-from" "^7.24.7" + "@babel/plugin-syntax-dynamic-import" "^7.8.3" + "@babel/plugin-syntax-export-default-from" "^7.24.7" + "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" + "@babel/plugin-syntax-optional-chaining" "^7.8.3" + "@babel/plugin-transform-async-generator-functions" "^7.25.4" + "@babel/plugin-transform-async-to-generator" "^7.24.7" + "@babel/plugin-transform-block-scoping" "^7.25.0" + "@babel/plugin-transform-class-properties" "^7.25.4" + "@babel/plugin-transform-classes" "^7.25.4" + "@babel/plugin-transform-destructuring" "^7.24.8" + "@babel/plugin-transform-flow-strip-types" "^7.25.2" + "@babel/plugin-transform-for-of" "^7.24.7" + "@babel/plugin-transform-modules-commonjs" "^7.24.8" + "@babel/plugin-transform-named-capturing-groups-regex" "^7.24.7" + "@babel/plugin-transform-nullish-coalescing-operator" "^7.24.7" + "@babel/plugin-transform-optional-catch-binding" "^7.24.7" + "@babel/plugin-transform-optional-chaining" "^7.24.8" + "@babel/plugin-transform-private-methods" "^7.24.7" + "@babel/plugin-transform-private-property-in-object" "^7.24.7" + "@babel/plugin-transform-react-display-name" "^7.24.7" + "@babel/plugin-transform-react-jsx" "^7.25.2" + "@babel/plugin-transform-react-jsx-self" "^7.24.7" + "@babel/plugin-transform-react-jsx-source" "^7.24.7" + "@babel/plugin-transform-regenerator" "^7.24.7" + "@babel/plugin-transform-runtime" "^7.24.7" + "@babel/plugin-transform-typescript" "^7.25.2" + "@babel/plugin-transform-unicode-regex" "^7.24.7" + "@react-native/babel-plugin-codegen" "0.85.3" + babel-plugin-syntax-hermes-parser "0.33.3" + babel-plugin-transform-flow-enums "^0.0.2" + react-refresh "^0.14.0" + +"@react-native/codegen@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/codegen/-/codegen-0.85.3.tgz#3168a42d240b66d1597f8e292ce71171fabb3b1c" + integrity sha512-/JkS1lGLyzBWP1FbgDwaqEf7qShIC6pUC1M0a/YMAd/v4iqR24MRkQWe7jkYvcBQ2LpEhs5NGE9InhxSv21zCA== + dependencies: + "@babel/core" "^7.25.2" + "@babel/parser" "^7.29.0" + hermes-parser "0.33.3" + invariant "^2.2.4" + nullthrows "^1.1.1" + tinyglobby "^0.2.15" + yargs "^17.6.2" + +"@react-native/community-cli-plugin@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/community-cli-plugin/-/community-cli-plugin-0.85.3.tgz#bc9008fe823bca059ab330861253e9be57f8cc46" + integrity sha512-fs85dmbIqNmtzEixDb0g+q6R3Vt4H9eAt8/inIZdDKfjN76+sUJA2r1nxODQ76bU23MrIbz8sI7KFBPaWk/zQw== + dependencies: + "@react-native/dev-middleware" "0.85.3" + debug "^4.4.0" + invariant "^2.2.4" + metro "^0.84.3" + metro-config "^0.84.3" + metro-core "^0.84.3" + semver "^7.1.3" + +"@react-native/debugger-frontend@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/debugger-frontend/-/debugger-frontend-0.85.3.tgz#c8c66a5bb766b22466ffb0adaf0f0074bd38b482" + integrity sha512-uAu7rM5o/Np1zgp6fi5zM1sP1aB8DcS7DdOLcj/TkSutOAjkMqqd2lWt1/+3S7qXexRHVK5XcP+o3VXo4L/V0A== + +"@react-native/debugger-shell@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/debugger-shell/-/debugger-shell-0.85.3.tgz#ad755fc280942c240cd833916ddcf89a86a34b1f" + integrity sha512-/jRAaT9boiCttIcEwS02WPwYkUihqsjSaK/TMtHz05vT6uMgac9PaQt5kzBQLIABv5aEIa5gtrMmKVz49MjkjQ== + dependencies: + cross-spawn "^7.0.6" + debug "^4.4.0" + fb-dotslash "0.5.8" + +"@react-native/dev-middleware@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/dev-middleware/-/dev-middleware-0.85.3.tgz#a5818ea674b0bbead230555697748b215ef3fc3a" + integrity sha512-JYzBiT4A8w+KQt+dOD5v+ti+tDrGoPnsSTuApq3Ls4RB5sfWbDlYMyz3dbc8qBIHz9tv0sQ5+eOu6Xwqzr5AQA== + dependencies: + "@isaacs/ttlcache" "^1.4.1" + "@react-native/debugger-frontend" "0.85.3" + "@react-native/debugger-shell" "0.85.3" + chrome-launcher "^0.15.2" + chromium-edge-launcher "^0.3.0" + connect "^3.6.5" + debug "^4.4.0" + invariant "^2.2.4" + nullthrows "^1.1.1" + open "^7.0.3" + serve-static "^1.16.2" + ws "^7.5.10" + +"@react-native/gradle-plugin@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/gradle-plugin/-/gradle-plugin-0.85.3.tgz#79f94aa38bc68be9b331cfd197de5bb53109465a" + integrity sha512-39dY2j50Q1pntejzwt3XL7vwXtrj8jcIfHq6E+gyu3jzYxZJVvMkMutQ39vSg6zinIQOX36oQDhidXUbCXzgoA== + +"@react-native/jest-preset@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/jest-preset/-/jest-preset-0.85.3.tgz#e7ce02f0fdf2b51d06097598f24a3e4f234478bb" + integrity sha512-ALPSrM0q2fU+5AXcOXzDKx7rxVKPMvygAZfsTWLdrGRVWIqf/HEfM0R8euQqIKUqmEuQ1TxMWN+px3h6gc4vow== + dependencies: + "@jest/create-cache-key-function" "^29.7.0" + "@react-native/js-polyfills" "0.85.3" + babel-jest "^29.7.0" + jest-environment-node "^29.7.0" + regenerator-runtime "^0.13.2" + +"@react-native/js-polyfills@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/js-polyfills/-/js-polyfills-0.85.3.tgz#f3eef60ee619f51f78f8db7489abc192e685508f" + integrity sha512-U2+aMshIXf1uFn77tpBb/xhHWB9vkVrMpt7kkucAugF8hJKYTDGB587X7WwelHduK2KBfhl4giSv0rzZGoef9A== + +"@react-native/normalize-colors@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/normalize-colors/-/normalize-colors-0.85.3.tgz#681f4be6c0a57b5bcf16b993b3bc96e5a45bf3a2" + integrity sha512-hj0PScZEhIbcOvQV5yMKX3ha4XEIOy/SVE1Rrpp0beW0dpNLOgSC7KDxGewmDnIHK9YdQUXGY9eMEfShUMIaZw== + +"@react-native/virtualized-lists@0.85.3": + version "0.85.3" + resolved "https://registry.yarnpkg.com/@react-native/virtualized-lists/-/virtualized-lists-0.85.3.tgz#0fe478a10505d7fd3cfd39de26b6673a1fd0e091" + integrity sha512-dsCjI//OIPEUJMyNHp4l7zNLVjCx7bcaRUceOCkU+IB17hkbtbGWvi7HjGFSzy7FJGmS/MOlcfpb72xXiy1Oig== + dependencies: + invariant "^2.2.4" + nullthrows "^1.1.1" + +"@sinclair/typebox@^0.27.8": + version "0.27.12" + resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.27.12.tgz#0cacd3cff047a32936b1ace47ea7c86eaab60a7f" + integrity sha512-hhyNJ+nbR6ZR7pToHvllEFun9TL0sbL+tk/ON75lo+Xas054uez98qRbsuNt7MBCyZKK4+8Yli/OAGZhmfBZ/g== + +"@sinclair/typebox@^0.34.0": + version "0.34.52" + resolved "https://registry.yarnpkg.com/@sinclair/typebox/-/typebox-0.34.52.tgz#62f8a686e4ab28a8944902e2ad2d648312ef11cb" + integrity sha512-XiMQh7qqVlxZzcVD+kkGMNGMzcTrDMLWI7S4x7z1MkCkbDPrekpZXEUK0eZqZFMuHQg2a2DZOcDIh9o5v3Gonw== + +"@sinonjs/commons@^3.0.0": + version "3.0.1" + resolved "https://registry.yarnpkg.com/@sinonjs/commons/-/commons-3.0.1.tgz#1029357e44ca901a615585f6d27738dbc89084cd" + integrity sha512-K3mCHKQ9sVh8o1C9cxkwxaOmXoAMlDxC1mYyHrjqOWEcBjYr76t96zL2zlj5dUGZ3HSw240X1qgH3Mjf1yJWpQ== + dependencies: + type-detect "4.0.8" + +"@sinonjs/fake-timers@^10.0.2": + version "10.3.0" + resolved "https://registry.yarnpkg.com/@sinonjs/fake-timers/-/fake-timers-10.3.0.tgz#55fdff1ecab9f354019129daf4df0dd4d923ea66" + integrity sha512-V4BG07kuYSUkTCSBHG8G8TNhM+F19jXFWnQtzj+we8DrkpSBCee9Z3Ms8yiGer/dlmhe35/Xdgyo3/0rQKg7YA== + dependencies: + "@sinonjs/commons" "^3.0.0" + +"@sumsub/react-native-mobilesdk-module@1.46.1": + version "1.46.1" + resolved "https://registry.yarnpkg.com/@sumsub/react-native-mobilesdk-module/-/react-native-mobilesdk-module-1.46.1.tgz#8bdef39768f8982162e3392242d8c5089c6f5fb9" + integrity sha512-xtyGRsJI3PDW6vPSy9C3wGSJTGOqHgds8bLjUz+ysaqFLeApSnLS28F2aeKReFiDAJBum86bt989VS09fgQuOw== + +"@testing-library/react-native@14.0.1": + version "14.0.1" + resolved "https://registry.yarnpkg.com/@testing-library/react-native/-/react-native-14.0.1.tgz#3f6c64f7174715818190f283e12c375eb9e7bc0a" + integrity sha512-2r2e2y8SkUNRWKRXlUGqDYunB+AkbdXUPn49Bs5rpv9oxRb0K3USBVugbPbAKJjfj4w5Ba91NJ8LcQCZyopUZA== + dependencies: + jest-matcher-utils "^30.4.1" + picocolors "^1.1.1" + pretty-format "^30.4.1" + redent "^3.0.0" + +"@types/babel__core@^7.1.14": + version "7.20.5" + resolved "https://registry.yarnpkg.com/@types/babel__core/-/babel__core-7.20.5.tgz#3df15f27ba85319caa07ba08d0721889bb39c017" + integrity sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA== + dependencies: + "@babel/parser" "^7.20.7" + "@babel/types" "^7.20.7" + "@types/babel__generator" "*" + "@types/babel__template" "*" + "@types/babel__traverse" "*" + +"@types/babel__generator@*": + version "7.27.0" + resolved "https://registry.yarnpkg.com/@types/babel__generator/-/babel__generator-7.27.0.tgz#b5819294c51179957afaec341442f9341e4108a9" + integrity sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg== + dependencies: + "@babel/types" "^7.0.0" + +"@types/babel__template@*": + version "7.4.4" + resolved "https://registry.yarnpkg.com/@types/babel__template/-/babel__template-7.4.4.tgz#5672513701c1b2199bc6dad636a9d7491586766f" + integrity sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A== + dependencies: + "@babel/parser" "^7.1.0" + "@babel/types" "^7.0.0" + +"@types/babel__traverse@*", "@types/babel__traverse@^7.0.6": + version "7.28.0" + resolved "https://registry.yarnpkg.com/@types/babel__traverse/-/babel__traverse-7.28.0.tgz#07d713d6cce0d265c9849db0cbe62d3f61f36f74" + integrity sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q== + dependencies: + "@babel/types" "^7.28.2" + +"@types/estree@^1.0.6": + version "1.0.9" + resolved "https://registry.yarnpkg.com/@types/estree/-/estree-1.0.9.tgz#cf3f0e876d7bee15a93ab925b82bf570a3904a24" + integrity sha512-GhdPgy1el4/ImP05X05Uw4cw2/M93BCUmnEvWZNStlCzEKME4Fkk+YpoA5OiHNQmoS7Cafb8Xa3Pya8m1Qrzeg== + +"@types/graceful-fs@^4.1.3": + version "4.1.9" + resolved "https://registry.yarnpkg.com/@types/graceful-fs/-/graceful-fs-4.1.9.tgz#2a06bc0f68a20ab37b3e36aa238be6abdf49e8b4" + integrity sha512-olP3sd1qOEe5dXTSaFvQG+02VdRXcdytWLAZsAq1PecU8uqQAhkrnbli7DagjtXKW/Bl7YJbUsa8MPcuc8LHEQ== + dependencies: + "@types/node" "*" + +"@types/istanbul-lib-coverage@*", "@types/istanbul-lib-coverage@^2.0.0", "@types/istanbul-lib-coverage@^2.0.1": + version "2.0.6" + resolved "https://registry.yarnpkg.com/@types/istanbul-lib-coverage/-/istanbul-lib-coverage-2.0.6.tgz#7739c232a1fee9b4d3ce8985f314c0c6d33549d7" + integrity sha512-2QF/t/auWm0lsy8XtKVPG19v3sSOQlJe/YHZgfjb/KBBHOGSV+J2q/S671rcq9uTBrLAXmZpqJiaQbMT+zNU1w== + +"@types/istanbul-lib-report@*": + version "3.0.3" + resolved "https://registry.yarnpkg.com/@types/istanbul-lib-report/-/istanbul-lib-report-3.0.3.tgz#53047614ae72e19fc0401d872de3ae2b4ce350bf" + integrity sha512-NQn7AHQnk/RSLOxrBbGyJM/aVQ+pjj5HCgasFxc0K/KhoATfQ/47AyUl15I2yBUpihjmas+a+VJBOqecrFH+uA== + dependencies: + "@types/istanbul-lib-coverage" "*" + +"@types/istanbul-reports@^3.0.0": + version "3.0.4" + resolved "https://registry.yarnpkg.com/@types/istanbul-reports/-/istanbul-reports-3.0.4.tgz#0f03e3d2f670fbdac586e34b433783070cc16f54" + integrity sha512-pk2B1NWalF9toCRu6gjBzR69syFjP4Od8WRAX+0mmf9lAjCRicLOWc+ZrxZHx/0XRjotgkF9t6iaMJ+aXcOdZQ== + dependencies: + "@types/istanbul-lib-report" "*" + +"@types/jest@29.5.14": + version "29.5.14" + resolved "https://registry.yarnpkg.com/@types/jest/-/jest-29.5.14.tgz#2b910912fa1d6856cadcd0c1f95af7df1d6049e5" + integrity sha512-ZN+4sdnLUbo8EVvVc2ao0GFW6oVrQRPn4K2lglySj7APvSrgzxHiNNK99us4WDMi57xxA2yggblIAMNhXOotLQ== + dependencies: + expect "^29.0.0" + pretty-format "^29.0.0" + +"@types/json-schema@^7.0.15": + version "7.0.15" + resolved "https://registry.yarnpkg.com/@types/json-schema/-/json-schema-7.0.15.tgz#596a1747233694d50f6ad8a7869fcb6f56cf5841" + integrity sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA== + +"@types/node@*": + version "26.2.0" + resolved "https://registry.yarnpkg.com/@types/node/-/node-26.2.0.tgz#5a4875a862fda8fdc57de8faa579bb81ecba1685" + integrity sha512-5IviulTZeRNp2vAJ514cc/HUlY5nZ9fCbq9DMyC52BrhFZACo3nI0R7qBxhQmo/d27NFe96ur/b7Wwxklda+kg== + dependencies: + undici-types "~8.3.0" + +"@types/react-reconciler@~0.33.0": + version "0.33.0" + resolved "https://registry.yarnpkg.com/@types/react-reconciler/-/react-reconciler-0.33.0.tgz#d27edab907998b3d9f18bc24e422d9aac34b741d" + integrity sha512-HZOXsKT0tGI9LlUw2LuedXsVeB88wFa536vVL0M6vE8zN63nI+sSr1ByxmPToP5K5bukaVscyeCJcF9guVNJ1g== + +"@types/react@19.2.3": + version "19.2.3" + resolved "https://registry.yarnpkg.com/@types/react/-/react-19.2.3.tgz#264e4304219ff8be9e1cb4ee923c3bc6d8587089" + integrity sha512-k5dJVszUiNr1DSe8Cs+knKR6IrqhqdhpUwzqhkS8ecQTSf3THNtbfIp/umqHMpX2bv+9dkx3fwDv/86LcSfvSg== + dependencies: + csstype "^3.0.2" + +"@types/stack-utils@^2.0.0": + version "2.0.3" + resolved "https://registry.yarnpkg.com/@types/stack-utils/-/stack-utils-2.0.3.tgz#6209321eb2c1712a7e7466422b8cb1fc0d9dd5d8" + integrity sha512-9aEbYZ3TbYMznPdcdr3SmIrLXwC/AKZXQeCf9Pgao5CKb8CyHuEX5jzWPTkvregvhRJHcpRO6BFoGW9ycaOkYw== + +"@types/yargs-parser@*": + version "21.0.3" + resolved "https://registry.yarnpkg.com/@types/yargs-parser/-/yargs-parser-21.0.3.tgz#815e30b786d2e8f0dcd85fd5bcf5e1a04d008f15" + integrity sha512-I4q9QU9MQv4oEOz4tAHJtNz1cwuLxn2F3xcc2iV5WdqLPpUnj30aUuxt1mAxYTG+oe8CZMV/+6rU4S4gRDzqtQ== + +"@types/yargs@^17.0.8": + version "17.0.35" + resolved "https://registry.yarnpkg.com/@types/yargs/-/yargs-17.0.35.tgz#07013e46aa4d7d7d50a49e15604c1c5340d4eb24" + integrity sha512-qUHkeCyQFxMXg79wQfTtfndEC+N9ZZg76HJftDJp+qH2tV7Gj4OJi7l+PiWwJ+pWtW8GwSmqsDj/oymhrTWXjg== + dependencies: + "@types/yargs-parser" "*" + +"@typescript-eslint/eslint-plugin@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/eslint-plugin/-/eslint-plugin-8.66.0.tgz#76e86aa5a2459fbf5bbd7a839c0dc0cce1d56224" + integrity sha512-p088eaGrzYz1s+7cov0aMOCkNGTJlVxF4jgubf28c8L0Cv9Rloj8YBHnv4hXLq6IIEE1AsjNWavO+k+8kP2Y0A== + dependencies: + "@eslint-community/regexpp" "^4.12.2" + "@typescript-eslint/scope-manager" "8.66.0" + "@typescript-eslint/type-utils" "8.66.0" + "@typescript-eslint/utils" "8.66.0" + "@typescript-eslint/visitor-keys" "8.66.0" + ignore "^7.0.5" + natural-compare "^1.4.0" + ts-api-utils "^2.5.0" + +"@typescript-eslint/parser@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/parser/-/parser-8.66.0.tgz#88e3865ecf73b0118134e7cb831da87a961a57a1" + integrity sha512-X6ypGChaWYk6PBtUg2BwuTZEFFcHJAtGTVJ9/lCTOufhZ4i9fNolQNnktq+kkMCwMj7V8Svsq7+TxSDslmhE0g== + dependencies: + "@typescript-eslint/scope-manager" "8.66.0" + "@typescript-eslint/types" "8.66.0" + "@typescript-eslint/typescript-estree" "8.66.0" + "@typescript-eslint/visitor-keys" "8.66.0" + debug "^4.4.3" + +"@typescript-eslint/project-service@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/project-service/-/project-service-8.66.0.tgz#828f788895df52d9eb2b543445a3a5a13e35ab4e" + integrity sha512-7MthGPTt4BP69lSryqpqq8HQqxuzynssckL/jyDyk3+TNMQ3y2jFWkptCrktWvBrP+EH787Nl5N5Qpw7WZg+5g== + dependencies: + "@typescript-eslint/tsconfig-utils" "^8.66.0" + "@typescript-eslint/types" "^8.66.0" + debug "^4.4.3" + +"@typescript-eslint/scope-manager@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/scope-manager/-/scope-manager-8.66.0.tgz#4fffcc6ebd0df9fe7983c0256967567ea6f5ac63" + integrity sha512-8TGcH25j9zqJ/IULB/ppyhRvxA8QYfFEZ7nfbg6/BN9spDgb8fPWQXlE5l8TWBL50EtUx007uZ1o9VOwrq2/9g== + dependencies: + "@typescript-eslint/types" "8.66.0" + "@typescript-eslint/visitor-keys" "8.66.0" + +"@typescript-eslint/tsconfig-utils@8.66.0", "@typescript-eslint/tsconfig-utils@^8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/tsconfig-utils/-/tsconfig-utils-8.66.0.tgz#3a89066c507aa30541dc176804685b4b444e1e52" + integrity sha512-9D5gLYZG4rOjcoag8MQ/fWI8WqA9wcPDyOGyWtWFhvM1lHRbliqUSPIY5J3zqCU1tvSwzXxnnjhQhz5Ne7mJ4g== + +"@typescript-eslint/type-utils@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/type-utils/-/type-utils-8.66.0.tgz#b2315303eca72fad9afa7be4f58f053c8f2a0479" + integrity sha512-LG2dWfjZQQp0ADtAu/EWJVayefGL2UEZ3CDeI44D9v3rXB/WYUqE/jpO28KrEKul5AySrmI+Zh1v6v+xW2U9+g== + dependencies: + "@typescript-eslint/types" "8.66.0" + "@typescript-eslint/typescript-estree" "8.66.0" + "@typescript-eslint/utils" "8.66.0" + debug "^4.4.3" + ts-api-utils "^2.5.0" + +"@typescript-eslint/types@8.66.0", "@typescript-eslint/types@^8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/types/-/types-8.66.0.tgz#3cacab94d3b564c1d48c56eb37b89f89a6d48479" + integrity sha512-H6gcYaSDOyvL3AD/jHUtUFo2jqGgn/F6nuyuZSu0QTesxL+cP4dQoIMrODRofuJC09g64+WgZ6tE19Y1N2YIFQ== + +"@typescript-eslint/typescript-estree@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/typescript-estree/-/typescript-estree-8.66.0.tgz#1a38c3a97dc6c669b66d585d7f90ebc4fbb32a50" + integrity sha512-8/x4INiiQb10jGgXYD7116/zQ+OL84ZIFn0za68wwFHCanT/VLbBEroWht8RV8fn0/ZCAoazHLQgwUC0UQcDfg== + dependencies: + "@typescript-eslint/project-service" "8.66.0" + "@typescript-eslint/tsconfig-utils" "8.66.0" + "@typescript-eslint/types" "8.66.0" + "@typescript-eslint/visitor-keys" "8.66.0" + debug "^4.4.3" + minimatch "^10.2.2" + semver "^7.7.3" + tinyglobby "^0.2.15" + ts-api-utils "^2.5.0" + +"@typescript-eslint/utils@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/utils/-/utils-8.66.0.tgz#e277d67427043cdca2580ee91aa62921e4689969" + integrity sha512-jasearZPolBw5NJNYGMwxzHMF83niVWmMU1VdHzG1CyfI2VS7f7nZltnKtHcg20hW+7Uo5GfK4MeDPoU3qI8EA== + dependencies: + "@eslint-community/eslint-utils" "^4.9.1" + "@typescript-eslint/scope-manager" "8.66.0" + "@typescript-eslint/types" "8.66.0" + "@typescript-eslint/typescript-estree" "8.66.0" + +"@typescript-eslint/visitor-keys@8.66.0": + version "8.66.0" + resolved "https://registry.yarnpkg.com/@typescript-eslint/visitor-keys/-/visitor-keys-8.66.0.tgz#4c494e94745fb2724a4f37a310091e56b644d18a" + integrity sha512-dkKR8q+lKciskj1Y3vthHktl+3cMLWGyVUP23bRiPZ5O9BRT++4EqDDV+TVeIKBL1VXVEqrJlz8MYbcnvJcAlg== + dependencies: + "@typescript-eslint/types" "8.66.0" + eslint-visitor-keys "^5.0.0" + +abbrev@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/abbrev/-/abbrev-3.0.1.tgz#8ac8b3b5024d31464fe2a5feeea9f4536bf44025" + integrity sha512-AO2ac6pjRB3SJmGJo+v5/aK6Omggp6fsLrs6wN9bd35ulu4cCwaAU9+7ZhXjeqHVkaHThLuzH0nZr0YpCDhygg== + +abort-controller@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/abort-controller/-/abort-controller-3.0.0.tgz#eaf54d53b62bae4138e809ca225c8439a6efb392" + integrity sha512-h8lQ8tacZYnR3vNQTgibj+tODHI5/+l06Au2Pcriv/Gmet0eaj4TwWH41sO9wnHDiQsEj19q0drzdWdeAHtweg== + dependencies: + event-target-shim "^5.0.0" + +accepts@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/accepts/-/accepts-2.0.0.tgz#bbcf4ba5075467f3f2131eab3cffc73c2f5d7895" + integrity sha512-5cvg6CtKwfgdmVqY1WIiXKc3Q1bkRqGLi+2W/6ao+6Y7gu/RCwRuAhGEzh5B4KlszSuTLgZYuqFqo5bImjNKng== + dependencies: + mime-types "^3.0.0" + negotiator "^1.0.0" + +acorn-jsx@^5.3.2: + version "5.3.2" + resolved "https://registry.yarnpkg.com/acorn-jsx/-/acorn-jsx-5.3.2.tgz#7ed5bb55908b3b2f1bc55c6af1653bada7f07937" + integrity sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ== + +acorn@^8.15.0: + version "8.18.0" + resolved "https://registry.yarnpkg.com/acorn/-/acorn-8.18.0.tgz#4faf01b2d6d326bfeed97aea1f52220b5f4c1940" + integrity sha512-lGq+9yr1/GuAWaVYIHRjvvySG5/4VfKIvC8EWxStPdcDh/Ka7FG3twP6v4d5BkravUilhIAsG4Qj83t02LWUPQ== + +agent-base@^7.1.0, agent-base@^7.1.2: + version "7.1.4" + resolved "https://registry.yarnpkg.com/agent-base/-/agent-base-7.1.4.tgz#e3cd76d4c548ee895d3c3fd8dc1f6c5b9032e7a8" + integrity sha512-MnA+YT8fwfJPgBx3m60MNqakm30XOkyIoH1y6huTQvC0PwZG7ki8NacLBcrPbNoo8vEZy7Jpuk7+jMO+CUovTQ== + +ajv-formats-draft2019@^1.6.1: + version "1.6.1" + resolved "https://registry.yarnpkg.com/ajv-formats-draft2019/-/ajv-formats-draft2019-1.6.1.tgz#6affe2220e7828360793776f1976de0420acccfb" + integrity sha512-JQPvavpkWDvIsBp2Z33UkYCtXCSpW4HD3tAZ+oL4iEFOk9obQZffx0yANwECt6vzr6ET+7HN5czRyqXbnq/u0Q== + dependencies: + punycode "^2.1.1" + schemes "^1.4.0" + smtp-address-parser "^1.0.3" + uri-js "^4.4.1" + +ajv-formats@^3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/ajv-formats/-/ajv-formats-3.0.1.tgz#3d5dc762bca17679c3c2ea7e90ad6b7532309578" + integrity sha512-8iUql50EUR+uUcdRQ3HDqa6EVyo3docL8g5WJ3FNcWmu62IbkGUue/pEyLBW8VGKKucTPgqeks4fIU1DA4yowQ== + dependencies: + ajv "^8.0.0" + +ajv@^6.14.0: + version "6.15.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-6.15.0.tgz#07e982c74626167aa7a2495c53817892d7139492" + integrity sha512-fgFx7Hfoq60ytK2c7DhnF8jIvzYgOMxfugjLOSMHjLIPgenqa7S7oaagATUq99mV6IYvN2tRmC0wnTYX6iPbMw== + dependencies: + fast-deep-equal "^3.1.1" + fast-json-stable-stringify "^2.0.0" + json-schema-traverse "^0.4.1" + uri-js "^4.2.2" + +ajv@^8.0.0, ajv@^8.12.0: + version "8.20.0" + resolved "https://registry.yarnpkg.com/ajv/-/ajv-8.20.0.tgz#304b3636add88ba7d936760dd50ece006dea95f9" + integrity sha512-Thbli+OlOj+iMPYFBVBfJ3OmCAnaSyNn4M1vz9T6Gka5Jt9ba/HIR56joy65tY6kx/FCF5VXNB819Y7/GUrBGA== + dependencies: + fast-deep-equal "^3.1.3" + fast-uri "^3.0.1" + json-schema-traverse "^1.0.0" + require-from-string "^2.0.2" + +anser@^1.4.9: + version "1.4.10" + resolved "https://registry.yarnpkg.com/anser/-/anser-1.4.10.tgz#befa3eddf282684bd03b63dcda3927aef8c2e35b" + integrity sha512-hCv9AqTQ8ycjpSd3upOJd7vFwW1JaoYQ7tpham03GJ1ca8/65rqn0RpaWpItOAd6ylW9wAw6luXYPJIyPFVOww== + +ansi-escapes@^4.2.1: + version "4.3.2" + resolved "https://registry.yarnpkg.com/ansi-escapes/-/ansi-escapes-4.3.2.tgz#6b2291d1db7d98b6521d5f1efa42d0f3a9feb65e" + integrity sha512-gKXj5ALrKWQLsYG9jlTRmR/xKluxHV+Z9QEwNIgCfM1/uwPMCuzVVnh5mwTd+OuBZcwSIMbqssNWRm1lE51QaQ== + dependencies: + type-fest "^0.21.3" + +ansi-regex@^5.0.0, ansi-regex@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-5.0.1.tgz#082cb2c89c9fe8659a311a53bd6a4dc5301db304" + integrity sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ== + +ansi-regex@^6.2.2: + version "6.3.0" + resolved "https://registry.yarnpkg.com/ansi-regex/-/ansi-regex-6.3.0.tgz#247c8e7b70a1a43b10ce14c0226fcbf58e8815d5" + integrity sha512-WpDfL7NO6j7tH88IDBNVdUJxDh9nmCteAVW9dsep846XdwF4naCBK+/tGLX3KJgcpgMRXCFlTM2hKGoK9FsdrQ== + +ansi-styles@^4.0.0, ansi-styles@^4.1.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-4.3.0.tgz#edd803628ae71c04c85ae7a0906edad34b648937" + integrity sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg== + dependencies: + color-convert "^2.0.1" + +ansi-styles@^5.0.0, ansi-styles@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-5.2.0.tgz#07449690ad45777d1924ac2abb2fc8895dba836b" + integrity sha512-Cxwpt2SfTzTtXcfOlzGEee8O+c+MmUgGrNiBcXnuWxuFJHe6a5Hz7qwhwe5OgaSYI0IJvkLqWX1ASG+cJOkEiA== + +ansi-styles@^6.1.0: + version "6.2.3" + resolved "https://registry.yarnpkg.com/ansi-styles/-/ansi-styles-6.2.3.tgz#c044d5dcc521a076413472597a1acb1f103c4041" + integrity sha512-4Dj6M28JB+oAH8kFkTLUo+a2jwOFkuqb3yucU0CANcRRUbxS0cP0nZYCGjcc3BNXwRIsUVmDGgzawme7zvJHvg== + +anymatch@^3.0.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/anymatch/-/anymatch-3.1.3.tgz#790c58b19ba1720a84205b57c618d5ad8524973e" + integrity sha512-KMReFUr0B4t+D+OBkjR3KYqvocp2XaSzO55UcB6mgQMd3KbcE+mWTyvVV7D/zsdEbNnV6acZUutkiHQXvTr1Rw== + dependencies: + normalize-path "^3.0.0" + picomatch "^2.0.4" + +argparse@^1.0.7: + version "1.0.10" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-1.0.10.tgz#bcd6791ea5ae09725e17e5ad988134cd40b3d911" + integrity sha512-o5Roy6tNG4SL/FOkCAN6RzjiakZS25RLYFrcMttJqbdd8BWrnA+fGz57iN5Pb06pvBGvl5gQ0B48dJlslXvoTg== + dependencies: + sprintf-js "~1.0.2" + +argparse@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/argparse/-/argparse-2.0.1.tgz#246f50f3ca78a3240f6c997e8a9bd1eac49e4b38" + integrity sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q== + +asap@~2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/asap/-/asap-2.0.6.tgz#e50347611d7e690943208bbdafebcbc2fb866d46" + integrity sha512-BSHWgDSAiKs50o2Re8ppvp3seVHXSRM44cdSsT9FfNEUUZLOGWVCsiWaRPWM1Znn+mqZ1OfVZ3z3DWEzSp7hRA== + +babel-jest@29.7.0, babel-jest@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/babel-jest/-/babel-jest-29.7.0.tgz#f4369919225b684c56085998ac63dbd05be020d5" + integrity sha512-BrvGY3xZSwEcCzKvKsCi2GgHqDqsYkOP4/by5xCgIwGXQxIEh+8ew3gmrE1y7XRR6LHZIj6yLYnUi/mm2KXKBg== + dependencies: + "@jest/transform" "^29.7.0" + "@types/babel__core" "^7.1.14" + babel-plugin-istanbul "^6.1.1" + babel-preset-jest "^29.6.3" + chalk "^4.0.0" + graceful-fs "^4.2.9" + slash "^3.0.0" + +babel-plugin-istanbul@^6.1.1: + version "6.1.1" + resolved "https://registry.yarnpkg.com/babel-plugin-istanbul/-/babel-plugin-istanbul-6.1.1.tgz#fa88ec59232fd9b4e36dbbc540a8ec9a9b47da73" + integrity sha512-Y1IQok9821cC9onCx5otgFfRm7Lm+I+wwxOx738M/WLPZ9Q42m4IG5W0FNX8WLL2gYMZo3JkuXIH2DOpWM+qwA== + dependencies: + "@babel/helper-plugin-utils" "^7.0.0" + "@istanbuljs/load-nyc-config" "^1.0.0" + "@istanbuljs/schema" "^0.1.2" + istanbul-lib-instrument "^5.0.4" + test-exclude "^6.0.0" + +babel-plugin-jest-hoist@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/babel-plugin-jest-hoist/-/babel-plugin-jest-hoist-29.6.3.tgz#aadbe943464182a8922c3c927c3067ff40d24626" + integrity sha512-ESAc/RJvGTFEzRwOTT4+lNDk/GNHMkKbNzsvT0qKRfDyyYTskxB5rnU2njIDYVxXCBHHEI1c0YwHob3WaYujOg== + dependencies: + "@babel/template" "^7.3.3" + "@babel/types" "^7.3.3" + "@types/babel__core" "^7.1.14" + "@types/babel__traverse" "^7.0.6" + +babel-plugin-polyfill-corejs2@^0.4.14: + version "0.4.17" + resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-corejs2/-/babel-plugin-polyfill-corejs2-0.4.17.tgz#198f970f1c99a856b466d1187e88ce30bd199d91" + integrity sha512-aTyf30K/rqAsNwN76zYrdtx8obu0E4KoUME29B1xj+B3WxgvWkp943vYQ+z8Mv3lw9xHXMHpvSPOBxzAkIa94w== + dependencies: + "@babel/compat-data" "^7.28.6" + "@babel/helper-define-polyfill-provider" "^0.6.8" + semver "^6.3.1" + +babel-plugin-polyfill-corejs3@^0.13.0: + version "0.13.0" + resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-corejs3/-/babel-plugin-polyfill-corejs3-0.13.0.tgz#bb7f6aeef7addff17f7602a08a6d19a128c30164" + integrity sha512-U+GNwMdSFgzVmfhNm8GJUX88AadB3uo9KpJqS3FaqNIPKgySuvMb+bHPsOmmuWyIcuqZj/pzt1RUIUZns4y2+A== + dependencies: + "@babel/helper-define-polyfill-provider" "^0.6.5" + core-js-compat "^3.43.0" + +babel-plugin-polyfill-regenerator@^0.6.5: + version "0.6.8" + resolved "https://registry.yarnpkg.com/babel-plugin-polyfill-regenerator/-/babel-plugin-polyfill-regenerator-0.6.8.tgz#8a6bfd5dd54239362b3d06ce47ac52b2d95d7721" + integrity sha512-M762rNHfSF1EV3SLtnCJXFoQbbIIz0OyRwnCmV0KPC7qosSfCO0QLTSuJX3ayAebubhE6oYBAYPrBA5ljowaZg== + dependencies: + "@babel/helper-define-polyfill-provider" "^0.6.8" + +babel-plugin-syntax-hermes-parser@0.33.3: + version "0.33.3" + resolved "https://registry.yarnpkg.com/babel-plugin-syntax-hermes-parser/-/babel-plugin-syntax-hermes-parser-0.33.3.tgz#07602f8163cc7e63c4ec17d47467f2a3c5db70e9" + integrity sha512-/Z9xYdaJ1lC0pT9do6TqCqhOSLfZ5Ot8D5za1p+feEfWYupCOfGbhhEXN9r2ZgJtDNUNRw/Z+T2CvAGKBqtqWA== + dependencies: + hermes-parser "0.33.3" + +babel-plugin-transform-flow-enums@^0.0.2: + version "0.0.2" + resolved "https://registry.yarnpkg.com/babel-plugin-transform-flow-enums/-/babel-plugin-transform-flow-enums-0.0.2.tgz#d1d0cc9bdc799c850ca110d0ddc9f21b9ec3ef25" + integrity sha512-g4aaCrDDOsWjbm0PUUeVnkcVd6AKJsVc/MbnPhEotEpkeJQP6b8nzewohQi7+QS8UyPehOhGWn0nOwjvWpmMvQ== + dependencies: + "@babel/plugin-syntax-flow" "^7.12.1" + +babel-preset-current-node-syntax@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/babel-preset-current-node-syntax/-/babel-preset-current-node-syntax-1.2.0.tgz#20730d6cdc7dda5d89401cab10ac6a32067acde6" + integrity sha512-E/VlAEzRrsLEb2+dv8yp3bo4scof3l9nR4lrld+Iy5NyVqgVYUJnDAmunkhPMisRI32Qc4iRiz425d8vM++2fg== + dependencies: + "@babel/plugin-syntax-async-generators" "^7.8.4" + "@babel/plugin-syntax-bigint" "^7.8.3" + "@babel/plugin-syntax-class-properties" "^7.12.13" + "@babel/plugin-syntax-class-static-block" "^7.14.5" + "@babel/plugin-syntax-import-attributes" "^7.24.7" + "@babel/plugin-syntax-import-meta" "^7.10.4" + "@babel/plugin-syntax-json-strings" "^7.8.3" + "@babel/plugin-syntax-logical-assignment-operators" "^7.10.4" + "@babel/plugin-syntax-nullish-coalescing-operator" "^7.8.3" + "@babel/plugin-syntax-numeric-separator" "^7.10.4" + "@babel/plugin-syntax-object-rest-spread" "^7.8.3" + "@babel/plugin-syntax-optional-catch-binding" "^7.8.3" + "@babel/plugin-syntax-optional-chaining" "^7.8.3" + "@babel/plugin-syntax-private-property-in-object" "^7.14.5" + "@babel/plugin-syntax-top-level-await" "^7.14.5" + +babel-preset-jest@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/babel-preset-jest/-/babel-preset-jest-29.6.3.tgz#fa05fa510e7d493896d7b0dd2033601c840f171c" + integrity sha512-0B3bhxR6snWXJZtR/RliHTDPRgn1sNHOR0yVtq/IiQFyuOVjFS+wuio/R4gSNkyYmKmJB4wGZv2NZanmKmTnNA== + dependencies: + babel-plugin-jest-hoist "^29.6.3" + babel-preset-current-node-syntax "^1.0.0" + +balanced-match@^1.0.0: + version "1.0.2" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-1.0.2.tgz#e83e3a7e3f300b34cb9d87f615fa0cbf357690ee" + integrity sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw== + +balanced-match@^4.0.2: + version "4.0.4" + resolved "https://registry.yarnpkg.com/balanced-match/-/balanced-match-4.0.4.tgz#bfb10662feed8196a2c62e7c68e17720c274179a" + integrity sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA== + +base64-js@^1.3.1, base64-js@^1.5.1: + version "1.5.1" + resolved "https://registry.yarnpkg.com/base64-js/-/base64-js-1.5.1.tgz#1b1b440160a5bf7ad40b650f095963481903930a" + integrity sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA== + +baseline-browser-mapping@^2.11.12: + version "2.11.13" + resolved "https://registry.yarnpkg.com/baseline-browser-mapping/-/baseline-browser-mapping-2.11.13.tgz#660073103c1bee93e54df55f117b7528adf6af19" + integrity sha512-k9HNuUVMlqVjQ9UHzfPjIqiDbWw7WqT1AoT7GL8VwvF3r0ZfArtgiSPAlmupyNquNgOJHTuH4CKYf8ttMTWBTQ== + +bindings@~1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/bindings/-/bindings-1.5.0.tgz#10353c9e945334bc0511a6d90b38fbc7c9c504df" + integrity sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ== + dependencies: + file-uri-to-path "1.0.0" + +bl@^4.0.3: + version "4.1.0" + resolved "https://registry.yarnpkg.com/bl/-/bl-4.1.0.tgz#451535264182bec2fbbc83a62ab98cf11d9f7b3a" + integrity sha512-1W07cM9gS6DcLperZfFSj+bWLtaPGSOHWhPiGzXmvVJbRLdG82sH/Kn8EtW1VqWVA54AKf2h5k5BbnIbwF3h6w== + dependencies: + buffer "^5.5.0" + inherits "^2.0.4" + readable-stream "^3.4.0" + +brace-expansion@1.1.21, brace-expansion@^1.1.7: + version "1.1.21" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-1.1.21.tgz#edf4fab5c64d051aea5a8def49aba1c7522279f3" + integrity sha512-9zeA+KLZNNzglF2TPKRQEDyx6Yby7daAkuy8MiPzpXPsYDWi/DRM8jmwUDxokQjYqBpv5DgPiwD4h4ZZSy1Ujw== + dependencies: + balanced-match "^1.0.0" + concat-map "0.0.1" + +brace-expansion@2.1.7, brace-expansion@^2.0.2: + version "2.1.7" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-2.1.7.tgz#14ea3836731823bb24740225ea43b941b436f9d1" + integrity sha512-uZbew1NqdmPDTMJ8ah1y+b+9QEJrfkXFk3RcTQw3X0jW/xRUvFKsg1CfQdSYGdTbXZWExtU3J3ccxtnfw1Fi0g== + dependencies: + balanced-match "^1.0.0" + +brace-expansion@5.0.12, brace-expansion@^5.0.8: + version "5.0.12" + resolved "https://registry.yarnpkg.com/brace-expansion/-/brace-expansion-5.0.12.tgz#995fbb4750a77c4d16a7dc942ff2ca6ef8e675ec" + integrity sha512-YovQ3rzhaLMIrDjNDMkNS01tea93qhEhG5xy8f6+R0l+dw3Ki+5sCoIoI942iuLZTHWogWktgwVDhU09iNEimQ== + dependencies: + balanced-match "^4.0.2" + +braces@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/braces/-/braces-3.0.3.tgz#490332f40919452272d55a8480adc0c441358789" + integrity sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA== + dependencies: + fill-range "^7.1.1" + +browserslist@^4.24.0, browserslist@^4.28.7: + version "4.28.8" + resolved "https://registry.yarnpkg.com/browserslist/-/browserslist-4.28.8.tgz#a3c79ceb70028527e5da7dafc887f3200b5168c0" + integrity sha512-V2NpofLblG64mfOtSgDhOJESZEGogzDMBv/q+W6oc4LXWP/q75eOXoOaaOu1EOadB9U4Bwx/e0yzbvwKH8zalA== + dependencies: + baseline-browser-mapping "^2.11.12" + caniuse-lite "^1.0.30001809" + electron-to-chromium "^1.5.402" + node-releases "^2.0.53" + update-browserslist-db "^1.3.0" + +bs-logger@^0.2.6: + version "0.2.6" + resolved "https://registry.yarnpkg.com/bs-logger/-/bs-logger-0.2.6.tgz#eb7d365307a72cf974cc6cda76b68354ad336bd8" + integrity sha512-pd8DCoxmbgc7hyPKOvxtqNcjYoOsABPQdcCUjGp3d42VR2CX1ORhk2A87oqqu5R1kk+76nsxZupkmyd+MVtCog== + dependencies: + fast-json-stable-stringify "2.x" + +bser@2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/bser/-/bser-2.1.1.tgz#e6787da20ece9d07998533cfd9de6f5c38f4bc05" + integrity sha512-gQxTNE/GAfIIrmHLUE3oJyp5FO6HRBfhjnw4/wMmA63ZGDJnWBmgY/lyQBpnDUkGmAhbSe39tx2d/iTOAfglwQ== + dependencies: + node-int64 "^0.4.0" + +buffer-from@^1.0.0: + version "1.1.2" + resolved "https://registry.yarnpkg.com/buffer-from/-/buffer-from-1.1.2.tgz#2b146a6fd72e80b4f55d255f35ed59a3a9a41bd5" + integrity sha512-E+XQCRwSbaaiChtv6k6Dwgc+bx+Bs6vuKJHHl5kox/BaKbhiXzqQOwK4cO22yElGp2OCmjwVhT3HmxgyPGnJfQ== + +buffer@^5.5.0: + version "5.7.1" + resolved "https://registry.yarnpkg.com/buffer/-/buffer-5.7.1.tgz#ba62e7c13133053582197160851a8f648e99eed0" + integrity sha512-EHcyIPBQ4BSGlvjB16k5KgAJ27CIsHY/2JBmCRReo48y9rQ3MaUzWX3KVlBa4U7MyX02HdVj0K7C3WaB3ju7FQ== + dependencies: + base64-js "^1.3.1" + ieee754 "^1.1.13" + +cacache@^19.0.1: + version "19.0.1" + resolved "https://registry.yarnpkg.com/cacache/-/cacache-19.0.1.tgz#3370cc28a758434c85c2585008bd5bdcff17d6cd" + integrity sha512-hdsUxulXCi5STId78vRVYEtDAjq99ICAUktLTeTYsLoTE6Z8dS0c8pWNCxwdrk9YfJeobDZc2Y186hD/5ZQgFQ== + dependencies: + "@npmcli/fs" "^4.0.0" + fs-minipass "^3.0.0" + glob "^10.2.2" + lru-cache "^10.0.1" + minipass "^7.0.3" + minipass-collect "^2.0.1" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + p-map "^7.0.2" + ssri "^12.0.0" + tar "^7.4.3" + unique-filename "^4.0.0" + +callsites@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/callsites/-/callsites-3.1.0.tgz#b3630abd8943432f54b3f0519238e33cd7df2f73" + integrity sha512-P8BjAsXvZS+VIDUI11hHCQEv74YT67YUi5JJFNWIqL235sBmjX4+qx9Muvls5ivyNENctx46xQLQ3aTuE7ssaQ== + +camelcase@^5.3.1: + version "5.3.1" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-5.3.1.tgz#e3c9b31569e106811df242f715725a1f4c494320" + integrity sha512-L28STB170nwWS63UjtlEOE3dldQApaJXZkOI1uMFfzf3rRuPegHaHesyee+YxQ+W6SvRDQV6UrdOdRiR153wJg== + +camelcase@^6.2.0: + version "6.3.0" + resolved "https://registry.yarnpkg.com/camelcase/-/camelcase-6.3.0.tgz#5685b95eb209ac9c0c177467778c9c84df58ba9a" + integrity sha512-Gmy6FhYlCY7uOElZUSbxo2UCDH8owEk996gkbrpsgGtrJLM3J7jGxl9Ic7Qwwj4ivOE5AWZWRMecDdF7hqGjFA== + +caniuse-lite@^1.0.30001809: + version "1.0.30001809" + resolved "https://registry.yarnpkg.com/caniuse-lite/-/caniuse-lite-1.0.30001809.tgz#e6cf71f14ddfe008f114dd2a846923be3c03a07b" + integrity sha512-xxWVywk6a6Arlk+hymeycyn/VgqEfLDxupvhH/xiY5SJ/18kmi9o6MiO320DCUzypORHLtvh0I4i04tUhCNHNQ== + +chalk@^4.0.0, chalk@^4.1.2: + version "4.1.2" + resolved "https://registry.yarnpkg.com/chalk/-/chalk-4.1.2.tgz#aac4e2b7734a740867aeb16bf02aad556a1e7a01" + integrity sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA== + dependencies: + ansi-styles "^4.1.0" + supports-color "^7.1.0" + +char-regex@^1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/char-regex/-/char-regex-1.0.2.tgz#d744358226217f981ed58f479b1d6bcc29545dcf" + integrity sha512-kWWXztvZ5SBQV+eRgKFeh8q5sLuZY2+8WUIzlxWVTg+oGwY14qylx1KbKzHd8P6ZYkAg0xyIDU9JMHhyJMZ1jw== + +chownr@^1.1.1: + version "1.1.4" + resolved "https://registry.yarnpkg.com/chownr/-/chownr-1.1.4.tgz#6fc9d7b42d32a583596337666e7d08084da2cc6b" + integrity sha512-jJ0bqzaylmJtVnNgzTeSOs8DPavpbYgEr/b0YL8/2GO3xJEhInFmhKMUnEJQjZumK7KXGFhUy89PrsJWlakBVg== + +chownr@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/chownr/-/chownr-3.0.0.tgz#9855e64ecd240a9cc4267ce8a4aa5d24a1da15e4" + integrity sha512-+IxzY9BZOQd/XuYPRmrvEVjF/nqj5kgT4kEq7VofrDoM1MxoRjEWkrCC3EtLi59TVawxTAn+orJwFQcrqEN1+g== + +chrome-launcher@^0.15.2: + version "0.15.2" + resolved "https://registry.yarnpkg.com/chrome-launcher/-/chrome-launcher-0.15.2.tgz#4e6404e32200095fdce7f6a1e1004f9bd36fa5da" + integrity sha512-zdLEwNo3aUVzIhKhTtXfxhdvZhUghrnmkvcAq2NoDd+LeOHKf03H5jwZ8T/STsAlzyALkBVK552iaG1fGf1xVQ== + dependencies: + "@types/node" "*" + escape-string-regexp "^4.0.0" + is-wsl "^2.2.0" + lighthouse-logger "^1.0.0" + +chromium-edge-launcher@^0.3.0: + version "0.3.0" + resolved "https://registry.yarnpkg.com/chromium-edge-launcher/-/chromium-edge-launcher-0.3.0.tgz#34d5ca8142fc059ea2b4482bdcb184393a399ffe" + integrity sha512-p03azHlGjtyRvFEee3cyvtsRYdniSkwjkzmM/KmVnqT5d7QkkwpJBhis/zCLMYdQMVJ5tt140TBNqqrZPaWeFA== + dependencies: + "@types/node" "*" + escape-string-regexp "^4.0.0" + is-wsl "^2.2.0" + lighthouse-logger "^1.0.0" + mkdirp "^1.0.4" + +ci-info@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-2.0.0.tgz#67a9e964be31a51e15e5010d58e6f12834002f46" + integrity sha512-5tK7EtrZ0N+OLFMthtqOj4fI2Jeb88C4CAZPu25LDVUgXJ0A3Js4PMGqrn0JU1W0Mh1/Z8wZzYPxqUrXeBboCQ== + +ci-info@^3.2.0: + version "3.9.0" + resolved "https://registry.yarnpkg.com/ci-info/-/ci-info-3.9.0.tgz#4279a62028a7b1f262f3473fc9605f5e218c59b4" + integrity sha512-NIxF55hv4nSqQswkAeiOi1r83xy8JldOFDTWiug55KBu9Jnblncd2U6ViHmYgHf01TPZS77NJBhBMKdWj9HQMQ== + +cjs-module-lexer@^1.0.0: + version "1.4.3" + resolved "https://registry.yarnpkg.com/cjs-module-lexer/-/cjs-module-lexer-1.4.3.tgz#0f79731eb8cfe1ec72acd4066efac9d61991b00d" + integrity sha512-9z8TZaGM1pfswYeXrUpzPrkx8UnWYdhJclsiYMm6x/w5+nN+8Tf/LnAgfLGQCm59qAOxU8WwHEq2vNwF6i4j+Q== + +cliui@^8.0.1: + version "8.0.1" + resolved "https://registry.yarnpkg.com/cliui/-/cliui-8.0.1.tgz#0c04b075db02cbfe60dc8e6cf2f5486b1a3608aa" + integrity sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ== + dependencies: + string-width "^4.2.0" + strip-ansi "^6.0.1" + wrap-ansi "^7.0.0" + +co@^4.6.0: + version "4.6.0" + resolved "https://registry.yarnpkg.com/co/-/co-4.6.0.tgz#6ea6bdf3d853ae54ccb8e47bfa0bf3f9031fb184" + integrity sha512-QVb0dM5HvG+uaxitm8wONl7jltx8dqhfU33DcqtOZcLSVIKSDDLDi7+0LbAKiyI8hD9u42m2YxXSkMGWThaecQ== + +collect-v8-coverage@^1.0.0: + version "1.0.3" + resolved "https://registry.yarnpkg.com/collect-v8-coverage/-/collect-v8-coverage-1.0.3.tgz#cc1f01eb8d02298cbc9a437c74c70ab4e5210b80" + integrity sha512-1L5aqIkwPfiodaMgQunkF1zRhNqifHBmtbbbxcr6yVxxBnliw4TDOW6NxpO8DJLgJ16OT+Y4ztZqP6p/FtXnAw== + +color-convert@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/color-convert/-/color-convert-2.0.1.tgz#72d3a68d598c9bdb3af2ad1e84f21d896abd4de3" + integrity sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ== + dependencies: + color-name "~1.1.4" + +color-name@~1.1.4: + version "1.1.4" + resolved "https://registry.yarnpkg.com/color-name/-/color-name-1.1.4.tgz#c2a09a87acbde69543de6f63fa3995c826c536a2" + integrity sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA== + +commander@^12.0.0: + version "12.1.0" + resolved "https://registry.yarnpkg.com/commander/-/commander-12.1.0.tgz#01423b36f501259fdaac4d0e4d60c96c991585d3" + integrity sha512-Vw8qHK3bZM9y/P10u3Vib8o/DdkvA2OtPtZvD871QKjy74Wj1WSKFILMPRPSdUSx5RFK1arlJzEtA4PkFgnbuA== + +commander@^14.0.0: + version "14.0.3" + resolved "https://registry.yarnpkg.com/commander/-/commander-14.0.3.tgz#425d79b48f9af82fcd9e4fc1ea8af6c5ec07bbc2" + integrity sha512-H+y0Jo/T1RZ9qPP4Eh1pkcQcLRglraJaSLoyOtHxu6AapkjWVCy2Sit1QQ4x3Dng8qDlSsZEet7g5Pq06MvTgw== + +commander@^2.19.0, commander@^2.20.0: + version "2.20.3" + resolved "https://registry.yarnpkg.com/commander/-/commander-2.20.3.tgz#fd485e84c03eb4881c20722ba48035e8531aeb33" + integrity sha512-GpVkmM8vF2vQUkj2LvZmD35JxeJOLCwJ9cUkugyk2nuhbv3+mJvpLYYt+0+USMxE+oj+ey/lJEnhZw75x/OMcQ== + +concat-map@0.0.1: + version "0.0.1" + resolved "https://registry.yarnpkg.com/concat-map/-/concat-map-0.0.1.tgz#d8a96bd77fd68df7793a73036a3ba0d5405d477b" + integrity sha512-/Srv4dswyQNBfohGpz9o6Yb3Gz3SrUDqBH5rTuhGR7ahtlbYKnVxw2bCFMRljaA7EXHaXZ8wsHdodFvbkhKmqg== + +connect@^3.6.5: + version "3.7.0" + resolved "https://registry.yarnpkg.com/connect/-/connect-3.7.0.tgz#5d49348910caa5e07a01800b030d0c35f20484f8" + integrity sha512-ZqRXc+tZukToSNmh5C2iWMSoV3X1YUcPbqEM4DkEG5tNQXrQUZCNVGGv3IuicnkMtPfGf3Xtp8WCXs295iQ1pQ== + dependencies: + debug "2.6.9" + finalhandler "1.1.2" + parseurl "~1.3.3" + utils-merge "1.0.1" + +content-type@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/content-type/-/content-type-2.1.0.tgz#d9389c43c0a8cf6a355db464d21e07092a40493a" + integrity sha512-mj7UPXE0jaqaOsukNZRUEfEi2AcL7C/vwmwcHV0O97eO1E1pxBZuyjlZrx5seTaNBg1U6+o35wpa35Qfcc+7ag== + +convert-source-map@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/convert-source-map/-/convert-source-map-2.0.0.tgz#4b560f649fc4e918dd0ab75cf4961e8bc882d82a" + integrity sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg== + +core-js-compat@^3.43.0: + version "3.50.0" + resolved "https://registry.yarnpkg.com/core-js-compat/-/core-js-compat-3.50.0.tgz#d5922c2a692ab1cba6078c920e7c5567421ae08e" + integrity sha512-XGpFGbMLHwSt74YLTKho7Ib242qi6O8MSX+sRokV4oz7iKXvQWGYZthjIhjRGMxjzVkAubBO512dKGYcefmX3Q== + dependencies: + browserslist "^4.28.7" + +create-jest@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/create-jest/-/create-jest-29.7.0.tgz#a355c5b3cb1e1af02ba177fe7afd7feee49a5320" + integrity sha512-Adz2bdH0Vq3F53KEMJOoftQFutWCukm6J24wbPWRO4k1kMY7gS7ds/uoJkNuV8wDCtWWnuwGcJwpWcih+zEW1Q== + dependencies: + "@jest/types" "^29.6.3" + chalk "^4.0.0" + exit "^0.1.2" + graceful-fs "^4.2.9" + jest-config "^29.7.0" + jest-util "^29.7.0" + prompts "^2.0.1" + +cross-spawn@^7.0.3, cross-spawn@^7.0.6: + version "7.0.6" + resolved "https://registry.yarnpkg.com/cross-spawn/-/cross-spawn-7.0.6.tgz#8a58fe78f00dcd70c370451759dfbfaf03e8ee9f" + integrity sha512-uV2QOWP2nWzsy2aMp8aRibhi9dlzF5Hgh5SHaB9OiTGEyDTiJJyx0uy51QXdyWbtAHNua4XJzUKca3OzKUd3vA== + dependencies: + path-key "^3.1.0" + shebang-command "^2.0.0" + which "^2.0.1" + +csstype@^3.0.2: + version "3.2.3" + resolved "https://registry.yarnpkg.com/csstype/-/csstype-3.2.3.tgz#ec48c0f3e993e50648c86da559e2610995cf989a" + integrity sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ== + +debug@2.6.9, debug@^2.6.9: + version "2.6.9" + resolved "https://registry.yarnpkg.com/debug/-/debug-2.6.9.tgz#5d128515df134ff327e90a4c93f4e077a536341f" + integrity sha512-bC7ElrdJaJnPbAP+1EotYvqZsb3ecl5wi6Bfi6BJTUcNowp6cvspg0jXznRTKDjm/E7AdgFBVeAPVMNcKGsHMA== + dependencies: + ms "2.0.0" + +debug@4, debug@^4.1.0, debug@^4.1.1, debug@^4.3.1, debug@^4.3.2, debug@^4.3.4, debug@^4.4.0, debug@^4.4.3: + version "4.4.3" + resolved "https://registry.yarnpkg.com/debug/-/debug-4.4.3.tgz#c6ae432d9bd9662582fce08709b038c58e9e3d6a" + integrity sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA== + dependencies: + ms "^2.1.3" + +decompress-response@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/decompress-response/-/decompress-response-6.0.0.tgz#ca387612ddb7e104bd16d85aab00d5ecf09c66fc" + integrity sha512-aW35yZM6Bb/4oJlZncMH2LCoZtJXTRxES17vE3hoRiowU2kWHaJKFkSBDnDR+cm9J+9QhXmREyIfv0pji9ejCQ== + dependencies: + mimic-response "^3.1.0" + +dedent@^1.0.0: + version "1.7.2" + resolved "https://registry.yarnpkg.com/dedent/-/dedent-1.7.2.tgz#34e2264ab538301e27cf7b07bf2369c19baa8dd9" + integrity sha512-WzMx3mW98SN+zn3hgemf4OzdmyNhhhKz5Ay0pUfQiMQ3e1g+xmTJWp/pKdwKVXhdSkAEGIIzqeuWrL3mV/AXbA== + +deep-extend@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/deep-extend/-/deep-extend-0.6.0.tgz#c4fa7c95404a17a9c3e8ca7e1537312b736330ac" + integrity sha512-LOHxIOaPYdHlJRtCQfDIVZtfw/ufM8+rVj649RIHzcm/vGwQRXFt6OPqIFWsm2XEMrNIEtWR64sY1LEKD2vAOA== + +deep-is@^0.1.3: + version "0.1.4" + resolved "https://registry.yarnpkg.com/deep-is/-/deep-is-0.1.4.tgz#a6f2dce612fadd2ef1f519b73551f17e85199831" + integrity sha512-oIPzksmTg4/MriiaYGO+okXDT7ztn/w3Eptv/+gSIdMdKsJo0u4CfYNFJPy+4SKMuCqGw2wxnA+URMg3t8a/bQ== + +deepmerge@^4.2.2: + version "4.3.1" + resolved "https://registry.yarnpkg.com/deepmerge/-/deepmerge-4.3.1.tgz#44b5f2147cd3b00d4b56137685966f26fd25dd4a" + integrity sha512-3sUqbMEc77XqpdNO7FRyRog+eW3ph+GYCbj+rK+uYyRMuwsVy0rMiVtPn+QJlKFvWP/1PYpapqYn0Me2knFn+A== + +depd@2.0.0, depd@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/depd/-/depd-2.0.0.tgz#b696163cc757560d09cf22cc8fad1571b79e76df" + integrity sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw== + +destroy@1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/destroy/-/destroy-1.2.0.tgz#4803735509ad8be552934c67df614f94e66fa015" + integrity sha512-2sJGJTaXIIaR1w4iJSNoN0hnMY7Gpc/n8D4qSCJw8QqFWXf7cuAgnEHxBpweaVcPevC2l3KpjYCx3NypQQgaJg== + +detect-libc@^2.0.0: + version "2.1.2" + resolved "https://registry.yarnpkg.com/detect-libc/-/detect-libc-2.1.2.tgz#689c5dcdc1900ef5583a4cb9f6d7b473742074ad" + integrity sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ== + +detect-newline@^3.0.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/detect-newline/-/detect-newline-3.1.0.tgz#576f5dfc63ae1a192ff192d8ad3af6308991b651" + integrity sha512-TLz+x/vEXm/Y7P7wn1EJFNLxYpUD4TgMosxY6fAVJUnJMbupHBOncxyWUG9OpTaH9EBD7uFI5LfEgmMOc54DsA== + +diff-sequences@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/diff-sequences/-/diff-sequences-29.6.3.tgz#4deaf894d11407c51efc8418012f9e70b84ea921" + integrity sha512-EjePK1srD3P08o2j4f0ExnylqRs5B9tJjcp9t1krH2qRi8CCdsYfwe9JgSLurFBWwq4uOlipzfk5fHNvwFKr8Q== + +discontinuous-range@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/discontinuous-range/-/discontinuous-range-1.0.0.tgz#e38331f0844bba49b9a9cb71c771585aab1bc65a" + integrity sha512-c68LpLbO+7kP/b1Hr1qs8/BJ09F5khZGTxqxZuhzxpmwJKOgRFHJWIb9/KmqnqHhLdO55aOxFH/EGBvUQbL/RQ== + +eastasianwidth@^0.2.0: + version "0.2.0" + resolved "https://registry.yarnpkg.com/eastasianwidth/-/eastasianwidth-0.2.0.tgz#696ce2ec0aa0e6ea93a397ffcf24aa7840c827cb" + integrity sha512-I88TYZWc9XiYHRQ4/3c5rjjfgkjhLyW2luGIheGERbNQ6OY7yTybanSpDXZa8y7VUP9YmDcYa+eyq4ca7iLqWA== + +ee-first@1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/ee-first/-/ee-first-1.1.1.tgz#590c61156b0ae2f4f0255732a158b266bc56b21d" + integrity sha512-WMwm9LhRUo+WUaRN+vRuETqG89IgZphVSNkdFgeb6sS/E4OrDIN7t48CAewSHXc6C8lefD8KKfr5vY61brQlow== + +electron-to-chromium@^1.5.402: + version "1.5.403" + resolved "https://registry.yarnpkg.com/electron-to-chromium/-/electron-to-chromium-1.5.403.tgz#8a6e422bc68c5d2fa4d8c5fa2ba9a583c3d4452c" + integrity sha512-MQsYmdaLzvaCX5j+ZZBr5Fm6uCCnPQcRtlvmvRlWqrXy+BH2O4ffXIAScF+JQznQWB9brWp4lSD9Z4yNmaf2BA== + +emittery@^0.13.1: + version "0.13.1" + resolved "https://registry.yarnpkg.com/emittery/-/emittery-0.13.1.tgz#c04b8c3457490e0847ae51fced3af52d338e3dad" + integrity sha512-DeWwawk6r5yR9jFgnDKYt4sLS0LmHJJi3ZOnb5/JdbYwj3nW+FxQnHIjhBKz8YLC7oRNPVM9NQ47I3CVx34eqQ== + +emoji-regex@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-8.0.0.tgz#e818fd69ce5ccfcb404594f842963bf53164cc37" + integrity sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A== + +emoji-regex@^9.2.2: + version "9.2.2" + resolved "https://registry.yarnpkg.com/emoji-regex/-/emoji-regex-9.2.2.tgz#840c8803b0d8047f4ff0cf963176b32d4ef3ed72" + integrity sha512-L18DaJsXSUk2+42pv8mLs5jJT2hqFkFE4j21wOmgbUqsZ2hL72NsUU785g9RXgo3s0ZNgVl42TiHp3ZtOv/Vyg== + +encodeurl@~1.0.2: + version "1.0.2" + resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-1.0.2.tgz#ad3ff4c86ec2d029322f5a02c3a9a606c95b3f59" + integrity sha512-TPJXq8JqFaVYm2CWmPvnP2Iyo4ZSM7/QKcSmuMLDObfpH5fi7RUGmd/rTDf+rut/saiDiQEeVTNgAmJEdAOx0w== + +encodeurl@~2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/encodeurl/-/encodeurl-2.0.0.tgz#7b8ea898077d7e409d3ac45474ea38eaf0857a58" + integrity sha512-Q0n9HRi4m6JuGIV1eFlmvJB7ZEVxu93IrMyiMsGC0lrMJMWzRgx6WGquyfQgZVb31vhGgXnfmPNNXmxnOkRBrg== + +encoding@^0.1.13: + version "0.1.13" + resolved "https://registry.yarnpkg.com/encoding/-/encoding-0.1.13.tgz#56574afdd791f54a8e9b2785c0582a2d26210fa9" + integrity sha512-ETBauow1T35Y/WZMkio9jiM0Z5xjHHmJ4XmjZOq1l/dXz3lr2sRn87nJy20RupqSh1F2m3HHPSp8ShIPQJrJ3A== + dependencies: + iconv-lite "^0.6.2" + +end-of-stream@^1.1.0, end-of-stream@^1.4.1: + version "1.4.5" + resolved "https://registry.yarnpkg.com/end-of-stream/-/end-of-stream-1.4.5.tgz#7344d711dea40e0b74abc2ed49778743ccedb08c" + integrity sha512-ooEGc6HP26xXq/N+GCGOT0JKCLDGrq2bQUZrQ7gyrJiZANJ/8YDTxTpQBXGMn+WbIQXNVpyWymm7KYVICQnyOg== + dependencies: + once "^1.4.0" + +env-paths@^2.2.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/env-paths/-/env-paths-2.2.1.tgz#420399d416ce1fbe9bc0a07c62fa68d67fd0f8f2" + integrity sha512-+h1lkLKhZMTYjog1VEpJNG7NZJWcuc2DDk/qsqSTRRCOXiLjeQ1d1/udrUGhqMxUgAlwKNZ0cf2uqan5GLuS2A== + +err-code@^2.0.2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/err-code/-/err-code-2.0.3.tgz#23c2f3b756ffdfc608d30e27c9a941024807e7f9" + integrity sha512-2bmlRpNKBxT/CRmPOlyISQpNj+qSeYvcym/uT0Jx2bMOlKLtSy1ZmLuVxSEKKyor/N5yhvp/ZiG1oE3DEYMSFA== + +error-ex@^1.3.1: + version "1.3.4" + resolved "https://registry.yarnpkg.com/error-ex/-/error-ex-1.3.4.tgz#b3a8d8bb6f92eecc1629e3e27d3c8607a8a32414" + integrity sha512-sqQamAnR14VgCr1A618A3sGrygcpK+HEbenA/HiEAkkUwcZIIB/tgWqHFxWgOyDh4nB4JCRimh79dR5Ywc9MDQ== + dependencies: + is-arrayish "^0.2.1" + +error-stack-parser@^2.0.6: + version "2.1.4" + resolved "https://registry.yarnpkg.com/error-stack-parser/-/error-stack-parser-2.1.4.tgz#229cb01cdbfa84440bfa91876285b94680188286" + integrity sha512-Sk5V6wVazPhq5MhpO+AUxJn5x7XSXGl1R93Vn7i+zS15KDVxQijejNCrz8340/2bgLBjR9GtEG8ZVKONDjcqGQ== + dependencies: + stackframe "^1.3.4" + +es-errors@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/es-errors/-/es-errors-1.3.0.tgz#05f75a25dab98e4fb1dcd5e1472c0546d5057c8f" + integrity sha512-Zf5H2Kxt2xjTvbJvP2ZWLEICxA6j+hAmMzIlypy4xcBg1vKVnx89Wy0GbS+kf5cwCVFFzdCFh2XSCFNULS6csw== + +escalade@^3.1.1, escalade@^3.2.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/escalade/-/escalade-3.2.0.tgz#011a3f69856ba189dffa7dc8fcce99d2a87903e5" + integrity sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA== + +escape-html@~1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/escape-html/-/escape-html-1.0.3.tgz#0258eae4d3d0c0974de1c169188ef0051d1d1988" + integrity sha512-NiSupZ4OeuGwr68lGIeym/ksIZMJodUGOSCZ/FSnTxcrekbvqrgdUxlJOMpijaKZVjAJrWrGs/6Jy8OMuyj9ow== + +escape-string-regexp@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-2.0.0.tgz#a30304e99daa32e23b2fd20f51babd07cffca344" + integrity sha512-UpzcLCXolUWcNu5HtVMHYdXJjArjsF9C0aNnquZYY4uW/Vu0miy5YoWvbV345HauVvcAUnpRuhMMcqTcGOY2+w== + +escape-string-regexp@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/escape-string-regexp/-/escape-string-regexp-4.0.0.tgz#14ba83a5d373e3d311e5afca29cf5bfad965bf34" + integrity sha512-TtpcNJ3XAzx3Gq8sWRzJaVajRs0uVxA2YAkdb1jm2YkPz4G6egUFAyA3n5vtEIZefPk5Wa4UXbKuS5fKkJWdgA== + +eslint-config-prettier@^10.1.8: + version "10.1.8" + resolved "https://registry.yarnpkg.com/eslint-config-prettier/-/eslint-config-prettier-10.1.8.tgz#15734ce4af8c2778cc32f0b01b37b0b5cd1ecb97" + integrity sha512-82GZUjRS0p/jganf6q1rEO25VSoHH0hKPCTrgillPjdI/3bgBhAE1QzHrHTizjpRvy6pGAvKjDJtk2pF9NDq8w== + +eslint-plugin-react-hooks@^7.1.1: + version "7.1.1" + resolved "https://registry.yarnpkg.com/eslint-plugin-react-hooks/-/eslint-plugin-react-hooks-7.1.1.tgz#e6742cad75d970c0a3f30d7d3fa80a4784f55927" + integrity sha512-f2I7Gw6JbvCexzIInuSbZpfdQ44D7iqdWX01FKLvrPgqxoE7oMj8clOfto8U6vYiz4yd5oKu39rRSVOe1zRu0g== + dependencies: + "@babel/core" "^7.24.4" + "@babel/parser" "^7.24.4" + hermes-parser "^0.25.1" + zod "^3.25.0 || ^4.0.0" + zod-validation-error "^3.5.0 || ^4.0.0" + +eslint-scope@^8.4.0: + version "8.4.0" + resolved "https://registry.yarnpkg.com/eslint-scope/-/eslint-scope-8.4.0.tgz#88e646a207fad61436ffa39eb505147200655c82" + integrity sha512-sNXOfKCn74rt8RICKMvJS7XKV/Xk9kA7DyJr8mJik3S7Cwgy3qlkkmyS2uQB3jiJg6VNdZd/pDBJu0nvG2NlTg== + dependencies: + esrecurse "^4.3.0" + estraverse "^5.2.0" + +eslint-visitor-keys@^3.4.3: + version "3.4.3" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-3.4.3.tgz#0cd72fe8550e3c2eae156a96a4dddcd1c8ac5800" + integrity sha512-wpc+LXeiyiisxPlEkUzU6svyS1frIO3Mgxj1fdy7Pm8Ygzguax2N3Fa/D/ag1WqbOprdI+uY6wMUl8/a2G+iag== + +eslint-visitor-keys@^4.2.1: + version "4.2.1" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-4.2.1.tgz#4cfea60fe7dd0ad8e816e1ed026c1d5251b512c1" + integrity sha512-Uhdk5sfqcee/9H/rCOJikYz67o0a2Tw2hGRPOG2Y1R2dg7brRe1uG0yaNQDHu+TO/uQPF/5eCapvYSmHUjt7JQ== + +eslint-visitor-keys@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/eslint-visitor-keys/-/eslint-visitor-keys-5.0.1.tgz#9e3c9489697824d2d4ce3a8ad12628f91e9f59be" + integrity sha512-tD40eHxA35h0PEIZNeIjkHoDR4YjjJp34biM0mDvplBe//mB+IHCqHDGV7pxF+7MklTvighcCPPZC7ynWyjdTA== + +eslint@^9.39.0: + version "9.39.5" + resolved "https://registry.yarnpkg.com/eslint/-/eslint-9.39.5.tgz#2a4e3c8b0f753196efae943c8ffaa8730fc6a3fa" + integrity sha512-DgZS62aPLXKlnxILS/AYCoRvHaZeXceIzlXPkkGGzJWSow1aEk0lbTlxUSlyjC8jcaKxAdOnTDz+o1JFSBsyjw== + dependencies: + "@eslint-community/eslint-utils" "^4.8.0" + "@eslint-community/regexpp" "^4.12.1" + "@eslint/config-array" "^0.21.2" + "@eslint/config-helpers" "^0.4.2" + "@eslint/core" "^0.17.0" + "@eslint/eslintrc" "^3.3.6" + "@eslint/js" "9.39.5" + "@eslint/plugin-kit" "^0.4.1" + "@humanfs/node" "^0.16.6" + "@humanwhocodes/module-importer" "^1.0.1" + "@humanwhocodes/retry" "^0.4.2" + "@types/estree" "^1.0.6" + ajv "^6.14.0" + chalk "^4.0.0" + cross-spawn "^7.0.6" + debug "^4.3.2" + escape-string-regexp "^4.0.0" + eslint-scope "^8.4.0" + eslint-visitor-keys "^4.2.1" + espree "^10.4.0" + esquery "^1.5.0" + esutils "^2.0.2" + fast-deep-equal "^3.1.3" + file-entry-cache "^8.0.0" + find-up "^5.0.0" + glob-parent "^6.0.2" + ignore "^5.2.0" + imurmurhash "^0.1.4" + is-glob "^4.0.0" + json-stable-stringify-without-jsonify "^1.0.1" + lodash.merge "^4.6.2" + minimatch "^3.1.5" + natural-compare "^1.4.0" + optionator "^0.9.3" + +espree@^10.0.1, espree@^10.4.0: + version "10.4.0" + resolved "https://registry.yarnpkg.com/espree/-/espree-10.4.0.tgz#d54f4949d4629005a1fa168d937c3ff1f7e2a837" + integrity sha512-j6PAQ2uUr79PZhBjP5C5fhl8e39FmRnOjsD5lGnWrFU8i2G776tBK7+nP8KuQUTTyAZUwfQqXAgrVH5MbH9CYQ== + dependencies: + acorn "^8.15.0" + acorn-jsx "^5.3.2" + eslint-visitor-keys "^4.2.1" + +esprima@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/esprima/-/esprima-4.0.1.tgz#13b04cdb3e6c5d19df91ab6987a8695619b0aa71" + integrity sha512-eGuFFw7Upda+g4p+QHvnW0RyTX/SVeJBDM/gCtMARO0cLuT2HcEKnTPvhjV6aGeqrCB/sbNop0Kszm0jsaWU4A== + +esquery@^1.5.0: + version "1.7.0" + resolved "https://registry.yarnpkg.com/esquery/-/esquery-1.7.0.tgz#08d048f261f0ddedb5bae95f46809463d9c9496d" + integrity sha512-Ap6G0WQwcU/LHsvLwON1fAQX9Zp0A2Y6Y/cJBl9r/JbW90Zyg4/zbG6zzKa2OTALELarYHmKu0GhpM5EO+7T0g== + dependencies: + estraverse "^5.1.0" + +esrecurse@^4.3.0: + version "4.3.0" + resolved "https://registry.yarnpkg.com/esrecurse/-/esrecurse-4.3.0.tgz#7ad7964d679abb28bee72cec63758b1c5d2c9921" + integrity sha512-KmfKL3b6G+RXvP8N1vr3Tq1kL/oCFgn2NYXEtqP8/L3pKapUA4G8cFVaoF3SU323CD4XypR/ffioHmkti6/Tag== + dependencies: + estraverse "^5.2.0" + +estraverse@^5.1.0, estraverse@^5.2.0: + version "5.3.0" + resolved "https://registry.yarnpkg.com/estraverse/-/estraverse-5.3.0.tgz#2eea5290702f26ab8fe5370370ff86c965d21123" + integrity sha512-MMdARuVEQziNTeJD8DgMqmhwR11BRQ/cBP+pLtYdSTnf3MIO8fFeiINEbX36ZdNlfU/7A9f3gUw49B3oQsvwBA== + +esutils@^2.0.2: + version "2.0.3" + resolved "https://registry.yarnpkg.com/esutils/-/esutils-2.0.3.tgz#74d2eb4de0b8da1293711910d50775b9b710ef64" + integrity sha512-kVscqXk4OCp68SZ0dkgEKVi6/8ij300KBWTJq32P/dYeWTSwK41WyTxalN1eRmA5Z9UU/LX9D7FWSmV9SAYx6g== + +etag@~1.8.1: + version "1.8.1" + resolved "https://registry.yarnpkg.com/etag/-/etag-1.8.1.tgz#41ae2eeb65efa62268aebfea83ac7d79299b0887" + integrity sha512-aIL5Fx7mawVa300al2BnEE4iNvo1qETxLrPI/o05L7z6go7fCw1J6EQmbK4FmJ2AS7kgVF/KEZWufBfdClMcPg== + +event-target-shim@^5.0.0: + version "5.0.1" + resolved "https://registry.yarnpkg.com/event-target-shim/-/event-target-shim-5.0.1.tgz#5d4d3ebdf9583d63a5333ce2deb7480ab2b05789" + integrity sha512-i/2XbnSz/uxRCU6+NdVJgKWDTM427+MqYbkQzD321DuCQJUqOuJKIA0IM2+W2xtYHdKOmZ4dR6fExsd4SXL+WQ== + +execa@^5.0.0: + version "5.1.1" + resolved "https://registry.yarnpkg.com/execa/-/execa-5.1.1.tgz#f80ad9cbf4298f7bd1d4c9555c21e93741c411dd" + integrity sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg== + dependencies: + cross-spawn "^7.0.3" + get-stream "^6.0.0" + human-signals "^2.1.0" + is-stream "^2.0.0" + merge-stream "^2.0.0" + npm-run-path "^4.0.1" + onetime "^5.1.2" + signal-exit "^3.0.3" + strip-final-newline "^2.0.0" + +exit@^0.1.2: + version "0.1.2" + resolved "https://registry.yarnpkg.com/exit/-/exit-0.1.2.tgz#0632638f8d877cc82107d30a0fff1a17cba1cd0c" + integrity sha512-Zk/eNKV2zbjpKzrsQ+n1G6poVbErQxJ0LBOJXaKZ1EViLzH+hrLu9cdXI4zw9dBQJslwBEpbQ2P1oS7nDxs6jQ== + +expand-template@^2.0.3: + version "2.0.3" + resolved "https://registry.yarnpkg.com/expand-template/-/expand-template-2.0.3.tgz#6e14b3fcee0f3a6340ecb57d2e8918692052a47c" + integrity sha512-XYfuKMvj4O35f/pOXLObndIRvyQ+/+6AhODh+OKWj9S9498pHHn/IMszH+gt0fBCRWMNfk1ZSp5x3AifmnI2vg== + +expect@^29.0.0, expect@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/expect/-/expect-29.7.0.tgz#578874590dcb3214514084c08115d8aee61e11bc" + integrity sha512-2Zks0hf1VLFYI1kbh0I5jP3KHHyCHpkfyHBzsSXRFgl/Bg9mWYfMW8oD+PdMPlEwy5HNsR9JutYy6pMeOh61nw== + dependencies: + "@jest/expect-utils" "^29.7.0" + jest-get-type "^29.6.3" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + +expo-modules-core@~3.0.29: + version "3.0.30" + resolved "https://registry.yarnpkg.com/expo-modules-core/-/expo-modules-core-3.0.30.tgz#ec4e216a33083afb0ddf314615d6d31a741984d6" + integrity sha512-a6IrpAn/Jbmwxi9L+hMmXKpNqnkUpoF7WHOpn02rVLyax2J0gB1vvCVE5rNydplEnt41Q6WxQwvcOjZaIkcSUg== + dependencies: + invariant "^2.2.4" + +exponential-backoff@^3.1.1: + version "3.1.3" + resolved "https://registry.yarnpkg.com/exponential-backoff/-/exponential-backoff-3.1.3.tgz#51cf92c1c0493c766053f9d3abee4434c244d2f6" + integrity sha512-ZgEeZXj30q+I0EN+CbSSpIyPaJ5HVQD18Z1m+u1FXbAeT94mr1zw50q4q6jiiC447Nl/YTcIYSAftiGqetwXCA== + +extend@^3.0.0: + version "3.0.2" + resolved "https://registry.yarnpkg.com/extend/-/extend-3.0.2.tgz#f8b1136b4071fbd8eb140aff858b1019ec2915fa" + integrity sha512-fjquC59cD7CyW6urNXK0FBufkZcoiGG80wTuPujX590cB5Ttln20E2UB4S/WARVqhXffZl2LNgS+gQdPIIim/g== + +fast-deep-equal@^3.1.1, fast-deep-equal@^3.1.3: + version "3.1.3" + resolved "https://registry.yarnpkg.com/fast-deep-equal/-/fast-deep-equal-3.1.3.tgz#3a7d56b559d6cbc3eb512325244e619a65c6c525" + integrity sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q== + +fast-json-stable-stringify@2.x, fast-json-stable-stringify@^2.0.0, fast-json-stable-stringify@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/fast-json-stable-stringify/-/fast-json-stable-stringify-2.1.0.tgz#874bf69c6f404c2b5d99c481341399fd55892633" + integrity sha512-lhd/wF+Lk98HZoTCtlVraHtfh5XYijIjalXck7saUtuanSDyLMxnHhSXEDJqHxD7msR8D0uCmqlkwjCV8xvwHw== + +fast-levenshtein@^2.0.6: + version "2.0.6" + resolved "https://registry.yarnpkg.com/fast-levenshtein/-/fast-levenshtein-2.0.6.tgz#3d8a5c66883a16a30ca8643e851f19baa7797917" + integrity sha512-DCXu6Ifhqcks7TZKY3Hxp3y6qphY5SJZmrWMDrKcERSOXWQdMhU9Ig/PYrzyw/ul9jOIyh0N4M0tbC5hodg8dw== + +fast-uri@^3.0.1: + version "3.1.8" + resolved "https://registry.yarnpkg.com/fast-uri/-/fast-uri-3.1.8.tgz#f7db8d942e20eead3cfe93b0beeb4eb0169e938b" + integrity sha512-GZMtZUTNRpOVIECoXwLNZS5xUGE+mVNbTB8h/7Rwh2TFWcBQiPzTgyZi05BF9UMZKkLJv8XBRJTlU7zg8+ZfMg== + +fb-dotslash@0.5.8: + version "0.5.8" + resolved "https://registry.yarnpkg.com/fb-dotslash/-/fb-dotslash-0.5.8.tgz#c5ef3dacd75e1ddb2197c367052464ddde0115f5" + integrity sha512-XHYLKk9J4BupDxi9bSEhkfss0m+Vr9ChTrjhf9l2iw3jB5C7BnY4GVPoMcqbrTutsKJso6yj2nAB6BI/F2oZaA== + +fb-watchman@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/fb-watchman/-/fb-watchman-2.0.2.tgz#e9524ee6b5c77e9e5001af0f85f3adbb8623255c" + integrity sha512-p5161BqbuCaSnB8jIbzQHOlpgsPmK5rJVDfDKO91Axs5NC1uu3HRQm6wt9cd9/+GtQQIO53JdGXXoyDpTAsgYA== + dependencies: + bser "2.1.1" + +fdir@^6.5.0: + version "6.5.0" + resolved "https://registry.yarnpkg.com/fdir/-/fdir-6.5.0.tgz#ed2ab967a331ade62f18d077dae192684d50d350" + integrity sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg== + +file-entry-cache@^8.0.0: + version "8.0.0" + resolved "https://registry.yarnpkg.com/file-entry-cache/-/file-entry-cache-8.0.0.tgz#7787bddcf1131bffb92636c69457bbc0edd6d81f" + integrity sha512-XXTUwCvisa5oacNGRP9SfNtYBNAMi+RPwBFmblZEF7N7swHYQS6/Zfk7SRwx4D5j3CH211YNRco1DEMNVfZCnQ== + dependencies: + flat-cache "^4.0.0" + +file-uri-to-path@1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/file-uri-to-path/-/file-uri-to-path-1.0.0.tgz#553a7b8446ff6f684359c445f1e37a05dacc33dd" + integrity sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw== + +fill-range@^7.1.1: + version "7.1.1" + resolved "https://registry.yarnpkg.com/fill-range/-/fill-range-7.1.1.tgz#44265d3cac07e3ea7dc247516380643754a05292" + integrity sha512-YsGpe3WHLK8ZYi4tWDg2Jy3ebRz2rXowDxnld4bkQB00cc/1Zw9AWnC0i9ztDJitivtQvaI9KaLyKrc+hBW0yg== + dependencies: + to-regex-range "^5.0.1" + +finalhandler@1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/finalhandler/-/finalhandler-1.1.2.tgz#b7e7d000ffd11938d0fdb053506f6ebabe9f587d" + integrity sha512-aAWcW57uxVNrQZqFXjITpW3sIUQmHGG3qSb9mUah9MgMC4NeWhNOlNjXEYq3HjRAvL6arUviZGGJsBg6z0zsWA== + dependencies: + debug "2.6.9" + encodeurl "~1.0.2" + escape-html "~1.0.3" + on-finished "~2.3.0" + parseurl "~1.3.3" + statuses "~1.5.0" + unpipe "~1.0.0" + +find-up@^4.0.0, find-up@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-4.1.0.tgz#97afe7d6cdc0bc5928584b7c8d7b16e8a9aa5d19" + integrity sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw== + dependencies: + locate-path "^5.0.0" + path-exists "^4.0.0" + +find-up@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/find-up/-/find-up-5.0.0.tgz#4c92819ecb7083561e4f4a240a86be5198f536fc" + integrity sha512-78/PXT1wlLLDgTzDs7sjq9hzz0vXD+zn+7wypEe4fXQxCmdmqfGsEPQxmiCSQI3ajFV91bVSsvNtrJRiW6nGng== + dependencies: + locate-path "^6.0.0" + path-exists "^4.0.0" + +flat-cache@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/flat-cache/-/flat-cache-4.0.1.tgz#0ece39fcb14ee012f4b0410bd33dd9c1f011127c" + integrity sha512-f7ccFPK3SXFHpx15UIGyRJ/FJQctuKZ0zVuN3frBo4HnK3cay9VEW0R6yPYFHC0AgqhukPzKjq22t5DmAyqGyw== + dependencies: + flatted "^3.2.9" + keyv "^4.5.4" + +flatted@^3.2.9: + version "3.4.4" + resolved "https://registry.yarnpkg.com/flatted/-/flatted-3.4.4.tgz#aeeca2a506303f0cee61c59e6c9f2a88d2f29fc6" + integrity sha512-5+ybhBZANEJxaH3X5evAFatUxLfEHSr7n6kYJ+1Qd0mUqr4eu9gIf6GDbWHf8RJijHrjjO8G+la14SlL2SeS1Q== + +flow-enums-runtime@^0.0.6: + version "0.0.6" + resolved "https://registry.yarnpkg.com/flow-enums-runtime/-/flow-enums-runtime-0.0.6.tgz#5bb0cd1b0a3e471330f4d109039b7eba5cb3e787" + integrity sha512-3PYnM29RFXwvAN6Pc/scUfkI7RwhQ/xqyLUyPNlXUp9S40zI8nup9tUSrTLSVnWGBN38FNiGWbwZOB6uR4OGdw== + +foreground-child@^3.1.0: + version "3.3.1" + resolved "https://registry.yarnpkg.com/foreground-child/-/foreground-child-3.3.1.tgz#32e8e9ed1b68a3497befb9ac2b6adf92a638576f" + integrity sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw== + dependencies: + cross-spawn "^7.0.6" + signal-exit "^4.0.1" + +fresh@~0.5.2: + version "0.5.2" + resolved "https://registry.yarnpkg.com/fresh/-/fresh-0.5.2.tgz#3d8cadd90d976569fa835ab1f8e4b23a105605a7" + integrity sha512-zJ2mQYM18rEFOudeV4GShTGIQ7RbzA7ozbU9I/XBpm7kqgMywgmylMwXHxZJmkVoYkna9d2pVXVXPdYTP9ej8Q== + +fs-constants@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs-constants/-/fs-constants-1.0.0.tgz#6be0de9be998ce16af8afc24497b9ee9b7ccd9ad" + integrity sha512-y6OAwoSIf7FyjMIv94u+b5rdheZEjzR63GTyZJm5qh4Bi+2YgwLCcI/fPFZkL5PSixOt6ZNKm+w+Hfp/Bciwow== + +fs-minipass@^3.0.0: + version "3.0.3" + resolved "https://registry.yarnpkg.com/fs-minipass/-/fs-minipass-3.0.3.tgz#79a85981c4dc120065e96f62086bf6f9dc26cc54" + integrity sha512-XUBA9XClHbnJWSfBzjkm6RvPsyg3sryZt06BEQoXcF7EK/xpGaQYJgQKDJSUH5SGZ76Y7pFx1QBnXz09rU5Fbw== + dependencies: + minipass "^7.0.3" + +fs.realpath@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/fs.realpath/-/fs.realpath-1.0.0.tgz#1504ad2523158caa40db4a2787cb01411994ea4f" + integrity sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw== + +fsevents@^2.3.2: + version "2.3.3" + resolved "https://registry.yarnpkg.com/fsevents/-/fsevents-2.3.3.tgz#cac6407785d03675a2a5e1a5305c697b347d90d6" + integrity sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw== + +function-bind@^1.1.2: + version "1.1.2" + resolved "https://registry.yarnpkg.com/function-bind/-/function-bind-1.1.2.tgz#2c02d864d97f3ea6c8830c464cbd11ab6eab7a1c" + integrity sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA== + +gensync@^1.0.0-beta.2: + version "1.0.0-beta.2" + resolved "https://registry.yarnpkg.com/gensync/-/gensync-1.0.0-beta.2.tgz#32a6ee76c3d7f52d46b2b1ae5d93fea8580a25e0" + integrity sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg== + +get-caller-file@^2.0.5: + version "2.0.5" + resolved "https://registry.yarnpkg.com/get-caller-file/-/get-caller-file-2.0.5.tgz#4f94412a82db32f36e3b0b9741f8a97feb031f7e" + integrity sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg== + +get-package-type@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/get-package-type/-/get-package-type-0.1.0.tgz#8de2d803cff44df3bc6c456e6668b36c3926e11a" + integrity sha512-pjzuKtY64GYfWizNAJ0fr9VqttZkNiK2iS430LtIHzjBEr6bX8Am2zm4sW4Ro5wjWW5cAlRL1qAMTcXbjNAO2Q== + +get-stream@^6.0.0: + version "6.0.1" + resolved "https://registry.yarnpkg.com/get-stream/-/get-stream-6.0.1.tgz#a262d8eef67aced57c2852ad6167526a43cbf7b7" + integrity sha512-ts6Wi+2j3jQjqi70w5AlN8DFnkSwC+MqmxEzdEALB2qXZYV3X/b1CTfgPLGJNMeAWxdPfU8FO1ms3NUfaHCPYg== + +github-from-package@0.0.0: + version "0.0.0" + resolved "https://registry.yarnpkg.com/github-from-package/-/github-from-package-0.0.0.tgz#97fb5d96bfde8973313f20e8288ef9a167fa64ce" + integrity sha512-SyHy3T1v2NUXn29OsWdxmK6RwHD+vkj3v8en8AOBZ1wBQ/hCAQ5bAQTD02kW4W9tUp/3Qh6J8r9EvntiyCmOOw== + +glob-parent@^6.0.2: + version "6.0.2" + resolved "https://registry.yarnpkg.com/glob-parent/-/glob-parent-6.0.2.tgz#6d237d99083950c79290f24c7642a3de9a28f9e3" + integrity sha512-XxwI8EOhVQgWp6iDL+3b0r86f4d6AX6zSU55HfB4ydCEuXLXc5FcYeOu+nnGftS4TEju/11rt4KJPTMgbfmv4A== + dependencies: + is-glob "^4.0.3" + +glob@^10.2.2: + version "10.5.0" + resolved "https://registry.yarnpkg.com/glob/-/glob-10.5.0.tgz#8ec0355919cd3338c28428a23d4f24ecc5fe738c" + integrity sha512-DfXN8DfhJ7NH3Oe7cFmu3NCu1wKbkReJ8TorzSAFbSKrlNaQSKfIzqYqVY8zlbs2NLBbWpRiU52GX2PbaBVNkg== + dependencies: + foreground-child "^3.1.0" + jackspeak "^3.1.2" + minimatch "^9.0.4" + minipass "^7.1.2" + package-json-from-dist "^1.0.0" + path-scurry "^1.11.1" + +glob@^7.1.3, glob@^7.1.4: + version "7.2.3" + resolved "https://registry.yarnpkg.com/glob/-/glob-7.2.3.tgz#b8df0fb802bbfa8e89bd1d938b4e16578ed44f2b" + integrity sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q== + dependencies: + fs.realpath "^1.0.0" + inflight "^1.0.4" + inherits "2" + minimatch "^3.1.1" + once "^1.3.0" + path-is-absolute "^1.0.0" + +globals@^14.0.0: + version "14.0.0" + resolved "https://registry.yarnpkg.com/globals/-/globals-14.0.0.tgz#898d7413c29babcf6bafe56fcadded858ada724e" + integrity sha512-oahGvuMGQlPw/ivIYBjVSrWAfWLBeku5tpPE2fOPLi+WHffIWbuh2tCjhyQhTBPMf5E9jDEH4FOmTYgYwbKwtQ== + +graceful-fs@^4.2.4, graceful-fs@^4.2.6, graceful-fs@^4.2.9: + version "4.2.11" + resolved "https://registry.yarnpkg.com/graceful-fs/-/graceful-fs-4.2.11.tgz#4183e4e8bf08bb6e05bbb2f7d2e0c8f712ca40e3" + integrity sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ== + +handlebars@^4.7.9: + version "4.7.10" + resolved "https://registry.yarnpkg.com/handlebars/-/handlebars-4.7.10.tgz#12419ea1b41391b3ffcf003f2164dcbce090c417" + integrity sha512-P5VJMVM7qgBn6vjXMw8WG9uVI+ncf2pi72j4de4yz5ZULLj2RGqLYaKOYGsgyrViQ0tePOVlN1tDCCXXtFqXKg== + dependencies: + minimist "^1.2.8" + neo-async "^2.6.2" + source-map "^0.6.1" + wordwrap "^1.0.0" + optionalDependencies: + uglify-js "^3.1.4" + +has-flag@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/has-flag/-/has-flag-4.0.0.tgz#944771fd9c81c81265c4d6941860da06bb59479b" + integrity sha512-EykJT/Q1KjTWctppgIAgfSO0tKVuZUjhgMr17kqTumMl6Afv3EISleU7qZUzoXDFTAHTDC4NOoG/ZxU3EvlMPQ== + +hasown@^2.0.3: + version "2.0.4" + resolved "https://registry.yarnpkg.com/hasown/-/hasown-2.0.4.tgz#8c62d8cb90beb2aad5d0a5b67581ad9854c3f003" + integrity sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A== + dependencies: + function-bind "^1.1.2" + +hermes-compiler@250829098.0.10: + version "250829098.0.10" + resolved "https://registry.yarnpkg.com/hermes-compiler/-/hermes-compiler-250829098.0.10.tgz#b31cae9a2517ee361c73966f76a556a1029af52b" + integrity sha512-TcRlZ0/TlyfJqquRFAWoyElVNnkdYRi/sEp4/Qy8/GYxjg8j2cS9D4MjuaQ+qimkmLN7AmO+44IznRf06mAr0w== + +hermes-estree@0.25.1: + version "0.25.1" + resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.25.1.tgz#6aeec17d1983b4eabf69721f3aa3eb705b17f480" + integrity sha512-0wUoCcLp+5Ev5pDW2OriHC2MJCbwLwuRx+gAqMTOkGKJJiBCLjtrvy4PWUGn6MIVefecRpzoOZ/UV6iGdOr+Cw== + +hermes-estree@0.33.3: + version "0.33.3" + resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.33.3.tgz#6d6b593d4b471119772c82bdb0212dfadabb6f17" + integrity sha512-6kzYZHCk8Fy1Uc+t3HGYyJn3OL4aeqKLTyina4UFtWl8I0kSL7OmKThaiX+Uh2f8nGw3mo4Ifxg0M5Zk3/Oeqg== + +hermes-estree@0.35.0: + version "0.35.0" + resolved "https://registry.yarnpkg.com/hermes-estree/-/hermes-estree-0.35.0.tgz#767cce0b14a68b4bc06cd5db7efe889f6188c565" + integrity sha512-xVx5Opwy8Oo1I5yGpVRhCvWL/iV3M+ylksSKVNlxxD90cpDpR/AR1jLYqK8HWihm065a6UI3HeyAmYzwS8NOOg== + +hermes-parser@0.33.3: + version "0.33.3" + resolved "https://registry.yarnpkg.com/hermes-parser/-/hermes-parser-0.33.3.tgz#da50ababb7a5ab636d339e7b2f6e3848e217e09d" + integrity sha512-Yg3HgaG4CqgyowtYjX/FsnPAuZdHOqSMtnbpylbptsQ9nwwSKsy6uRWcGO5RK0EqiX12q8HvDWKgeAVajRO5DA== + dependencies: + hermes-estree "0.33.3" + +hermes-parser@0.35.0: + version "0.35.0" + resolved "https://registry.yarnpkg.com/hermes-parser/-/hermes-parser-0.35.0.tgz#7625ec2f34ab897c2a17a7bea9788d136d5fd8c9" + integrity sha512-9JLjeHxBx8T4CAsydZR49PNZUaix+WpQJwu9p2010lu+7Kwl6D/7wYFFJxoz+aXkaaClp9Zfg6W6/zVlSJORaA== + dependencies: + hermes-estree "0.35.0" + +hermes-parser@^0.25.1: + version "0.25.1" + resolved "https://registry.yarnpkg.com/hermes-parser/-/hermes-parser-0.25.1.tgz#5be0e487b2090886c62bd8a11724cd766d5f54d1" + integrity sha512-6pEjquH3rqaI6cYAXYPcz9MS4rY6R4ngRgrgfDshRptUZIc3lw0MCIJIGDj9++mfySOuPTHB4nrSW99BCvOPIA== + dependencies: + hermes-estree "0.25.1" + +hosted-git-info@^9.0.0: + version "9.0.3" + resolved "https://registry.yarnpkg.com/hosted-git-info/-/hosted-git-info-9.0.3.tgz#637b511ce62a28e4261a92b8da0a4d6be3522cd4" + integrity sha512-Hc+ghLoSt6QaYZUv0WBiIvmMDZuZZ7oaDvdH8MbfOO4lOsxdXLEvuC6ePoGs9H1X9oCLyq6+NVN0MKqD+ydxyg== + dependencies: + lru-cache "^11.1.0" + +html-escaper@^2.0.0: + version "2.0.2" + resolved "https://registry.yarnpkg.com/html-escaper/-/html-escaper-2.0.2.tgz#dfd60027da36a36dfcbe236262c00a5822681453" + integrity sha512-H2iMtd0I4Mt5eYiapRdIDjp+XzelXQ0tFE4JS7YFwFevXXMmOp9myNrUvCg0D6ws8iqkRPBfKHgbwig1SmlLfg== + +http-cache-semantics@^4.1.1: + version "4.3.0" + resolved "https://registry.yarnpkg.com/http-cache-semantics/-/http-cache-semantics-4.3.0.tgz#09eead3b16c6d85552857cc3fbd888d8353a2aaf" + integrity sha512-M5t5LlJpS1UHMjvwRQVdFHvPISGeLAxNcrWuJkeGh0KxsqCHZ1O3NXZU/8x7cD0BDcGW8kapxMKTvwlqrNkHkA== + +http-errors@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/http-errors/-/http-errors-2.0.1.tgz#36d2f65bc909c8790018dd36fb4d93da6caae06b" + integrity sha512-4FbRdAX+bSdmo4AUFuS0WNiPz8NgFt+r8ThgNWmlrjQjt1Q7ZR9+zTlce2859x4KSXrwIsaeTqDoKQmtP8pLmQ== + dependencies: + depd "~2.0.0" + inherits "~2.0.4" + setprototypeof "~1.2.0" + statuses "~2.0.2" + toidentifier "~1.0.1" + +http-proxy-agent@^7.0.0: + version "7.0.2" + resolved "https://registry.yarnpkg.com/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz#9a8b1f246866c028509486585f62b8f2c18c270e" + integrity sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig== + dependencies: + agent-base "^7.1.0" + debug "^4.3.4" + +https-proxy-agent@^7.0.1, https-proxy-agent@^7.0.5: + version "7.0.6" + resolved "https://registry.yarnpkg.com/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz#da8dfeac7da130b05c2ba4b59c9b6cd66611a6b9" + integrity sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw== + dependencies: + agent-base "^7.1.2" + debug "4" + +human-signals@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/human-signals/-/human-signals-2.1.0.tgz#dc91fcba42e4d06e4abaed33b3e7a3c02f514ea0" + integrity sha512-B4FFZ6q/T2jhhksgkbEW3HBvWIfDW85snkQgawt07S7J5QXTk6BkNV+0yAeZrM5QpMAdYlocGoljn0sJ/WQkFw== + +iconv-lite@^0.6.2: + version "0.6.3" + resolved "https://registry.yarnpkg.com/iconv-lite/-/iconv-lite-0.6.3.tgz#a52f80bf38da1952eb5c681790719871a1a72501" + integrity sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw== + dependencies: + safer-buffer ">= 2.1.2 < 3.0.0" + +ieee754@^1.1.13: + version "1.2.1" + resolved "https://registry.yarnpkg.com/ieee754/-/ieee754-1.2.1.tgz#8eb7a10a63fff25d15a57b001586d177d1b0d352" + integrity sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA== + +ignore@^5.2.0: + version "5.3.2" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-5.3.2.tgz#3cd40e729f3643fd87cb04e50bf0eb722bc596f5" + integrity sha512-hsBTNUqQTDwkWtcdYI2i06Y/nUBEsNEDJKjWdigLvegy8kDuJAS8uRlpkkcQpyEXL0Z/pjDy5HBmMjRCJ2gq+g== + +ignore@^7.0.5: + version "7.0.6" + resolved "https://registry.yarnpkg.com/ignore/-/ignore-7.0.6.tgz#6a57aaef4c90df27ac3590875d29e8f11988c88e" + integrity sha512-BAg6QkE8W+TuQLrrw0Ugr7HegXduRuuj8/ti2kSOc+jz1dmx8/WNcjr6XGnq5YpDWxFwwaavqD0+jIUOKelTsw== + +import-fresh@^3.2.1: + version "3.3.1" + resolved "https://registry.yarnpkg.com/import-fresh/-/import-fresh-3.3.1.tgz#9cecb56503c0ada1f2741dbbd6546e4b13b57ccf" + integrity sha512-TR3KfrTZTYLPB6jUjfx6MF9WcWrHL9su5TObK4ZkYgBdWKPOFoSoQIdEuTuR82pmtxH2spWG9h6etwfr1pLBqQ== + dependencies: + parent-module "^1.0.0" + resolve-from "^4.0.0" + +import-local@^3.0.2: + version "3.2.0" + resolved "https://registry.yarnpkg.com/import-local/-/import-local-3.2.0.tgz#c3d5c745798c02a6f8b897726aba5100186ee260" + integrity sha512-2SPlun1JUPWoM6t3F0dw0FkCF/jWY8kttcY4f599GLTSjh2OCuuhdTkJQsEcZzBqbXZGKMK2OqW1oZsjtf/gQA== + dependencies: + pkg-dir "^4.2.0" + resolve-cwd "^3.0.0" + +imurmurhash@^0.1.4: + version "0.1.4" + resolved "https://registry.yarnpkg.com/imurmurhash/-/imurmurhash-0.1.4.tgz#9218b9b2b928a238b13dc4fb6b6d576f231453ea" + integrity sha512-JmXMZ6wuvDmLiHEml9ykzqO6lwFbof0GG4IkcGaENdCRDDmMVnny7s5HsIgHCbaq0w2MyPhDqkhTUgS2LU2PHA== + +indent-string@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/indent-string/-/indent-string-4.0.0.tgz#624f8f4497d619b2d9768531d58f4122854d7251" + integrity sha512-EdDDZu4A2OyIK7Lr/2zG+w5jmbuk1DVBnEwREQvBzspBJkCEbRa8GxU1lghYcaGJCnRWibjDXlq779X1/y5xwg== + +inflight@^1.0.4: + version "1.0.6" + resolved "https://registry.yarnpkg.com/inflight/-/inflight-1.0.6.tgz#49bd6331d7d02d0c09bc910a1075ba8165b56df9" + integrity sha512-k92I/b08q4wvFscXCLvqfsHCrjrF7yiXsQuIVvVE7N82W3+aqpzuUdBbfhWcy/FZR3/4IgflMgKLOsvPDrGCJA== + dependencies: + once "^1.3.0" + wrappy "1" + +inherits@2, inherits@^2.0.3, inherits@^2.0.4, inherits@~2.0.4: + version "2.0.4" + resolved "https://registry.yarnpkg.com/inherits/-/inherits-2.0.4.tgz#0fa2c64f932917c3433a0ded55363aae37416b7c" + integrity sha512-k/vGaX4/Yla3WzyMCvTQOXYeIHvqOKtnqBduzTHpzpQZzAskKMhZ2K+EnBiSM9zGSoIFeMpXKxa4dYeZIQqewQ== + +ini@~1.3.0: + version "1.3.8" + resolved "https://registry.yarnpkg.com/ini/-/ini-1.3.8.tgz#a29da425b48806f34767a4efce397269af28432c" + integrity sha512-JV/yugV2uzW5iMRSiZAyDtQd+nxtUnjeLt0acNdw98kKLrvuRVyB80tsREOE7yvGVgalhZ6RNXCmEHkUKBKxew== + +invariant@^2.2.4: + version "2.2.4" + resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6" + integrity sha512-phJfQVBuaJM5raOpJjSfkiD6BpbCE4Ns//LaXl6wGYtUBY83nWS6Rf9tXm2e8VaK60JEjYldbPif/A2B1C2gNA== + dependencies: + loose-envify "^1.0.0" + +ip-address@^10.1.1: + version "10.7.1" + resolved "https://registry.yarnpkg.com/ip-address/-/ip-address-10.7.1.tgz#df8031c20df6b7f1dcc9f68c4f4fa5ee71c45d39" + integrity sha512-4OUAqU9Z1i3vCnS05hzGiFnEMDpQ+62pAD/MVQOp83fYyNC8GleCqaS0QikQBmcWCrKFiUs/B8ztRRiYOAXuCA== + +is-arrayish@^0.2.1: + version "0.2.1" + resolved "https://registry.yarnpkg.com/is-arrayish/-/is-arrayish-0.2.1.tgz#77c99840527aa8ecb1a8ba697b80645a7a926a9d" + integrity sha512-zz06S8t0ozoDXMG+ube26zeCTNXcKIPJZJi8hBrF4idCLms4CG9QtK7qBl1boi5ODzFpjswb5JPmHCbMpjaYzg== + +is-core-module@^2.16.1: + version "2.16.2" + resolved "https://registry.yarnpkg.com/is-core-module/-/is-core-module-2.16.2.tgz#3e07450a8080ebce3fbf0cac494f4d2ab324e082" + integrity sha512-evOr8xfXKxE6qSR0hSXL2r3sd7ALj8+7jQEUvPYcm5sgZFdJ+AYzT6yNmJenvIYQBgIGwfwz08sL8zoL7yq2BA== + dependencies: + hasown "^2.0.3" + +is-docker@^2.0.0: + version "2.2.1" + resolved "https://registry.yarnpkg.com/is-docker/-/is-docker-2.2.1.tgz#33eeabe23cfe86f14bde4408a02c0cfb853acdaa" + integrity sha512-F+i2BKsFrH66iaUFc0woD8sLy8getkwTwtOBjvs56Cx4CgJDeKQeqfz8wAYiSb8JOprWhHH5p77PbmYCvvUuXQ== + +is-extglob@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/is-extglob/-/is-extglob-2.1.1.tgz#a88c02535791f02ed37c76a1b9ea9773c833f8c2" + integrity sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ== + +is-fullwidth-code-point@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz#f116f8064fe90b3f7844a38997c0b75051269f1d" + integrity sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg== + +is-generator-fn@^2.0.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/is-generator-fn/-/is-generator-fn-2.1.0.tgz#7d140adc389aaf3011a8f2a2a4cfa6faadffb118" + integrity sha512-cTIB4yPYL/Grw0EaSzASzg6bBy9gqCofvWN8okThAYIxKJZC+udlRAmGbM0XLeniEJSs8uEgHPGuHSe1XsOLSQ== + +is-glob@^4.0.0, is-glob@^4.0.3: + version "4.0.3" + resolved "https://registry.yarnpkg.com/is-glob/-/is-glob-4.0.3.tgz#64f61e42cbbb2eec2071a9dac0b28ba1e65d5084" + integrity sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg== + dependencies: + is-extglob "^2.1.1" + +is-number@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/is-number/-/is-number-7.0.0.tgz#7535345b896734d5f80c4d06c50955527a14f12b" + integrity sha512-41Cifkg6e8TylSpdtTpeLVMqvSBEVzTttHvERD741+pnZ8ANv0004MRL43QKPDlK9cGvNp6NZWZUBlbGXYxxng== + +is-stream@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/is-stream/-/is-stream-2.0.1.tgz#fac1e3d53b97ad5a9d0ae9cef2389f5810a5c077" + integrity sha512-hFoiJiTl63nn+kstHGBtewWSKnQLpyb155KHheA1l39uvtO9nWIop1p3udqPcUd/xbF1VLMO4n7OI6p7RbngDg== + +is-wsl@^2.1.1, is-wsl@^2.2.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/is-wsl/-/is-wsl-2.2.0.tgz#74a4c76e77ca9fd3f932f290c17ea326cd157271" + integrity sha512-fKzAra0rGJUUBwGBgNkHZuToZcn+TtXHpeCgmkMJMMYx1sQDYaCSyjJBSCa2nH1DGm7s3n1oBnohoVTBaN7Lww== + dependencies: + is-docker "^2.0.0" + +isexe@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-2.0.0.tgz#e8fbf374dc556ff8947a10dcb0572d633f2cfa10" + integrity sha512-RHxMLp9lnKHGHRng9QFhRCMbYAcVpn69smSGcq3f36xjgVVWThj4qqLbTLlq7Ssj8B+fIQ1EuCEGI2lKsyQeIw== + +isexe@^3.1.1: + version "3.1.5" + resolved "https://registry.yarnpkg.com/isexe/-/isexe-3.1.5.tgz#42e368f68d5e10dadfee4fda7b550bc2d8892dc9" + integrity sha512-6B3tLtFqtQS4ekarvLVMZ+X+VlvQekbe4taUkf/rhVO3d/h0M2rfARm/pXLcPEsjjMsFgrFgSrhQIxcSVrBz8w== + +istanbul-lib-coverage@^3.0.0, istanbul-lib-coverage@^3.2.0: + version "3.2.2" + resolved "https://registry.yarnpkg.com/istanbul-lib-coverage/-/istanbul-lib-coverage-3.2.2.tgz#2d166c4b0644d43a39f04bf6c2edd1e585f31756" + integrity sha512-O8dpsF+r0WV/8MNRKfnmrtCWhuKjxrq2w+jpzBL5UZKTi2LeVWnWOmWRxFlesJONmc+wLAGvKQZEOanko0LFTg== + +istanbul-lib-instrument@^5.0.4: + version "5.2.1" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-5.2.1.tgz#d10c8885c2125574e1c231cacadf955675e1ce3d" + integrity sha512-pzqtp31nLv/XFOzXGuvhCb8qhjmTVo5vjVk19XE4CRlSWz0KoeJ3bw9XsA7nOp9YBf4qHjwBxkDzKcME/J29Yg== + dependencies: + "@babel/core" "^7.12.3" + "@babel/parser" "^7.14.7" + "@istanbuljs/schema" "^0.1.2" + istanbul-lib-coverage "^3.2.0" + semver "^6.3.0" + +istanbul-lib-instrument@^6.0.0: + version "6.0.3" + resolved "https://registry.yarnpkg.com/istanbul-lib-instrument/-/istanbul-lib-instrument-6.0.3.tgz#fa15401df6c15874bcb2105f773325d78c666765" + integrity sha512-Vtgk7L/R2JHyyGW07spoFlB8/lpjiOLTjMdms6AFMraYt3BaJauod/NGrfnVG/y4Ix1JEuMRPDPEj2ua+zz1/Q== + dependencies: + "@babel/core" "^7.23.9" + "@babel/parser" "^7.23.9" + "@istanbuljs/schema" "^0.1.3" + istanbul-lib-coverage "^3.2.0" + semver "^7.5.4" + +istanbul-lib-report@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/istanbul-lib-report/-/istanbul-lib-report-3.0.1.tgz#908305bac9a5bd175ac6a74489eafd0fc2445a7d" + integrity sha512-GCfE1mtsHGOELCU8e/Z7YWzpmybrx/+dSTfLrvY8qRmaY6zXTKWn6WQIjaAFw069icm6GVMNkgu0NzI4iPZUNw== + dependencies: + istanbul-lib-coverage "^3.0.0" + make-dir "^4.0.0" + supports-color "^7.1.0" + +istanbul-lib-source-maps@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/istanbul-lib-source-maps/-/istanbul-lib-source-maps-4.0.1.tgz#895f3a709fcfba34c6de5a42939022f3e4358551" + integrity sha512-n3s8EwkdFIJCG3BPKBYvskgXGoy88ARzvegkitk60NxRdwltLOTaH7CUiMRXvwYorl0Q712iEjcWB+fK/MrWVw== + dependencies: + debug "^4.1.1" + istanbul-lib-coverage "^3.0.0" + source-map "^0.6.1" + +istanbul-reports@^3.1.3: + version "3.2.0" + resolved "https://registry.yarnpkg.com/istanbul-reports/-/istanbul-reports-3.2.0.tgz#cb4535162b5784aa623cee21a7252cf2c807ac93" + integrity sha512-HGYWWS/ehqTV3xN10i23tkPkpH46MLCIMFNCaaKNavAXTF1RkqxawEPtnjnGZ6XKSInBKkiOA5BKS+aZiY3AvA== + dependencies: + html-escaper "^2.0.0" + istanbul-lib-report "^3.0.0" + +jackspeak@^3.1.2: + version "3.4.3" + resolved "https://registry.yarnpkg.com/jackspeak/-/jackspeak-3.4.3.tgz#8833a9d89ab4acde6188942bd1c53b6390ed5a8a" + integrity sha512-OGlZQpz2yfahA/Rd1Y8Cd9SIEsqvXkLVoSw/cgwhnhFMDbsQFeZYoJJ7bIZBS9BcamUW96asq/npPWugM+RQBw== + dependencies: + "@isaacs/cliui" "^8.0.2" + optionalDependencies: + "@pkgjs/parseargs" "^0.11.0" + +jest-changed-files@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-changed-files/-/jest-changed-files-29.7.0.tgz#1c06d07e77c78e1585d020424dedc10d6e17ac3a" + integrity sha512-fEArFiwf1BpQ+4bXSprcDc3/x4HSzL4al2tozwVpDFpsxALjLYdyiIK4e5Vz66GQJIbXJ82+35PtysofptNX2w== + dependencies: + execa "^5.0.0" + jest-util "^29.7.0" + p-limit "^3.1.0" + +jest-circus@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-circus/-/jest-circus-29.7.0.tgz#b6817a45fcc835d8b16d5962d0c026473ee3668a" + integrity sha512-3E1nCMgipcTkCocFwM90XXQab9bS+GMsjdpmPrlelaxwD93Ad8iVEjX/vvHPdLPnFf+L40u+5+iutRdA1N9myw== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/expect" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + co "^4.6.0" + dedent "^1.0.0" + is-generator-fn "^2.0.0" + jest-each "^29.7.0" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-runtime "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" + p-limit "^3.1.0" + pretty-format "^29.7.0" + pure-rand "^6.0.0" + slash "^3.0.0" + stack-utils "^2.0.3" + +jest-cli@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-cli/-/jest-cli-29.7.0.tgz#5592c940798e0cae677eec169264f2d839a37995" + integrity sha512-OVVobw2IubN/GSYsxETi+gOe7Ka59EFMR/twOU3Jb2GnKKeMGJB5SGUUrEz3SFVmJASUdZUzy83sLNNQ2gZslg== + dependencies: + "@jest/core" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" + chalk "^4.0.0" + create-jest "^29.7.0" + exit "^0.1.2" + import-local "^3.0.2" + jest-config "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" + yargs "^17.3.1" + +jest-config@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-config/-/jest-config-29.7.0.tgz#bcbda8806dbcc01b1e316a46bb74085a84b0245f" + integrity sha512-uXbpfeQ7R6TZBqI3/TxCU4q4ttk3u0PJeC+E0zbfSoSjq6bJ7buBPxzQPL0ifrkY4DNu4JUdk0ImlBUYi840eQ== + dependencies: + "@babel/core" "^7.11.6" + "@jest/test-sequencer" "^29.7.0" + "@jest/types" "^29.6.3" + babel-jest "^29.7.0" + chalk "^4.0.0" + ci-info "^3.2.0" + deepmerge "^4.2.2" + glob "^7.1.3" + graceful-fs "^4.2.9" + jest-circus "^29.7.0" + jest-environment-node "^29.7.0" + jest-get-type "^29.6.3" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-runner "^29.7.0" + jest-util "^29.7.0" + jest-validate "^29.7.0" + micromatch "^4.0.4" + parse-json "^5.2.0" + pretty-format "^29.7.0" + slash "^3.0.0" + strip-json-comments "^3.1.1" + +jest-diff@30.4.1: + version "30.4.1" + resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-30.4.1.tgz#26691c73975768409af4a66b2754cea3182aa2dc" + integrity sha512-CRpFK0RtLriVDGcPPAnR6HMVI8bSR2jnUIgralhauzYQZIb4RH9AtEInTuQr65LmmGggGcRT6HIASxwqsVsmlA== + dependencies: + "@jest/diff-sequences" "30.4.0" + "@jest/get-type" "30.1.0" + chalk "^4.1.2" + pretty-format "30.4.1" + +jest-diff@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-diff/-/jest-diff-29.7.0.tgz#017934a66ebb7ecf6f205e84699be10afd70458a" + integrity sha512-LMIgiIrhigmPrs03JHpxUh2yISK3vLFPkAodPeo0+BuF7wA2FoQbkEg1u8gBYBThncu7e1oEDUfIXVuTqLRUjw== + dependencies: + chalk "^4.0.0" + diff-sequences "^29.6.3" + jest-get-type "^29.6.3" + pretty-format "^29.7.0" + +jest-docblock@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-docblock/-/jest-docblock-29.7.0.tgz#8fddb6adc3cdc955c93e2a87f61cfd350d5d119a" + integrity sha512-q617Auw3A612guyaFgsbFeYpNP5t2aoUNLwBUbc/0kD1R4t9ixDbyFTHd1nok4epoVFpr7PmeWHrhvuV3XaJ4g== + dependencies: + detect-newline "^3.0.0" + +jest-each@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-each/-/jest-each-29.7.0.tgz#162a9b3f2328bdd991beaabffbb74745e56577d1" + integrity sha512-gns+Er14+ZrEoC5fhOfYCY1LOHHr0TI+rQUHZS8Ttw2l7gl+80eHc/gFf2Ktkw0+SIACDTeWvpFcv3B04VembQ== + dependencies: + "@jest/types" "^29.6.3" + chalk "^4.0.0" + jest-get-type "^29.6.3" + jest-util "^29.7.0" + pretty-format "^29.7.0" + +jest-environment-node@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-environment-node/-/jest-environment-node-29.7.0.tgz#0b93e111dda8ec120bc8300e6d1fb9576e164376" + integrity sha512-DOSwCRqXirTOyheM+4d5YZOrWcdu0LNZ87ewUoywbcb2XR4wKgqiG8vNeYwhjFMbEkfju7wx2GYH0P2gevGvFw== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/fake-timers" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + jest-mock "^29.7.0" + jest-util "^29.7.0" + +jest-get-type@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/jest-get-type/-/jest-get-type-29.6.3.tgz#36f499fdcea197c1045a127319c0481723908fd1" + integrity sha512-zrteXnqYxfQh7l5FHyL38jL39di8H8rHoecLH3JNxH3BwOrBsNeabdap5e0I23lD4HHI8W5VFBZqG4Eaq5LNcw== + +jest-haste-map@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-haste-map/-/jest-haste-map-29.7.0.tgz#3c2396524482f5a0506376e6c858c3bbcc17b104" + integrity sha512-fP8u2pyfqx0K1rGn1R9pyE0/KTn+G7PxktWidOBTqFPLYX0b9ksaMFkhK5vrS3DVun09pckLdlx90QthlW7AmA== + dependencies: + "@jest/types" "^29.6.3" + "@types/graceful-fs" "^4.1.3" + "@types/node" "*" + anymatch "^3.0.3" + fb-watchman "^2.0.0" + graceful-fs "^4.2.9" + jest-regex-util "^29.6.3" + jest-util "^29.7.0" + jest-worker "^29.7.0" + micromatch "^4.0.4" + walker "^1.0.8" + optionalDependencies: + fsevents "^2.3.2" + +jest-leak-detector@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-leak-detector/-/jest-leak-detector-29.7.0.tgz#5b7ec0dadfdfec0ca383dc9aa016d36b5ea4c728" + integrity sha512-kYA8IJcSYtST2BY9I+SMC32nDpBT3J2NvWJx8+JCuCdl/CR1I4EKUJROiP8XtCcxqgTTBGJNdbB1A8XRKbTetw== + dependencies: + jest-get-type "^29.6.3" + pretty-format "^29.7.0" + +jest-matcher-utils@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-29.7.0.tgz#ae8fec79ff249fd592ce80e3ee474e83a6c44f12" + integrity sha512-sBkD+Xi9DtcChsI3L3u0+N0opgPYnCRPtGcQYrgXmR+hmt/fYfWAL0xRXYU8eWOdfuLgBe0YCW3AFtnRLagq/g== + dependencies: + chalk "^4.0.0" + jest-diff "^29.7.0" + jest-get-type "^29.6.3" + pretty-format "^29.7.0" + +jest-matcher-utils@^30.4.1: + version "30.4.1" + resolved "https://registry.yarnpkg.com/jest-matcher-utils/-/jest-matcher-utils-30.4.1.tgz#3fee8c89dbd8fc6e60eb590def9897e18f110ec4" + integrity sha512-zvYfX5CaeEkFrrLS9suWe9rvJrm9J1Iv3ua8kIBv9GEPzcnsfBf0bob37la7s67fs0nlBC3EuvkOLnXQKxtx4A== + dependencies: + "@jest/get-type" "30.1.0" + chalk "^4.1.2" + jest-diff "30.4.1" + pretty-format "30.4.1" + +jest-message-util@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-message-util/-/jest-message-util-29.7.0.tgz#8bc392e204e95dfe7564abbe72a404e28e51f7f3" + integrity sha512-GBEV4GRADeP+qtB2+6u61stea8mGcOT4mCtrYISZwfu9/ISHFJ/5zOMXYbpBE9RsS5+Gb63DW4FgmnKJ79Kf6w== + dependencies: + "@babel/code-frame" "^7.12.13" + "@jest/types" "^29.6.3" + "@types/stack-utils" "^2.0.0" + chalk "^4.0.0" + graceful-fs "^4.2.9" + micromatch "^4.0.4" + pretty-format "^29.7.0" + slash "^3.0.0" + stack-utils "^2.0.3" + +jest-mock@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-mock/-/jest-mock-29.7.0.tgz#4e836cf60e99c6fcfabe9f99d017f3fdd50a6347" + integrity sha512-ITOMZn+UkYS4ZFh83xYAOzWStloNzJFO2s8DWrE4lhtGD+AorgnbkiKERe4wQVBydIGPx059g6riW5Btp6Llnw== + dependencies: + "@jest/types" "^29.6.3" + "@types/node" "*" + jest-util "^29.7.0" + +jest-pnp-resolver@^1.2.2: + version "1.2.3" + resolved "https://registry.yarnpkg.com/jest-pnp-resolver/-/jest-pnp-resolver-1.2.3.tgz#930b1546164d4ad5937d5540e711d4d38d4cad2e" + integrity sha512-+3NpwQEnRoIBtx4fyhblQDPgJI0H1IEIkX7ShLUjPGA7TtUTvI1oiKi3SR4oBR0hQhQR80l4WAe5RrXBwWMA8w== + +jest-regex-util@^29.6.3: + version "29.6.3" + resolved "https://registry.yarnpkg.com/jest-regex-util/-/jest-regex-util-29.6.3.tgz#4a556d9c776af68e1c5f48194f4d0327d24e8a52" + integrity sha512-KJJBsRCyyLNWCNBOvZyRDnAIfUiRJ8v+hOBQYGn8gDyF3UegwiP4gwRR3/SDa42g1YbVycTidUF3rKjyLFDWbg== + +jest-resolve-dependencies@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-resolve-dependencies/-/jest-resolve-dependencies-29.7.0.tgz#1b04f2c095f37fc776ff40803dc92921b1e88428" + integrity sha512-un0zD/6qxJ+S0et7WxeI3H5XSe9lTBBR7bOHCHXkKR6luG5mwDDlIzVQ0V5cZCuoTgEdcdwzTghYkTWfubi+nA== + dependencies: + jest-regex-util "^29.6.3" + jest-snapshot "^29.7.0" + +jest-resolve@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-resolve/-/jest-resolve-29.7.0.tgz#64d6a8992dd26f635ab0c01e5eef4399c6bcbc30" + integrity sha512-IOVhZSrg+UvVAshDSDtHyFCCBUl/Q3AAJv8iZ6ZjnZ74xzvwuzLXid9IIIPgTnY62SJjfuupMKZsZQRsCvxEgA== + dependencies: + chalk "^4.0.0" + graceful-fs "^4.2.9" + jest-haste-map "^29.7.0" + jest-pnp-resolver "^1.2.2" + jest-util "^29.7.0" + jest-validate "^29.7.0" + resolve "^1.20.0" + resolve.exports "^2.0.0" + slash "^3.0.0" + +jest-runner@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-runner/-/jest-runner-29.7.0.tgz#809af072d408a53dcfd2e849a4c976d3132f718e" + integrity sha512-fsc4N6cPCAahybGBfTRcq5wFR6fpLznMg47sY5aDpsoejOcVYFb07AHuSnR0liMcPTgBsA3ZJL6kFOjPdoNipQ== + dependencies: + "@jest/console" "^29.7.0" + "@jest/environment" "^29.7.0" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + emittery "^0.13.1" + graceful-fs "^4.2.9" + jest-docblock "^29.7.0" + jest-environment-node "^29.7.0" + jest-haste-map "^29.7.0" + jest-leak-detector "^29.7.0" + jest-message-util "^29.7.0" + jest-resolve "^29.7.0" + jest-runtime "^29.7.0" + jest-util "^29.7.0" + jest-watcher "^29.7.0" + jest-worker "^29.7.0" + p-limit "^3.1.0" + source-map-support "0.5.13" + +jest-runtime@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-runtime/-/jest-runtime-29.7.0.tgz#efecb3141cf7d3767a3a0cc8f7c9990587d3d817" + integrity sha512-gUnLjgwdGqW7B4LvOIkbKs9WGbn+QLqRQQ9juC6HndeDiezIwhDP+mhMwHWCEcfQ5RUXa6OPnFF8BJh5xegwwQ== + dependencies: + "@jest/environment" "^29.7.0" + "@jest/fake-timers" "^29.7.0" + "@jest/globals" "^29.7.0" + "@jest/source-map" "^29.6.3" + "@jest/test-result" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + cjs-module-lexer "^1.0.0" + collect-v8-coverage "^1.0.0" + glob "^7.1.3" + graceful-fs "^4.2.9" + jest-haste-map "^29.7.0" + jest-message-util "^29.7.0" + jest-mock "^29.7.0" + jest-regex-util "^29.6.3" + jest-resolve "^29.7.0" + jest-snapshot "^29.7.0" + jest-util "^29.7.0" + slash "^3.0.0" + strip-bom "^4.0.0" + +jest-snapshot@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-snapshot/-/jest-snapshot-29.7.0.tgz#c2c574c3f51865da1bb329036778a69bf88a6be5" + integrity sha512-Rm0BMWtxBcioHr1/OX5YCP8Uov4riHvKPknOGs804Zg9JGZgmIBkbtlxJC/7Z4msKYVbIJtfU+tKb8xlYNfdkw== + dependencies: + "@babel/core" "^7.11.6" + "@babel/generator" "^7.7.2" + "@babel/plugin-syntax-jsx" "^7.7.2" + "@babel/plugin-syntax-typescript" "^7.7.2" + "@babel/types" "^7.3.3" + "@jest/expect-utils" "^29.7.0" + "@jest/transform" "^29.7.0" + "@jest/types" "^29.6.3" + babel-preset-current-node-syntax "^1.0.0" + chalk "^4.0.0" + expect "^29.7.0" + graceful-fs "^4.2.9" + jest-diff "^29.7.0" + jest-get-type "^29.6.3" + jest-matcher-utils "^29.7.0" + jest-message-util "^29.7.0" + jest-util "^29.7.0" + natural-compare "^1.4.0" + pretty-format "^29.7.0" + semver "^7.5.3" + +jest-util@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-util/-/jest-util-29.7.0.tgz#23c2b62bfb22be82b44de98055802ff3710fc0bc" + integrity sha512-z6EbKajIpqGKU56y5KBUgy1dt1ihhQJgWzUlZHArA/+X2ad7Cb5iF+AK1EWVL/Bo7Rz9uurpqw6SiBCefUbCGA== + dependencies: + "@jest/types" "^29.6.3" + "@types/node" "*" + chalk "^4.0.0" + ci-info "^3.2.0" + graceful-fs "^4.2.9" + picomatch "^2.2.3" + +jest-validate@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-validate/-/jest-validate-29.7.0.tgz#7bf705511c64da591d46b15fce41400d52147d9c" + integrity sha512-ZB7wHqaRGVw/9hST/OuFUReG7M8vKeq0/J2egIGLdvjHCmYqGARhzXmtgi+gVeZ5uXFF219aOc3Ls2yLg27tkw== + dependencies: + "@jest/types" "^29.6.3" + camelcase "^6.2.0" + chalk "^4.0.0" + jest-get-type "^29.6.3" + leven "^3.1.0" + pretty-format "^29.7.0" + +jest-watcher@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-watcher/-/jest-watcher-29.7.0.tgz#7810d30d619c3a62093223ce6bb359ca1b28a2f2" + integrity sha512-49Fg7WXkU3Vl2h6LbLtMQ/HyB6rXSIX7SqvBLQmssRBGN9I0PNvPmAmCWSOY6SOvrjhI/F7/bGAv9RtnsPA03g== + dependencies: + "@jest/test-result" "^29.7.0" + "@jest/types" "^29.6.3" + "@types/node" "*" + ansi-escapes "^4.2.1" + chalk "^4.0.0" + emittery "^0.13.1" + jest-util "^29.7.0" + string-length "^4.0.1" + +jest-worker@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest-worker/-/jest-worker-29.7.0.tgz#acad073acbbaeb7262bd5389e1bcf43e10058d4a" + integrity sha512-eIz2msL/EzL9UFTFFx7jBTkeZfku0yUAyZZZmJ93H2TYEiroIx2PQjEXcwYtYl8zXCxb+PAmA2hLIt/6ZEkPHw== + dependencies: + "@types/node" "*" + jest-util "^29.7.0" + merge-stream "^2.0.0" + supports-color "^8.0.0" + +jest@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/jest/-/jest-29.7.0.tgz#994676fc24177f088f1c5e3737f5697204ff2613" + integrity sha512-NIy3oAFp9shda19hy4HK0HRTWKtPJmGdnvywu01nOqNC2vZg+Z+fvJDxpMQA88eb2I9EcafcdjYgsDthnYTvGw== + dependencies: + "@jest/core" "^29.7.0" + "@jest/types" "^29.6.3" + import-local "^3.0.2" + jest-cli "^29.7.0" + +"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499" + integrity sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ== + +js-yaml@^3.13.1, js-yaml@^3.15.2: + version "3.15.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-3.15.2.tgz#3f83823ac6be17f570f23b2ecdef3777ff5ea364" + integrity sha512-6EuL879VkRA+1Cz578mKMiKvjPNEuk6+r1JaFzoSWejZmtf7xWbIyw1e3KkxlkzTIt9Taw6JBhEppG7utc1P+w== + dependencies: + argparse "^1.0.7" + esprima "^4.0.0" + +js-yaml@^4.1.1, js-yaml@^4.3.0, js-yaml@^4.3.2: + version "4.3.2" + resolved "https://registry.yarnpkg.com/js-yaml/-/js-yaml-4.3.2.tgz#8e44fb14a2643c59726bb15787b5f1512cb3d3fb" + integrity sha512-SFNOvSJ+Dgf/9An904Yx+CgSlIPCkIpao4qo51lpee25TIRejdH3rhR4EZMGoNx3/TP3O+wzWuiTFl4sqbltzA== + dependencies: + argparse "^2.0.1" + +jsc-safe-url@^0.2.2: + version "0.2.4" + resolved "https://registry.yarnpkg.com/jsc-safe-url/-/jsc-safe-url-0.2.4.tgz#141c14fbb43791e88d5dc64e85a374575a83477a" + integrity sha512-0wM3YBWtYePOjfyXQH5MWQ8H7sdk5EXSwZvmSLKk2RboVQ2Bu239jycHDz5J/8Blf3K0Qnoy2b6xD+z10MFB+Q== + +jsesc@^3.0.2, jsesc@~3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/jsesc/-/jsesc-3.1.0.tgz#74d335a234f67ed19907fdadfac7ccf9d409825d" + integrity sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA== + +json-buffer@3.0.1: + version "3.0.1" + resolved "https://registry.yarnpkg.com/json-buffer/-/json-buffer-3.0.1.tgz#9338802a30d3b6605fbe0613e094008ca8c05a13" + integrity sha512-4bV5BfR2mqfQTJm+V5tPPdf+ZpuhiIvTuAB5g8kcrXOZpTT/QwwVRWBywX1ozr6lEuPdbHxwaJlm9G6mI2sfSQ== + +json-parse-even-better-errors@^2.3.0: + version "2.3.1" + resolved "https://registry.yarnpkg.com/json-parse-even-better-errors/-/json-parse-even-better-errors-2.3.1.tgz#7c47805a94319928e05777405dc12e1f7a4ee02d" + integrity sha512-xyFwyhro/JEof6Ghe2iz2NcXoj2sloNsWr/XsERDK/oiPCfaNhl5ONfp+jQdAZRQQ0IJWNzH9zIZF7li91kh2w== + +json-schema-traverse@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-0.4.1.tgz#69f6a87d9513ab8bb8fe63bdb0979c448e684660" + integrity sha512-xbbCH5dCYU5T8LcEhhuh7HJ88HXuW3qsI3Y0zOZFKfZEHcpWiHU/Jxzk629Brsab/mMiHQti9wMP+845RPe3Vg== + +json-schema-traverse@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/json-schema-traverse/-/json-schema-traverse-1.0.0.tgz#ae7bcb3656ab77a73ba5c49bf654f38e6b6860e2" + integrity sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug== + +json-stable-stringify-without-jsonify@^1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/json-stable-stringify-without-jsonify/-/json-stable-stringify-without-jsonify-1.0.1.tgz#9db7b59496ad3f3cfef30a75142d2d930ad72651" + integrity sha512-Bdboy+l7tA3OGW6FjyFHWkP5LuByj1Tk33Ljyq0axyzdk9//JSi2u3fP1QSmd1KNwq6VOKYGlAu87CisVir6Pw== + +json5@^2.2.3: + version "2.2.3" + resolved "https://registry.yarnpkg.com/json5/-/json5-2.2.3.tgz#78cd6f1a19bdc12b73db5ad0c61efd66c1e29283" + integrity sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg== + +keyv@^4.5.4: + version "4.5.4" + resolved "https://registry.yarnpkg.com/keyv/-/keyv-4.5.4.tgz#a879a99e29452f942439f2a405e3af8b31d4de93" + integrity sha512-oxVHkHR/EJf2CNXnWxRLW6mg7JyCCUcG0DtEGmL2ctUo1PNTin1PUil+r/+4r5MpVgC/fn1kjsx7mjSujKqIpw== + dependencies: + json-buffer "3.0.1" + +kleur@^3.0.3: + version "3.0.3" + resolved "https://registry.yarnpkg.com/kleur/-/kleur-3.0.3.tgz#a79c9ecc86ee1ce3fa6206d1216c501f147fc07e" + integrity sha512-eTIzlVOSUR+JxdDFepEYcBMtZ9Qqdef+rnzWdRZuMbOywu5tO2w2N7rqjoANZ5k9vywhL6Br1VRjUIgTQx4E8w== + +leven@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/leven/-/leven-3.1.0.tgz#77891de834064cccba82ae7842bb6b14a13ed7f2" + integrity sha512-qsda+H8jTaUaN/x5vzW2rzc+8Rw4TAQ/4KjB46IwK5VH+IlVeeeje/EoZRpiXvIqjFgK84QffqPztGI3VBLG1A== + +levn@^0.4.1: + version "0.4.1" + resolved "https://registry.yarnpkg.com/levn/-/levn-0.4.1.tgz#ae4562c007473b932a6200d403268dd2fffc6ade" + integrity sha512-+bT2uH4E5LGE7h/n3evcS/sQlJXCpIp6ym8OWJ5eV6+67Dsql/LaaT7qJBAt2rzfoa/5QBGBhxDix1dMt2kQKQ== + dependencies: + prelude-ls "^1.2.1" + type-check "~0.4.0" + +libxmljs2@^0.35||^0.37: + version "0.37.0" + resolved "https://registry.yarnpkg.com/libxmljs2/-/libxmljs2-0.37.0.tgz#ee637d6220b348b74ef2697d1a9d2b2007628643" + integrity sha512-Xb78V8GZouoZFrq8cCwx7+G3WYOcJG0xb3YUbweSyE4z2EIrQCZMr3Ye/dHn4mESs6YxUMeQeUZm5IXg+iLHog== + dependencies: + bindings "~1.5.0" + nan "~2.22.2" + node-gyp "^11.2.0" + prebuild-install "^7.1.3" + +lighthouse-logger@^1.0.0: + version "1.4.2" + resolved "https://registry.yarnpkg.com/lighthouse-logger/-/lighthouse-logger-1.4.2.tgz#aef90f9e97cd81db367c7634292ee22079280aaa" + integrity sha512-gPWxznF6TKmUHrOQjlVo2UbaL2EJ71mb2CCeRs/2qBpi4L/g4LUVc9+3lKQ6DTUZwJswfM7ainGrLO1+fOqa2g== + dependencies: + debug "^2.6.9" + marky "^1.2.2" + +lines-and-columns@^1.1.6: + version "1.2.4" + resolved "https://registry.yarnpkg.com/lines-and-columns/-/lines-and-columns-1.2.4.tgz#eca284f75d2965079309dc0ad9255abb2ebc1632" + integrity sha512-7ylylesZQ/PV29jhEDl3Ufjo6ZX7gCqJr5F7PKrqc93v7fzSymt1BpwEU8nAUXs8qzzvqhbjhK5QZg6Mt/HkBg== + +locate-path@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-5.0.0.tgz#1afba396afd676a6d42504d0a67a3a7eb9f62aa0" + integrity sha512-t7hw9pI+WvuwNJXwk5zVHpyhIqzg2qTlklJOf0mVxGSbe3Fp2VieZcduNYjaLDoy6p9uGpQEGWG87WpMKlNq8g== + dependencies: + p-locate "^4.1.0" + +locate-path@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/locate-path/-/locate-path-6.0.0.tgz#55321eb309febbc59c4801d931a72452a681d286" + integrity sha512-iPZK6eYjbxRu3uB4/WZ3EsEIMJFMqAoopl3R+zuq0UjcAm/MO6KCweDgPfP3elTztoKP3KtnVHxTn2NHBSDVUw== + dependencies: + p-locate "^5.0.0" + +lodash.debounce@^4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/lodash.debounce/-/lodash.debounce-4.0.8.tgz#82d79bff30a67c4005ffd5e2515300ad9ca4d7af" + integrity sha512-FT1yDzDYEoYWhnSGnpE/4Kj1fLZkDFyqRb7fNt6FdYOSxlUWAtp42Eh6Wb0rGIv/m9Bgo7x4GhQbm5Ys4SG5ow== + +lodash.memoize@^4.1.2: + version "4.1.2" + resolved "https://registry.yarnpkg.com/lodash.memoize/-/lodash.memoize-4.1.2.tgz#bcc6c49a42a2840ed997f323eada5ecd182e0bfe" + integrity sha512-t7j+NzmgnQzTAYXcsHYLgimltOV1MXHtlOWf6GjL9Kj8GK5FInw5JotxvbOs+IvV1/Dzo04/fCGfLVs7aXb4Ag== + +lodash.merge@^4.6.2: + version "4.6.2" + resolved "https://registry.yarnpkg.com/lodash.merge/-/lodash.merge-4.6.2.tgz#558aa53b43b661e1925a0afdfa36a9a1085fe57a" + integrity sha512-0KpjqXRVvrYyCsX1swR/XTK0va6VQkQM6MNo7PqW77ByjAhoARA8EfrP1N4+KlKj8YS0ZUCtRT/YUuhyYDujIQ== + +lodash.throttle@^4.1.1: + version "4.1.1" + resolved "https://registry.yarnpkg.com/lodash.throttle/-/lodash.throttle-4.1.1.tgz#c23e91b710242ac70c37f1e1cda9274cc39bf2f4" + integrity sha512-wIkUCfVKpVsWo3JSZlc+8MB5it+2AN5W8J7YVMST30UrvcQNZ1Okbj+rbVniijTWE6FGYy4XJq/rHkas8qJMLQ== + +loose-envify@^1.0.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/loose-envify/-/loose-envify-1.4.0.tgz#71ee51fa7be4caec1a63839f7e682d8132d30caf" + integrity sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q== + dependencies: + js-tokens "^3.0.0 || ^4.0.0" + +lru-cache@^10.0.1, lru-cache@^10.2.0: + version "10.4.3" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-10.4.3.tgz#410fc8a17b70e598013df257c2446b7f3383f119" + integrity sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ== + +lru-cache@^11.1.0: + version "11.5.2" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-11.5.2.tgz#00e16665c90c620fba14a3c368732a976493f760" + integrity sha512-4pfM1Ff0x50o0tQwb5ucw/RzNyD0/YJME6IVcStalZuMWxdt3sR3huStTtxz4PUmvZfRguvDejasvQ2kifR11g== + +lru-cache@^5.1.1: + version "5.1.1" + resolved "https://registry.yarnpkg.com/lru-cache/-/lru-cache-5.1.1.tgz#1da27e6710271947695daf6848e847f01d84b920" + integrity sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w== + dependencies: + yallist "^3.0.2" + +make-dir@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/make-dir/-/make-dir-4.0.0.tgz#c3c2307a771277cd9638305f915c29ae741b614e" + integrity sha512-hXdUTZYIVOt1Ex//jAQi+wTZZpUpwBj/0QsOzqegb3rGMMeJiSEu5xLHnYfBrRV4RH2+OCSOO95Is/7x1WJ4bw== + dependencies: + semver "^7.5.3" + +make-error@^1.3.6: + version "1.3.6" + resolved "https://registry.yarnpkg.com/make-error/-/make-error-1.3.6.tgz#2eb2e37ea9b67c4891f684a1394799af484cf7a2" + integrity sha512-s8UhlNe7vPKomQhC1qFelMokr/Sc3AgNbso3n74mVPA5LTZwkB9NlXf4XPamLxJE8h0gh73rM94xvwRT2CVInw== + +make-fetch-happen@^14.0.3: + version "14.0.3" + resolved "https://registry.yarnpkg.com/make-fetch-happen/-/make-fetch-happen-14.0.3.tgz#d74c3ecb0028f08ab604011e0bc6baed483fcdcd" + integrity sha512-QMjGbFTP0blj97EeidG5hk/QhKQ3T4ICckQGLgz38QF7Vgbk6e6FTARN8KhKxyBbWn8R0HU+bnw8aSoFPD4qtQ== + dependencies: + "@npmcli/agent" "^3.0.0" + cacache "^19.0.1" + http-cache-semantics "^4.1.1" + minipass "^7.0.2" + minipass-fetch "^4.0.0" + minipass-flush "^1.0.5" + minipass-pipeline "^1.2.4" + negotiator "^1.0.0" + proc-log "^5.0.0" + promise-retry "^2.0.1" + ssri "^12.0.0" + +makeerror@1.0.12: + version "1.0.12" + resolved "https://registry.yarnpkg.com/makeerror/-/makeerror-1.0.12.tgz#3e5dd2079a82e812e983cc6610c4a2cb0eaa801a" + integrity sha512-JmqCvUhmt43madlpFzG4BQzG2Z3m6tvQDNKdClZnO3VbIudJYmxsT0FNJMeiB2+JTSlTQTSbU8QdesVmwJcmLg== + dependencies: + tmpl "1.0.5" + +marky@^1.2.2: + version "1.3.0" + resolved "https://registry.yarnpkg.com/marky/-/marky-1.3.0.tgz#422b63b0baf65022f02eda61a238eccdbbc14997" + integrity sha512-ocnPZQLNpvbedwTy9kNrQEsknEfgvcLMvOtz3sFeWApDq1MXH1TqkCIx58xlpESsfwQOnuBO9beyQuNGzVvuhQ== + +memoize-one@^5.0.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/memoize-one/-/memoize-one-5.2.1.tgz#8337aa3c4335581839ec01c3d594090cebe8f00e" + integrity sha512-zYiwtZUcYyXKo/np96AGZAckk+FWWsUdJ3cHGGmld7+AhvcWmQyGCYUh1hc4Q/pkOhb65dQR/pqCyK0cOaHz4Q== + +merge-stream@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/merge-stream/-/merge-stream-2.0.0.tgz#52823629a14dd00c9770fb6ad47dc6310f2c1f60" + integrity sha512-abv/qOcuPfk3URPfDzmZU1LKmuw8kT+0nIHvKrKgFrwifol/doWcdA4ZqsWQ8ENrFKkd67Mfpo/LovbIUsbt3w== + +metro-babel-transformer@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-babel-transformer/-/metro-babel-transformer-0.84.5.tgz#38610674043edb8e007139adaf3c13082914f35d" + integrity sha512-2WbHILKMiJUzfdjmGOQOqU1bWi9//gqiclc/tkk/AIsrrVw3efhZ1uhkOwMTxUEPOzqoo091H0olLmVZH5FHGQ== + dependencies: + "@babel/core" "^7.25.2" + flow-enums-runtime "^0.0.6" + hermes-parser "0.35.0" + metro-cache-key "0.84.5" + nullthrows "^1.1.1" + +metro-cache-key@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-cache-key/-/metro-cache-key-0.84.5.tgz#f4eea64f8a78ad626c335493fc8d0edce65f9b7d" + integrity sha512-3dPB2TnvGjjf0/9O7AXVQURKXuQNauTZE7WpTGTlR017Gh/B5y0m/2wcqxfveUguHSpu89KhVxCAlr2k/H7uhQ== + dependencies: + flow-enums-runtime "^0.0.6" + +metro-cache@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-cache/-/metro-cache-0.84.5.tgz#cc622b62b6d51b69bd8a2ea3f8a86076f12dc445" + integrity sha512-WHS0n2OxQqtwEjSeQFPePNrMvEFhmQcUQM9cRJMHByWoi/GMWFBEWOf7hVkAM/0KRutAXNbDlSu/cZB6CyxgQQ== + dependencies: + exponential-backoff "^3.1.1" + flow-enums-runtime "^0.0.6" + https-proxy-agent "^7.0.5" + metro-core "0.84.5" + +metro-config@0.84.5, metro-config@^0.84.3: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-config/-/metro-config-0.84.5.tgz#a45b1556bd61393cd4853393ac2b11eefdd7a217" + integrity sha512-zie+uN6oohscowi2S7ByU+wUw6CrT4ZxW9uAbONOObSxx86RGmnIAmjXHLkfmcdYoY7jzOPEbqcI6oeVmqyBQA== + dependencies: + connect "^3.6.5" + flow-enums-runtime "^0.0.6" + jest-validate "^29.7.0" + metro "0.84.5" + metro-cache "0.84.5" + metro-core "0.84.5" + metro-runtime "0.84.5" + yaml "^2.6.1" + +metro-core@0.84.5, metro-core@^0.84.3: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-core/-/metro-core-0.84.5.tgz#8a7c9f7156df82cc2b9cae75504e9546d637bb7e" + integrity sha512-xwm605hCi5Y6eJTTb8ZWo6pkUcoBEIyiQOfkZh5GwtDwUrP9SNhTQZhzJHrBCwwxlf3Ptl/pxWJgQ1rsNYMnrA== + dependencies: + flow-enums-runtime "^0.0.6" + lodash.throttle "^4.1.1" + metro-resolver "0.84.5" + +metro-file-map@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-file-map/-/metro-file-map-0.84.5.tgz#c3d76a90012dbd05a7da461364d8939b407e7f7d" + integrity sha512-mlm/JL8toSbSc2akpKIGmzvrVRSCgZ5vkbycI34oMLoOnLGuLyC8WTyVJ6P0hZG/usDaGwZSl/s9BCRriqjGJA== + dependencies: + debug "^4.4.0" + fb-watchman "^2.0.0" + flow-enums-runtime "^0.0.6" + graceful-fs "^4.2.4" + invariant "^2.2.4" + jest-worker "^29.7.0" + micromatch "^4.0.4" + nullthrows "^1.1.1" + walker "^1.0.7" + +metro-minify-terser@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-minify-terser/-/metro-minify-terser-0.84.5.tgz#796a4986e172537d2b0d08358a96df1dc2428e60" + integrity sha512-BJoFwCEDsYnagPqarayInv2+diCDNDdLlaof/p6s9w4gh+gc9HXYM+pDvsKGKKUumpZswNF3Z/ftTMqKl/5IBg== + dependencies: + flow-enums-runtime "^0.0.6" + terser "^5.15.0" + +metro-resolver@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-resolver/-/metro-resolver-0.84.5.tgz#bc2d8aa10eb9ec9044dec099dc6f4c28f1306f3a" + integrity sha512-VSSnepg1k6LyCwtb6eirWdAWlpKwBG8Rdtsr1mU38rMelFyWgh3/QuMSiZIZAIjwg/fsa8GhW5/FO54CAUPCEA== + dependencies: + flow-enums-runtime "^0.0.6" + +metro-runtime@0.84.5, metro-runtime@^0.84.3: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-runtime/-/metro-runtime-0.84.5.tgz#2c13f2177f5d3951f7f62188c223e84a520ed87c" + integrity sha512-U1m2+d1Pr+JO2/iVXBB2OfXXityz7tqwIorxfrT15IEgaHvpJBq/OHiqnOWPKJbUl3JcxjcdviZZOKk85oK4Qg== + dependencies: + "@babel/runtime" "^7.25.0" + flow-enums-runtime "^0.0.6" + +metro-source-map@0.84.5, metro-source-map@^0.84.3: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-source-map/-/metro-source-map-0.84.5.tgz#1338cc7ca3666dc126eb5ef4b3514a6a8b8b7f05" + integrity sha512-2BtV5L9uPc49F13Gn5wiP6bX/EncqzqTIk2VL/0F/96Vo0YEOjluT/qktQjFODfqGFsucwnh5mPEAl/2jVEfeg== + dependencies: + "@babel/traverse" "^7.29.0" + "@babel/types" "^7.29.0" + flow-enums-runtime "^0.0.6" + invariant "^2.2.4" + metro-symbolicate "0.84.5" + nullthrows "^1.1.1" + ob1 "0.84.5" + source-map "^0.5.6" + vlq "^1.0.0" + +metro-symbolicate@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-symbolicate/-/metro-symbolicate-0.84.5.tgz#dc8224940fc59ed8b934b7ab8b63fc68c081e0bf" + integrity sha512-rQ40zYDAkaWBN9yvjUuAD0ZpzBMZSoKyGYXnb5JrfbKjun7fTvfoLHL3KXFYenBTYZkQtlp4cKSCv/1utxFyOw== + dependencies: + flow-enums-runtime "^0.0.6" + invariant "^2.2.4" + metro-source-map "0.84.5" + nullthrows "^1.1.1" + source-map "^0.5.6" + vlq "^1.0.0" + +metro-transform-plugins@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-transform-plugins/-/metro-transform-plugins-0.84.5.tgz#fab2aa3e5cae11d414c871feae8cafa1c7f746f7" + integrity sha512-+InaSVGaOyt0DyRo4Y/zIdPI6CZwnbNho5LAL23tgmuGwv7fyfkF7kKfPjZcfxXBcoYdTLLFnCfCH/dHSiCqNg== + dependencies: + "@babel/core" "^7.25.2" + "@babel/generator" "^7.29.1" + "@babel/template" "^7.28.6" + "@babel/traverse" "^7.29.0" + flow-enums-runtime "^0.0.6" + nullthrows "^1.1.1" + +metro-transform-worker@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro-transform-worker/-/metro-transform-worker-0.84.5.tgz#57543a44e1054d1adbfa054d1a7a907981c1c455" + integrity sha512-ui1Z8x4s5RL36gMmKLaMMO7O9NNDHNdthEZSCDQHAau3JcAsTaFOK6I+2q4I/kW5u8hSEjJk9L45TXSVJw6g1A== + dependencies: + "@babel/core" "^7.25.2" + "@babel/generator" "^7.29.1" + "@babel/parser" "^7.29.0" + "@babel/types" "^7.29.0" + flow-enums-runtime "^0.0.6" + metro "0.84.5" + metro-babel-transformer "0.84.5" + metro-cache "0.84.5" + metro-cache-key "0.84.5" + metro-minify-terser "0.84.5" + metro-source-map "0.84.5" + metro-transform-plugins "0.84.5" + nullthrows "^1.1.1" + +metro@0.84.5, metro@^0.84.3: + version "0.84.5" + resolved "https://registry.yarnpkg.com/metro/-/metro-0.84.5.tgz#c7402b9a5a80fa22501705e7d121f59d866bf06f" + integrity sha512-r1liLkyFZMVSEMNjU1CJU5pRzs3NdkxHqXS60O25c0rCIqAR+cGk7rPydw/g0WAIKVXojIBIF45yYBPagJGcgw== + dependencies: + "@babel/code-frame" "^7.29.0" + "@babel/core" "^7.25.2" + "@babel/generator" "^7.29.1" + "@babel/parser" "^7.29.0" + "@babel/template" "^7.28.6" + "@babel/traverse" "^7.29.0" + "@babel/types" "^7.29.0" + accepts "^2.0.0" + ci-info "^2.0.0" + connect "^3.6.5" + debug "^4.4.0" + error-stack-parser "^2.0.6" + flow-enums-runtime "^0.0.6" + graceful-fs "^4.2.4" + hermes-parser "0.35.0" + invariant "^2.2.4" + jest-worker "^29.7.0" + jsc-safe-url "^0.2.2" + lodash.throttle "^4.1.1" + metro-babel-transformer "0.84.5" + metro-cache "0.84.5" + metro-cache-key "0.84.5" + metro-config "0.84.5" + metro-core "0.84.5" + metro-file-map "0.84.5" + metro-resolver "0.84.5" + metro-runtime "0.84.5" + metro-source-map "0.84.5" + metro-symbolicate "0.84.5" + metro-transform-plugins "0.84.5" + metro-transform-worker "0.84.5" + mime-types "^3.0.1" + nullthrows "^1.1.1" + serialize-error "^2.1.0" + source-map "^0.5.6" + throat "^5.0.0" + ws "^7.5.10" + yargs "^17.6.2" + +micromatch@^4.0.4: + version "4.0.8" + resolved "https://registry.yarnpkg.com/micromatch/-/micromatch-4.0.8.tgz#d66fa18f3a47076789320b9b1af32bd86d9fa202" + integrity sha512-PXwfBhYu0hBCPw8Dn0E+WDYb7af3dSLVWKi3HGv84IdF4TyFoC0ysxFd0Goxw7nSv4T/PzEJQxsYsEiFCKo2BA== + dependencies: + braces "^3.0.3" + picomatch "^2.3.1" + +mime-db@^1.54.0: + version "1.54.0" + resolved "https://registry.yarnpkg.com/mime-db/-/mime-db-1.54.0.tgz#cddb3ee4f9c64530dff640236661d42cb6a314f5" + integrity sha512-aU5EJuIN2WDemCcAp2vFBfp/m4EAhWJnUNSSw0ixs7/kXbd6Pg64EmwJkNdFhB8aWt1sH2CTXrLxo/iAGV3oPQ== + +mime-types@^3.0.0, mime-types@^3.0.1: + version "3.0.2" + resolved "https://registry.yarnpkg.com/mime-types/-/mime-types-3.0.2.tgz#39002d4182575d5af036ffa118100f2524b2e2ab" + integrity sha512-Lbgzdk0h4juoQ9fCKXW4by0UJqj+nOOrI9MJ1sSj4nI8aI2eo1qmvQEie4VD1glsS250n15LsWsYtCugiStS5A== + dependencies: + mime-db "^1.54.0" + +mime@1.6.0: + version "1.6.0" + resolved "https://registry.yarnpkg.com/mime/-/mime-1.6.0.tgz#32cd9e5c64553bd58d19a568af452acff04981b1" + integrity sha512-x0Vn8spI+wuJ1O6S7gnbaQg8Pxh4NNHb7KSINmEWKiPE4RKOplvijn+NkmYmmRgP68mc70j2EbeTFRsrswaQeg== + +mimic-fn@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/mimic-fn/-/mimic-fn-2.1.0.tgz#7ed2c2ccccaf84d3ffcb7a69b57711fc2083401b" + integrity sha512-OqbOk5oEQeAZ8WXWydlu9HJjz9WVdEIvamMCcXmuqUYjTknH/sqsWvhQ3vgwKFRR1HpjvNBKQ37nbJgYzGqGcg== + +mimic-response@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/mimic-response/-/mimic-response-3.1.0.tgz#2d1d59af9c1b129815accc2c46a022a5ce1fa3c9" + integrity sha512-z0yWI+4FDrrweS8Zmt4Ej5HdJmky15+L2e6Wgn3+iK5fWzb6T3fhNFq2+MeTRb064c6Wr4N/wv0DzQTjNzHNGQ== + +min-indent@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/min-indent/-/min-indent-1.0.1.tgz#a63f681673b30571fbe8bc25686ae746eefa9869" + integrity sha512-I9jwMn07Sy/IwOj3zVkVik2JTvgpaykDZEigL6Rx6N9LbMywwUSMtxET+7lVoDLLd3O3IXwJwvuuns8UB/HeAg== + +minimatch@^10.2.2: + version "10.2.6" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-10.2.6.tgz#fd956bbe0b77241e9f15ac5dccb1c638060968ef" + integrity sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A== + dependencies: + brace-expansion "^5.0.8" + +minimatch@^3.0.4, minimatch@^3.1.1, minimatch@^3.1.5: + version "3.1.5" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-3.1.5.tgz#580c88f8d5445f2bd6aa8f3cadefa0de79fbd69e" + integrity sha512-VgjWUsnnT6n+NUk6eZq77zeFdpW2LWDzP6zFGrCbHXiYNul5Dzqk2HHQ5uFH2DNW5Xbp8+jVzaeNt94ssEEl4w== + dependencies: + brace-expansion "^1.1.7" + +minimatch@^9.0.4: + version "9.0.9" + resolved "https://registry.yarnpkg.com/minimatch/-/minimatch-9.0.9.tgz#9b0cb9fcb78087f6fd7eababe2511c4d3d60574e" + integrity sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg== + dependencies: + brace-expansion "^2.0.2" + +minimist@^1.2.0, minimist@^1.2.3, minimist@^1.2.8: + version "1.2.8" + resolved "https://registry.yarnpkg.com/minimist/-/minimist-1.2.8.tgz#c1a464e7693302e082a075cee0c057741ac4772c" + integrity sha512-2yyAR8qBkN3YuheJanUpWC5U3bb5osDywNB8RzDVlDwDHbocAJveqqj1u8+SVD7jkWT4yvsHCpWqqWqAxb0zCA== + +minipass-collect@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/minipass-collect/-/minipass-collect-2.0.1.tgz#1621bc77e12258a12c60d34e2276ec5c20680863" + integrity sha512-D7V8PO9oaz7PWGLbCACuI1qEOsq7UKfLotx/C0Aet43fCUB/wfQ7DYeq2oR/svFJGYDHPr38SHATeaj/ZoKHKw== + dependencies: + minipass "^7.0.3" + +minipass-fetch@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/minipass-fetch/-/minipass-fetch-4.0.1.tgz#f2d717d5a418ad0b1a7274f9b913515d3e78f9e5" + integrity sha512-j7U11C5HXigVuutxebFadoYBbd7VSdZWggSe64NVdvWNBqGAiXPL2QVCehjmw7lY1oF9gOllYbORh+hiNgfPgQ== + dependencies: + minipass "^7.0.3" + minipass-sized "^1.0.3" + minizlib "^3.0.1" + optionalDependencies: + encoding "^0.1.13" + +minipass-flush@^1.0.5: + version "1.0.7" + resolved "https://registry.yarnpkg.com/minipass-flush/-/minipass-flush-1.0.7.tgz#145c383d5ae294b36030aa80d4e872d08bebcb73" + integrity sha512-TbqTz9cUwWyHS2Dy89P3ocAGUGxKjjLuR9z8w4WUTGAVgEj17/4nhgo2Du56i0Fm3Pm30g4iA8Lcqctc76jCzA== + dependencies: + minipass "^3.0.0" + +minipass-pipeline@^1.2.4: + version "1.2.4" + resolved "https://registry.yarnpkg.com/minipass-pipeline/-/minipass-pipeline-1.2.4.tgz#68472f79711c084657c067c5c6ad93cddea8214c" + integrity sha512-xuIq7cIOt09RPRJ19gdi4b+RiNvDFYe5JH+ggNvBqGqpQXcru3PcRmOZuHBKWK1Txf9+cQ+HMVN4d6z46LZP7A== + dependencies: + minipass "^3.0.0" + +minipass-sized@^1.0.3: + version "1.0.3" + resolved "https://registry.yarnpkg.com/minipass-sized/-/minipass-sized-1.0.3.tgz#70ee5a7c5052070afacfbc22977ea79def353b70" + integrity sha512-MbkQQ2CTiBMlA2Dm/5cY+9SWFEN8pzzOXi6rlM5Xxq0Yqbda5ZQy9sU75a673FE9ZK0Zsbr6Y5iP6u9nktfg2g== + dependencies: + minipass "^3.0.0" + +minipass@^3.0.0: + version "3.3.6" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-3.3.6.tgz#7bba384db3a1520d18c9c0e5251c3444e95dd94a" + integrity sha512-DxiNidxSEK+tHG6zOIklvNOwm3hvCrbUrdtzY74U6HKTJxvIDfOUL5W5P2Ghd3DTkhhKPYGqeNUIh5qcM4YBfw== + dependencies: + yallist "^4.0.0" + +"minipass@^5.0.0 || ^6.0.2 || ^7.0.0", minipass@^7.0.2, minipass@^7.0.3, minipass@^7.0.4, minipass@^7.1.2: + version "7.1.3" + resolved "https://registry.yarnpkg.com/minipass/-/minipass-7.1.3.tgz#79389b4eb1bb2d003a9bba87d492f2bd37bdc65b" + integrity sha512-tEBHqDnIoM/1rXME1zgka9g6Q2lcoCkxHLuc7ODJ5BxbP5d4c2Z5cGgtXAku59200Cx7diuHTOYfSBD8n6mm8A== + +minizlib@^3.0.1, minizlib@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/minizlib/-/minizlib-3.1.0.tgz#6ad76c3a8f10227c9b51d1c9ac8e30b27f5a251c" + integrity sha512-KZxYo1BUkWD2TVFLr0MQoM8vUUigWD3LlD83a/75BqC+4qE0Hb1Vo5v1FgcfaNXvfXzr+5EhQ6ing/CaBijTlw== + dependencies: + minipass "^7.1.2" + +mkdirp-classic@^0.5.2, mkdirp-classic@^0.5.3: + version "0.5.3" + resolved "https://registry.yarnpkg.com/mkdirp-classic/-/mkdirp-classic-0.5.3.tgz#fa10c9115cc6d8865be221ba47ee9bed78601113" + integrity sha512-gKLcREMhtuZRwRAfqP3RFW+TK4JqApVBtOIftVgjuABpAtpxhPGaDcfvbhNvD0B8iD1oUr/txX35NjcaY6Ns/A== + +mkdirp@^1.0.4: + version "1.0.4" + resolved "https://registry.yarnpkg.com/mkdirp/-/mkdirp-1.0.4.tgz#3eb5ed62622756d79a5f0e2a221dfebad75c2f7e" + integrity sha512-vVqVZQyf3WLx2Shd0qJ9xuvqgAyKPLAiqITEtqW0oIUjzo3PePDd6fW9iFz30ef7Ysp/oiWqbhszeGWW2T6Gzw== + +moo@^0.5.0: + version "0.5.3" + resolved "https://registry.yarnpkg.com/moo/-/moo-0.5.3.tgz#dfcdb40ff6f1a03c34af5df7f9717cecfa88c38c" + integrity sha512-m2fmM2dDm7GZQsY7KK2cme8agi+AAljILjQnof7p1ZMDe6dQ4bdnSMx0cPppudoeNv5hEFQirN6u+O4fDE0IWA== + +ms@2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.0.0.tgz#5608aeadfc00be6c2901df5f9861788de0d597c8" + integrity sha512-Tpp60P6IUJDTuOq/5Z8cdskzJujfwqfOTkrwIwj7IRISpnkJnT6SyJ4PCPnGMoFjC9ddhal5KVIYtAt97ix05A== + +ms@2.1.3, ms@^2.1.3: + version "2.1.3" + resolved "https://registry.yarnpkg.com/ms/-/ms-2.1.3.tgz#574c8138ce1d2b5861f0b44579dbadd60c6615b2" + integrity sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA== + +nan@~2.22.2: + version "2.22.2" + resolved "https://registry.yarnpkg.com/nan/-/nan-2.22.2.tgz#6b504fd029fb8f38c0990e52ad5c26772fdacfbb" + integrity sha512-DANghxFkS1plDdRsX0X9pm0Z6SJNN6gBdtXfanwoZ8hooC5gosGFSBGRYHUVPz1asKA/kMRqDRdHrluZ61SpBQ== + +napi-build-utils@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/napi-build-utils/-/napi-build-utils-2.0.0.tgz#13c22c0187fcfccce1461844136372a47ddc027e" + integrity sha512-GEbrYkbfF7MoNaoh2iGG84Mnf/WZfB0GdGEsM8wz7Expx/LlWf5U8t9nvJKXSp3qr5IsEbK04cBGhol/KwOsWA== + +natural-compare@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/natural-compare/-/natural-compare-1.4.0.tgz#4abebfeed7541f2c27acfb29bdbbd15c8d5ba4f7" + integrity sha512-OWND8ei3VtNC9h7V60qff3SVobHr996CTwgxubgyQYEpg290h9J0buyECNNJexkFm5sOajh5G116RYA1c8ZMSw== + +nearley@^2.20.1: + version "2.20.1" + resolved "https://registry.yarnpkg.com/nearley/-/nearley-2.20.1.tgz#246cd33eff0d012faf197ff6774d7ac78acdd474" + integrity sha512-+Mc8UaAebFzgV+KpI5n7DasuuQCHA89dmwm7JXw3TV43ukfNQ9DnBH3Mdb2g/I4Fdxc26pwimBWvjIw0UAILSQ== + dependencies: + commander "^2.19.0" + moo "^0.5.0" + railroad-diagrams "^1.0.0" + randexp "0.4.6" + +negotiator@^1.0.0: + version "1.1.0" + resolved "https://registry.yarnpkg.com/negotiator/-/negotiator-1.1.0.tgz#16e003d0db4ac24fd9df168edf871625deeae3df" + integrity sha512-NMPBRMJgiQHjbd8phG3Vebdx4kZ1H121rbl5IkMqeOsahptB9BKo/d7oJ3zTXqTgagn2bWlNSXkh0QUGM31RYg== + dependencies: + content-type "^2.1.0" + +neo-async@^2.6.2: + version "2.6.2" + resolved "https://registry.yarnpkg.com/neo-async/-/neo-async-2.6.2.tgz#b4aafb93e3aeb2d8174ca53cf163ab7d7308305f" + integrity sha512-Yd3UES5mWCSqR+qNT93S3UoYUkqAZ9lLg8a7g9rimsWmYGK8cVToA4/sF3RrshdyV3sAGMXVUmpMYOw+dLpOuw== + +node-abi@^3.3.0: + version "3.96.0" + resolved "https://registry.yarnpkg.com/node-abi/-/node-abi-3.96.0.tgz#8b038bc6cca97d6cec2e9aafdb81b900da1ff80d" + integrity sha512-rebQ/lz7i0EkoLzUVSrKRzA69zMkwLp95kKMWoMDkkM00Suxz0D7zEQPwRml5fQum24mj7bPvmlgLAmu2JCiYg== + dependencies: + semver "^7.3.5" + +node-gyp@^11.2.0: + version "11.5.0" + resolved "https://registry.yarnpkg.com/node-gyp/-/node-gyp-11.5.0.tgz#82661b5f40647a7361efe918e3cea76d297fcc56" + integrity sha512-ra7Kvlhxn5V9Slyus0ygMa2h+UqExPqUIkfk7Pc8QTLT956JLSy51uWFwHtIYy0vI8cB4BDhc/S03+880My/LQ== + dependencies: + env-paths "^2.2.0" + exponential-backoff "^3.1.1" + graceful-fs "^4.2.6" + make-fetch-happen "^14.0.3" + nopt "^8.0.0" + proc-log "^5.0.0" + semver "^7.3.5" + tar "^7.4.3" + tinyglobby "^0.2.12" + which "^5.0.0" + +node-int64@^0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/node-int64/-/node-int64-0.4.0.tgz#87a9065cdb355d3182d8f94ce11188b825c68a3b" + integrity sha512-O5lz91xSOeoXP6DulyHfllpq+Eg00MWitZIbtPfoSEvqIHdl5gfcY6hYzDWnj0qD5tz52PI08u9qUvSVeUBeHw== + +node-releases@^2.0.53: + version "2.0.53" + resolved "https://registry.yarnpkg.com/node-releases/-/node-releases-2.0.53.tgz#0fe5ad8a7935e075172f574e56f0c20f07fa41af" + integrity sha512-D9UOmYG3UH1V+ENW56t5QXBwJw1YEY18ruVeus89Rw+SyIgjPkCO84bRzO3uNIYosJbNwiabWVn48o3uJLjxFQ== + +nopt@^8.0.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/nopt/-/nopt-8.1.0.tgz#b11d38caf0f8643ce885818518064127f602eae3" + integrity sha512-ieGu42u/Qsa4TFktmaKEwM6MQH0pOWnaB3htzh0JRtx84+Mebc0cbZYN5bC+6WTZ4+77xrL9Pn5m7CV6VIkV7A== + dependencies: + abbrev "^3.0.0" + +"normalize-package-data@^7.0.0 || ^8.0.0": + version "8.0.0" + resolved "https://registry.yarnpkg.com/normalize-package-data/-/normalize-package-data-8.0.0.tgz#bdce7ff2d6ba891b853e179e45a5337766e304a7" + integrity sha512-RWk+PI433eESQ7ounYxIp67CYuVsS1uYSonX3kA6ps/3LWfjVQa/ptEg6Y3T6uAMq1mWpX9PQ+qx+QaHpsc7gQ== + dependencies: + hosted-git-info "^9.0.0" + semver "^7.3.5" + validate-npm-package-license "^3.0.4" + +normalize-path@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/normalize-path/-/normalize-path-3.0.0.tgz#0dcd69ff23a1c9b11fd0978316644a0388216a65" + integrity sha512-6eZs5Ls3WtCisHWp9S2GUy8dqkpGi4BVSz3GaqiE6ezub0512ESztXUwUB6C6IKbQkY2Pnb/mD4WYojCRwcwLA== + +npm-run-path@^4.0.1: + version "4.0.1" + resolved "https://registry.yarnpkg.com/npm-run-path/-/npm-run-path-4.0.1.tgz#b7ecd1e5ed53da8e37a55e1c2269e0b97ed748ea" + integrity sha512-S48WzZW777zhNIrn7gxOlISNAqi9ZC/uQFnRdbeIHhZhCA6UqpkOT8T1G7BvfdgP4Er8gF4sUbaS0i7QvIfCWw== + dependencies: + path-key "^3.0.0" + +nullthrows@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/nullthrows/-/nullthrows-1.1.1.tgz#7818258843856ae971eae4208ad7d7eb19a431b1" + integrity sha512-2vPPEi+Z7WqML2jZYddDIfy5Dqb0r2fze2zTxNNknZaFpVHU3mFB3R+DWeJWGVx0ecvttSGlJTI+WG+8Z4cDWw== + +ob1@0.84.5: + version "0.84.5" + resolved "https://registry.yarnpkg.com/ob1/-/ob1-0.84.5.tgz#5b103040a271723e555f77be3d54aaf4c32d9db5" + integrity sha512-aH9RkoZc7w/90HBamFxTw8ZLFr05wXS+iOnvmrgo53Ep8Pyrm5FieQSaPIVROkfFVQISeD/zo92fes26TOwe+A== + dependencies: + flow-enums-runtime "^0.0.6" + +on-finished@~2.3.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.3.0.tgz#20f1336481b083cd75337992a16971aa2d906947" + integrity sha512-ikqdkGAAyf/X/gPhXGvfgAytDZtDbr+bkNUJ0N9h5MI/dmdgCs3l6hoHrcUv41sRKew3jIwrp4qQDXiK99Utww== + dependencies: + ee-first "1.1.1" + +on-finished@~2.4.1: + version "2.4.1" + resolved "https://registry.yarnpkg.com/on-finished/-/on-finished-2.4.1.tgz#58c8c44116e54845ad57f14ab10b03533184ac3f" + integrity sha512-oVlzkg3ENAhCk2zdv7IJwd/QUD4z2RxRwpkcGY8psCVcCYZNq4wYnVWALHM+brtuJjePWiYF/ClmuDr8Ch5+kg== + dependencies: + ee-first "1.1.1" + +once@^1.3.0, once@^1.3.1, once@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/once/-/once-1.4.0.tgz#583b1aa775961d4b113ac17d9c50baef9dd76bd1" + integrity sha512-lNaJgI+2Q5URQBkccEKHTQOPaXdUxnZZElQTZY0MFUAuaEqe1E+Nyvgdz/aIyNi6Z9MzO5dv1H8n58/GELp3+w== + dependencies: + wrappy "1" + +onetime@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/onetime/-/onetime-5.1.2.tgz#d0e96ebb56b07476df1dd9c4806e5237985ca45e" + integrity sha512-kbpaSSGJTWdAY5KPVeMOKXSrPtr8C8C7wodJbcsd51jRnmD+GZu8Y0VoU6Dm5Z4vWr0Ig/1NKuWRKf7j5aaYSg== + dependencies: + mimic-fn "^2.1.0" + +open@^7.0.3: + version "7.4.2" + resolved "https://registry.yarnpkg.com/open/-/open-7.4.2.tgz#b8147e26dcf3e426316c730089fd71edd29c2321" + integrity sha512-MVHddDVweXZF3awtlAS+6pgKLlm/JgxZ90+/NBurBoQctVOOB/zDdVjcyPzQ+0laDGbsWgrRkflI65sQeOgT9Q== + dependencies: + is-docker "^2.0.0" + is-wsl "^2.1.1" + +optionator@^0.9.3: + version "0.9.4" + resolved "https://registry.yarnpkg.com/optionator/-/optionator-0.9.4.tgz#7ea1c1a5d91d764fb282139c88fe11e182a3a734" + integrity sha512-6IpQ7mKUxRcZNLIObR0hz7lxsapSSIYNZJwXPGeF0mTVqGKFIXj1DQcMoT22S3ROcLyY/rz0PWaWZ9ayWmad9g== + dependencies: + deep-is "^0.1.3" + fast-levenshtein "^2.0.6" + levn "^0.4.1" + prelude-ls "^1.2.1" + type-check "^0.4.0" + word-wrap "^1.2.5" + +p-limit@^2.2.0: + version "2.3.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-2.3.0.tgz#3dd33c647a214fdfffd835933eb086da0dc21db1" + integrity sha512-//88mFWSJx8lxCzwdAABTJL2MyWB12+eIY7MDL2SqLmAkeKU9qxRvWuSyTjm3FUmpBEMuFfckAIqEaVGUDxb6w== + dependencies: + p-try "^2.0.0" + +p-limit@^3.0.2, p-limit@^3.1.0: + version "3.1.0" + resolved "https://registry.yarnpkg.com/p-limit/-/p-limit-3.1.0.tgz#e1daccbe78d0d1388ca18c64fea38e3e57e3706b" + integrity sha512-TYOanM3wGwNGsZN2cVTYPArw454xnXj5qmWF1bEoAc4+cU/ol7GVh7odevjp1FNHduHc3KZMcFduxU5Xc6uJRQ== + dependencies: + yocto-queue "^0.1.0" + +p-locate@^4.1.0: + version "4.1.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-4.1.0.tgz#a3428bb7088b3a60292f66919278b7c297ad4f07" + integrity sha512-R79ZZ/0wAxKGu3oYMlz8jy/kbhsNrS7SKZ7PxEHBgJ5+F2mtFW2fK2cOtBh1cHYkQsbzFV7I+EoRKe6Yt0oK7A== + dependencies: + p-limit "^2.2.0" + +p-locate@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/p-locate/-/p-locate-5.0.0.tgz#83c8315c6785005e3bd021839411c9e110e6d834" + integrity sha512-LaNjtRWUBY++zB5nE/NwcaoMylSPk+S+ZHNB1TzdbMJMny6dynpAGt7X/tl/QYq3TIeE6nxHppbo2LGymrG5Pw== + dependencies: + p-limit "^3.0.2" + +p-map@^7.0.2: + version "7.0.8" + resolved "https://registry.yarnpkg.com/p-map/-/p-map-7.0.8.tgz#e2ce27eff78cd934a78908a3cede58330a3a5543" + integrity sha512-MitaVsCuCFIvOLLPIU7NnfrZvS9H9h7kwMUkDo+T2pEISaJD48IV9S8iIdXB7PsvvdxyYcsSTTrr90XKsbulNw== + +p-try@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/p-try/-/p-try-2.2.0.tgz#cb2868540e313d61de58fafbe35ce9004d5540e6" + integrity sha512-R4nPAVTAU0B9D35/Gk3uJf/7XYbQcyohSKdvAxIRSNghFl4e71hVoGnBNQz9cWaXxO2I10KTC+3jMdvvoKw6dQ== + +package-json-from-dist@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/package-json-from-dist/-/package-json-from-dist-1.0.1.tgz#4f1471a010827a86f94cfd9b0727e36d267de505" + integrity sha512-UEZIS3/by4OC8vL3P2dTXRETpebLI2NiI5vIrjaD/5UtrkFX/tNbwjTSRAGC/+7CAo2pIcBaRgWmcBBHcsaCIw== + +packageurl-js@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/packageurl-js/-/packageurl-js-2.0.1.tgz#a8fa43a64971b5dd0dca5fb904b950a6cc317a6f" + integrity sha512-N5ixXjzTy4QDQH0Q9YFjqIWd6zH6936Djpl2m9QNFmDv5Fum8q8BjkpAcHNMzOFE0IwQrFhJWex3AN6kS0OSwg== + +parent-module@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/parent-module/-/parent-module-1.0.1.tgz#691d2709e78c79fae3a156622452d00762caaaa2" + integrity sha512-GQ2EWRpQV8/o+Aw8YqtfZZPfNRWZYkbidE9k5rpl/hC3vtHHBfGm2Ifi6qWV+coDGkrUKZAxE3Lot5kcsRlh+g== + dependencies: + callsites "^3.0.0" + +parse-json@^5.2.0: + version "5.2.0" + resolved "https://registry.yarnpkg.com/parse-json/-/parse-json-5.2.0.tgz#c76fc66dee54231c962b22bcc8a72cf2f99753cd" + integrity sha512-ayCKvm/phCGxOkYRSCM82iDwct8/EonSEgCSxWxD7ve6jHggsFl4fZVQBPRNgQoKiuV/odhFrGzQXZwbifC8Rg== + dependencies: + "@babel/code-frame" "^7.0.0" + error-ex "^1.3.1" + json-parse-even-better-errors "^2.3.0" + lines-and-columns "^1.1.6" + +parseurl@~1.3.3: + version "1.3.3" + resolved "https://registry.yarnpkg.com/parseurl/-/parseurl-1.3.3.tgz#9da19e7bee8d12dff0513ed5b76957793bc2e8d4" + integrity sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ== + +path-exists@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/path-exists/-/path-exists-4.0.0.tgz#513bdbe2d3b95d7762e8c1137efa195c6c61b5b3" + integrity sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w== + +path-is-absolute@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/path-is-absolute/-/path-is-absolute-1.0.1.tgz#174b9268735534ffbc7ace6bf53a5a9e1b5c5f5f" + integrity sha512-AVbw3UJ2e9bq64vSaS9Am0fje1Pa8pbGqTTsmXfaIiMpnr5DlDhfJOuLj9Sf95ZPVDAUerDfEk88MPmPe7UCQg== + +path-key@^3.0.0, path-key@^3.1.0: + version "3.1.1" + resolved "https://registry.yarnpkg.com/path-key/-/path-key-3.1.1.tgz#581f6ade658cbba65a0d3380de7753295054f375" + integrity sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q== + +path-parse@^1.0.7: + version "1.0.7" + resolved "https://registry.yarnpkg.com/path-parse/-/path-parse-1.0.7.tgz#fbc114b60ca42b30d9daf5858e4bd68bbedb6735" + integrity sha512-LDJzPVEEEPR+y48z93A0Ed0yXb8pAByGWo/k5YYdYgpY2/2EsOsksJrq7lOHxryrVOn1ejG6oAp8ahvOIQD8sw== + +path-scurry@^1.11.1: + version "1.11.1" + resolved "https://registry.yarnpkg.com/path-scurry/-/path-scurry-1.11.1.tgz#7960a668888594a0720b12a911d1a742ab9f11d2" + integrity sha512-Xa4Nw17FS9ApQFJ9umLiJS4orGjm7ZzwUrwamcGQuHSzDyth9boKDaycYdDcZDuqYATXw4HFXgaqWTctW/v1HA== + dependencies: + lru-cache "^10.2.0" + minipass "^5.0.0 || ^6.0.2 || ^7.0.0" + +picocolors@^1.1.1: + version "1.1.1" + resolved "https://registry.yarnpkg.com/picocolors/-/picocolors-1.1.1.tgz#3d321af3eab939b083c8f929a1d12cda81c26b6b" + integrity sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA== + +picomatch@^2.0.4, picomatch@^2.2.3, picomatch@^2.3.1: + version "2.3.2" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-2.3.2.tgz#5a942915e26b372dc0f0e6753149a16e6b1c5601" + integrity sha512-V7+vQEJ06Z+c5tSye8S+nHUfI51xoXIXjHQ99cQtKUkQqqO1kO/KCJUfZXuB47h/YBlDhah2H3hdUGXn8ie0oA== + +picomatch@^4.0.4: + version "4.0.5" + resolved "https://registry.yarnpkg.com/picomatch/-/picomatch-4.0.5.tgz#51ea57a17d86f605f81039595fbc40ed06a55fab" + integrity sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A== + +pirates@^4.0.4: + version "4.0.7" + resolved "https://registry.yarnpkg.com/pirates/-/pirates-4.0.7.tgz#643b4a18c4257c8a65104b73f3049ce9a0a15e22" + integrity sha512-TfySrs/5nm8fQJDcBDuUng3VOUKsd7S+zqvbOTiGXHfxX4wK31ard+hoNuvkicM/2YFzlpDgABOevKSsB4G/FA== + +pkg-dir@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/pkg-dir/-/pkg-dir-4.2.0.tgz#f099133df7ede422e81d1d8448270eeb3e4261f3" + integrity sha512-HRDzbaKjC+AOWVXxAU/x54COGeIv9eb+6CkDSQoNTt4XyWoIJvuPsXizxu/Fr23EiekbtZwmh1IcIG/l/a10GQ== + dependencies: + find-up "^4.0.0" + +prebuild-install@^7.1.3: + version "7.1.3" + resolved "https://registry.yarnpkg.com/prebuild-install/-/prebuild-install-7.1.3.tgz#d630abad2b147443f20a212917beae68b8092eec" + integrity sha512-8Mf2cbV7x1cXPUILADGI3wuhfqWvtiLA1iclTDbFRZkgRQS0NqsPZphna9V+HyTEadheuPmjaJMsbzKQFOzLug== + dependencies: + detect-libc "^2.0.0" + expand-template "^2.0.3" + github-from-package "0.0.0" + minimist "^1.2.3" + mkdirp-classic "^0.5.3" + napi-build-utils "^2.0.0" + node-abi "^3.3.0" + pump "^3.0.0" + rc "^1.2.7" + simple-get "^4.0.0" + tar-fs "^2.0.0" + tunnel-agent "^0.6.0" + +prelude-ls@^1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/prelude-ls/-/prelude-ls-1.2.1.tgz#debc6489d7a6e6b0e7611888cec880337d316396" + integrity sha512-vkcDPrRZo1QZLbn5RLGPpg/WmIQ65qoWWhcGKf/b5eplkkarX0m9z8ppCat4mlOqUsWpyNuYgO3VRyrYHSzX5g== + +prettier@^3.6.2: + version "3.9.6" + resolved "https://registry.yarnpkg.com/prettier/-/prettier-3.9.6.tgz#b3ea5146515d40fc53f18aa63f74dfab1e10dbf6" + integrity sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g== + +pretty-format@30.4.1, pretty-format@^30.4.1: + version "30.4.1" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-30.4.1.tgz#0911652e92e1e91f475e3e6a16e628e50649ea69" + integrity sha512-K6KiKMHTL4jjX4u3Kir2EW07nRfcqVTXIImx50wbjHQTcZPgg+gjVeNTIT3l3L1Rd4UefxfogquC9J37SoFyyw== + dependencies: + "@jest/schemas" "30.4.1" + ansi-styles "^5.2.0" + react-is-18 "npm:react-is@^18.3.1" + react-is-19 "npm:react-is@^19.2.5" + +pretty-format@^29.0.0, pretty-format@^29.7.0: + version "29.7.0" + resolved "https://registry.yarnpkg.com/pretty-format/-/pretty-format-29.7.0.tgz#ca42c758310f365bfa71a0bda0a807160b776812" + integrity sha512-Pdlw/oPxN+aXdmM9R00JVC9WVFoCLTKJvDVLgmJ+qAffBMxsV85l/Lu7sNx4zSzPyoL2euImuEwHhOXdEgNFZQ== + dependencies: + "@jest/schemas" "^29.6.3" + ansi-styles "^5.0.0" + react-is "^18.0.0" + +proc-log@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/proc-log/-/proc-log-5.0.0.tgz#e6c93cf37aef33f835c53485f314f50ea906a9d8" + integrity sha512-Azwzvl90HaF0aCz1JrDdXQykFakSSNPaPoiZ9fm5qJIMHioDZEi7OAdRwSm6rSoPtY3Qutnm3L7ogmg3dc+wbQ== + +promise-retry@^2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/promise-retry/-/promise-retry-2.0.1.tgz#ff747a13620ab57ba688f5fc67855410c370da22" + integrity sha512-y+WKFlBR8BGXnsNlIHFGPZmyDf3DFMoLhaflAnyZgV6rG6xu+JwesTo2Q9R6XwYmtmwAFCkAk3e35jEdoeh/3g== + dependencies: + err-code "^2.0.2" + retry "^0.12.0" + +promise@^8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/promise/-/promise-8.3.0.tgz#8cb333d1edeb61ef23869fbb8a4ea0279ab60e0a" + integrity sha512-rZPNPKTOYVNEEKFaq1HqTgOwZD+4/YHS5ukLzQCypkj+OkYx7iv0mA91lJlpPPZ8vMau3IIGj5Qlwrx+8iiSmg== + dependencies: + asap "~2.0.6" + +prompts@^2.0.1: + version "2.4.2" + resolved "https://registry.yarnpkg.com/prompts/-/prompts-2.4.2.tgz#7b57e73b3a48029ad10ebd44f74b01722a4cb069" + integrity sha512-NxNv/kLguCA7p3jE8oL2aEBsrJWgAakBpgmgK6lpPWV+WuOmY6r2/zbAVnP+T8bQlA0nzHXSJSJW0Hq7ylaD2Q== + dependencies: + kleur "^3.0.3" + sisteransi "^1.0.5" + +pump@^3.0.0: + version "3.0.4" + resolved "https://registry.yarnpkg.com/pump/-/pump-3.0.4.tgz#1f313430527fa8b905622ebd22fe1444e757ab3c" + integrity sha512-VS7sjc6KR7e1ukRFhQSY5LM2uBWAUPiOPa/A3mkKmiMwSmRFUITt0xuj+/lesgnCv+dPIEYlkzrcyXgquIHMcA== + dependencies: + end-of-stream "^1.1.0" + once "^1.3.1" + +punycode@^2.1.0, punycode@^2.1.1: + version "2.3.1" + resolved "https://registry.yarnpkg.com/punycode/-/punycode-2.3.1.tgz#027422e2faec0b25e1549c3e1bd8309b9133b6e5" + integrity sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg== + +pure-rand@^6.0.0: + version "6.1.0" + resolved "https://registry.yarnpkg.com/pure-rand/-/pure-rand-6.1.0.tgz#d173cf23258231976ccbdb05247c9787957604f2" + integrity sha512-bVWawvoZoBYpp6yIoQtQXHZjmz35RSVHnUOTefl8Vcjr8snTPY1wnpSPMWekcFwbxI6gtmT7rSYPFvz71ldiOA== + +railroad-diagrams@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/railroad-diagrams/-/railroad-diagrams-1.0.0.tgz#eb7e6267548ddedfb899c1b90e57374559cddb7e" + integrity sha512-cz93DjNeLY0idrCNOH6PviZGRN9GJhsdm9hpn1YCS879fj4W+x5IFJhhkRZcwVgMmFF7R82UA/7Oh+R8lLZg6A== + +randexp@0.4.6: + version "0.4.6" + resolved "https://registry.yarnpkg.com/randexp/-/randexp-0.4.6.tgz#e986ad5e5e31dae13ddd6f7b3019aa7c87f60ca3" + integrity sha512-80WNmd9DA0tmZrw9qQa62GPPWfuXJknrmVmLcxvq4uZBdYqb1wYoKTmnlGUchvVWe0XiLupYkBoXVOxz3C8DYQ== + dependencies: + discontinuous-range "1.0.0" + ret "~0.1.10" + +range-parser@~1.2.1: + version "1.2.1" + resolved "https://registry.yarnpkg.com/range-parser/-/range-parser-1.2.1.tgz#3cf37023d199e1c24d1a55b84800c2f3e6468031" + integrity sha512-Hrgsx+orqoygnmhFbKaHE6c296J+HTAQXoxEF6gNupROmmGJRoyzfG3ccAveqCBrwr/2yxQ5BVd/GTl5agOwSg== + +rc@^1.2.7: + version "1.2.8" + resolved "https://registry.yarnpkg.com/rc/-/rc-1.2.8.tgz#cd924bf5200a075b83c188cd6b9e211b7fc0d3ed" + integrity sha512-y3bGgqKj3QBdxLbLkomlohkvsA8gdAiUQlSBJnBhfn+BPxg4bc62d8TcBW15wavDfgexCgccckhcZvywyQYPOw== + dependencies: + deep-extend "^0.6.0" + ini "~1.3.0" + minimist "^1.2.0" + strip-json-comments "~2.0.1" + +react-devtools-core@^6.1.5: + version "6.1.5" + resolved "https://registry.yarnpkg.com/react-devtools-core/-/react-devtools-core-6.1.5.tgz#c5eca79209dab853a03b2158c034c5166975feee" + integrity sha512-ePrwPfxAnB+7hgnEr8vpKxL9cmnp7F322t8oqcPshbIQQhDKgFDW4tjhF2wjVbdXF9O/nyuy3sQWd9JGpiLPvA== + dependencies: + shell-quote "^1.6.1" + ws "^7" + +"react-is-18@npm:react-is@^18.3.1": + version "18.3.1" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e" + integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg== + +"react-is-19@npm:react-is@^19.2.5": + version "19.2.8" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-19.2.8.tgz#09826f9fbc187bc668e3e5c62edc001f804d5018" + integrity sha512-s5un28nYxKJw5gvUHyW5PCC28CvBqLu9r3cWgzHT4Vo/5fqqkFcdRYsGcKf50WMPpjjFZS5d76fn3YCo2njKwQ== + +react-is@^18.0.0: + version "18.3.1" + resolved "https://registry.yarnpkg.com/react-is/-/react-is-18.3.1.tgz#e83557dc12eae63a99e003a46388b1dcbb44db7e" + integrity sha512-/LLMVyas0ljjAtoYiPqYiL8VWXzUUdThrmU5+n20DZv+a+ClRoevUzw5JxU+Ieh5/c87ytoTBV9G1FiKfNJdmg== + +react-native-persona@2.48.0: + version "2.48.0" + resolved "https://registry.yarnpkg.com/react-native-persona/-/react-native-persona-2.48.0.tgz#5f1f14fe831dcb13151573e7b3f56af90b594c94" + integrity sha512-xTQ3QQm5qafrKghj+2ALXVnyVIF1qmfac3sctTVpYEiVkrIls1QUslJlXITSjYGYYdyNyLtm4BpaF/72+Jhf9g== + +react-native@0.85.3: + version "0.85.3" + resolved "https://registry.yarnpkg.com/react-native/-/react-native-0.85.3.tgz#4a3d25c63a2fd320ffb093e20269cf47d585d483" + integrity sha512-HN/fGC+3nZVcDNcw7gfbM/DuqZAvI9Mz+/SxuhODaua4JY0BPzhfTzWXRyTR4mRgMHmShTPpH2PYMTxvZrsdZA== + dependencies: + "@react-native/assets-registry" "0.85.3" + "@react-native/codegen" "0.85.3" + "@react-native/community-cli-plugin" "0.85.3" + "@react-native/gradle-plugin" "0.85.3" + "@react-native/js-polyfills" "0.85.3" + "@react-native/normalize-colors" "0.85.3" + "@react-native/virtualized-lists" "0.85.3" + abort-controller "^3.0.0" + anser "^1.4.9" + ansi-regex "^5.0.0" + babel-plugin-syntax-hermes-parser "0.33.3" + base64-js "^1.5.1" + commander "^12.0.0" + flow-enums-runtime "^0.0.6" + hermes-compiler "250829098.0.10" + invariant "^2.2.4" + memoize-one "^5.0.0" + metro-runtime "^0.84.3" + metro-source-map "^0.84.3" + nullthrows "^1.1.1" + pretty-format "^29.7.0" + promise "^8.3.0" + react-devtools-core "^6.1.5" + react-refresh "^0.14.0" + regenerator-runtime "^0.13.2" + scheduler "0.27.0" + semver "^7.1.3" + stacktrace-parser "^0.1.10" + tinyglobby "^0.2.15" + whatwg-fetch "^3.0.0" + ws "^7.5.10" + yargs "^17.6.2" + +react-reconciler@~0.33.0: + version "0.33.0" + resolved "https://registry.yarnpkg.com/react-reconciler/-/react-reconciler-0.33.0.tgz#9dd20208d45baa5b0b4701781f858236657f15e1" + integrity sha512-KetWRytFv1epdpJc3J4G75I4WrplZE5jOL7Yq0p34+OVOKF4Se7WrdIdVC45XsSSmUTlht2FM/fM1FZb1mfQeA== + dependencies: + scheduler "^0.27.0" + +react-refresh@^0.14.0: + version "0.14.2" + resolved "https://registry.yarnpkg.com/react-refresh/-/react-refresh-0.14.2.tgz#3833da01ce32da470f1f936b9d477da5c7028bf9" + integrity sha512-jCvmsr+1IUSMUyzOkRcvnVbX3ZYC6g9TDrDbFuFmRDq7PD4yaGbLKNQL6k2jnArV8hjYxh7hVhAZB6s9HDGpZA== + +react@19.2.3: + version "19.2.3" + resolved "https://registry.yarnpkg.com/react/-/react-19.2.3.tgz#d83e5e8e7a258cf6b4fe28640515f99b87cd19b8" + integrity sha512-Ku/hhYbVjOQnXDZFv2+RibmLFGwFdeeKHFcOTlrt7xplBnya5OGn/hIRDsqDiSUcfORsDC7MPxwork8jBwsIWA== + +readable-stream@^3.1.1, readable-stream@^3.4.0: + version "3.6.2" + resolved "https://registry.yarnpkg.com/readable-stream/-/readable-stream-3.6.2.tgz#56a9b36ea965c00c5a93ef31eb111a0f11056967" + integrity sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA== + dependencies: + inherits "^2.0.3" + string_decoder "^1.1.1" + util-deprecate "^1.0.1" + +redent@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/redent/-/redent-3.0.0.tgz#e557b7998316bb53c9f1f56fa626352c6963059f" + integrity sha512-6tDA8g98We0zd0GvVeMT9arEOnTw9qM03L9cJXaCjrip1OO764RDBLBfrB4cwzNGDj5OA5ioymC9GkizgWJDUg== + dependencies: + indent-string "^4.0.0" + strip-indent "^3.0.0" + +regenerate-unicode-properties@^10.2.2: + version "10.2.2" + resolved "https://registry.yarnpkg.com/regenerate-unicode-properties/-/regenerate-unicode-properties-10.2.2.tgz#aa113812ba899b630658c7623466be71e1f86f66" + integrity sha512-m03P+zhBeQd1RGnYxrGyDAPpWX/epKirLrp8e3qevZdVkKtnCrjjWczIbYc8+xd6vcTStVlqfycTx1KR4LOr0g== + dependencies: + regenerate "^1.4.2" + +regenerate@^1.4.2: + version "1.4.2" + resolved "https://registry.yarnpkg.com/regenerate/-/regenerate-1.4.2.tgz#b9346d8827e8f5a32f7ba29637d398b69014848a" + integrity sha512-zrceR/XhGYU/d/opr2EKO7aRHUeiBI8qjtfHqADTwZd6Szfy16la6kqD0MIUs5z5hx6AaKa+PixpPrR289+I0A== + +regenerator-runtime@^0.13.2: + version "0.13.11" + resolved "https://registry.yarnpkg.com/regenerator-runtime/-/regenerator-runtime-0.13.11.tgz#f6dca3e7ceec20590d07ada785636a90cdca17f9" + integrity sha512-kY1AZVr2Ra+t+piVaJ4gxaFaReZVH40AKNo7UCX6W+dEwBo/2oZJzqfuN1qLq1oL45o56cPaTXELwrTh8Fpggg== + +regexpu-core@^6.3.1: + version "6.4.0" + resolved "https://registry.yarnpkg.com/regexpu-core/-/regexpu-core-6.4.0.tgz#3580ce0c4faedef599eccb146612436b62a176e5" + integrity sha512-0ghuzq67LI9bLXpOX/ISfve/Mq33a4aFRzoQYhnnok1JOFpmE/A2TBGkNVenOGEeSBCjIiWcc6MVOG5HEQv0sA== + dependencies: + regenerate "^1.4.2" + regenerate-unicode-properties "^10.2.2" + regjsgen "^0.8.0" + regjsparser "^0.13.0" + unicode-match-property-ecmascript "^2.0.0" + unicode-match-property-value-ecmascript "^2.2.1" + +regjsgen@^0.8.0: + version "0.8.0" + resolved "https://registry.yarnpkg.com/regjsgen/-/regjsgen-0.8.0.tgz#df23ff26e0c5b300a6470cad160a9d090c3a37ab" + integrity sha512-RvwtGe3d7LvWiDQXeQw8p5asZUmfU1G/l6WbUXeHta7Y2PEIvBTwH6E2EfmYUK8pxcxEdEmaomqyp0vZZ7C+3Q== + +regjsparser@^0.13.0: + version "0.13.2" + resolved "https://registry.yarnpkg.com/regjsparser/-/regjsparser-0.13.2.tgz#f654734b5c588b22ba3e21693b30523417180808" + integrity sha512-NgRBy2Nx/bE+9F27nVHnqcN5HjyLmecqsqx2PJHu3/IEtADD4WuxuXIVExD5PoSDFVrl78dOonfcOe5O+5nbzQ== + dependencies: + jsesc "~3.1.0" + +require-directory@^2.1.1: + version "2.1.1" + resolved "https://registry.yarnpkg.com/require-directory/-/require-directory-2.1.1.tgz#8c64ad5fd30dab1c976e2344ffe7f792a6a6df42" + integrity sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q== + +require-from-string@^2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/require-from-string/-/require-from-string-2.0.2.tgz#89a7fdd938261267318eafe14f9c32e598c36909" + integrity sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw== + +resolve-cwd@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/resolve-cwd/-/resolve-cwd-3.0.0.tgz#0f0075f1bb2544766cf73ba6a6e2adfebcb13f2d" + integrity sha512-OrZaX2Mb+rJCpH/6CpSqt9xFVpN++x01XnN2ie9g6P5/3xelLAkXWVADpdz1IHD/KFfEXyE6V0U01OQ3UO2rEg== + dependencies: + resolve-from "^5.0.0" + +resolve-from@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-4.0.0.tgz#4abcd852ad32dd7baabfe9b40e00a36db5f392e6" + integrity sha512-pb/MYmXstAkysRFx8piNI1tGFNQIFA3vkE3Gq4EuA1dF6gHp/+vgZqsCGJapvy8N3Q+4o7FwvquPJcnZ7RYy4g== + +resolve-from@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/resolve-from/-/resolve-from-5.0.0.tgz#c35225843df8f776df21c57557bc087e9dfdfc69" + integrity sha512-qYg9KP24dD5qka9J47d0aVky0N+b4fTU89LN9iDnjB5waksiC49rvMB0PrUJQGoTmH50XPiqOvAjDfaijGxYZw== + +resolve.exports@^2.0.0: + version "2.0.3" + resolved "https://registry.yarnpkg.com/resolve.exports/-/resolve.exports-2.0.3.tgz#41955e6f1b4013b7586f873749a635dea07ebe3f" + integrity sha512-OcXjMsGdhL4XnbShKpAcSqPMzQoYkYyhbEaeSko47MjRP9NfEQMhZkXL1DoFlt9LWQn4YttrdnV6X2OiyzBi+A== + +resolve@^1.20.0, resolve@^1.22.11: + version "1.22.12" + resolved "https://registry.yarnpkg.com/resolve/-/resolve-1.22.12.tgz#f5b2a680897c69c238a13cd16b15671f8b73549f" + integrity sha512-TyeJ1zif53BPfHootBGwPRYT1RUt6oGWsaQr8UyZW/eAm9bKoijtvruSDEmZHm92CwS9nj7/fWttqPCgzep8CA== + dependencies: + es-errors "^1.3.0" + is-core-module "^2.16.1" + path-parse "^1.0.7" + supports-preserve-symlinks-flag "^1.0.0" + +ret@~0.1.10: + version "0.1.15" + resolved "https://registry.yarnpkg.com/ret/-/ret-0.1.15.tgz#b8a4825d5bdb1fc3f6f53c2bc33f81388681c7bc" + integrity sha512-TTlYpa+OL+vMMNG24xSlQGEJ3B/RzEfUlLct7b5G/ytav+wPrplCpVMFuwzXbkecJrb6IYo1iFb0S9v37754mg== + +retry@^0.12.0: + version "0.12.0" + resolved "https://registry.yarnpkg.com/retry/-/retry-0.12.0.tgz#1b42a6266a21f07421d1b0b54b7dc167b01c013b" + integrity sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow== + +safe-buffer@^5.0.1, safe-buffer@~5.2.0: + version "5.2.1" + resolved "https://registry.yarnpkg.com/safe-buffer/-/safe-buffer-5.2.1.tgz#1eaf9fa9bdb1fdd4ec75f58f9cdb4e6b7827eec6" + integrity sha512-rp3So07KcdmmKbGvgaNxQSJr7bGVSVk5S9Eq1F+ppbRo70+YeaDxkw5Dd8NPN+GD6bjnYm2VuPuCXmpuYvmCXQ== + +"safer-buffer@>= 2.1.2 < 3.0.0": + version "2.1.2" + resolved "https://registry.yarnpkg.com/safer-buffer/-/safer-buffer-2.1.2.tgz#44fa161b0187b9549dd84bb91802f9bd8385cd6a" + integrity sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg== + +scheduler@0.27.0, scheduler@^0.27.0: + version "0.27.0" + resolved "https://registry.yarnpkg.com/scheduler/-/scheduler-0.27.0.tgz#0c4ef82d67d1e5c1e359e8fc76d3a87f045fe5bd" + integrity sha512-eNv+WrVbKu1f3vbYJT/xtiF5syA5HPIMtf9IgY/nKg0sWqzAUEvqY/xm7OcZc/qafLx/iO9FgOmeSAp4v5ti/Q== + +schemes@^1.4.0: + version "1.4.0" + resolved "https://registry.yarnpkg.com/schemes/-/schemes-1.4.0.tgz#9d03302275e562488dd3afa7b654ed42e00569ec" + integrity sha512-ImFy9FbCsQlVgnE3TCWmLPCFnVzx0lHL/l+umHplDqAKd0dzFpnS6lFZIpagBlYhKwzVmlV36ec0Y1XTu8JBAQ== + dependencies: + extend "^3.0.0" + +semver@^6.3.0, semver@^6.3.1: + version "6.3.1" + resolved "https://registry.yarnpkg.com/semver/-/semver-6.3.1.tgz#556d2ef8689146e46dcea4bfdd095f3434dffcb4" + integrity sha512-BR7VvDCVHO+q2xBEWskxS6DJE1qRnb7DxzUrogb71CWoSficBxYsiAGd+Kl0mmq/MprG9yArRkyrQxTO6XjMzA== + +semver@^7.1.3, semver@^7.3.5, semver@^7.5.3, semver@^7.5.4, semver@^7.7.3, semver@^7.8.5: + version "7.8.5" + resolved "https://registry.yarnpkg.com/semver/-/semver-7.8.5.tgz#39b646037dd50c14fb451e7e4cac58ed8b863f69" + integrity sha512-Y7/KDsb8LjooZpwaqGyulO6DQlksgCncchHGk+sZIY4SBvUocMBEFH5Ur1fI4dV+Jvl0w6cjvucaIi40puRioA== + +send@~0.19.1: + version "0.19.2" + resolved "https://registry.yarnpkg.com/send/-/send-0.19.2.tgz#59bc0da1b4ea7ad42736fd642b1c4294e114ff29" + integrity sha512-VMbMxbDeehAxpOtWJXlcUS5E8iXh6QmN+BkRX1GARS3wRaXEEgzCcB10gTQazO42tpNIya8xIyNx8fll1OFPrg== + dependencies: + debug "2.6.9" + depd "2.0.0" + destroy "1.2.0" + encodeurl "~2.0.0" + escape-html "~1.0.3" + etag "~1.8.1" + fresh "~0.5.2" + http-errors "~2.0.1" + mime "1.6.0" + ms "2.1.3" + on-finished "~2.4.1" + range-parser "~1.2.1" + statuses "~2.0.2" + +serialize-error@^2.1.0: + version "2.1.0" + resolved "https://registry.yarnpkg.com/serialize-error/-/serialize-error-2.1.0.tgz#50b679d5635cdf84667bdc8e59af4e5b81d5f60a" + integrity sha512-ghgmKt5o4Tly5yEG/UJp8qTd0AN7Xalw4XBtDEKP655B699qMEtra1WlXeE6WIvdEG481JvRxULKsInq/iNysw== + +serve-static@^1.16.2: + version "1.16.3" + resolved "https://registry.yarnpkg.com/serve-static/-/serve-static-1.16.3.tgz#a97b74d955778583f3862a4f0b841eb4d5d78cf9" + integrity sha512-x0RTqQel6g5SY7Lg6ZreMmsOzncHFU7nhnRWkKgWuMTu5NN0DR5oruckMqRvacAN9d5w6ARnRBXl9xhDCgfMeA== + dependencies: + encodeurl "~2.0.0" + escape-html "~1.0.3" + parseurl "~1.3.3" + send "~0.19.1" + +setprototypeof@~1.2.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/setprototypeof/-/setprototypeof-1.2.0.tgz#66c9a24a73f9fc28cbe66b09fed3d33dcaf1b424" + integrity sha512-E5LDX7Wrp85Kil5bhZv46j8jOeboKq5JMmYM3gVGdGH8xFpPWXUMsNrlODCrkoxMEeNi/XZIwuRvY4XNwYMJpw== + +shebang-command@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/shebang-command/-/shebang-command-2.0.0.tgz#ccd0af4f8835fbdc265b82461aaf0c36663f34ea" + integrity sha512-kHxr2zZpYtdmrN1qDjrrX/Z1rR1kG8Dx+gkpK1G4eXmvXswmcE1hTWBWYUzlraYw1/yZp6YuDY77YtvbN0dmDA== + dependencies: + shebang-regex "^3.0.0" + +shebang-regex@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/shebang-regex/-/shebang-regex-3.0.0.tgz#ae16f1644d873ecad843b0307b143362d4c42172" + integrity sha512-7++dFhtcx3353uBaq8DDR4NuxBetBzC7ZQOhmTQInHEd6bSrXdiEyzCvG07Z44UYdLShWUyXt5M/yhz8ekcb1A== + +shell-quote@^1.6.1: + version "1.12.0" + resolved "https://registry.yarnpkg.com/shell-quote/-/shell-quote-1.12.0.tgz#e98fdfd2e921d8a58ae2820f4fc0f75c39f09675" + integrity sha512-PcByqNyT/38F2kDNi006HAMRJaULuBzq/FOsw3qdZvX/GA9W/jamDaRskgHjubHiftXK5sIFxLNkvrXUwcof6Q== + +signal-exit@^3.0.3, signal-exit@^3.0.7: + version "3.0.7" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-3.0.7.tgz#a9a1767f8af84155114eaabd73f99273c8f59ad9" + integrity sha512-wnD2ZE+l+SPC/uoS0vXeE9L1+0wuaMqKlfz9AMUo38JsyLSBWSFcHR1Rri62LZc12vLr1gb3jl7iwQhgwpAbGQ== + +signal-exit@^4.0.1: + version "4.1.0" + resolved "https://registry.yarnpkg.com/signal-exit/-/signal-exit-4.1.0.tgz#952188c1cbd546070e2dd20d0f41c0ae0530cb04" + integrity sha512-bzyZ1e88w9O1iNJbKnOlvYTrWPDl46O1bG0D3XInv+9tkPrxrN8jUUTiFlDkkmKWgn1M6CfIA13SuGqOa9Korw== + +simple-concat@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/simple-concat/-/simple-concat-1.0.1.tgz#f46976082ba35c2263f1c8ab5edfe26c41c9552f" + integrity sha512-cSFtAPtRhljv69IK0hTVZQ+OfE9nePi/rtJmw5UjHeVyVroEqJXP1sFztKUy1qU+xvz3u/sfYJLa947b7nAN2Q== + +simple-get@^4.0.0: + version "4.0.1" + resolved "https://registry.yarnpkg.com/simple-get/-/simple-get-4.0.1.tgz#4a39db549287c979d352112fa03fd99fd6bc3543" + integrity sha512-brv7p5WgH0jmQJr1ZDDfKDOSeWWg+OVypG99A/5vYGPqJ6pxiaHLy8nxtFjBA7oMa01ebA9gfh1uMCFqOuXxvA== + dependencies: + decompress-response "^6.0.0" + once "^1.3.1" + simple-concat "^1.0.0" + +sisteransi@^1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/sisteransi/-/sisteransi-1.0.5.tgz#134d681297756437cc05ca01370d3a7a571075ed" + integrity sha512-bLGGlR1QxBcynn2d5YmDX4MGjlZvy2MRBDRNHLJ8VI6l6+9FUiyTFNJ0IveOSP0bcXgVDPRcfGqA0pjaqUpfVg== + +slash@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/slash/-/slash-3.0.0.tgz#6539be870c165adbd5240220dbe361f1bc4d4634" + integrity sha512-g9Q1haeby36OSStwb4ntCGGGaKsaVSjQ68fBxoQcutl5fS1vuY18H3wSt3jFyFtrkx+Kz0V1G85A4MyAdDMi2Q== + +smart-buffer@^4.2.0: + version "4.2.0" + resolved "https://registry.yarnpkg.com/smart-buffer/-/smart-buffer-4.2.0.tgz#6e1d71fa4f18c05f7d0ff216dd16a481d0e8d9ae" + integrity sha512-94hK0Hh8rPqQl2xXc3HsaBoOXKV20MToPkcXvwbISWLEs+64sBq5kFgn2kJDHb1Pry9yrP0dxrCI9RRci7RXKg== + +smtp-address-parser@^1.0.3: + version "1.1.0" + resolved "https://registry.yarnpkg.com/smtp-address-parser/-/smtp-address-parser-1.1.0.tgz#681a4cd27a2df5feb3c7425b235ac8f05ea34d49" + integrity sha512-Gz11jbNU0plrReU9Sj7fmshSBxxJ9ShdD2q4ktHIHo/rpTH6lFyQoYHYKINPJtPe8aHFnsbtW46Ls0tCCBsIZg== + dependencies: + nearley "^2.20.1" + +socks-proxy-agent@^8.0.3: + version "8.0.5" + resolved "https://registry.yarnpkg.com/socks-proxy-agent/-/socks-proxy-agent-8.0.5.tgz#b9cdb4e7e998509d7659d689ce7697ac21645bee" + integrity sha512-HehCEsotFqbPW9sJ8WVYB6UbmIMv7kUUORIF2Nncq4VQvBfNBLibW9YZR5dlYCSUhwcD628pRllm7n+E+YTzJw== + dependencies: + agent-base "^7.1.2" + debug "^4.3.4" + socks "^2.8.3" + +socks@^2.8.3: + version "2.8.10" + resolved "https://registry.yarnpkg.com/socks/-/socks-2.8.10.tgz#23aab4dccc1fdae110aaf4fa51cd190552432dc5" + integrity sha512-e0VyvkVTwVYViNovRkZ9aodhxVlyoMn7eJhVUPxZ+eK9P/7CBkxvvsBOHqFPEH416726W8tLXXXjKwqgTErrCQ== + dependencies: + ip-address "^10.1.1" + smart-buffer "^4.2.0" + +source-map-support@0.5.13: + version "0.5.13" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.13.tgz#31b24a9c2e73c2de85066c0feb7d44767ed52932" + integrity sha512-SHSKFHadjVA5oR4PPqhtAVdcBWwRYVd6g6cAXnIbRiIwc2EhPrTuKUBdSLvlEKyIP3GCf89fltvcZiP9MMFA1w== + dependencies: + buffer-from "^1.0.0" + source-map "^0.6.0" + +source-map-support@~0.5.20: + version "0.5.21" + resolved "https://registry.yarnpkg.com/source-map-support/-/source-map-support-0.5.21.tgz#04fe7c7f9e1ed2d662233c28cb2b35b9f63f6e4f" + integrity sha512-uBHU3L3czsIyYXKX88fdrGovxdSCoTGDRZ6SYXtSRxLZUzHg5P/66Ht6uoUlHu9EZod+inXhKo3qQgwXUT/y1w== + dependencies: + buffer-from "^1.0.0" + source-map "^0.6.0" + +source-map@^0.5.6: + version "0.5.7" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.5.7.tgz#8a039d2d1021d22d1ea14c80d8ea468ba2ef3fcc" + integrity sha512-LbrmJOMUSdEVxIKvdcJzQC+nQhe8FUZQTXQy6+I75skNgn3OoQ0DZA8YnFa7gp8tqtL3KPf1kmo0R5DoApeSGQ== + +source-map@^0.6.0, source-map@^0.6.1: + version "0.6.1" + resolved "https://registry.yarnpkg.com/source-map/-/source-map-0.6.1.tgz#74722af32e9614e9c287a8d0bbde48b5e2f1a263" + integrity sha512-UjgapumWlbMhkBgzT7Ykc5YXUT46F0iKu8SGXq0bcwP5dz/h0Plj6enJqjz1Zbq2l5WaqYnrVbwWOWMyF3F47g== + +spdx-correct@^3.0.0: + version "3.2.0" + resolved "https://registry.yarnpkg.com/spdx-correct/-/spdx-correct-3.2.0.tgz#4f5ab0668f0059e34f9c00dce331784a12de4e9c" + integrity sha512-kN9dJbvnySHULIluDHy32WHRUu3Og7B9sbY7tsFLctQkIqnMh3hErYgdMjTYuqmcXX+lK5T1lnUt3G7zNswmZA== + dependencies: + spdx-expression-parse "^3.0.0" + spdx-license-ids "^3.0.0" + +spdx-exceptions@^2.1.0: + version "2.5.0" + resolved "https://registry.yarnpkg.com/spdx-exceptions/-/spdx-exceptions-2.5.0.tgz#5d607d27fc806f66d7b64a766650fa890f04ed66" + integrity sha512-PiU42r+xO4UbUS1buo3LPJkjlO7430Xn5SVAhdpzzsPHsjbYVflnnFdATgabnLude+Cqu25p6N+g2lw/PFsa4w== + +spdx-expression-parse@^3.0.0: + version "3.0.1" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-3.0.1.tgz#cf70f50482eefdc98e3ce0a6833e4a53ceeba679" + integrity sha512-cbqHunsQWnJNE6KhVSMsMeH5H/L9EpymbzqTQ3uLwNCLZ1Q481oWaofqH7nO6V07xlXwY6PhQdQ2IedWx/ZK4Q== + dependencies: + spdx-exceptions "^2.1.0" + spdx-license-ids "^3.0.0" + +"spdx-expression-parse@^3.0.1 || ^4.0.0": + version "4.0.0" + resolved "https://registry.yarnpkg.com/spdx-expression-parse/-/spdx-expression-parse-4.0.0.tgz#a23af9f3132115465dac215c099303e4ceac5794" + integrity sha512-Clya5JIij/7C6bRR22+tnGXbc4VKlibKSVj2iHvVeX5iMW7s1SIQlqu699JkODJJIhh/pUu8L0/VLh8xflD+LQ== + dependencies: + spdx-exceptions "^2.1.0" + spdx-license-ids "^3.0.0" + +spdx-license-ids@^3.0.0: + version "3.0.23" + resolved "https://registry.yarnpkg.com/spdx-license-ids/-/spdx-license-ids-3.0.23.tgz#b069e687b1291a32f126893ed76a27a745ee2133" + integrity sha512-CWLcCCH7VLu13TgOH+r8p1O/Znwhqv/dbb6lqWy67G+pT1kHmeD/+V36AVb/vq8QMIQwVShJ6Ssl5FPh0fuSdw== + +sprintf-js@~1.0.2: + version "1.0.3" + resolved "https://registry.yarnpkg.com/sprintf-js/-/sprintf-js-1.0.3.tgz#04e6926f662895354f3dd015203633b857297e2c" + integrity sha512-D9cPgkvLlV3t3IzL0D0YLvGA9Ahk4PcvVwUbN0dSGr1aP0Nrt4AEnTUbuGvquEC0mA64Gqt1fzirlRs5ibXx8g== + +ssri@^12.0.0: + version "12.0.0" + resolved "https://registry.yarnpkg.com/ssri/-/ssri-12.0.0.tgz#bcb4258417c702472f8191981d3c8a771fee6832" + integrity sha512-S7iGNosepx9RadX82oimUkvr0Ct7IjJbEbs4mJcTxst8um95J3sDYU1RBEOvdu6oL1Wek2ODI5i4MAw+dZ6cAQ== + dependencies: + minipass "^7.0.3" + +stack-utils@^2.0.3: + version "2.0.6" + resolved "https://registry.yarnpkg.com/stack-utils/-/stack-utils-2.0.6.tgz#aaf0748169c02fc33c8232abccf933f54a1cc34f" + integrity sha512-XlkWvfIm6RmsWtNJx+uqtKLS8eqFbxUg0ZzLXqY0caEy9l7hruX8IpiDnjsLavoBgqCCR71TqWO8MaXYheJ3RQ== + dependencies: + escape-string-regexp "^2.0.0" + +stackframe@^1.3.4: + version "1.3.4" + resolved "https://registry.yarnpkg.com/stackframe/-/stackframe-1.3.4.tgz#b881a004c8c149a5e8efef37d51b16e412943310" + integrity sha512-oeVtt7eWQS+Na6F//S4kJ2K2VbRlS9D43mAlMyVpVWovy9o+jfgH8O9agzANzaiLjclA0oYzUXEM4PurhSUChw== + +stacktrace-parser@^0.1.10: + version "0.1.11" + resolved "https://registry.yarnpkg.com/stacktrace-parser/-/stacktrace-parser-0.1.11.tgz#c7c08f9b29ef566b9a6f7b255d7db572f66fabc4" + integrity sha512-WjlahMgHmCJpqzU8bIBy4qtsZdU9lRlcZE3Lvyej6t4tuOuv1vk57OW3MBrj6hXBFx/nNoC9MPMTcr5YA7NQbg== + dependencies: + type-fest "^0.7.1" + +statuses@~1.5.0: + version "1.5.0" + resolved "https://registry.yarnpkg.com/statuses/-/statuses-1.5.0.tgz#161c7dac177659fd9811f43771fa99381478628c" + integrity sha512-OpZ3zP+jT1PI7I8nemJX4AKmAX070ZkYPVWV/AaKTJl+tXCTGyVdC1a4SL8RUQYEwk/f34ZX8UTykN68FwrqAA== + +statuses@~2.0.2: + version "2.0.2" + resolved "https://registry.yarnpkg.com/statuses/-/statuses-2.0.2.tgz#8f75eecef765b5e1cfcdc080da59409ed424e382" + integrity sha512-DvEy55V3DB7uknRo+4iOGT5fP1slR8wQohVdknigZPMpMstaKJQWhwiYBACJE3Ul2pTnATihhBYnRhZQHGBiRw== + +string-length@^4.0.1: + version "4.0.2" + resolved "https://registry.yarnpkg.com/string-length/-/string-length-4.0.2.tgz#a8a8dc7bd5c1a82b9b3c8b87e125f66871b6e57a" + integrity sha512-+l6rNN5fYHNhZZy41RXsYptCjA2Igmq4EG7kZAYFQI1E1VTXarr6ZPXBg6eq7Y6eK4FEhY6AJlyuFIb/v/S0VQ== + dependencies: + char-regex "^1.0.2" + strip-ansi "^6.0.0" + +"string-width-cjs@npm:string-width@^4.2.0": + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^4.1.0, string-width@^4.2.0, string-width@^4.2.3: + version "4.2.3" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-4.2.3.tgz#269c7117d27b05ad2e536830a8ec895ef9c6d010" + integrity sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g== + dependencies: + emoji-regex "^8.0.0" + is-fullwidth-code-point "^3.0.0" + strip-ansi "^6.0.1" + +string-width@^5.0.1, string-width@^5.1.2: + version "5.1.2" + resolved "https://registry.yarnpkg.com/string-width/-/string-width-5.1.2.tgz#14f8daec6d81e7221d2a357e668cab73bdbca794" + integrity sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA== + dependencies: + eastasianwidth "^0.2.0" + emoji-regex "^9.2.2" + strip-ansi "^7.0.1" + +string_decoder@^1.1.1: + version "1.3.0" + resolved "https://registry.yarnpkg.com/string_decoder/-/string_decoder-1.3.0.tgz#42f114594a46cf1a8e30b0a84f56c78c3edac21e" + integrity sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA== + dependencies: + safe-buffer "~5.2.0" + +"strip-ansi-cjs@npm:strip-ansi@^6.0.1": + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^6.0.0, strip-ansi@^6.0.1: + version "6.0.1" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-6.0.1.tgz#9e26c63d30f53443e9489495b2105d37b67a85d9" + integrity sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A== + dependencies: + ansi-regex "^5.0.1" + +strip-ansi@^7.0.1: + version "7.2.0" + resolved "https://registry.yarnpkg.com/strip-ansi/-/strip-ansi-7.2.0.tgz#d22a269522836a627af8d04b5c3fd2c7fa3e32e3" + integrity sha512-yDPMNjp4WyfYBkHnjIRLfca1i6KMyGCtsVgoKe/z1+6vukgaENdgGBZt+ZmKPc4gavvEZ5OgHfHdrazhgNyG7w== + dependencies: + ansi-regex "^6.2.2" + +strip-bom@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/strip-bom/-/strip-bom-4.0.0.tgz#9c3505c1db45bcedca3d9cf7a16f5c5aa3901878" + integrity sha512-3xurFv5tEgii33Zi8Jtp55wEIILR9eh34FAW00PZf+JnSsTmV/ioewSgQl97JHvgjoRGwPShsWm+IdrxB35d0w== + +strip-final-newline@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/strip-final-newline/-/strip-final-newline-2.0.0.tgz#89b852fb2fcbe936f6f4b3187afb0a12c1ab58ad" + integrity sha512-BrpvfNAE3dcvq7ll3xVumzjKjZQ5tI1sEUIKr3Uoks0XUl45St3FlatVqef9prk4jRDzhW6WZg+3bk93y6pLjA== + +strip-indent@^3.0.0: + version "3.0.0" + resolved "https://registry.yarnpkg.com/strip-indent/-/strip-indent-3.0.0.tgz#c32e1cee940b6b3432c771bc2c54bcce73cd3001" + integrity sha512-laJTa3Jb+VQpaC6DseHhF7dXVqHTfJPCRDaEbid/drOhgitgYku/letMUqOXFoWV0zIIUbjpdH2t+tYj4bQMRQ== + dependencies: + min-indent "^1.0.0" + +strip-json-comments@^3.1.1: + version "3.1.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-3.1.1.tgz#31f1281b3832630434831c310c01cccda8cbe006" + integrity sha512-6fPc+R4ihwqP6N/aIv2f1gMH8lOVtWQHoqC4yK6oSDVVocumAsfCqjkXnqiYMhmMwS/mEHLp7Vehlt3ql6lEig== + +strip-json-comments@~2.0.1: + version "2.0.1" + resolved "https://registry.yarnpkg.com/strip-json-comments/-/strip-json-comments-2.0.1.tgz#3c531942e908c2697c0ec344858c286c7ca0a60a" + integrity sha512-4gB8na07fecVVkOI6Rs4e7T6NOTki5EmL7TUduTs6bu3EdnSycntVJ4re8kgZA+wx9IueI2Y11bfbgwtzuE0KQ== + +supports-color@^7.1.0: + version "7.2.0" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-7.2.0.tgz#1b7dcdcb32b8138801b3e478ba6a51caa89648da" + integrity sha512-qpCAvRl9stuOHveKsn7HncJRvv501qIacKzQlO/+Lwxc9+0q2wLyv4Dfvt80/DPn2pqOBsJdDiogXGR9+OvwRw== + dependencies: + has-flag "^4.0.0" + +supports-color@^8.0.0: + version "8.1.1" + resolved "https://registry.yarnpkg.com/supports-color/-/supports-color-8.1.1.tgz#cd6fc17e28500cff56c1b86c0a7fd4a54a73005c" + integrity sha512-MpUEN2OodtUzxvKQl72cUF7RQ5EiHsGvSsVG0ia9c5RbWGL2CI4C7EpPS8UTBIplnlzZiNuV56w+FuNxy3ty2Q== + dependencies: + has-flag "^4.0.0" + +supports-preserve-symlinks-flag@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/supports-preserve-symlinks-flag/-/supports-preserve-symlinks-flag-1.0.0.tgz#6eda4bd344a3c94aea376d4cc31bc77311039e09" + integrity sha512-ot0WnXS9fgdkgIcePe6RHNk1WA8+muPa6cSjeR3V8K27q9BB1rTE3R1p7Hv0z1ZyAc8s6Vvv8DIyWf681MAt0w== + +tar-fs@^2.0.0: + version "2.1.5" + resolved "https://registry.yarnpkg.com/tar-fs/-/tar-fs-2.1.5.tgz#33e9c29413dce0c58ada7ff77db4e5a30afffe70" + integrity sha512-OboTd8mmMhZDNPV+UjQcK9yKAatXu2aJ+r1w4im1Otd4M4fl2hwvdoXUxIYHFTHWK/3y3FarBP70v3vwmGlOxw== + dependencies: + chownr "^1.1.1" + mkdirp-classic "^0.5.2" + pump "^3.0.0" + tar-stream "^2.1.4" + +tar-stream@^2.1.4: + version "2.2.0" + resolved "https://registry.yarnpkg.com/tar-stream/-/tar-stream-2.2.0.tgz#acad84c284136b060dc3faa64474aa9aebd77287" + integrity sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ== + dependencies: + bl "^4.0.3" + end-of-stream "^1.4.1" + fs-constants "^1.0.0" + inherits "^2.0.3" + readable-stream "^3.1.1" + +tar@^7.4.3: + version "7.5.22" + resolved "https://registry.yarnpkg.com/tar/-/tar-7.5.22.tgz#a696f998136e71487dc3f869a85bba2c67971ba9" + integrity sha512-MFO/QzvtAOmJbkhOaCTvbGcFN9L9b+JunIsDwaKljSOdcLMea3NJ1k9Usz/rjdfSXTq4dfzfeS7W4p4YOAAHeA== + dependencies: + "@isaacs/fs-minipass" "^4.0.0" + chownr "^3.0.0" + minipass "^7.1.2" + minizlib "^3.1.0" + yallist "^5.0.0" + +terser@^5.15.0: + version "5.50.0" + resolved "https://registry.yarnpkg.com/terser/-/terser-5.50.0.tgz#4e560a46704f9172f96ba31c3bd6dc108ad2cead" + integrity sha512-CN9BVxWhgS/hRxtUMjtC2uRWSTcSfQFHMDWma6sKKfIivCD91sM+FOPfvwoaRMqCSrUpe1nv3jDamd9eEQ4y+w== + dependencies: + "@jridgewell/source-map" "^0.3.3" + acorn "^8.15.0" + commander "^2.20.0" + source-map-support "~0.5.20" + +test-exclude@^6.0.0: + version "6.0.0" + resolved "https://registry.yarnpkg.com/test-exclude/-/test-exclude-6.0.0.tgz#04a8698661d805ea6fa293b6cb9e63ac044ef15e" + integrity sha512-cAGWPIyOHU6zlmg88jwm7VRyXnMN7iV68OGAbYDk/Mh/xC/pzVPlQtY6ngoIH/5/tciuhGfvESU8GrHrcxD56w== + dependencies: + "@istanbuljs/schema" "^0.1.2" + glob "^7.1.4" + minimatch "^3.0.4" + +test-renderer@^1.0.0: + version "1.2.0" + resolved "https://registry.yarnpkg.com/test-renderer/-/test-renderer-1.2.0.tgz#b106039bd4df8a40ea3de3718a6f346df184957b" + integrity sha512-JYiEGbgBGtmHAWX8Kf99gGRL1HtjcRVHLrmJNTZL4vFs9XrnWcuL45Iszw/pO4094+JR7havSrN+ds6YTOpSQA== + dependencies: + "@types/react-reconciler" "~0.33.0" + react-reconciler "~0.33.0" + +throat@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/throat/-/throat-5.0.0.tgz#c5199235803aad18754a667d659b5e72ce16764b" + integrity sha512-fcwX4mndzpLQKBS1DVYhGAcYaYt7vsHNIvQV+WXMvnow5cgjPphq5CaayLaGsjRdSCKZFNGt7/GYAuXaNOiYCA== + +tinyglobby@^0.2.12, tinyglobby@^0.2.15: + version "0.2.17" + resolved "https://registry.yarnpkg.com/tinyglobby/-/tinyglobby-0.2.17.tgz#562a9a6c9eb2b3b123d39719f9af5bb44fcd7631" + integrity sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g== + dependencies: + fdir "^6.5.0" + picomatch "^4.0.4" + +tmpl@1.0.5: + version "1.0.5" + resolved "https://registry.yarnpkg.com/tmpl/-/tmpl-1.0.5.tgz#8683e0b902bb9c20c4f726e3c0b69f36518c07cc" + integrity sha512-3f0uOEAQwIqGuWW2MVzYg8fV/QNnc/IpuJNG837rLuczAaLVHslWHZQj4IGiEl5Hs3kkbhwL9Ab7Hrsmuj+Smw== + +to-regex-range@^5.0.1: + version "5.0.1" + resolved "https://registry.yarnpkg.com/to-regex-range/-/to-regex-range-5.0.1.tgz#1648c44aae7c8d988a326018ed72f5b4dd0392e4" + integrity sha512-65P7iz6X5yEr1cwcgvQxbbIw7Uk3gOy5dIdtZ4rDveLqhrdJP+Li/Hx6tyK0NEb+2GCyneCMJiGqrADCSNk8sQ== + dependencies: + is-number "^7.0.0" + +toidentifier@~1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/toidentifier/-/toidentifier-1.0.1.tgz#3be34321a88a820ed1bd80dfaa33e479fbb8dd35" + integrity sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA== + +ts-api-utils@^2.5.0: + version "2.5.0" + resolved "https://registry.yarnpkg.com/ts-api-utils/-/ts-api-utils-2.5.0.tgz#4acd4a155e22734990a5ed1fe9e97f113bcb37c1" + integrity sha512-OJ/ibxhPlqrMM0UiNHJ/0CKQkoKF243/AEmplt3qpRgkW8VG7IfOS41h7V8TjITqdByHzrjcS/2si+y4lIh8NA== + +ts-jest@^29.4.5: + version "29.4.12" + resolved "https://registry.yarnpkg.com/ts-jest/-/ts-jest-29.4.12.tgz#c34cd91f02d364e9286d2c016843315fd0efff76" + integrity sha512-Ov6ClY53Fflh6BGAnY2DlTq1hYDrTycz2PVTXBWFW2CU+9zrEqAp9fWdGXl42EXO5RLSFAcAZ2JFKbP+zBTFfw== + dependencies: + bs-logger "^0.2.6" + fast-json-stable-stringify "^2.1.0" + handlebars "^4.7.9" + json5 "^2.2.3" + lodash.memoize "^4.1.2" + make-error "^1.3.6" + semver "^7.8.5" + type-fest "^4.41.0" + yargs-parser "^21.1.1" + +tunnel-agent@^0.6.0: + version "0.6.0" + resolved "https://registry.yarnpkg.com/tunnel-agent/-/tunnel-agent-0.6.0.tgz#27a5dea06b36b04a0a9966774b290868f0fc40fd" + integrity sha512-McnNiV1l8RYeY8tBgEpuodCC1mLUdbSN+CYBL7kJsJNInOP8UjDDEwdk6Mw60vdLLrr5NHKZhMAOSrR2NZuQ+w== + dependencies: + safe-buffer "^5.0.1" + +type-check@^0.4.0, type-check@~0.4.0: + version "0.4.0" + resolved "https://registry.yarnpkg.com/type-check/-/type-check-0.4.0.tgz#07b8203bfa7056c0657050e3ccd2c37730bab8f1" + integrity sha512-XleUoc9uwGXqjWwXaUTZAmzMcFZ5858QA2vvx1Ur5xIcixXIP+8LnFDgRplU30us6teqdlskFfu+ae4K79Ooew== + dependencies: + prelude-ls "^1.2.1" + +type-detect@4.0.8: + version "4.0.8" + resolved "https://registry.yarnpkg.com/type-detect/-/type-detect-4.0.8.tgz#7646fb5f18871cfbb7749e69bd39a6388eb7450c" + integrity sha512-0fr/mIH1dlO+x7TlcMy+bIDqKPsw/70tVyeHW787goQjhmqaZe10uwLujubK9q9Lg6Fiho1KUKDYz0Z7k7g5/g== + +type-fest@^0.21.3: + version "0.21.3" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.21.3.tgz#d260a24b0198436e133fa26a524a6d65fa3b2e37" + integrity sha512-t0rzBq87m3fVcduHDUFhKmyyX+9eo6WQjZvf51Ea/M0Q7+T374Jp1aUiyUl0GKxp8M/OETVHSDvmkyPgvX+X2w== + +type-fest@^0.7.1: + version "0.7.1" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-0.7.1.tgz#8dda65feaf03ed78f0a3f9678f1869147f7c5c48" + integrity sha512-Ne2YiiGN8bmrmJJEuTWTLJR32nh/JdL1+PSicowtNb0WFpn59GK8/lfD61bVtzguz7b3PBt74nxpv/Pw5po5Rg== + +type-fest@^4.41.0: + version "4.41.0" + resolved "https://registry.yarnpkg.com/type-fest/-/type-fest-4.41.0.tgz#6ae1c8e5731273c2bf1f58ad39cbae2c91a46c58" + integrity sha512-TeTSQ6H5YHvpqVwBRcnLDCBnDOHWYu7IvGbHT6N8AOymcr9PJGjc1GTtiWZTYg0NCgYwvnYWEkVChQAr9bjfwA== + +typescript-eslint@^8.38.0: + version "8.66.0" + resolved "https://registry.yarnpkg.com/typescript-eslint/-/typescript-eslint-8.66.0.tgz#0809b6d25c8a0924690ba30dc1f05607093c11fb" + integrity sha512-QlEbBPz/RuJ1XUHj29nm3t0F/O/cSlEnntozqPOYHnnTGAXFamnMBu5i9Vn6vhUPHGAjR+Vl+5J8vPN/BMUrJw== + dependencies: + "@typescript-eslint/eslint-plugin" "8.66.0" + "@typescript-eslint/parser" "8.66.0" + "@typescript-eslint/typescript-estree" "8.66.0" + "@typescript-eslint/utils" "8.66.0" + +typescript@^5.9.3: + version "5.9.3" + resolved "https://registry.yarnpkg.com/typescript/-/typescript-5.9.3.tgz#5b4f59e15310ab17a216f5d6cf53ee476ede670f" + integrity sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw== + +uglify-js@^3.1.4: + version "3.19.3" + resolved "https://registry.yarnpkg.com/uglify-js/-/uglify-js-3.19.3.tgz#82315e9bbc6f2b25888858acd1fff8441035b77f" + integrity sha512-v3Xu+yuwBXisp6QYTcH4UbH+xYJXqnq2m/LtQVWKWzYc1iehYnLixoQDN9FH6/j9/oybfd6W9Ghwkl8+UMKTKQ== + +undici-types@~8.3.0: + version "8.3.0" + resolved "https://registry.yarnpkg.com/undici-types/-/undici-types-8.3.0.tgz#44e9fc9f3244648cdea35e4f9bb2d681e9410809" + integrity sha512-j375ScV60dom+YkPFIfTLcOiPxkN/buHz5GobjLhixFuANaNs3C9l4GmrWqejgXWJ7BbJcFYpTEUkS1Ge8bpZQ== + +unicode-canonical-property-names-ecmascript@^2.0.0: + version "2.0.1" + resolved "https://registry.yarnpkg.com/unicode-canonical-property-names-ecmascript/-/unicode-canonical-property-names-ecmascript-2.0.1.tgz#cb3173fe47ca743e228216e4a3ddc4c84d628cc2" + integrity sha512-dA8WbNeb2a6oQzAQ55YlT5vQAWGV9WXOsi3SskE3bcCdM0P4SDd+24zS/OCacdRq5BkdsRj9q3Pg6YyQoxIGqg== + +unicode-match-property-ecmascript@^2.0.0: + version "2.0.0" + resolved "https://registry.yarnpkg.com/unicode-match-property-ecmascript/-/unicode-match-property-ecmascript-2.0.0.tgz#54fd16e0ecb167cf04cf1f756bdcc92eba7976c3" + integrity sha512-5kaZCrbp5mmbz5ulBkDkbY0SsPOjKqVS35VpL9ulMPfSl0J0Xsm+9Evphv9CoIZFwre7aJoa94AY6seMKGVN5Q== + dependencies: + unicode-canonical-property-names-ecmascript "^2.0.0" + unicode-property-aliases-ecmascript "^2.0.0" + +unicode-match-property-value-ecmascript@^2.2.1: + version "2.2.1" + resolved "https://registry.yarnpkg.com/unicode-match-property-value-ecmascript/-/unicode-match-property-value-ecmascript-2.2.1.tgz#65a7adfad8574c219890e219285ce4c64ed67eaa" + integrity sha512-JQ84qTuMg4nVkx8ga4A16a1epI9H6uTXAknqxkGF/aFfRLw1xC/Bp24HNLaZhHSkWd3+84t8iXnp1J0kYcZHhg== + +unicode-property-aliases-ecmascript@^2.0.0: + version "2.2.0" + resolved "https://registry.yarnpkg.com/unicode-property-aliases-ecmascript/-/unicode-property-aliases-ecmascript-2.2.0.tgz#301d4f8a43d2b75c97adfad87c9dd5350c9475d1" + integrity sha512-hpbDzxUY9BFwX+UeBnxv3Sh1q7HFxj48DTmXchNgRa46lO8uj3/1iEn3MiNUYTg1g9ctIqXCCERn8gYZhHC5lQ== + +unique-filename@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/unique-filename/-/unique-filename-4.0.0.tgz#a06534d370e7c977a939cd1d11f7f0ab8f1fed13" + integrity sha512-XSnEewXmQ+veP7xX2dS5Q4yZAvO40cBN2MWkJ7D/6sW4Dg6wYBNwM1Vrnz1FhH5AdeLIlUXRI9e28z1YZi71NQ== + dependencies: + unique-slug "^5.0.0" + +unique-slug@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/unique-slug/-/unique-slug-5.0.0.tgz#ca72af03ad0dbab4dad8aa683f633878b1accda8" + integrity sha512-9OdaqO5kwqR+1kVgHAhsp5vPNU0hnxRa26rBFNfNgM7M6pNtgzeBn3s/xbyCQL3dcjzOatcef6UUHpB/6MaETg== + dependencies: + imurmurhash "^0.1.4" + +unpipe@~1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/unpipe/-/unpipe-1.0.0.tgz#b2bf4ee8514aae6165b4817829d21b2ef49904ec" + integrity sha512-pjy2bYhSsufwWlKwPc+l3cN7+wuJlK6uz0YdJEOlQDbl6jo/YlPi4mb8agUkVC8BF7V8NuzeyPNqRksA3hztKQ== + +update-browserslist-db@^1.3.0: + version "1.3.0" + resolved "https://registry.yarnpkg.com/update-browserslist-db/-/update-browserslist-db-1.3.0.tgz#9ff2604d5b949051639c01a223a16619f8a2b2c7" + integrity sha512-x/M6q3w4Ybp91CNaS4S69UnliqR3BzRpOT6LWbksjth0S/+jhfaPJsWjt/TewpT8j9eLIojUf5jr29WextHroA== + dependencies: + escalade "^3.2.0" + picocolors "^1.1.1" + +uri-js@^4.2.2, uri-js@^4.4.1: + version "4.4.1" + resolved "https://registry.yarnpkg.com/uri-js/-/uri-js-4.4.1.tgz#9b1a52595225859e55f669d928f88c6c57f2a77e" + integrity sha512-7rKUyy33Q1yc98pQ1DAmLtwX109F7TIfWlW1Ydo8Wl1ii1SeHieeh0HHfPeL2fMXK6z0s8ecKs9frCuLJvndBg== + dependencies: + punycode "^2.1.0" + +util-deprecate@^1.0.1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/util-deprecate/-/util-deprecate-1.0.2.tgz#450d4dc9fa70de732762fbd2d4a28981419a0ccf" + integrity sha512-EPD5q1uXyFxJpCrLnCc1nHnq3gOa6DZBocAIiI2TaSCA7VCJ1UJDMagCzIkXNsUYfD1daK//LTEQ8xiIbrHtcw== + +utils-merge@1.0.1: + version "1.0.1" + resolved "https://registry.yarnpkg.com/utils-merge/-/utils-merge-1.0.1.tgz#9f95710f50a267947b2ccc124741c1028427e713" + integrity sha512-pMZTvIkT1d+TFGvDOqodOclx0QWkkgi6Tdoa8gC8ffGAAqz9pzPTZWAybbsHHoED/ztMtkv/VoYTYyShUn81hA== + +v8-to-istanbul@^9.0.1: + version "9.3.0" + resolved "https://registry.yarnpkg.com/v8-to-istanbul/-/v8-to-istanbul-9.3.0.tgz#b9572abfa62bd556c16d75fdebc1a411d5ff3175" + integrity sha512-kiGUalWN+rgBJ/1OHZsBtU4rXZOfj/7rKQxULKlIzwzQSvMJUUNgPwJEEh7gU6xEVxC0ahoOBvN2YI8GH6FNgA== + dependencies: + "@jridgewell/trace-mapping" "^0.3.12" + "@types/istanbul-lib-coverage" "^2.0.1" + convert-source-map "^2.0.0" + +validate-npm-package-license@^3.0.4: + version "3.0.4" + resolved "https://registry.yarnpkg.com/validate-npm-package-license/-/validate-npm-package-license-3.0.4.tgz#fc91f6b9c7ba15c857f4cb2c5defeec39d4f410a" + integrity sha512-DpKm2Ui/xN7/HQKCtpZxoRWBhZ9Z0kqtygG8XCgNQ8ZlDnxuQmWhj566j8fN4Cu3/JmbhsDo7fcAJq4s9h27Ew== + dependencies: + spdx-correct "^3.0.0" + spdx-expression-parse "^3.0.0" + +vlq@^1.0.0: + version "1.0.1" + resolved "https://registry.yarnpkg.com/vlq/-/vlq-1.0.1.tgz#c003f6e7c0b4c1edd623fd6ee50bbc0d6a1de468" + integrity sha512-gQpnTgkubC6hQgdIcRdYGDSDc+SaujOdyesZQMv6JlfQee/9Mp0Qhnys6WxDWvQnL5WZdT7o2Ul187aSt0Rq+w== + +walker@^1.0.7, walker@^1.0.8: + version "1.0.8" + resolved "https://registry.yarnpkg.com/walker/-/walker-1.0.8.tgz#bd498db477afe573dc04185f011d3ab8a8d7653f" + integrity sha512-ts/8E8l5b7kY0vlWLewOkDXMmPdLcVV4GmOQLyxuSswIJsweeFZtAsMF7k1Nszz+TYBQrlYRmzOnr398y1JemQ== + dependencies: + makeerror "1.0.12" + +whatwg-fetch@^3.0.0: + version "3.6.20" + resolved "https://registry.yarnpkg.com/whatwg-fetch/-/whatwg-fetch-3.6.20.tgz#580ce6d791facec91d37c72890995a0b48d31c70" + integrity sha512-EqhiFU6daOA8kpjOWTL0olhVOF3i7OrFzSYiGsEMB8GcXS+RrzauAERX65xMeNWVqxA6HXH2m69Z9LaKKdisfg== + +which@^2.0.1: + version "2.0.2" + resolved "https://registry.yarnpkg.com/which/-/which-2.0.2.tgz#7c6a8dd0a636a0327e10b59c9286eee93f3f51b1" + integrity sha512-BLI3Tl1TW3Pvl70l3yq3Y64i+awpwXqsGBYWkkqMtnbXgrMD+yj7rhW0kuEDxzJaYXGjEW5ogapKNMEKNMjibA== + dependencies: + isexe "^2.0.0" + +which@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/which/-/which-5.0.0.tgz#d93f2d93f79834d4363c7d0c23e00d07c466c8d6" + integrity sha512-JEdGzHwwkrbWoGOlIHqQ5gtprKGOenpDHpxE9zVR1bWbOtYRyPPHMe9FaP6x61CmNaTThSkb0DAJte5jD+DmzQ== + dependencies: + isexe "^3.1.1" + +word-wrap@^1.2.5: + version "1.2.5" + resolved "https://registry.yarnpkg.com/word-wrap/-/word-wrap-1.2.5.tgz#d2c45c6dd4fbce621a66f136cbe328afd0410b34" + integrity sha512-BN22B5eaMMI9UMtjrGd5g5eCYPpCPDUy0FJXbYsaT5zYxjFOckS53SQDE3pWkVoWpHXVb3BrYcEN4Twa55B5cA== + +wordwrap@^1.0.0: + version "1.0.0" + resolved "https://registry.yarnpkg.com/wordwrap/-/wordwrap-1.0.0.tgz#27584810891456a4171c8d0226441ade90cbcaeb" + integrity sha512-gvVzJFlPycKc5dZN4yPkP8w7Dc37BtP1yczEneOb4uq34pXZcvrtRTmWV8W+Ume+XCxKgbjM+nevkyFPMybd4Q== + +"wrap-ansi-cjs@npm:wrap-ansi@^7.0.0": + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^7.0.0: + version "7.0.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-7.0.0.tgz#67e145cff510a6a6984bdf1152911d69d2eb9e43" + integrity sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q== + dependencies: + ansi-styles "^4.0.0" + string-width "^4.1.0" + strip-ansi "^6.0.0" + +wrap-ansi@^8.1.0: + version "8.1.0" + resolved "https://registry.yarnpkg.com/wrap-ansi/-/wrap-ansi-8.1.0.tgz#56dc22368ee570face1b49819975d9b9a5ead214" + integrity sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ== + dependencies: + ansi-styles "^6.1.0" + string-width "^5.0.1" + strip-ansi "^7.0.1" + +wrappy@1: + version "1.0.2" + resolved "https://registry.yarnpkg.com/wrappy/-/wrappy-1.0.2.tgz#b5243d8f3ec1aa35f1364605bc0d1036e30ab69f" + integrity sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ== + +write-file-atomic@^4.0.2: + version "4.0.2" + resolved "https://registry.yarnpkg.com/write-file-atomic/-/write-file-atomic-4.0.2.tgz#a9df01ae5b77858a027fd2e80768ee433555fcfd" + integrity sha512-7KxauUdBmSdWnmpaGFg+ppNjKF8uNLry8LyzjauQDOVONfFLNKrKvQOxZ/VuTIcS/gge/YNahf5RIIQWTSarlg== + dependencies: + imurmurhash "^0.1.4" + signal-exit "^3.0.7" + +ws@^7, ws@^7.5.10: + version "7.5.13" + resolved "https://registry.yarnpkg.com/ws/-/ws-7.5.13.tgz#12aa507eaca76c295c278b1aebf4698ab2c1845f" + integrity sha512-rsKI6xDBFVf4r/x8XyChGK04QR/XHroxs/jUcoWvtEZM8TPU/X/uIY9B1CsSzYws9ZJb/6bbBu7dPhFW00CAoA== + +"xmlbuilder2@^3.0.2 || ^4.0.3": + version "4.0.3" + resolved "https://registry.yarnpkg.com/xmlbuilder2/-/xmlbuilder2-4.0.3.tgz#91660fa6d30f19d716f8b1194c567686d4402c63" + integrity sha512-bx8Q1STctnNaaDymWnkfQLKofs0mGNN7rLLapJlGuV3VlvegD7Ls4ggMjE3aUSWItCCzU0PEv45lI87iSigiCA== + dependencies: + "@oozcitak/dom" "^2.0.2" + "@oozcitak/infra" "^2.0.2" + "@oozcitak/util" "^10.0.0" + js-yaml "^4.1.1" + +y18n@^5.0.5: + version "5.0.8" + resolved "https://registry.yarnpkg.com/y18n/-/y18n-5.0.8.tgz#7f4934d0f7ca8c56f95314939ddcd2dd91ce1d55" + integrity sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA== + +yallist@^3.0.2: + version "3.1.1" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-3.1.1.tgz#dbb7daf9bfd8bac9ab45ebf602b8cbad0d5d08fd" + integrity sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g== + +yallist@^4.0.0: + version "4.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-4.0.0.tgz#9bb92790d9c0effec63be73519e11a35019a3a72" + integrity sha512-3wdGidZyq5PB084XLES5TpOSRA3wjXAlIWMhum2kRcv/41Sn2emQ0dycQW4uZXLejwKvg6EsvbdlVL+FYEct7A== + +yallist@^5.0.0: + version "5.0.0" + resolved "https://registry.yarnpkg.com/yallist/-/yallist-5.0.0.tgz#00e2de443639ed0d78fd87de0d27469fbcffb533" + integrity sha512-YgvUTfwqyc7UXVMrB+SImsVYSmTS8X/tSrtdNZMImM+n7+QTriRXyXim0mBrTXNeqzVF0KWGgHPeiyViFFrNDw== + +yaml@^2.6.1: + version "2.9.0" + resolved "https://registry.yarnpkg.com/yaml/-/yaml-2.9.0.tgz#78274afd93598a1dfdd6130df6a566defcbf9aa4" + integrity sha512-2AvhNX3mb8zd6Zy7INTtSpl1F15HW6Wnqj0srWlkKLcpYl/gMIMJiyuGq2KeI2YFxUPjdlB+3Lc10seMLtL4cA== + +yargs-parser@^21.1.1: + version "21.1.1" + resolved "https://registry.yarnpkg.com/yargs-parser/-/yargs-parser-21.1.1.tgz#9096bceebf990d21bb31fa9516e0ede294a77d35" + integrity sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw== + +yargs@^17.3.1, yargs@^17.6.2: + version "17.7.3" + resolved "https://registry.yarnpkg.com/yargs/-/yargs-17.7.3.tgz#779dffe6bcafec596a7172e983289a588647faaa" + integrity sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g== + dependencies: + cliui "^8.0.1" + escalade "^3.1.1" + get-caller-file "^2.0.5" + require-directory "^2.1.1" + string-width "^4.2.3" + y18n "^5.0.5" + yargs-parser "^21.1.1" + +yocto-queue@^0.1.0: + version "0.1.0" + resolved "https://registry.yarnpkg.com/yocto-queue/-/yocto-queue-0.1.0.tgz#0294eb3dee05028d31ee1a5fa2c556a6aaf10a1b" + integrity sha512-rVksvsnNCdJ/ohGc6xgPwyN8eheCxsiLM8mxuE/t/mOVqJewPuO1miLpTHQiRgTKCLexL4MeAFVagts7HmNZ2Q== + +"zod-validation-error@^3.5.0 || ^4.0.0": + version "4.0.2" + resolved "https://registry.yarnpkg.com/zod-validation-error/-/zod-validation-error-4.0.2.tgz#bc605eba49ce0fcd598c127fee1c236be3f22918" + integrity sha512-Q6/nZLe6jxuU80qb/4uJ4t5v2VEZ44lzQjPDhYJNztRQ4wyWc6VF3D3Kb/fAuPetZQnhS3hnajCf9CsWesghLQ== + +"zod@^3.25.0 || ^4.0.0": + version "4.4.3" + resolved "https://registry.yarnpkg.com/zod/-/zod-4.4.3.tgz#b680f172885d18bbebf21a834ea25e55a1bbf356" + integrity sha512-ytENFjIJFl2UwYglde2jchW2Hwm4GJFLDiSXWdTrJQBIN9Fcyp7n4DhxJEiWNAJMV1/BqWfW/kkg71UDcHJyTQ==