Merged
feat(a4p): 添加arkts实现 #332
wangweizhenAdd on Oct 9
feat(a4p): 添加arkts实现 #332
Merged
Total: 49 files changed+9843-0
| @@ -0,0 +1,8 @@ | |||
| 1 | +{ | ||
| 2 | + "string": [ | ||
| 3 | + { | ||
| 4 | + "name": "app_name", | ||
| 5 | + "value": "a4p_test" | ||
| 6 | + } | ||
| 7 | + ] | ||
| 8 | +} | ||
| @@ -0,0 +1,7 @@ | |||
| 1 | +{ | ||
| 2 | + "layered-image": | ||
| 3 | + { | ||
| 4 | + "background" : "$media:background", | ||
| 5 | + "foreground" : "$media:foreground" | ||
| 6 | + } | ||
| 7 | +} | ||
| @@ -0,0 +1,305 @@ | |||
| 1 | +# A4P ArkTS SDK | ||
| 2 | + | ||
| 3 | +English | [简体中文](./README_zh.md) | ||
| 4 | + | ||
| 5 | +HarmonyOS (ArkTS) implementation of the A4P (Agent-to-Agent Payment) payment-intent | ||
| 6 | +protocol, delivered as a HAR library (module name `a4p`). It covers the signed intent | ||
| 7 | +lifecycle (create → issue → authorize → activate), payment execution accounting against | ||
| 8 | +the frozen authorization snapshot, and the canonical JSON codec used for signing and | ||
| 9 | +persistence. Cryptography is pluggable through the `Signer` / `SignatureVerifier` | ||
| 10 | +interfaces. The Java port in [`A4P-java-sdk/`](../A4P-java-sdk) was ported from this SDK. | ||
| 11 | + | ||
| 12 | +## Build and test | ||
| 13 | + | ||
| 14 | +Requirements: DevEco Studio 5.0 or later with HarmonyOS SDK `5.0.0(12)` (API 12). | ||
| 15 | +Command-line builds additionally need `ohpm`, `hvigorw` and Bash (Git Bash on Windows | ||
| 16 | +works); the script also packages the on-device test HAP, which requires `java` (DevEco | ||
| 17 | +Studio's bundled JBR works). The library itself has no third-party dependencies | ||
| 18 | +(`@ohos/hypium` is a test-only dev dependency). | ||
| 19 | + | ||
| 20 | +The build script always cleans previous outputs first, then runs `ohpm install`, | ||
| 21 | +`hvigor clean`, `assembleHar` (release) and `genOnDeviceTestHap`: | ||
| 22 | + | ||
| 23 | +```sh | ||
| 24 | +scripts/build.sh # resolve ohpm/hvigorw from PATH | ||
| 25 | +scripts/build.sh --ohpm <path> --hvigorw <path> # or pass explicit locations | ||
| 26 | +``` | ||
| 27 | + | ||
| 28 | +Artifacts: | ||
| 29 | + | ||
| 30 | +- HAR: `a4p/build/default/outputs/default/a4p.har` | ||
| 31 | +- On-device test HAP: `a4p/build/default/outputs/ohosTest/a4p-ohosTest-unsigned.hap` | ||
| 32 | + | ||
| 33 | +Tests run in DevEco Studio against `a4p/src/ohosTest`, or on a device from the built | ||
| 34 | +test HAP. There is no example app; the test sources double as reference usage (see | ||
| 35 | +[Tests](#tests)). | ||
| 36 | + | ||
| 37 | +### Consuming the library | ||
| 38 | + | ||
| 39 | +Add the module (source path or built HAR) to the consumer module's `oh-package.json5` | ||
| 40 | +and run `ohpm install`: | ||
| 41 | + | ||
| 42 | +```json5 | ||
| 43 | +{ | ||
| 44 | + "dependencies": { | ||
| 45 | + "a4p": "file:../A4P-arkts-sdk/a4p" | ||
| 46 | + } | ||
| 47 | +} | ||
| 48 | +``` | ||
| 49 | + | ||
| 50 | +```typescript | ||
| 51 | +import { A4p, A4pCodec, A4pErrorCode } from 'a4p'; | ||
| 52 | +``` | ||
| 53 | + | ||
| 54 | +Everything is exported from the single `Index.ets` entry: the `A4p` and `A4pCodec` | ||
| 55 | +namespaces, the `Signer` / `SignatureVerifier` interfaces, and the data models. | ||
| 56 | + | ||
| 57 | +## API | ||
| 58 | + | ||
| 59 | +| Specification | ArkTS | | ||
| 60 | +| --- | --- | | ||
| 61 | +| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, now?])` returns `IntentL1` | | ||
| 62 | +| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, now?])` returns `IntentL2` | | ||
| 63 | +| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` returns `IntentL3` | | ||
| 64 | +| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` returns `IntentExecutionContext` | | ||
| 65 | +| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` returns `VerificationResult` | | ||
| 66 | +| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` returns `IntentExecutionContext` | | ||
| 67 | +| `createExecution / completeExecution / cancelExecution` | Functions on the `A4p` namespace, returning `IntentExecutionContext` | | ||
| 68 | +| Failure reporting | No result wrapper: APIs return data directly and throw a `BusinessError`-shaped error whose `code` is an `A4pErrorCode` (the concrete class is module-internal; catch structurally) | | ||
| 69 | +| Codec | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` return `String`; each `deserialize…` counterpart validates the structure and returns the object | | ||
| 70 | +| Crypto | None bundled: `Signer.sign(Uint8Array): SignatureInfo` and `SignatureVerifier.verify(Uint8Array, SignatureInfo): VerificationResult` are supplied by the application | | ||
| 71 | +| Data model | Plain interfaces and string enums (`AI_PAY`, `RSA3072`, `ACTIVE`, `PENDING`) | | ||
| 72 | + | ||
| 73 | +`now?` marks the optional explicit-clock parameter described below. | ||
| 74 | + | ||
| 75 | +The sketch below shows the shape of the calls; the ohosTest sources (in particular | ||
| 76 | +`A4p.test.ets` and `mock/TestDataFactory.ets`) are complete, compiling references. | ||
| 77 | + | ||
| 78 | +```typescript | ||
| 79 | +// The agent creates and signs L1; the server verifies it, issues and signs L2 | ||
| 80 | +// with the three identities; the user verifies L2 and signs L3. | ||
| 81 | +const intentL1 = A4p.createIntent(request, agentSigner); | ||
| 82 | +const intentL2 = A4p.issueIntent(intentL1, agentVerifier, issueContext, serverSigner); | ||
| 83 | +const intentL3 = A4p.signIntent(intentL2, serverVerifier, signingEnv, userSigner); | ||
| 84 | + | ||
| 85 | +// Activate: verify the user's L3 signature and freeze the authorization snapshot. | ||
| 86 | +let context = A4p.activateIntent(intentL3, userVerifier, now); | ||
| 87 | + | ||
| 88 | +// Reserve, then complete, one order against the activated intent. | ||
| 89 | +context = A4p.createExecution(context, execution, now); | ||
| 90 | +context = A4p.completeExecution(context, executionId, now); | ||
| 91 | + | ||
| 92 | +// Failures throw structurally BusinessError-shaped errors; branch on the code. | ||
| 93 | +try { | ||
| 94 | + context = A4p.createExecution(context, execution, now); | ||
| 95 | +} catch (e) { | ||
| 96 | + const err = e as BusinessError<number>; | ||
| 97 | + if (err.code === A4pErrorCode.A4P_AMOUNT_EXCEEDED) { /* budget exhausted */ } | ||
| 98 | +} | ||
| 99 | +``` | ||
| 100 | + | ||
| 101 | +A failed `createExecution` can still have moved the context to `EXPIRED` (the lazy flip | ||
| 102 | +described below), so persist the context after every call. | ||
| 103 | +`A4pCodec.serializeIntentExecutionContext` / `deserializeIntentExecutionContext` provide | ||
| 104 | +the persisted form; deserialization re-validates the whole stored structure — the | ||
| 105 | +authorized L3 chain, the `intentId` derivation, every ledger record (status-bound | ||
| 106 | +finalization timestamps, `execution.id === executionId`, `periodIndex` presence matching | ||
| 107 | +the intent's periodicity) and the accounting snapshot (period figures and | ||
| 108 | +`leftExecutionCount` present exactly when their caps apply) — and re-freezes the | ||
| 109 | +authorization snapshot. | ||
| 110 | + | ||
| 111 | +Optional fields are `undefined`; absent optional fields are omitted from signed JSON. | ||
| 112 | +Monetary amounts are positive integers in the application's agreed minor unit. All | ||
| 113 | +protocol numbers must be integers within the JavaScript safe-integer range; values that | ||
| 114 | +are not integers must be carried as strings. Values handed to the SDK must be plain | ||
| 115 | +objects (object literals), not class instances — canonical serialization rejects class | ||
| 116 | +instances with `A4P_SERIALIZE_FAIL`. | ||
| 117 | + | ||
| 118 | +Lifecycle and execution functions all take an optional explicit clock (`now`, epoch | ||
| 119 | +milliseconds) and default to `Date.now()`. An explicit `now` must be a non-negative safe | ||
| 120 | +integer. Use it for reproducible signed bytes in tests and for caller-side clock-skew | ||
| 121 | +policies; the SDK itself applies no tolerance, and production code must derive `now` | ||
| 122 | +from a trusted clock, never from a client-provided timestamp. Order timestamps are | ||
| 123 | +recorded, not evaluated: quota periods and validity are judged against `now`. | ||
| 124 | + | ||
| 125 | +Required strings must be non-blank (JavaScript `trim()` whitespace). A product needs a | ||
| 126 | +non-blank seller id and at least one non-blank `spuId`/`skuId`; seller id + spuId + | ||
| 127 | +skuId is the whitelist matching key, and a product may appear at most once per group and | ||
| 128 | +in at most one group. A period rule requires all of `anchorTime`, `periodSeconds` and | ||
| 129 | +`maxExecutionCountPerPeriod`, with `anchorTime <= validFrom` and | ||
| 130 | +`periodSeconds <= 9007199254740`. Chain timestamps are monotonic: | ||
| 131 | +`L1.timestamp <= L2.timestamp <= L3.timestamp <= activation`. Activation applies no | ||
| 132 | +validity-window check: an intent can be activated before `validFrom` (and even after | ||
| 133 | +`validUntil`); the window is enforced at reservation time, where an early reservation | ||
| 134 | +fails with `A4P_TIMESTAMP_TOO_EARLY`. Length limits and sensitive-data filtering of | ||
| 135 | +`intentConversation` are the Agent's responsibility. | ||
| 136 | + | ||
| 137 | +### Result codes | ||
| 138 | + | ||
| 139 | +Callers branch on the numeric `code`; the message is a fixed diagnostic text per code | ||
| 140 | +(the specific cause is logged via hilog at the throw site). The values come from the | ||
| 141 | +`A4pErrorCode` enum. `0` means success and every other value is a protocol failure. | ||
| 142 | + | ||
| 143 | +| Code | Constant | Meaning | | ||
| 144 | +| --- | --- | --- | | ||
| 145 | +| 0 | `A4P_SUCCESS` | Operation completed successfully | | ||
| 146 | +| 1001 | `A4P_INVALID_PARAMETER` | Invalid parameter | | ||
| 147 | +| 1002 | `A4P_UNSUPPORTED_VERSION` | Unsupported version | | ||
| 148 | +| 1003 | `A4P_DUPLICATE_ID` | Duplicate ID | | ||
| 149 | +| 2001 | `A4P_SIGNING_FAIL` | Signing failed | | ||
| 150 | +| 2002 | `A4P_VERIFY_FAIL` | Verification failed | | ||
| 151 | +| 3001 | `A4P_INVALID_STATUS` | Invalid status | | ||
| 152 | +| 3002 | `A4P_TIMESTAMP_EXPIRED` | Timestamp expired | | ||
| 153 | +| 3003 | `A4P_TIMESTAMP_TOO_EARLY` | Timestamp too early | | ||
| 154 | +| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | Execution count exceeded | | ||
| 155 | +| 4002 | `A4P_AMOUNT_EXCEEDED` | Amount exceeded | | ||
| 156 | +| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | Defined for code-table compatibility; never thrown by this SDK (per-period limits report 4004) | | ||
| 157 | +| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | Period execution count exceeded | | ||
| 158 | +| 4005 | `A4P_CART_MISMATCH` | Cart does not match the authorized resource | | ||
| 159 | +| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | Single order amount exceeded | | ||
| 160 | +| 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | Product not authorized | | ||
| 161 | +| 5001 | `A4P_SERIALIZE_FAIL` | Serialization failed | | ||
| 162 | +| 5002 | `A4P_DESERIALIZE_FAIL` | Deserialization failed | | ||
| 163 | +| 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error | | ||
| 164 | + | ||
| 165 | +`2001` and `2002` also cover the crypto boundary: a `Signer`/`SignatureVerifier` that | ||
| 166 | +throws, returns nothing, or returns a malformed result is mapped to these codes by the | ||
| 167 | +SDK, so raw exceptions never leak through the lifecycle APIs. | ||
| 168 | + | ||
| 169 | +## Execution semantics | ||
| 170 | + | ||
| 171 | +- Pending and completed records both consume amount, count and period quota; only an | ||
| 172 | + explicit cancel releases quota. Unknown downstream outcomes do not roll back. | ||
| 173 | +- The cart must match the whitelist template exactly: `cartItems` and `itemsWhiteList` | ||
| 174 | + have the same length, each cart item is paired with a distinct group listing its | ||
| 175 | + product (OR within a group, AND across groups), and its quantity equals the group's | ||
| 176 | + `quantity`. The cart order does not matter. A wrong size, a group matched twice, a | ||
| 177 | + wrong quantity or an uncovered group fails with `A4P_CART_MISMATCH`; a product outside | ||
| 178 | + every group fails with `A4P_PRODUCT_NOT_AUTHORIZED`. | ||
| 179 | +- `orderId` is the payment idempotency key: an order id already in the ledger, canceled | ||
| 180 | + records included, is rejected with `A4P_DUPLICATE_ID`. Duplicate execution ids remain | ||
| 181 | + rejected after cancellation; a provided execution id must be non-blank, an absent one | ||
| 182 | + is generated. | ||
| 183 | +- Reservation checks run in a fixed order: request structure; action and currency | ||
| 184 | + against the authorized intent; context status; validity window (`validFrom`, the | ||
| 185 | + `activatedTime` floor, the lazy EXPIRED flip); duplicate execution/order ids; the | ||
| 186 | + execution-count cap, the single-order cap, the remaining amount; whitelist scope and | ||
| 187 | + template; period quota. | ||
| 188 | +- `amount` is caller-declared: the SDK validates it against the signed caps but never | ||
| 189 | + reconciles it with the cart (`Product` carries no price). Binding the amount to actual | ||
| 190 | + prices is the responsibility of the party holding the authoritative product catalog. | ||
| 191 | +- Revocation requires an ACTIVE context and blocks reservations, but pending executions | ||
| 192 | + can still complete or cancel. | ||
| 193 | +- A reservation past `validUntil` flips the context to EXPIRED even though the call | ||
| 194 | + fails; pending records can still be finalized in EXPIRED and REVOKED states. | ||
| 195 | +- An ACTIVE context becomes CONSUMED when a completion leaves no pending record and | ||
| 196 | + either the count cap is reached or the amount budget is exhausted. REVOKED and | ||
| 197 | + EXPIRED are terminal. | ||
| 198 | +- `executionInfo` always provides `leftAmount`; `periodIndex`/`leftPeriodExecutionCount` | ||
| 199 | + appear only for periodic intents and `leftExecutionCount` only when `maxExecuteCount` | ||
| 200 | + is present — non-applicable figures are omitted, not null. The snapshot is always | ||
| 201 | + re-derived from the ledger, never maintained by hand. | ||
| 202 | +- The caller's execution object is never mutated: the id is resolved locally and lands | ||
| 203 | + on the ledger's own deep copy after every check has passed. The ledger is append-only. | ||
| 204 | +- Completion books no quota but re-derives the accounting snapshot at the evaluation | ||
| 205 | + instant, so the period figures follow `now`, not the last ledger mutation. | ||
| 206 | +- The authorized intent is deep-cloned and deep-frozen at activation; execution checks | ||
| 207 | + read the immutable snapshot while the ledger and figures stay mutable. | ||
| 208 | +- Context operations carry no locks. That is safe in the ArkTS single-threaded runtime, | ||
| 209 | + **not** across processes or independently activated copies of the same `intentId`. | ||
| 210 | +- `verifyIntentAuthenticity` verifies the L3 chain and the server's L2 signature, not | ||
| 211 | + the user signature, and does not depend on any context status. | ||
| 212 | + | ||
| 213 | +The ledger is in-memory. The integrating service (the intent center) must persist the | ||
| 214 | +context inside a database transaction locked by `intentId`, prevent replay of the same | ||
| 215 | +`intentId`, and bind keys to identities. | ||
| 216 | + | ||
| 217 | +## Wire format and security | ||
| 218 | + | ||
| 219 | +The canonical JSON and Base64URL rules behind every signature are the ones documented in | ||
| 220 | +[canonical-json-spec.md](../A4P-java-sdk/docs/canonical-json-spec.md): keys sorted by | ||
| 221 | +UTF-16 code units, no whitespace, finite safe integers only, `undefined` omitted, | ||
| 222 | +signing strips only the complete top-level `sign` property (nested chain signatures | ||
| 223 | +stay), UTF-8 without BOM, and RFC 4648 Base64URL without padding, with the decoder | ||
| 224 | +rejecting padding, non-URL-safe characters and nonzero unused trailing bits. JSON field | ||
| 225 | +names are the interface property names (`intentConversation`, `structuredIntent.resource`, | ||
| 226 | +`userIdentity.id`), every enum is serialized by name (`"AI_PAY"`, `"CONSUMED"`, | ||
| 227 | +`"PENDING"`), and the protocol version is `1.0`. | ||
| 228 | + | ||
| 229 | +Each level's signature covers the level without its whole `sign` object, so that level's | ||
| 230 | +`alg` and `keyIdentifier` are not part of its own signed bytes; the next level's | ||
| 231 | +signature covers them. This is the specified design. `alg` must be `RSA3072` (validated | ||
| 232 | +structurally, since `alg` is detached metadata). Verifiers must resolve keys exclusively | ||
| 233 | +from `keyIdentifier` against keys they trust for the role, and must reject any `alg` | ||
| 234 | +incompatible with the resolved key type — never trust the incoming `alg`. This is the | ||
| 235 | +primary defense against algorithm- and key-confusion attacks (the same class as unsigned | ||
| 236 | +JWT headers, cf. RFC 8725). | ||
| 237 | + | ||
| 238 | +The SDK bundles no cryptographic implementation. For the `RSA3072` suite, supply | ||
| 239 | +`Signer`/`SignatureVerifier` built on `@kit.CryptoArchitectureKit` using | ||
| 240 | +`SHA256withRSA` (PKCS#1 v1.5) with 3072-bit keys and unpadded Base64URL, so peers | ||
| 241 | +interoperate with the Java SDK's `Rsa3072` adapter. | ||
| 242 | + | ||
| 243 | +Caller-supplied objects are deep-cloned into intents (never aliased), and the activated | ||
| 244 | +snapshot is deep-frozen. An internal, unexported `A4pHttp` module builds and parses | ||
| 245 | +request/response envelopes for the three protocol endpoints | ||
| 246 | +(`/a4p/v1/intent/proposal|authorization|submission`, media type `application/a4p+json`) | ||
| 247 | +and maps every error code to an HTTP status (401 signature failures, 409 state and quota | ||
| 248 | +conflicts, 426 unsupported version, 400 parameter errors, 500 the rest); it is exercised | ||
| 249 | +by tests but not part of the public API until the specification settles the bindings. | ||
| 250 | + | ||
| 251 | +## Version and compatibility | ||
| 252 | + | ||
| 253 | +The protocol version is `1.0`. Every level this SDK creates is stamped with it, and each | ||
| 254 | +step validates the levels it receives, rejecting a mismatch (including mixed-version | ||
| 255 | +chains) with `A4P_UNSUPPORTED_VERSION`. The HAR version is `1.0.0`; protocol | ||
| 256 | +compatibility is governed by the `version` field, not by the HAR version. | ||
| 257 | + | ||
| 258 | +The Java port ([`A4P-java-sdk/`](../A4P-java-sdk)) was ported from this SDK and shares | ||
| 259 | +the canonical JSON rules and the error-code table, but it follows the API | ||
| 260 | +specification's newer field spellings (`resources` where this SDK signs `resource`, an | ||
| 261 | +explicit `version` on `Execution`). Serialized intents are therefore not byte-identical | ||
| 262 | +across the two SDKs; check the field names before exchanging wire data. | ||
| 263 | + | ||
| 264 | +## Known limitations | ||
| 265 | + | ||
| 266 | +- The ledger is in-memory and per-context. Durability, locked persistence, replay | ||
| 267 | + prevention and key-to-identity binding belong to the intent center. | ||
| 268 | +- No cryptographic implementation is bundled; applications supply `Signer` / | ||
| 269 | + `SignatureVerifier`. The XOR-based `MockSigner` in the test sources is a deterministic | ||
| 270 | + test double and must not be used for authorization. | ||
| 271 | +- HTTP bindings are internal and unexported until the specification settles them; only | ||
| 272 | + in-process calls and canonical JSON serialization are public. | ||
| 273 | +- `verifyIntentAuthenticity` deliberately does not verify the user signature. | ||
| 274 | +- Deserialization is structural (JSON.parse semantics): unknown fields and duplicate | ||
| 275 | + JSON keys are not rejected, unlike the stricter Java port. | ||
| 276 | +- Activation applies no validity-window check; the window is enforced at reservation | ||
| 277 | + time (with the lazy EXPIRED flip). | ||
| 278 | +- Context operations are unsynchronized: safe in the single-threaded ArkTS runtime | ||
| 279 | + only, not across processes or independently activated copies. | ||
| 280 | + | ||
| 281 | +## More documentation | ||
| 282 | + | ||
| 283 | +| Document | Contents | | ||
| 284 | +| --- | --- | | ||
| 285 | +| [canonical-json-spec.md](../A4P-java-sdk/docs/canonical-json-spec.md) | Canonical JSON and Base64URL rules behind every signature (the rules this SDK implements). | | ||
| 286 | + | ||
| 287 | +## Tests | ||
| 288 | + | ||
| 289 | +On-device hypium suites under `a4p/src/ohosTest` (300+ cases): | ||
| 290 | + | ||
| 291 | +- `A4p.test.ets` — lifecycle (create/issue/sign/activate/verify/revoke), blank and | ||
| 292 | + structural validation, signer/verifier failure guards, execution accounting, quota | ||
| 293 | + caps and rollback, order idempotency, cart template matching, period boundaries, | ||
| 294 | + check ordering, expiry finalization and terminal states. | ||
| 295 | +- `A4pCodec.test.ets` — deterministic and key-order-independent serialization, the | ||
| 296 | + golden wire form at a fixed clock, round-trips, and context restore (including | ||
| 297 | + re-freezing the authorized snapshot). | ||
| 298 | +- `A4pHttp.test.ets` — envelope builders and parsers, the complete error-code → | ||
| 299 | + HTTP-status table, and the proposal → authorization → submission flow. | ||
| 300 | +- `Utils.test.ets` — base64url, UTF-8 and canonical JSON edge cases, including | ||
| 301 | + rejection of non-canonical encodings. | ||
| 302 | + | ||
| 303 | +Run them in DevEco Studio against `a4p/src/ohosTest`, or install the built test HAP on | ||
| 304 | +a device. The test doubles (`MockSigner`, `MockVerifier`, `TestDataFactory`) are | ||
| 305 | +deterministic fakes for tests only, not authorization-grade cryptography. | ||
| @@ -0,0 +1,270 @@ | |||
| 1 | +# A4P ArkTS SDK | ||
| 2 | + | ||
| 3 | +[English](./README.md) | 简体中文 | ||
| 4 | + | ||
| 5 | +A4P(Agent-to-Agent Payment)支付意图协议的 HarmonyOS(ArkTS)实现,以 HAR 库(模块名 | ||
| 6 | +`a4p`)形式交付。覆盖带签名的意图生命周期(创建 → 签发 → 授权 → 激活)、基于冻结授权 | ||
| 7 | +快照的支付执行记账,以及用于签名与持久化的规范化 JSON(canonical JSON)编解码。密码学 | ||
| 8 | +通过 `Signer` / `SignatureVerifier` 接口由使用方注入。仓库中的 Java 移植版 | ||
| 9 | +[`A4P-java-sdk/`](../A4P-java-sdk) 即移植自本 SDK。 | ||
| 10 | + | ||
| 11 | +## 构建与测试 | ||
| 12 | + | ||
| 13 | +环境要求:DevEco Studio 5.0 及以上,HarmonyOS SDK `5.0.0(12)`(API 12)。命令行构建 | ||
| 14 | +还需要 `ohpm`、`hvigorw` 与 Bash 环境(Windows 上可用 Git Bash);脚本会同时打包端侧 | ||
| 15 | +测试 HAP,该步骤需要 `java`(DevEco Studio 自带的 JBR 即可)。库本身没有第三方依赖 | ||
| 16 | +(`@ohos/hypium` 仅为测试期开发依赖)。 | ||
| 17 | + | ||
| 18 | +构建脚本总是先清理历史产物,再依次执行 `ohpm install`、`hvigor clean`、 | ||
| 19 | +`assembleHar`(release)与 `genOnDeviceTestHap`: | ||
| 20 | + | ||
| 21 | +```sh | ||
| 22 | +scripts/build.sh # 从 PATH 解析 ohpm/hvigorw | ||
| 23 | +scripts/build.sh --ohpm <path> --hvigorw <path> # 或显式指定位置 | ||
| 24 | +``` | ||
| 25 | + | ||
| 26 | +产物: | ||
| 27 | + | ||
| 28 | +- HAR 库:`a4p/build/default/outputs/default/a4p.har` | ||
| 29 | +- 端侧测试 HAP:`a4p/build/default/outputs/ohosTest/a4p-ohosTest-unsigned.hap` | ||
| 30 | + | ||
| 31 | +测试可在 DevEco Studio 中针对 `a4p/src/ohosTest` 运行,也可将打包好的测试 HAP 安装到 | ||
| 32 | +设备上运行。本 SDK 不带示例应用;测试源码兼作参考用法(见[测试](#测试))。 | ||
| 33 | + | ||
| 34 | +### 引入本库 | ||
| 35 | + | ||
| 36 | +在使用方模块的 `oh-package.json5` 中添加依赖(源码路径或构建好的 HAR),然后执行 | ||
| 37 | +`ohpm install`: | ||
| 38 | + | ||
| 39 | +```json5 | ||
| 40 | +{ | ||
| 41 | + "dependencies": { | ||
| 42 | + "a4p": "file:../A4P-arkts-sdk/a4p" | ||
| 43 | + } | ||
| 44 | +} | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +```typescript | ||
| 48 | +import { A4p, A4pCodec, A4pErrorCode } from 'a4p'; | ||
| 49 | +``` | ||
| 50 | + | ||
| 51 | +所有公共内容都从唯一的 `Index.ets` 入口导出:`A4p` 与 `A4pCodec` 两个命名空间、 | ||
| 52 | +`Signer` / `SignatureVerifier` 接口,以及全部数据模型。 | ||
| 53 | + | ||
| 54 | +## API | ||
| 55 | + | ||
| 56 | +| 规范 | ArkTS | | ||
| 57 | +| --- | --- | | ||
| 58 | +| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, now?])` 返回 `IntentL1` | | ||
| 59 | +| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, now?])` 返回 `IntentL2` | | ||
| 60 | +| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` 返回 `IntentL3` | | ||
| 61 | +| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` 返回 `IntentExecutionContext` | | ||
| 62 | +| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` 返回 `VerificationResult` | | ||
| 63 | +| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` 返回 `IntentExecutionContext` | | ||
| 64 | +| `createExecution / completeExecution / cancelExecution` | `A4p` 命名空间下的函数,返回 `IntentExecutionContext` | | ||
| 65 | +| 失败上报 | 无结果包装:API 直接返回数据,失败时抛出符合 `BusinessError` 形态的错误,`code` 为 `A4pErrorCode`(具体类为模块内部实现,按结构捕获) | | ||
| 66 | +| 编解码 | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` 返回 `String`;对应的每个 `deserialize…` 先做结构校验再返回对象 | | ||
| 67 | +| 密码学 | 不内置:`Signer.sign(Uint8Array): SignatureInfo` 与 `SignatureVerifier.verify(Uint8Array, SignatureInfo): VerificationResult` 由应用提供 | | ||
| 68 | +| 数据模型 | 普通接口与字符串枚举(`AI_PAY`、`RSA3072`、`ACTIVE`、`PENDING`) | | ||
| 69 | + | ||
| 70 | +`now?` 表示下文说明的可选显式时钟参数。 | ||
| 71 | + | ||
| 72 | +下面的片段展示调用形态;完整可编译的参考实现见 ohosTest 测试源码(尤其是 | ||
| 73 | +`A4p.test.ets` 与 `mock/TestDataFactory.ets`)。 | ||
| 74 | + | ||
| 75 | +```typescript | ||
| 76 | +// Agent 创建并签名 L1;服务端验证后签发 L2 并绑定三方身份;用户验证 L2 后签名 L3。 | ||
| 77 | +const intentL1 = A4p.createIntent(request, agentSigner); | ||
| 78 | +const intentL2 = A4p.issueIntent(intentL1, agentVerifier, issueContext, serverSigner); | ||
| 79 | +const intentL3 = A4p.signIntent(intentL2, serverVerifier, signingEnv, userSigner); | ||
| 80 | + | ||
| 81 | +// 激活:验证用户的 L3 签名,冻结授权快照。 | ||
| 82 | +let context = A4p.activateIntent(intentL3, userVerifier, now); | ||
| 83 | + | ||
| 84 | +// 针对已激活的意图预留一笔订单,然后完成它。 | ||
| 85 | +context = A4p.createExecution(context, execution, now); | ||
| 86 | +context = A4p.completeExecution(context, executionId, now); | ||
| 87 | + | ||
| 88 | +// 失败以 BusinessError 形态抛出,按 code 分支处理。 | ||
| 89 | +try { | ||
| 90 | + context = A4p.createExecution(context, execution, now); | ||
| 91 | +} catch (e) { | ||
| 92 | + const err = e as BusinessError<number>; | ||
| 93 | + if (err.code === A4pErrorCode.A4P_AMOUNT_EXCEEDED) { /* 额度已用尽 */ } | ||
| 94 | +} | ||
| 95 | +``` | ||
| 96 | + | ||
| 97 | +失败的 `createExecution` 仍可能已把 context 置为 `EXPIRED`(见下文的惰性翻转),因此 | ||
| 98 | +每次调用后都要持久化 context。`A4pCodec.serializeIntentExecutionContext` / | ||
| 99 | +`deserializeIntentExecutionContext` 提供持久化形式;反序列化会重新校验存储的完整结构 | ||
| 100 | +——已授权的 L3 链、`intentId` 的推导、每一条账本记录(与状态绑定的终结时间戳、 | ||
| 101 | +`execution.id === executionId`、`periodIndex` 的有无与意图周期性一致)以及记账快照 | ||
| 102 | +(周期数值与 `leftExecutionCount` 恰在对应上限存在时出现)——并重新冻结授权快照。 | ||
| 103 | + | ||
| 104 | +可选字段用 `undefined` 表示;缺席的可选字段不会出现在签名 JSON 中。金额是应用约定的 | ||
| 105 | +最小货币单位下的正整数。所有协议数值都必须是 JavaScript 安全整数范围内的整数;不是 | ||
| 106 | +整数的值必须以字符串承载。传给 SDK 的值必须是普通对象(对象字面量),不能是类实例 | ||
| 107 | +——规范化序列化会以 `A4P_SERIALIZE_FAIL` 拒绝类实例。 | ||
| 108 | + | ||
| 109 | +生命周期与执行函数都接受可选的显式时钟(`now`,epoch 毫秒),缺省使用 `Date.now()`。 | ||
| 110 | +显式 `now` 必须是非负安全整数。测试中传入固定值可让签名字节可复现,也可用于实现 | ||
| 111 | +调用方的时钟偏移策略;SDK 自身不做任何时钟容差,生产代码必须从可信时钟取值,绝不能 | ||
| 112 | +使用客户端提供的时间戳。订单时间戳只被记录、不被评估:配额周期与有效期均以 `now` | ||
| 113 | +判定。 | ||
| 114 | + | ||
| 115 | +必填字符串不能为空白(使用 JavaScript `trim()` 的空白字符集)。一个商品需要非空白的 | ||
| 116 | +seller id,且 `spuId`/`skuId` 至少提供一个非空白值;seller id + spuId + skuId 是白名单 | ||
| 117 | +匹配键,一个商品在每个分组内至多出现一次,且至多属于一个分组。周期规则要求 | ||
| 118 | +`anchorTime`、`periodSeconds`、`maxExecutionCountPerPeriod` 三者同时提供,且 | ||
| 119 | +`anchorTime <= validFrom`、`periodSeconds <= 9007199254740`。链上时间戳单调: | ||
| 120 | +`L1.timestamp <= L2.timestamp <= L3.timestamp <= 激活时刻`。激活不做有效期窗口检查: | ||
| 121 | +意图可以在 `validFrom` 之前(甚至 `validUntil` 之后)被激活;窗口在预留时才被强制, | ||
| 122 | +早于窗口的预留以 `A4P_TIMESTAMP_TOO_EARLY` 失败。`intentConversation` 的长度限制与 | ||
| 123 | +敏感数据过滤由 Agent 负责。 | ||
| 124 | + | ||
| 125 | +### 结果码 | ||
| 126 | + | ||
| 127 | +调用方按数值 `code` 分支处理;消息是按码固定的诊断文本(具体原因在抛出点通过 | ||
| 128 | +hilog 记录)。取值来自 `A4pErrorCode` 枚举。`0` 表示成功,其他任何值都是协议失败。 | ||
| 129 | + | ||
| 130 | +| 码 | 常量 | 含义 | | ||
| 131 | +| --- | --- | --- | | ||
| 132 | +| 0 | `A4P_SUCCESS` | 操作成功 | | ||
| 133 | +| 1001 | `A4P_INVALID_PARAMETER` | 参数无效 | | ||
| 134 | +| 1002 | `A4P_UNSUPPORTED_VERSION` | 版本不受支持 | | ||
| 135 | +| 1003 | `A4P_DUPLICATE_ID` | ID 重复 | | ||
| 136 | +| 2001 | `A4P_SIGNING_FAIL` | 签名失败 | | ||
| 137 | +| 2002 | `A4P_VERIFY_FAIL` | 验证失败 | | ||
| 138 | +| 3001 | `A4P_INVALID_STATUS` | 状态无效 | | ||
| 139 | +| 3002 | `A4P_TIMESTAMP_EXPIRED` | 时间戳已过期 | | ||
| 140 | +| 3003 | `A4P_TIMESTAMP_TOO_EARLY` | 时间戳过早 | | ||
| 141 | +| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | 超出执行次数上限 | | ||
| 142 | +| 4002 | `A4P_AMOUNT_EXCEEDED` | 超出金额上限 | | ||
| 143 | +| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | 为码表兼容而定义;本 SDK 不返回此码(周期执行次数超限使用 4004) | | ||
| 144 | +| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | 超出周期执行次数上限 | | ||
| 145 | +| 4005 | `A4P_CART_MISMATCH` | 购物车与授权资源不符 | | ||
| 146 | +| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | 超出单笔订单金额上限 | | ||
| 147 | +| 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | 商品未被授权 | | ||
| 148 | +| 5001 | `A4P_SERIALIZE_FAIL` | 序列化失败 | | ||
| 149 | +| 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 | | ||
| 150 | +| 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 | | ||
| 151 | + | ||
| 152 | +`2001` 与 `2002` 同样覆盖密码学边界:抛出异常、不返回结果或返回畸形结果的 | ||
| 153 | +`Signer`/`SignatureVerifier` 会被 SDK 映射为这两个码,原始异常不会穿透生命周期 API。 | ||
| 154 | + | ||
| 155 | +## 执行语义 | ||
| 156 | + | ||
| 157 | +- 待处理与已完成记录都占用金额、次数和周期配额;只有显式取消会释放配额,下游结果 | ||
| 158 | + 未知则不回滚。 | ||
| 159 | +- 购物车必须与白名单模板精确匹配:`cartItems` 与 `itemsWhiteList` 长度相同,每个购物车 | ||
| 160 | + 条目与一个不同的、列出该商品的分组配对(组内 OR,组间 AND),且数量等于该分组的 | ||
| 161 | + `quantity`。购物车顺序无关。长度不符、一个分组被匹配两次、数量不符或有分组未覆盖, | ||
| 162 | + 以 `A4P_CART_MISMATCH` 失败;商品不在任何分组中,以 `A4P_PRODUCT_NOT_AUTHORIZED` | ||
| 163 | + 失败。 | ||
| 164 | +- `orderId` 是支付的幂等键:账本中已存在的订单 ID(含已取消记录)会以 | ||
| 165 | + `A4P_DUPLICATE_ID` 被拒绝。重复的执行 ID 在取消之后依然被拒绝;调用方提供的执行 ID | ||
| 166 | + 不能为空白,缺席时自动生成。 | ||
| 167 | +- 预留检查按固定顺序执行:请求结构;动作与币种是否与已授权意图一致;context 状态; | ||
| 168 | + 有效期窗口(`validFrom`、`activatedTime` 下限、惰性置为 EXPIRED);执行/订单 ID 重复; | ||
| 169 | + 执行次数上限、单笔上限、剩余金额;白名单范围与模板;周期配额。 | ||
| 170 | +- `amount` 由调用方声明:SDK 只校验其不超过签名的金额上限,不与购物车对账(`Product` | ||
| 171 | + 不含价格)。将金额绑定到真实价格是持有权威商品目录一方的职责。 | ||
| 172 | +- 撤销要求 context 处于 ACTIVE 并阻止新的预留,但待处理执行仍可完成或取消。 | ||
| 173 | +- 超过 `validUntil` 的预留会把 context 置为 EXPIRED,尽管该次调用失败;待处理记录在 | ||
| 174 | + EXPIRED 与 REVOKED 状态下仍可被终结。 | ||
| 175 | +- 当一次完成操作之后不再有待处理记录,且要么达到次数上限、要么金额预算用尽时,ACTIVE | ||
| 176 | + 的 context 变为 CONSUMED。REVOKED 与 EXPIRED 是终态。 | ||
| 177 | +- `executionInfo` 始终给出 `leftAmount`;`periodIndex`/`leftPeriodExecutionCount` 仅在 | ||
| 178 | + 周期意图上出现,`leftExecutionCount` 仅在存在 `maxExecuteCount` 时出现——不适用的数值 | ||
| 179 | + 被省略而非置 null。快照始终由账本推导,从不手工维护。 | ||
| 180 | +- 调用方的 execution 对象不会被改动:ID 在本地解析,且只在全部检查通过后写入账本自己的 | ||
| 181 | + 深拷贝。账本只追加。 | ||
| 182 | +- 完成操作不占用配额,但会按评估时刻重新推导记账快照,因此周期数值跟随 `now`,而不是 | ||
| 183 | + 最近一次账本变更。 | ||
| 184 | +- 已授权意图在激活时被深拷贝并深度冻结;执行检查读取不可变快照,而账本与数值保持 | ||
| 185 | + 可变。 | ||
| 186 | +- context 操作不加锁。这在 ArkTS 单线程运行时中是安全的,但**不**覆盖多个进程或同一个 | ||
| 187 | + `intentId` 各自独立激活的副本。 | ||
| 188 | +- `verifyIntentAuthenticity` 校验 L3 链与服务端的 L2 签名,不校验用户签名,也不依赖任何 | ||
| 189 | + context 状态。 | ||
| 190 | + | ||
| 191 | +账本位于内存中。接入方(意图中心)必须在以 `intentId` 加锁的数据库事务中持久化 | ||
| 192 | +context,防止同一个 `intentId` 被重放,并把密钥与身份绑定。 | ||
| 193 | + | ||
| 194 | +## 线格式与安全 | ||
| 195 | + | ||
| 196 | +每次签名背后的 canonical JSON 与 Base64URL 规则即 | ||
| 197 | +[canonical-json-spec.md](../A4P-java-sdk/docs/canonical-json-spec.md) 所记录的内容:键按 | ||
| 198 | +UTF-16 码元排序、无空白、仅限有限安全整数、`undefined` 省略、签名时仅移除顶层完整的 | ||
| 199 | +`sign` 属性(链上下层签名保留)、UTF-8 编码不带 BOM,以及 RFC 4648 无填充 Base64URL, | ||
| 200 | +解码端拒绝填充、非 URL 安全字符与非零的未用尾随位。JSON 字段名即接口属性名 | ||
| 201 | +(`intentConversation`、`structuredIntent.resource`、`userIdentity.id`),每个枚举都按 | ||
| 202 | +名称序列化(`"AI_PAY"`、`"CONSUMED"`、`"PENDING"`),协议版本为 `1.0`。 | ||
| 203 | + | ||
| 204 | +每一层的签名覆盖该层除去整个 `sign` 对象之后的内容,因此该层自己的 `alg` 与 | ||
| 205 | +`keyIdentifier` 不在其自身签名字节内;它们由下一层的签名覆盖。这是规范规定的设计。 | ||
| 206 | +`alg` 必须是 `RSA3072`(因 `alg` 是分离元数据,结构校验即拒绝未知值)。验证方必须仅凭 | ||
| 207 | +`keyIdentifier` 在自己为该角色信任的密钥中解析,并拒绝与解析出的密钥类型不兼容的任何 | ||
| 208 | +`alg`——绝不要信任传入的 `alg`。这是防御算法/密钥混淆攻击的主要手段(同类问题参见 | ||
| 209 | +RFC 8725 的未签名 JWT 头部)。 | ||
| 210 | + | ||
| 211 | +SDK 不内置任何密码学实现。`RSA3072` 套件请基于 `@kit.CryptoArchitectureKit` 提供 | ||
| 212 | +`Signer`/`SignatureVerifier`,使用 `SHA256withRSA`(PKCS#1 v1.5)、3072 位密钥与无填充 | ||
| 213 | +Base64URL,以便与 Java SDK 的 `Rsa3072` 适配器互操作。 | ||
| 214 | + | ||
| 215 | +调用方提供的对象会被深拷贝进意图(绝不别名引用),激活后的快照被深度冻结。内部有一个 | ||
| 216 | +未导出的 `A4pHttp` 模块,为三个协议端点 | ||
| 217 | +(`/a4p/v1/intent/proposal|authorization|submission`,媒体类型 `application/a4p+json`) | ||
| 218 | +构建与解析请求/响应封套,并把每个错误码映射到 HTTP 状态(签名失败 401、状态与配额 | ||
| 219 | +冲突 409、版本不受支持 426、参数错误 400、其余 500);它有测试覆盖,但在规范确定绑定 | ||
| 220 | +之前不属于公共 API。 | ||
| 221 | + | ||
| 222 | +## 版本与兼容性 | ||
| 223 | + | ||
| 224 | +协议版本为 `1.0`。本 SDK 创建的每一层都写入该常量,每一步都会校验所收到的各层,不一致 | ||
| 225 | +(包括混合版本的链)时以 `A4P_UNSUPPORTED_VERSION` 拒绝。HAR 版本为 `1.0.0`;协议兼容 | ||
| 226 | +性由 `version` 字段决定,而不是由 HAR 版本决定。 | ||
| 227 | + | ||
| 228 | +Java 移植版([`A4P-java-sdk/`](../A4P-java-sdk))移植自本 SDK,与本文共享 canonical JSON | ||
| 229 | +规则与错误码表,但它遵循 API 规范中更新的字段拼写(本 SDK 签名 `resource`,Java 侧为 | ||
| 230 | +`resources`;`Execution` 上多出显式的 `version` 字段)。因此两个 SDK 序列化出的意图并非 | ||
| 231 | +字节级一致;交换线格式数据前请先核对字段名。 | ||
| 232 | + | ||
| 233 | +## 已知限制 | ||
| 234 | + | ||
| 235 | +- 账本是内存内的、以单个 context 为粒度。持久化、加锁写入、防重放以及密钥与身份的绑定 | ||
| 236 | + 都由意图中心负责。 | ||
| 237 | +- 不内置密码学实现;`Signer`/`SignatureVerifier` 由应用提供。测试源码中基于 XOR 的 | ||
| 238 | + `MockSigner` 只是确定性的测试替身,不得用于授权。 | ||
| 239 | +- HTTP 绑定为内部实现且未导出,待规范确定后再开放;公共能力仅限进程内调用与 canonical | ||
| 240 | + JSON 序列化。 | ||
| 241 | +- `verifyIntentAuthenticity` 有意不校验用户签名。 | ||
| 242 | +- 反序列化是结构性的(JSON.parse 语义):不拒绝未知字段与重复 JSON 键,这一点不如 | ||
| 243 | + Java 移植版严格。 | ||
| 244 | +- 激活不做有效期窗口检查;窗口在预留时强制(伴随惰性的 EXPIRED 翻转)。 | ||
| 245 | +- context 操作无同步保护:仅在 ArkTS 单线程运行时中安全,不覆盖多进程或各自独立激活的 | ||
| 246 | + 副本。 | ||
| 247 | + | ||
| 248 | +## 更多文档 | ||
| 249 | + | ||
| 250 | +| 文档 | 内容 | | ||
| 251 | +| --- | --- | | ||
| 252 | +| [canonical-json-spec.md](../A4P-java-sdk/docs/canonical-json-spec.md) | 每次签名背后的 canonical JSON 与 Base64URL 规则(本 SDK 实现的即该规则)。 | | ||
| 253 | + | ||
| 254 | +## 测试 | ||
| 255 | + | ||
| 256 | +端侧 hypium 测试套件位于 `a4p/src/ohosTest`(300+ 用例): | ||
| 257 | + | ||
| 258 | +- `A4p.test.ets`——生命周期(创建/签发/签名/激活/核验/撤销)、空白与结构校验、签名器/ | ||
| 259 | + 验证器失败防护、执行记账、配额上限与回滚、订单幂等、购物车模板匹配、周期边界、检查 | ||
| 260 | + 顺序、过期终结与终态。 | ||
| 261 | +- `A4pCodec.test.ets`——确定性与键序无关的序列化、固定时钟下的 golden 线格式、往返 | ||
| 262 | + 编解码,以及 context 恢复(包括重新冻结授权快照)。 | ||
| 263 | +- `A4pHttp.test.ets`——封套构建与解析、完整的错误码 → HTTP 状态映射表,以及 | ||
| 264 | + proposal → authorization → submission 全流程。 | ||
| 265 | +- `Utils.test.ets`——base64url、UTF-8 与 canonical JSON 的边界用例,包括对非规范编码的 | ||
| 266 | + 拒绝。 | ||
| 267 | + | ||
| 268 | +在 DevEco Studio 中针对 `a4p/src/ohosTest` 运行,或将构建出的测试 HAP 安装到设备上运行。 | ||
| 269 | +测试替身(`MockSigner`、`MockVerifier`、`TestDataFactory`)仅是确定性假实现,不是可用于 | ||
| 270 | +授权的密码学实现。 | ||
| @@ -0,0 +1,36 @@ | |||
| 1 | +{ | ||
| 2 | + "apiType": "stageMode", | ||
| 3 | + "buildOption": { | ||
| 4 | + "resOptions": { | ||
| 5 | + "copyCodeResource": { | ||
| 6 | + "enable": false | ||
| 7 | + } | ||
| 8 | + } | ||
| 9 | + }, | ||
| 10 | + "buildOptionSet": [ | ||
| 11 | + { | ||
| 12 | + "name": "release", | ||
| 13 | + "arkOptions": { | ||
| 14 | + "obfuscation": { | ||
| 15 | + "ruleOptions": { | ||
| 16 | + "enable": true, | ||
| 17 | + "files": [ | ||
| 18 | + "./obfuscation-rules.txt" | ||
| 19 | + ] | ||
| 20 | + }, | ||
| 21 | + "consumerFiles": [ | ||
| 22 | + "./consumer-rules.txt" | ||
| 23 | + ] | ||
| 24 | + } | ||
| 25 | + }, | ||
| 26 | + }, | ||
| 27 | + ], | ||
| 28 | + "targets": [ | ||
| 29 | + { | ||
| 30 | + "name": "default" | ||
| 31 | + }, | ||
| 32 | + { | ||
| 33 | + "name": "ohosTest" | ||
| 34 | + } | ||
| 35 | + ] | ||
| 36 | +} | ||
| @@ -0,0 +1,148 @@ | |||
| 1 | +# A4P HAR consumer obfuscation rules. | ||
| 2 | +# | ||
| 3 | +# The A4P wire format and every signature are computed over the canonical | ||
| 4 | +# JSON of the intent objects: the codec walks the real property names, so | ||
| 5 | +# the field names kept below are signature-bearing bytes. A consuming app | ||
| 6 | +# that enables -enable-property-obfuscation without these keeps renames | ||
| 7 | +# the SDK's properties and produces JSON that no other A4P implementation | ||
| 8 | +# (Java SDK, server) can parse or verify, while responses it receives | ||
| 9 | +# fail to parse against renamed keys. | ||
| 10 | +# | ||
| 11 | +# This file ships with the HAR (merged into the consuming app's rules | ||
| 12 | +# automatically). The kept names cover the SDK's full public property | ||
| 13 | +# surface — anything the app's obfuscator must NOT rename because a | ||
| 14 | +# pre-compiled SDK object or a cross-boundary call depends on it: | ||
| 15 | +# - model fields (wire format, signature payloads) | ||
| 16 | +# - namespace members (A4p.*/A4pCodec.*: app call sites resolve | ||
| 17 | +# against the pre-compiled HAR bytecode, which keeps these names) | ||
| 18 | +# - enum members (app accesses on the pre-compiled enum objects) | ||
| 19 | +# - Signer.sign / SignatureVerifier.verify (app implements, SDK calls) | ||
| 20 | +# - VerificationResult / HTTP envelope / thrown BusinessError fields | ||
| 21 | +# (code, message, data, valid) | ||
| 22 | +# | ||
| 23 | +# Trade-off: kept names are never renamed anywhere in the consuming app, | ||
| 24 | +# including its own fields with the same spelling. That is the inherent | ||
| 25 | +# price of a wire-format SDK. | ||
| 26 | +# | ||
| 27 | +# Keep in sync with obfuscation-rules.txt and with the public surface in | ||
| 28 | +# Index.ets and src/main/ets/models/: every new wire-visible field, | ||
| 29 | +# namespace member, or enum member MUST be added here in the same change. | ||
| 30 | +# The golden wire-key test (A4pCodec.test.ets, GoldenWireKeys describe) | ||
| 31 | +# fails if a wire field name drifts. | ||
| 32 | +-keep-property-name | ||
| 33 | +version | ||
| 34 | +timestamp | ||
| 35 | +sign | ||
| 36 | +verify | ||
| 37 | +alg | ||
| 38 | +keyIdentifier | ||
| 39 | +action | ||
| 40 | +status | ||
| 41 | +code | ||
| 42 | +message | ||
| 43 | +name | ||
| 44 | +data | ||
| 45 | +valid | ||
| 46 | +id | ||
| 47 | +intentId | ||
| 48 | +intentConversation | ||
| 49 | +intentSummary | ||
| 50 | +structuredIntent | ||
| 51 | +intentL1 | ||
| 52 | +intentL2 | ||
| 53 | +userIdentity | ||
| 54 | +agentIdentity | ||
| 55 | +serviceProviderIdentity | ||
| 56 | +signingEnv | ||
| 57 | +authorizedIntent | ||
| 58 | +activatedTime | ||
| 59 | +executions | ||
| 60 | +executionInfo | ||
| 61 | +resource | ||
| 62 | +constraints | ||
| 63 | +singleOrderMaxAmount | ||
| 64 | +totalMaxAmount | ||
| 65 | +currency | ||
| 66 | +validFrom | ||
| 67 | +validUntil | ||
| 68 | +maxExecuteCount | ||
| 69 | +anchorTime | ||
| 70 | +periodSeconds | ||
| 71 | +maxExecutionCountPerPeriod | ||
| 72 | +itemsWhiteList | ||
| 73 | +whiteList | ||
| 74 | +quantity | ||
| 75 | +product | ||
| 76 | +seller | ||
| 77 | +spusku | ||
| 78 | +spuId | ||
| 79 | +skuId | ||
| 80 | +cartItems | ||
| 81 | +orderId | ||
| 82 | +amount | ||
| 83 | +executionContent | ||
| 84 | +execution | ||
| 85 | +executionId | ||
| 86 | +periodIndex | ||
| 87 | +reservedAt | ||
| 88 | +completedAt | ||
| 89 | +canceledAt | ||
| 90 | +leftAmount | ||
| 91 | +leftExecutionCount | ||
| 92 | +leftPeriodExecutionCount | ||
| 93 | +identityProvider | ||
| 94 | +additionalInfo | ||
| 95 | +device | ||
| 96 | +app | ||
| 97 | +model | ||
| 98 | +os | ||
| 99 | +method | ||
| 100 | +path | ||
| 101 | +headers | ||
| 102 | +body | ||
| 103 | +statusCode | ||
| 104 | +createIntent | ||
| 105 | +issueIntent | ||
| 106 | +signIntent | ||
| 107 | +activateIntent | ||
| 108 | +verifyIntentAuthenticity | ||
| 109 | +revokeIntent | ||
| 110 | +createExecution | ||
| 111 | +completeExecution | ||
| 112 | +cancelExecution | ||
| 113 | +serializeIntentL1 | ||
| 114 | +deserializeIntentL1 | ||
| 115 | +serializeIntentL2 | ||
| 116 | +deserializeIntentL2 | ||
| 117 | +serializeIntentL3 | ||
| 118 | +deserializeIntentL3 | ||
| 119 | +serializeIntentExecutionContext | ||
| 120 | +deserializeIntentExecutionContext | ||
| 121 | +A4P_SUCCESS | ||
| 122 | +A4P_INVALID_PARAMETER | ||
| 123 | +A4P_UNSUPPORTED_VERSION | ||
| 124 | +A4P_DUPLICATE_ID | ||
| 125 | +A4P_SIGNING_FAIL | ||
| 126 | +A4P_VERIFY_FAIL | ||
| 127 | +A4P_INVALID_STATUS | ||
| 128 | +A4P_TIMESTAMP_EXPIRED | ||
| 129 | +A4P_TIMESTAMP_TOO_EARLY | ||
| 130 | +A4P_EXECUTION_COUNT_EXCEEDED | ||
| 131 | +A4P_AMOUNT_EXCEEDED | ||
| 132 | +A4P_PERIOD_COUNT_EXCEEDED | ||
| 133 | +A4P_PERIOD_EXECUTION_COUNT_EXCEEDED | ||
| 134 | +A4P_CART_MISMATCH | ||
| 135 | +A4P_SINGLE_ORDER_AMOUNT_EXCEEDED | ||
| 136 | +A4P_PRODUCT_NOT_AUTHORIZED | ||
| 137 | +A4P_SERIALIZE_FAIL | ||
| 138 | +A4P_DESERIALIZE_FAIL | ||
| 139 | +A4P_INTERNAL_ERROR | ||
| 140 | +AI_PAY | ||
| 141 | +RSA3072 | ||
| 142 | +ACTIVE | ||
| 143 | +CONSUMED | ||
| 144 | +REVOKED | ||
| 145 | +EXPIRED | ||
| 146 | +PENDING | ||
| 147 | +COMPLETED | ||
| 148 | +CANCELED | ||
| @@ -0,0 +1,6 @@ | |||
| 1 | +import { harTasks } from '@ohos/hvigor-ohos-plugin'; | ||
| 2 | + | ||
| 3 | +export default { | ||
| 4 | + system: harTasks, /* Built-in plugin of Hvigor. It cannot be modified. */ | ||
| 5 | + plugins: [] /* Custom plugin to extend the functionality of Hvigor. */ | ||
| 6 | +} | ||
| @@ -0,0 +1,197 @@ | |||
| 1 | +# Define project specific obfuscation rules here. | ||
| 2 | +# You can include the obfuscation configuration files in the current module's build-profile.json5. | ||
| 3 | +# | ||
| 4 | +# For more details, see | ||
| 5 | +# https://developer.huawei.com/consumer/cn/doc/harmonyos-guides/source-obfuscation | ||
| 6 | + | ||
| 7 | +# Obfuscation options: | ||
| 8 | +# -disable-obfuscation: disable all obfuscations | ||
| 9 | +# -enable-property-obfuscation: obfuscate the property names | ||
| 10 | +# -enable-toplevel-obfuscation: obfuscate the names in the global scope | ||
| 11 | +# -compact: remove unnecessary blank spaces and all line feeds | ||
| 12 | +# -remove-log: remove all console.* statements | ||
| 13 | +# -print-namecache: print the name cache that contains the mapping from the old names to new names | ||
| 14 | +# -apply-namecache: reuse the given cache file | ||
| 15 | + | ||
| 16 | +# Keep options: | ||
| 17 | +# -keep-property-name: specifies property names that you want to keep | ||
| 18 | +# -keep-global-name: specifies names that you want to keep in the global scope | ||
| 19 | + | ||
| 20 | +-enable-property-obfuscation | ||
| 21 | +-enable-toplevel-obfuscation | ||
| 22 | +# -enable-filename-obfuscation | ||
| 23 | +-enable-export-obfuscation | ||
| 24 | + | ||
| 25 | +# The full public property surface — every member of every type exported | ||
| 26 | +# from Index.ets, plus the HTTP envelope literals. Matching is | ||
| 27 | +# case-sensitive. Three distinct reasons to keep each name: | ||
| 28 | +# - model fields: the canonical JSON and every signature are computed | ||
| 29 | +# over the real property names, so a renamed field makes this module's | ||
| 30 | +# output unverifiable against every other A4P implementation and | ||
| 31 | +# server; | ||
| 32 | +# - namespace members (A4p.*/A4pCodec.*) and enum members: consumer | ||
| 33 | +# call sites resolve against this module's pre-compiled bytecode, so | ||
| 34 | +# the names must survive in both the shipped .abc and the shipped | ||
| 35 | +# .d.ts; | ||
| 36 | +# - Signer.sign / SignatureVerifier.verify: implemented by the | ||
| 37 | +# consuming app, called from this module's bytecode. | ||
| 38 | +# Keep in sync with consumer-rules.txt (the copy shipped to consuming | ||
| 39 | +# apps) and with Index.ets / src/main/ets/models/: every new exported | ||
| 40 | +# member or wire-visible field MUST be added here in the same change. | ||
| 41 | +-keep-property-name | ||
| 42 | +version | ||
| 43 | +timestamp | ||
| 44 | +sign | ||
| 45 | +verify | ||
| 46 | +alg | ||
| 47 | +keyIdentifier | ||
| 48 | +action | ||
| 49 | +status | ||
| 50 | +code | ||
| 51 | +message | ||
| 52 | +name | ||
| 53 | +data | ||
| 54 | +valid | ||
| 55 | +id | ||
| 56 | +intentId | ||
| 57 | +intentConversation | ||
| 58 | +intentSummary | ||
| 59 | +structuredIntent | ||
| 60 | +intentL1 | ||
| 61 | +intentL2 | ||
| 62 | +userIdentity | ||
| 63 | +agentIdentity | ||
| 64 | +serviceProviderIdentity | ||
| 65 | +signingEnv | ||
| 66 | +authorizedIntent | ||
| 67 | +activatedTime | ||
| 68 | +executions | ||
| 69 | +executionInfo | ||
| 70 | +resource | ||
| 71 | +constraints | ||
| 72 | +singleOrderMaxAmount | ||
| 73 | +totalMaxAmount | ||
| 74 | +currency | ||
| 75 | +validFrom | ||
| 76 | +validUntil | ||
| 77 | +maxExecuteCount | ||
| 78 | +anchorTime | ||
| 79 | +periodSeconds | ||
| 80 | +maxExecutionCountPerPeriod | ||
| 81 | +itemsWhiteList | ||
| 82 | +whiteList | ||
| 83 | +quantity | ||
| 84 | +product | ||
| 85 | +seller | ||
| 86 | +spusku | ||
| 87 | +spuId | ||
| 88 | +skuId | ||
| 89 | +cartItems | ||
| 90 | +orderId | ||
| 91 | +amount | ||
| 92 | +executionContent | ||
| 93 | +execution | ||
| 94 | +executionId | ||
| 95 | +periodIndex | ||
| 96 | +reservedAt | ||
| 97 | +completedAt | ||
| 98 | +canceledAt | ||
| 99 | +leftAmount | ||
| 100 | +leftExecutionCount | ||
| 101 | +leftPeriodExecutionCount | ||
| 102 | +identityProvider | ||
| 103 | +additionalInfo | ||
| 104 | +device | ||
| 105 | +app | ||
| 106 | +model | ||
| 107 | +os | ||
| 108 | +method | ||
| 109 | +path | ||
| 110 | +headers | ||
| 111 | +body | ||
| 112 | +statusCode | ||
| 113 | +createIntent | ||
| 114 | +issueIntent | ||
| 115 | +signIntent | ||
| 116 | +activateIntent | ||
| 117 | +verifyIntentAuthenticity | ||
| 118 | +revokeIntent | ||
| 119 | +createExecution | ||
| 120 | +completeExecution | ||
| 121 | +cancelExecution | ||
| 122 | +serializeIntentL1 | ||
| 123 | +deserializeIntentL1 | ||
| 124 | +serializeIntentL2 | ||
| 125 | +deserializeIntentL2 | ||
| 126 | +serializeIntentL3 | ||
| 127 | +deserializeIntentL3 | ||
| 128 | +serializeIntentExecutionContext | ||
| 129 | +deserializeIntentExecutionContext | ||
| 130 | +A4P_SUCCESS | ||
| 131 | +A4P_INVALID_PARAMETER | ||
| 132 | +A4P_UNSUPPORTED_VERSION | ||
| 133 | +A4P_DUPLICATE_ID | ||
| 134 | +A4P_SIGNING_FAIL | ||
| 135 | +A4P_VERIFY_FAIL | ||
| 136 | +A4P_INVALID_STATUS | ||
| 137 | +A4P_TIMESTAMP_EXPIRED | ||
| 138 | +A4P_TIMESTAMP_TOO_EARLY | ||
| 139 | +A4P_EXECUTION_COUNT_EXCEEDED | ||
| 140 | +A4P_AMOUNT_EXCEEDED | ||
| 141 | +A4P_PERIOD_COUNT_EXCEEDED | ||
| 142 | +A4P_PERIOD_EXECUTION_COUNT_EXCEEDED | ||
| 143 | +A4P_CART_MISMATCH | ||
| 144 | +A4P_SINGLE_ORDER_AMOUNT_EXCEEDED | ||
| 145 | +A4P_PRODUCT_NOT_AUTHORIZED | ||
| 146 | +A4P_SERIALIZE_FAIL | ||
| 147 | +A4P_DESERIALIZE_FAIL | ||
| 148 | +A4P_INTERNAL_ERROR | ||
| 149 | +AI_PAY | ||
| 150 | +RSA3072 | ||
| 151 | +ACTIVE | ||
| 152 | +CONSUMED | ||
| 153 | +REVOKED | ||
| 154 | +EXPIRED | ||
| 155 | +PENDING | ||
| 156 | +COMPLETED | ||
| 157 | +CANCELED | ||
| 158 | + | ||
| 159 | +# Every name exported from Index.ets (case-sensitive): with | ||
| 160 | +# -enable-export-obfuscation, renamed exports would rewrite the shipped | ||
| 161 | +# .d.ts (import { i } from "./d/f") and break every consumer's source. | ||
| 162 | +# Any new export added to Index.ets MUST be added here in the same | ||
| 163 | +# change. | ||
| 164 | +-keep-global-name | ||
| 165 | +A4p | ||
| 166 | +A4pCodec | ||
| 167 | +Signer | ||
| 168 | +SignatureVerifier | ||
| 169 | +VerificationResult | ||
| 170 | +CreateIntentRequest | ||
| 171 | +IntentIssueContext | ||
| 172 | +A4pErrorCode | ||
| 173 | +PaymentConstraints | ||
| 174 | +Product | ||
| 175 | +ItemWhiteList | ||
| 176 | +ShoppingItems | ||
| 177 | +CartItem | ||
| 178 | +SellerInfo | ||
| 179 | +SpuSkuInfo | ||
| 180 | +UserIdentity | ||
| 181 | +AgentIdentity | ||
| 182 | +ServiceProviderIdentity | ||
| 183 | +SigningEnv | ||
| 184 | +StructuredIntent | ||
| 185 | +IntentL1 | ||
| 186 | +IntentL2 | ||
| 187 | +IntentL3 | ||
| 188 | +SignatureInfo | ||
| 189 | +IntentActionType | ||
| 190 | +AlgorithmType | ||
| 191 | +Order | ||
| 192 | +Execution | ||
| 193 | +IntentExecutionStatus | ||
| 194 | +ExecutionStatus | ||
| 195 | +ExecutionRecord | ||
| 196 | +PaymentExecutionInfo | ||
| 197 | +IntentExecutionContext | ||
| @@ -0,0 +1,165 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +import { A4pErrorCode } from '../models/common'; | ||
| 6 | +import { IntentL1, IntentL2, IntentL3 } from '../models/intent'; | ||
| 7 | +import { IntentExecutionContext } from '../models/execution'; | ||
| 8 | +import { a4pThrow } from '../internal/result'; | ||
| 9 | +import { canonicalStringify, deepFreeze } from '../internal/utils'; | ||
| 10 | +import { | ||
| 11 | + validateIntentL1, validateIntentL2, validateIntentL3, validateIntentExecutionContext | ||
| 12 | +} from '../internal/validation'; | ||
| 13 | + | ||
| 14 | +/** | ||
| 15 | + * Canonical JSON codec for the intent levels and the execution context: | ||
| 16 | + * serialization produces the canonical form, deserialization parses and | ||
| 17 | + * structurally validates the result, so a malformed intent or context | ||
| 18 | + * never passes through the codec. | ||
| 19 | + */ | ||
| 20 | +export namespace A4pCodec { | ||
| 21 | + | ||
| 22 | + /** | ||
| 23 | + * Serializes an IntentL1 to canonical JSON. | ||
| 24 | + * @param { IntentL1 } intentL1 - The Level 1 intent to serialize. | ||
| 25 | + * @returns { string } The canonical JSON string representation. | ||
| 26 | + * @throws { BusinessError } 5001 - Serialization failed. | ||
| 27 | + */ | ||
| 28 | + export function serializeIntentL1(intentL1: IntentL1): string { | ||
| 29 | + return canonicalStringify(intentL1 as Object); | ||
| 30 | + } | ||
| 31 | + | ||
| 32 | + /** | ||
| 33 | + * Deserializes an IntentL1 from canonical JSON, validating its structure. | ||
| 34 | + * @param { string } serialized - The canonical JSON string to deserialize. | ||
| 35 | + * @returns { IntentL1 } The deserialized and validated IntentL1. | ||
| 36 | + * @throws { BusinessError } 1001 - Invalid parameter. | ||
| 37 | + * @throws { BusinessError } 5002 - Deserialization failed. | ||
| 38 | + */ | ||
| 39 | + export function deserializeIntentL1(serialized: string): IntentL1 { | ||
| 40 | + if (!serialized) { | ||
| 41 | + a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER, 'Serialized string is required'); | ||
| 42 | + } | ||
| 43 | + let obj: IntentL1; | ||
| 44 | + try { | ||
| 45 | + obj = JSON.parse(serialized) as IntentL1; | ||
| 46 | + } catch (e) { | ||
| 47 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Failed to deserialize IntentL1: ' + (e as Error).message); | ||
| 48 | + } | ||
| 49 | + const validationError = validateIntentL1(obj); | ||
| 50 | + if (validationError) { | ||
| 51 | + a4pThrow(validationError.code, validationError.detail); | ||
| 52 | + } | ||
| 53 | + return obj; | ||
| 54 | + } | ||
| 55 | + | ||
| 56 | + /** | ||
| 57 | + * Serializes an IntentL2 to canonical JSON. | ||
| 58 | + * @param { IntentL2 } intentL2 - The Level 2 intent to serialize. | ||
| 59 | + * @returns { string } The canonical JSON string representation. | ||
| 60 | + * @throws { BusinessError } 5001 - Serialization failed. | ||
| 61 | + */ | ||
| 62 | + export function serializeIntentL2(intentL2: IntentL2): string { | ||
| 63 | + return canonicalStringify(intentL2 as Object); | ||
| 64 | + } | ||
| 65 | + | ||
| 66 | + /** | ||
| 67 | + * Deserializes an IntentL2 from canonical JSON, validating its structure. | ||
| 68 | + * @param { string } serialized - The canonical JSON string to deserialize. | ||
| 69 | + * @returns { IntentL2 } The deserialized and validated IntentL2. | ||
| 70 | + * @throws { BusinessError } 1001 - Invalid parameter. | ||
| 71 | + * @throws { BusinessError } 5002 - Deserialization failed. | ||
| 72 | + */ | ||
| 73 | + export function deserializeIntentL2(serialized: string): IntentL2 { | ||
| 74 | + if (!serialized) { | ||
| 75 | + a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER, 'Serialized string is required'); | ||
| 76 | + } | ||
| 77 | + let obj: IntentL2; | ||
| 78 | + try { | ||
| 79 | + obj = JSON.parse(serialized) as IntentL2; | ||
| 80 | + } catch (e) { | ||
| 81 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Failed to deserialize IntentL2: ' + (e as Error).message); | ||
| 82 | + } | ||
| 83 | + const validationError = validateIntentL2(obj); | ||
| 84 | + if (validationError) { | ||
| 85 | + a4pThrow(validationError.code, validationError.detail); | ||
| 86 | + } | ||
| 87 | + return obj; | ||
| 88 | + } | ||
| 89 | + | ||
| 90 | + /** | ||
| 91 | + * Serializes an IntentL3 to canonical JSON. | ||
| 92 | + * @param { IntentL3 } intentL3 - The Level 3 intent to serialize. | ||
| 93 | + * @returns { string } The canonical JSON string representation. | ||
| 94 | + * @throws { BusinessError } 5001 - Serialization failed. | ||
| 95 | + */ | ||
| 96 | + export function serializeIntentL3(intentL3: IntentL3): string { | ||
| 97 | + return canonicalStringify(intentL3 as Object); | ||
| 98 | + } | ||
| 99 | + | ||
| 100 | + /** | ||
| 101 | + * Deserializes an IntentL3 from canonical JSON, validating its structure. | ||
| 102 | + * @param { string } serialized - The canonical JSON string to deserialize. | ||
| 103 | + * @returns { IntentL3 } The deserialized and validated IntentL3. | ||
| 104 | + * @throws { BusinessError } 1001 - Invalid parameter. | ||
| 105 | + * @throws { BusinessError } 5002 - Deserialization failed. | ||
| 106 | + */ | ||
| 107 | + export function deserializeIntentL3(serialized: string): IntentL3 { | ||
| 108 | + if (!serialized) { | ||
| 109 | + a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER, 'Serialized string is required'); | ||
| 110 | + } | ||
| 111 | + let obj: IntentL3; | ||
| 112 | + try { | ||
| 113 | + obj = JSON.parse(serialized) as IntentL3; | ||
| 114 | + } catch (e) { | ||
| 115 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Failed to deserialize IntentL3: ' + (e as Error).message); | ||
| 116 | + } | ||
| 117 | + const validationError = validateIntentL3(obj); | ||
| 118 | + if (validationError) { | ||
| 119 | + a4pThrow(validationError.code, validationError.detail); | ||
| 120 | + } | ||
| 121 | + return obj; | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + /** | ||
| 125 | + * Serializes an IntentExecutionContext to canonical JSON. | ||
| 126 | + * @param { IntentExecutionContext } context - The execution context to serialize. | ||
| 127 | + * @returns { string } The canonical JSON string representation. | ||
| 128 | + * @throws { BusinessError } 5001 - Serialization failed. | ||
| 129 | + */ | ||
| 130 | + export function serializeIntentExecutionContext(context: IntentExecutionContext): string { | ||
| 131 | + return canonicalStringify(context as Object); | ||
| 132 | + } | ||
| 133 | + | ||
| 134 | + /** | ||
| 135 | + * Deserializes an IntentExecutionContext from canonical JSON, validating | ||
| 136 | + * its structure: the authorized intent chain, the intentId derivation, | ||
| 137 | + * every ledger record, and the accounting snapshot (see | ||
| 138 | + * validateIntentExecutionContext). The authorization snapshot is | ||
| 139 | + * re-frozen on the way out, preserving the activation invariant — | ||
| 140 | + * execution checks read an immutable snapshot while the ledger and the | ||
| 141 | + * accounting figures stay mutable. | ||
| 142 | + * @param { string } serialized - The canonical JSON string to deserialize. | ||
| 143 | + * @returns { IntentExecutionContext } The deserialized and validated IntentExecutionContext. | ||
| 144 | + * @throws { BusinessError } 1001 - Invalid parameter. | ||
| 145 | + * @throws { BusinessError } 5002 - Deserialization failed. | ||
| 146 | + */ | ||
| 147 | + export function deserializeIntentExecutionContext(serialized: string): IntentExecutionContext { | ||
| 148 | + if (!serialized) { | ||
| 149 | + a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER, 'Serialized string is required'); | ||
| 150 | + } | ||
| 151 | + let obj: IntentExecutionContext; | ||
| 152 | + try { | ||
| 153 | + obj = JSON.parse(serialized) as IntentExecutionContext; | ||
| 154 | + } catch (e) { | ||
| 155 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, | ||
| 156 | + 'Failed to deserialize IntentExecutionContext: ' + (e as Error).message); | ||
| 157 | + } | ||
| 158 | + const validationError = validateIntentExecutionContext(obj); | ||
| 159 | + if (validationError) { | ||
| 160 | + a4pThrow(validationError.code, validationError.detail); | ||
| 161 | + } | ||
| 162 | + obj.authorizedIntent = deepFreeze(obj.authorizedIntent); | ||
| 163 | + return obj; | ||
| 164 | + } | ||
| 165 | +} | ||
| @@ -0,0 +1,35 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | +import { SignatureInfo } from "../models/intent"; | ||
| 5 | + | ||
| 6 | +/** | ||
| 7 | + * Signer Interface | ||
| 8 | + * | ||
| 9 | + * Defines the contract for cryptographic signing operations. | ||
| 10 | + * Implementations provide algorithm info, key identification, and signing capability. | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/** | ||
| 14 | + * Interface for signing data with a cryptographic key. | ||
| 15 | + * | ||
| 16 | + * Contract: implementations return an `alg` identifier and a `keyIdentifier` | ||
| 17 | + * consistent with the key actually used for signing. Both are detached | ||
| 18 | + * metadata, not covered by the signature — verifiers bind the algorithm | ||
| 19 | + * set to the key resolved from `keyIdentifier` (see SignatureVerifier), | ||
| 20 | + * so a mismatched pair fails verification. | ||
| 21 | + * | ||
| 22 | + * A signer that throws, returns nothing, or returns a malformed | ||
| 23 | + * SignatureInfo (undefined `alg`, blank `keyIdentifier` or `sign`) fails | ||
| 24 | + * the calling API with A4P_SIGNING_FAIL — the result is validated before | ||
| 25 | + * it is attached to the intent (see runSigner in api/a4p.ts), mirroring | ||
| 26 | + * the verifier-side guard on a verifier's return value. | ||
| 27 | + */ | ||
| 28 | +export interface Signer { | ||
| 29 | + /** | ||
| 30 | + * Signs the provided data bytes. | ||
| 31 | + * @param { Uint8Array } data - The data to sign as a byte array. | ||
| 32 | + * @returns { SignatureInfo } The SignatureInfo containing alg, keyIdentifier, and sign. | ||
| 33 | + */ | ||
| 34 | + sign(data: Uint8Array): SignatureInfo; | ||
| 35 | +} | ||
AA4P-arkts-sdk/a4p/src/main/ets/api/verifier.ts+39-0File content is under review, please try again later
| @@ -0,0 +1,164 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +import { ExecutionRecord, ExecutionStatus, PaymentExecutionInfo, IntentExecutionContext } from '../models/execution'; | ||
| 6 | +import { PaymentConstraints } from '../models/constraint'; | ||
| 7 | + | ||
| 8 | +/** | ||
| 9 | + * Execution accounting helpers. | ||
| 10 | + * | ||
| 11 | + * All quota figures (accumulated amount, execution count, period execution | ||
| 12 | + * count, remaining budgets) are derived from the append-only `executions` | ||
| 13 | + * ledger — never maintained as independent counters — so canceling a record | ||
| 14 | + * releases its amount, count slot, and period slot by construction. The | ||
| 15 | + * ledger itself stays append-only: `executions.length` never decreases. | ||
| 16 | + */ | ||
| 17 | + | ||
| 18 | +/** | ||
| 19 | + * The resolved period rule of a periodic intent: the all-or-nothing | ||
| 20 | + * `anchorTime`/`periodSeconds`/`maxExecutionCountPerPeriod` triple with | ||
| 21 | + * the optionality resolved away (see periodRuleOf). | ||
| 22 | + */ | ||
| 23 | +export interface PeriodRule { | ||
| 24 | + /** Anchor time for period calculation (milliseconds since epoch) */ | ||
| 25 | + anchorTime: number; | ||
| 26 | + /** Period duration in seconds */ | ||
| 27 | + periodSeconds: number; | ||
| 28 | + /** Maximum number of non-canceled executions allowed per period */ | ||
| 29 | + maxExecutionCountPerPeriod: number; | ||
| 30 | +} | ||
| 31 | + | ||
| 32 | +/** | ||
| 33 | + * The period rule of the constraints, or null for non-periodic intents. | ||
| 34 | + * The rule is all-or-nothing: all three fields present (periodic) or all | ||
| 35 | + * three omitted (non-periodic); validation rejects partial rules. | ||
| 36 | + * @param constraints - The payment constraints to resolve the period rule from | ||
| 37 | + * @returns The resolved period rule, or null when the constraints are non-periodic | ||
| 38 | + */ | ||
| 39 | +export function periodRuleOf(constraints: PaymentConstraints): PeriodRule | null { | ||
| 40 | + const anchorTime: number | undefined = constraints.anchorTime; | ||
| 41 | + const periodSeconds: number | undefined = constraints.periodSeconds; | ||
| 42 | + const maxExecutionCountPerPeriod: number | undefined = constraints.maxExecutionCountPerPeriod; | ||
| 43 | + if (anchorTime === undefined || periodSeconds === undefined || maxExecutionCountPerPeriod === undefined) { | ||
| 44 | + return null; | ||
| 45 | + } | ||
| 46 | + return { | ||
| 47 | + anchorTime: anchorTime, | ||
| 48 | + periodSeconds: periodSeconds, | ||
| 49 | + maxExecutionCountPerPeriod: maxExecutionCountPerPeriod, | ||
| 50 | + }; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/** | ||
| 54 | + * Period index a given time falls into, relative to the anchor. | ||
| 55 | + * @param rule - The resolved period rule defining the period structure | ||
| 56 | + * @param now - The evaluation instant in epoch milliseconds | ||
| 57 | + * @returns The zero-based period index | ||
| 58 | + */ | ||
| 59 | +export function computeCurrentPeriodIndex(rule: PeriodRule, now: number): number { | ||
| 60 | + return Math.floor((now - rule.anchorTime) / (rule.periodSeconds * 1000)); | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +/** | ||
| 64 | + * Whether the record counts toward quotas (amount, execution count, | ||
| 65 | + * current period): canceled records are excluded (their quota was | ||
| 66 | + * released). | ||
| 67 | + */ | ||
| 68 | +function isCountedRecord(record: ExecutionRecord): boolean { | ||
| 69 | + return record.status !== ExecutionStatus.CANCELED; | ||
| 70 | +} | ||
| 71 | + | ||
| 72 | +/** | ||
| 73 | + * Number of non-canceled records in the ledger. | ||
| 74 | + * @param executions - The execution records ledger to count from | ||
| 75 | + * @returns The count of non-canceled records | ||
| 76 | + */ | ||
| 77 | +export function computeExecutionCount(executions: ExecutionRecord[]): number { | ||
| 78 | + let count: number = 0; | ||
| 79 | + for (let i = 0; i < executions.length; i++) { | ||
| 80 | + if (isCountedRecord(executions[i])) { | ||
| 81 | + count += 1; | ||
| 82 | + } | ||
| 83 | + } | ||
| 84 | + return count; | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/** | ||
| 88 | + * Number of non-canceled records within the given period. | ||
| 89 | + * @param executions - The execution records ledger to count from | ||
| 90 | + * @param periodIndex - The period index to count records for | ||
| 91 | + * @returns The count of non-canceled records in the specified period | ||
| 92 | + */ | ||
| 93 | +export function computePeriodExecutionCount(executions: ExecutionRecord[], periodIndex: number): number { | ||
| 94 | + let count: number = 0; | ||
| 95 | + for (let i = 0; i < executions.length; i++) { | ||
| 96 | + if (executions[i].periodIndex === periodIndex && isCountedRecord(executions[i])) { | ||
| 97 | + count += 1; | ||
| 98 | + } | ||
| 99 | + } | ||
| 100 | + return count; | ||
| 101 | +} | ||
| 102 | + | ||
| 103 | +/** | ||
| 104 | + * Sum of `amount` across all non-canceled execution records in the ledger. | ||
| 105 | + * Canceled records are excluded because cancel is an explicit definitive | ||
| 106 | + * outcome that releases quota. | ||
| 107 | + * @param executions - The execution records ledger | ||
| 108 | + * @returns The accumulated payment amount in cents | ||
| 109 | + */ | ||
| 110 | +export function computeAccumulatedAmount(executions: ExecutionRecord[]): number { | ||
| 111 | + let sum: number = 0; | ||
| 112 | + for (let i = 0; i < executions.length; i++) { | ||
| 113 | + if (isCountedRecord(executions[i])) { | ||
| 114 | + sum += executions[i].execution.executionContent.amount; | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | + return sum; | ||
| 118 | +} | ||
| 119 | + | ||
| 120 | +/** | ||
| 121 | + * Derives the execution-info snapshot from the payment constraints and the | ||
| 122 | + * executions ledger: | ||
| 123 | + * - fields whose cap does not apply are omitted: `leftExecutionCount` when | ||
| 124 | + * the intent carries no `maxExecuteCount` cap, and the period figures | ||
| 125 | + * (`periodIndex`, `leftPeriodExecutionCount`) for non-periodic intents; | ||
| 126 | + * - all figures count only non-canceled records (an explicit cancel | ||
| 127 | + * releases the quota); | ||
| 128 | + * - period figures are relative to the period containing `now`. | ||
| 129 | + * @param constraints - The authorized payment constraints | ||
| 130 | + * @param executions - The execution records ledger | ||
| 131 | + * @param now - The evaluation instant in epoch milliseconds | ||
| 132 | + * @returns The derived execution info | ||
| 133 | + */ | ||
| 134 | +export function computeExecutionInfo(constraints: PaymentConstraints, executions: ExecutionRecord[], | ||
| 135 | + now: number): PaymentExecutionInfo { | ||
| 136 | + const info: PaymentExecutionInfo = { | ||
| 137 | + leftAmount: constraints.totalMaxAmount - computeAccumulatedAmount(executions) | ||
| 138 | + }; | ||
| 139 | + const countCap: number | undefined = constraints.maxExecuteCount; | ||
| 140 | + if (countCap !== undefined) { | ||
| 141 | + info.leftExecutionCount = countCap - computeExecutionCount(executions); | ||
| 142 | + } | ||
| 143 | + const rule: PeriodRule | null = periodRuleOf(constraints); | ||
| 144 | + if (rule !== null) { | ||
| 145 | + const periodIndex: number = computeCurrentPeriodIndex(rule, now); | ||
| 146 | + info.periodIndex = periodIndex; | ||
| 147 | + info.leftPeriodExecutionCount = rule.maxExecutionCountPerPeriod - | ||
| 148 | + computePeriodExecutionCount(executions, periodIndex); | ||
| 149 | + } | ||
| 150 | + return info; | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/** | ||
| 154 | + * Recomputes the execution info of the context from the executions ledger. | ||
| 155 | + * Must be called after every ledger mutation so the materialized fields can | ||
| 156 | + * never drift from the records. The execution count is not materialized — | ||
| 157 | + * it is derived from the ledger's non-canceled records. | ||
| 158 | + * @param context - The execution context whose accounting fields to recompute | ||
| 159 | + * @param now - The evaluation instant in epoch milliseconds for period calculation | ||
| 160 | + */ | ||
| 161 | +export function recomputeAccounting(context: IntentExecutionContext, now: number): void { | ||
| 162 | + const constraints: PaymentConstraints = context.authorizedIntent.intentL2.intentL1.structuredIntent.constraints; | ||
| 163 | + context.executionInfo = computeExecutionInfo(constraints, context.executions, now); | ||
| 164 | +} | ||
AA4P-arkts-sdk/a4p/src/main/ets/internal/http.ts+426-0File content is under review, please try again later
| @@ -0,0 +1,21 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +import { hilog } from '@kit.PerformanceAnalysisKit'; | ||
| 6 | +import { A4pErrorCode } from '../models/common'; | ||
| 7 | + | ||
| 8 | +const LOG_DOMAIN: number = 0x0000; | ||
| 9 | +const LOG_TAG: string = 'A4P'; | ||
| 10 | + | ||
| 11 | +/** | ||
| 12 | + * Records the specific cause behind an A4P error code via hilog. Thrown | ||
| 13 | + * A4pErrors carry only the fixed message for their code, so this is where | ||
| 14 | + * the differing reasons (field paths, current statuses, underlying error | ||
| 15 | + * messages) are recorded for diagnostics. | ||
| 16 | + * @param code - The A4P error code the detail belongs to | ||
| 17 | + * @param detail - The specific cause distinguishing this failure | ||
| 18 | + */ | ||
| 19 | +export function logErrorDetail(code: A4pErrorCode, detail: string): void { | ||
| 20 | + hilog.error(LOG_DOMAIN, LOG_TAG, 'code %{public}d: %{public}s', code, detail); | ||
| 21 | +} | ||
| @@ -0,0 +1,24 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +import { A4pError, A4pErrorCode } from '../models/common'; | ||
| 6 | +import { logErrorDetail } from './log'; | ||
| 7 | + | ||
| 8 | +/** | ||
| 9 | + * Thrown by all A4P APIs on failure. All failures — validation, signature, | ||
| 10 | + * state, serialization — surface as a thrown A4pError carrying the error | ||
| 11 | + * code; APIs return their data directly on success. The thrown error's | ||
| 12 | + * message is fixed per code (see a4pErrorMessage), so identical codes | ||
| 13 | + * always carry identical messages; the specific cause — which field | ||
| 14 | + * failed validation, what the underlying error was — is recorded via | ||
| 15 | + * hilog, not embedded in the error message. | ||
| 16 | + * @param code - The A4P error code identifying the failure category | ||
| 17 | + * @param detail - The specific cause distinguishing this failure; logged via hilog | ||
| 18 | + */ | ||
| 19 | +export function a4pThrow(code: A4pErrorCode, detail?: string): never { | ||
| 20 | + if (detail) { | ||
| 21 | + logErrorDetail(code, detail); | ||
| 22 | + } | ||
| 23 | + throw new A4pError(code); | ||
| 24 | +} | ||
| @@ -0,0 +1,395 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Internal utilities: base64url and UTF-8 codecs, canonical JSON | ||
| 7 | + * serialization, and deep clone/freeze helpers. | ||
| 8 | + */ | ||
| 9 | + | ||
| 10 | +import { A4pErrorCode } from '../models/common'; | ||
| 11 | +import { a4pThrow } from './result'; | ||
| 12 | + | ||
| 13 | +const BASE64URL_CHARS: string = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_'; | ||
| 14 | + | ||
| 15 | +/** | ||
| 16 | + * Encodes a byte array to a base64url string (unpadded). | ||
| 17 | + * @param data - The byte array to encode | ||
| 18 | + * @returns The base64url-encoded string | ||
| 19 | + */ | ||
| 20 | +export function base64UrlEncode(data: Uint8Array): string { | ||
| 21 | + let result: string = ''; | ||
| 22 | + const len: number = data.length; | ||
| 23 | + for (let i = 0; i < len; i += 3) { | ||
| 24 | + const a: number = data[i]; | ||
| 25 | + const b: number = i + 1 < len ? data[i + 1] : 0; | ||
| 26 | + const c: number = i + 2 < len ? data[i + 2] : 0; | ||
| 27 | + result += BASE64URL_CHARS[(a >> 2) & 0x3F]; | ||
| 28 | + result += BASE64URL_CHARS[((a << 4) | (b >> 4)) & 0x3F]; | ||
| 29 | + if (i + 1 < len) { | ||
| 30 | + result += BASE64URL_CHARS[((b << 2) | (c >> 6)) & 0x3F]; | ||
| 31 | + } | ||
| 32 | + if (i + 2 < len) { | ||
| 33 | + result += BASE64URL_CHARS[c & 0x3F]; | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | + return result; | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/** | ||
| 40 | + * Decodes a base64url string (unpadded) to a byte array. | ||
| 41 | + * Rejects non-canonical encodings where unused trailing bits are non-zero. | ||
| 42 | + * @param str - The base64url string to decode | ||
| 43 | + * @returns The decoded byte array | ||
| 44 | + * @throws A4pError with A4P_DESERIALIZE_FAIL on invalid length, character, or non-canonical encoding | ||
| 45 | + */ | ||
| 46 | +export function base64UrlDecode(str: string): Uint8Array { | ||
| 47 | + const len: number = str.length; | ||
| 48 | + // A valid base64url string (unpadded) has length % 4 != 1; a trailing | ||
| 49 | + // group of one character carries no bits and is never produced by encode. | ||
| 50 | + if (len % 4 === 1) { | ||
| 51 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url length: ' + len); | ||
| 52 | + } | ||
| 53 | + const byteLen: number = Math.floor(len * 3 / 4); | ||
| 54 | + const result: Uint8Array = new Uint8Array(byteLen); | ||
| 55 | + | ||
| 56 | + let byteIndex: number = 0; | ||
| 57 | + for (let i = 0; i < len; i += 4) { | ||
| 58 | + const a: number = BASE64URL_CHARS.indexOf(str[i]); | ||
| 59 | + if (a < 0) { | ||
| 60 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url character at position ' + i); | ||
| 61 | + } | ||
| 62 | + const b: number = i + 1 < len ? BASE64URL_CHARS.indexOf(str[i + 1]) : 0; | ||
| 63 | + if (i + 1 < len && b < 0) { | ||
| 64 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url character at position ' + (i + 1)); | ||
| 65 | + } | ||
| 66 | + const c: number = i + 2 < len ? BASE64URL_CHARS.indexOf(str[i + 2]) : 0; | ||
| 67 | + if (i + 2 < len && c < 0) { | ||
| 68 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url character at position ' + (i + 2)); | ||
| 69 | + } | ||
| 70 | + const d: number = i + 3 < len ? BASE64URL_CHARS.indexOf(str[i + 3]) : 0; | ||
| 71 | + if (i + 3 < len && d < 0) { | ||
| 72 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url character at position ' + (i + 3)); | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + // Reject non-canonical encodings: trailing groups must carry their | ||
| 76 | + // unused bits as zero, otherwise the same bytes could be encoded in | ||
| 77 | + // multiple ways and break signature determinism. | ||
| 78 | + // A 2-char tail encodes 1 byte: the low 4 bits of b are unused. | ||
| 79 | + if (i + 2 >= len && (b & 0x0F) !== 0) { | ||
| 80 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url padding bits at position ' + (i + 1)); | ||
| 81 | + } | ||
| 82 | + // A 3-char tail encodes 2 bytes: the low 2 bits of c are unused. | ||
| 83 | + if (i + 3 >= len && (c & 0x03) !== 0) { | ||
| 84 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid base64url padding bits at position ' + (i + 2)); | ||
| 85 | + } | ||
| 86 | + | ||
| 87 | + if (byteIndex < byteLen) { | ||
| 88 | + result[byteIndex++] = ((a << 2) | (b >> 4)) & 0xFF; | ||
| 89 | + } | ||
| 90 | + if (byteIndex < byteLen) { | ||
| 91 | + result[byteIndex++] = ((b << 4) | (c >> 2)) & 0xFF; | ||
| 92 | + } | ||
| 93 | + if (byteIndex < byteLen) { | ||
| 94 | + result[byteIndex++] = ((c << 6) | d) & 0xFF; | ||
| 95 | + } | ||
| 96 | + } | ||
| 97 | + return result; | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/** | ||
| 101 | + * Encodes a string to a UTF-8 byte array. | ||
| 102 | + * @param str - The string to encode | ||
| 103 | + * @returns The UTF-8 encoded byte array | ||
| 104 | + * @throws A4pError with A4P_SERIALIZE_FAIL on lone surrogates (high or low) in the input | ||
| 105 | + */ | ||
| 106 | +export function encodeUtf8(str: string): Uint8Array { | ||
| 107 | + const bytes: number[] = []; | ||
| 108 | + for (let i = 0; i < str.length; i++) { | ||
| 109 | + let c: number = str.charCodeAt(i); | ||
| 110 | + if (c < 0x80) { | ||
| 111 | + bytes.push(c); | ||
| 112 | + } else if (c < 0x800) { | ||
| 113 | + bytes.push(0xc0 | (c >> 6)); | ||
| 114 | + bytes.push(0x80 | (c & 0x3f)); | ||
| 115 | + } else if (c >= 0xd800 && c <= 0xdbff) { | ||
| 116 | + const hi: number = c; | ||
| 117 | + const lo: number = str.charCodeAt(++i); | ||
| 118 | + // Note: charCodeAt out of bounds returns NaN, and NaN compares false | ||
| 119 | + // against everything — so the check must be "not in range", not | ||
| 120 | + // "out of range", to catch both NaN and non-surrogate followers. | ||
| 121 | + if (!(lo >= 0xdc00 && lo <= 0xdfff)) { | ||
| 122 | + a4pThrow(A4pErrorCode.A4P_SERIALIZE_FAIL, 'Invalid UTF-16 string: lone surrogate at position ' + (i - 1)); | ||
| 123 | + } | ||
| 124 | + c = 0x10000 + ((hi - 0xd800) << 10) + (lo - 0xdc00); | ||
| 125 | + bytes.push(0xf0 | (c >> 18)); | ||
| 126 | + bytes.push(0x80 | ((c >> 12) & 0x3f)); | ||
| 127 | + bytes.push(0x80 | ((c >> 6) & 0x3f)); | ||
| 128 | + bytes.push(0x80 | (c & 0x3f)); | ||
| 129 | + } else if (c >= 0xdc00 && c <= 0xdfff) { | ||
| 130 | + // A low surrogate without a preceding high surrogate is exactly as | ||
| 131 | + // invalid as the lone high surrogate above: it would otherwise fall | ||
| 132 | + // through to the 3-byte branch and be emitted as a CESU-8-style | ||
| 133 | + // sequence, which is not UTF-8. | ||
| 134 | + a4pThrow(A4pErrorCode.A4P_SERIALIZE_FAIL, 'Invalid UTF-16 string: lone surrogate at position ' + i); | ||
| 135 | + } else { | ||
| 136 | + bytes.push(0xe0 | (c >> 12)); | ||
| 137 | + bytes.push(0x80 | ((c >> 6) & 0x3f)); | ||
| 138 | + bytes.push(0x80 | (c & 0x3f)); | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + return new Uint8Array(bytes); | ||
| 142 | +} | ||
| 143 | + | ||
| 144 | +/** Reads the UTF-8 continuation byte at index i, returning its 6 data bits. */ | ||
| 145 | +function readContinuation(bytes: Uint8Array, i: number): number { | ||
| 146 | + if (i >= bytes.length) { | ||
| 147 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Truncated UTF-8 sequence'); | ||
| 148 | + } | ||
| 149 | + const b: number = bytes[i]; | ||
| 150 | + if ((b & 0xc0) !== 0x80) { | ||
| 151 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Invalid UTF-8 continuation byte at index ' + i); | ||
| 152 | + } | ||
| 153 | + return b & 0x3f; | ||
| 154 | +} | ||
| 155 | + | ||
| 156 | +/** | ||
| 157 | + * Decodes a UTF-8 byte array to a string. | ||
| 158 | + * @param bytes - The UTF-8 byte array to decode | ||
| 159 | + * @returns The decoded string | ||
| 160 | + * @throws A4pError with A4P_DESERIALIZE_FAIL on invalid, overlong, or | ||
| 161 | + * surrogate-encoded UTF-8 sequences | ||
| 162 | + */ | ||
| 163 | +export function decodeUtf8(bytes: Uint8Array): string { | ||
| 164 | + let str: string = ''; | ||
| 165 | + let i: number = 0; | ||
| 166 | + while (i < bytes.length) { | ||
| 167 | + const b: number = bytes[i++]; | ||
| 168 | + if (b < 0x80) { | ||
| 169 | + str += String.fromCharCode(b); | ||
| 170 | + } else if (b < 0xc0) { | ||
| 171 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Unexpected UTF-8 continuation byte at index ' + (i - 1)); | ||
| 172 | + } else if (b < 0xe0) { | ||
| 173 | + const c: number = ((b & 0x1f) << 6) | readContinuation(bytes, i++); | ||
| 174 | + // Lead bytes 0xC0/0xC1 always decode below 0x80: overlong forms of | ||
| 175 | + // 1-byte characters, rejected like the 3/4-byte branches so a | ||
| 176 | + // string keeps exactly one byte representation. | ||
| 177 | + if (c < 0x80) { | ||
| 178 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Overlong UTF-8 encoding at index ' + (i - 2)); | ||
| 179 | + } | ||
| 180 | + str += String.fromCharCode(c); | ||
| 181 | + } else if (b < 0xf0) { | ||
| 182 | + const c: number = ((b & 0x0f) << 12) | (readContinuation(bytes, i++) << 6) | readContinuation(bytes, i++); | ||
| 183 | + if (c < 0x800) { | ||
| 184 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Overlong UTF-8 encoding at index ' + (i - 3)); | ||
| 185 | + } | ||
| 186 | + // Surrogate code points have no UTF-8 encoding: 3-byte sequences in | ||
| 187 | + // that range are CESU-8/WTF-8, and decoding them would build lone | ||
| 188 | + // surrogates (or accidental pairs) into the string. | ||
| 189 | + if (c >= 0xd800 && c <= 0xdfff) { | ||
| 190 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'UTF-8-encoded surrogate code point at index ' + (i - 3)); | ||
| 191 | + } | ||
| 192 | + str += String.fromCharCode(c); | ||
| 193 | + } else { | ||
| 194 | + const c: number = ((b & 0x07) << 18) | (readContinuation(bytes, i++) << 12) | | ||
| 195 | + (readContinuation(bytes, i++) << 6) | readContinuation(bytes, i++); | ||
| 196 | + if (c < 0x10000 || c > 0x10ffff) { | ||
| 197 | + a4pThrow(A4pErrorCode.A4P_DESERIALIZE_FAIL, 'Overlong or out-of-range UTF-8 encoding at index ' + (i - 4)); | ||
| 198 | + } | ||
| 199 | + const offset: number = c - 0x10000; | ||
| 200 | + str += String.fromCharCode(0xd800 + (offset >> 10), 0xdc00 + (offset & 0x3ff)); | ||
| 201 | + } | ||
| 202 | + } | ||
| 203 | + return str; | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/** | ||
| 207 | + * Serializes a value to canonical JSON: sorted keys, no whitespace, | ||
| 208 | + * integers only, undefined values omitted. | ||
| 209 | + * @param value - The value to serialize (plain objects, arrays, primitives) | ||
| 210 | + * @returns The canonical JSON string | ||
| 211 | + * @throws A4pError with A4P_SERIALIZE_FAIL on non-plain objects, non-safe integers, or non-finite numbers | ||
| 212 | + */ | ||
| 213 | +export function canonicalStringify(value: Object): string { | ||
| 214 | + if (value === null || value === undefined) { | ||
| 215 | + return 'null'; | ||
| 216 | + } | ||
| 217 | + if (typeof value === 'boolean') { | ||
| 218 | + return value ? 'true' : 'false'; | ||
| 219 | + } | ||
| 220 | + if (typeof value === 'number') { | ||
| 221 | + // Canonical JSON number invariant: every number must be a finite | ||
| 222 | + // safe integer, rendered as a decimal digit string. Anything else | ||
| 223 | + // cannot round-trip identically across implementations and must | ||
| 224 | + // fail loudly instead of silently normalizing. | ||
| 225 | + if (!isFinite(value) || Math.floor(value) !== value || | ||
| 226 | + value > Number.MAX_SAFE_INTEGER || value < -Number.MAX_SAFE_INTEGER) { | ||
| 227 | + a4pThrow(A4pErrorCode.A4P_SERIALIZE_FAIL, 'canonicalStringify only supports finite safe integers, got: ' + value); | ||
| 228 | + } | ||
| 229 | + return value.toString(); | ||
| 230 | + } | ||
| 231 | + if (typeof value === 'string') { | ||
| 232 | + return escapeJsonString(value); | ||
| 233 | + } | ||
| 234 | + if (Array.isArray(value)) { | ||
| 235 | + const items: string[] = []; | ||
| 236 | + for (let i = 0; i < value.length; i++) { | ||
| 237 | + items.push(canonicalStringify(value[i] as Object)); | ||
| 238 | + } | ||
| 239 | + return '[' + items.join(',') + ']'; | ||
| 240 | + } | ||
| 241 | + if (typeof value === 'object') { | ||
| 242 | + // Only plain objects have a deterministic key set; anything else | ||
| 243 | + // (Date, Map, Set, typed arrays, class instances) would silently | ||
| 244 | + // serialize to "{}" or misordered indices, so reject it outright. | ||
| 245 | + const proto: object | null = Object.getPrototypeOf(value); | ||
| 246 | + if (proto !== Object.prototype && proto !== null) { | ||
| 247 | + a4pThrow(A4pErrorCode.A4P_SERIALIZE_FAIL, | ||
| 248 | + 'canonicalStringify only supports plain objects, arrays and primitives, got: ' + | ||
| 249 | + (proto ? (proto.constructor ? proto.constructor.name : 'unknown') : 'null prototype')); | ||
| 250 | + } | ||
| 251 | + // Default sort compares UTF-16 code units — the canonical key | ||
| 252 | + // order. It is NOT Unicode code point order: the two differ for | ||
| 253 | + // keys mixing astral characters with BMP characters above U+D7FF, | ||
| 254 | + // so a code-point sort would diverge from the reference. | ||
| 255 | + const keys: string[] = Object.keys(value as Record<string, Object>).sort(); | ||
| 256 | + const pairs: string[] = []; | ||
| 257 | + for (let i = 0; i < keys.length; i++) { | ||
| 258 | + const k: string = keys[i]; | ||
| 259 | + const v: Object = (value as Record<string, Object>)[k]; | ||
| 260 | + if (v === undefined) { | ||
| 261 | + continue; | ||
| 262 | + } | ||
| 263 | + pairs.push(escapeJsonString(k) + ':' + canonicalStringify(v)); | ||
| 264 | + } | ||
| 265 | + return '{' + pairs.join(',') + '}'; | ||
| 266 | + } | ||
| 267 | + return 'null'; | ||
| 268 | +} | ||
| 269 | + | ||
| 270 | +/** Escapes a string per JSON: quotes, backslash, and control characters. */ | ||
| 271 | +function escapeJsonString(s: string): string { | ||
| 272 | + let result: string = '"'; | ||
| 273 | + for (let i = 0; i < s.length; i++) { | ||
| 274 | + const c: string = s[i]; | ||
| 275 | + switch (c) { | ||
| 276 | + case '"': | ||
| 277 | + result += '\\"'; | ||
| 278 | + break; | ||
| 279 | + case '\\': | ||
| 280 | + result += '\\\\'; | ||
| 281 | + break; | ||
| 282 | + case '\b': | ||
| 283 | + result += '\\b'; | ||
| 284 | + break; | ||
| 285 | + case '\f': | ||
| 286 | + result += '\\f'; | ||
| 287 | + break; | ||
| 288 | + case '\n': | ||
| 289 | + result += '\\n'; | ||
| 290 | + break; | ||
| 291 | + case '\r': | ||
| 292 | + result += '\\r'; | ||
| 293 | + break; | ||
| 294 | + case '\t': | ||
| 295 | + result += '\\t'; | ||
| 296 | + break; | ||
| 297 | + default: | ||
| 298 | + if (c.charCodeAt(0) < 0x20) { | ||
| 299 | + result += '\\u' + c.charCodeAt(0).toString(16).padStart(4, '0'); | ||
| 300 | + } else { | ||
| 301 | + result += c; | ||
| 302 | + } | ||
| 303 | + break; | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + return result + '"'; | ||
| 307 | +} | ||
| 308 | + | ||
| 309 | +/** | ||
| 310 | + * Strips the top-level `sign` field (the whole SignatureInfo) only: | ||
| 311 | + * signatures of nested intents (e.g. intentL1.sign inside intentL2) | ||
| 312 | + * stay in the signed payload so each signature covers the full chain | ||
| 313 | + * below it. The stripped object is detached signature metadata — | ||
| 314 | + * `alg`/`keyIdentifier` are not part of the signed bytes. | ||
| 315 | + */ | ||
| 316 | +function stripTopLevelSign(obj: object): Object { | ||
| 317 | + const src: Record<string, Object> = obj as Record<string, Object>; | ||
| 318 | + if (!Object.prototype.hasOwnProperty.call(src, 'sign')) { | ||
| 319 | + return obj as Object; | ||
| 320 | + } | ||
| 321 | + const clone: Record<string, Object> = {}; | ||
| 322 | + const keys: string[] = Object.keys(src); | ||
| 323 | + for (let i = 0; i < keys.length; i++) { | ||
| 324 | + if (keys[i] !== 'sign') { | ||
| 325 | + clone[keys[i]] = src[keys[i]]; | ||
| 326 | + } | ||
| 327 | + } | ||
| 328 | + return clone as Object; | ||
| 329 | +} | ||
| 330 | + | ||
| 331 | +/** | ||
| 332 | + * Produces the signable bytes for an intent object: canonical JSON with | ||
| 333 | + * the top-level sign field stripped, encoded as UTF-8. | ||
| 334 | + * @param obj - The intent object to convert to signable bytes | ||
| 335 | + * @returns The UTF-8 encoded canonical JSON bytes (without top-level sign) | ||
| 336 | + */ | ||
| 337 | +export function toSignableBytes(obj: object): Uint8Array { | ||
| 338 | + const canonical: string = canonicalStringify(stripTopLevelSign(obj)); | ||
| 339 | + return encodeUtf8(canonical); | ||
| 340 | +} | ||
| 341 | + | ||
| 342 | +/** | ||
| 343 | + * Deep-copies a plain-object tree (arrays and object literals only). | ||
| 344 | + * Used when embedding a lower-level intent into a higher-level one so the | ||
| 345 | + * two do not share references: mutating the caller's original after | ||
| 346 | + * issuance would silently invalidate the covering signature. | ||
| 347 | + * @param value - The value to deep-copy | ||
| 348 | + * @returns A deep copy of the value | ||
| 349 | + */ | ||
| 350 | +export function deepClone<T>(value: T): T { | ||
| 351 | + if (value === null || typeof value !== 'object') { | ||
| 352 | + return value; | ||
| 353 | + } | ||
| 354 | + if (Array.isArray(value)) { | ||
| 355 | + const arr: Object[] = []; | ||
| 356 | + for (let i = 0; i < value.length; i++) { | ||
| 357 | + arr.push(deepClone(value[i] as Object)); | ||
| 358 | + } | ||
| 359 | + return arr as Object as T; | ||
| 360 | + } | ||
| 361 | + const src: Record<string, Object> = value as Record<string, Object>; | ||
| 362 | + const out: Record<string, Object> = {}; | ||
| 363 | + const keys: string[] = Object.keys(src); | ||
| 364 | + for (let i = 0; i < keys.length; i++) { | ||
| 365 | + out[keys[i]] = deepClone(src[keys[i]]); | ||
| 366 | + } | ||
| 367 | + return out as Object as T; | ||
| 368 | +} | ||
| 369 | + | ||
| 370 | +/** | ||
| 371 | + * Recursively freezes a plain-object tree. This is protection against | ||
| 372 | + * accidental mutation of the authorization snapshot, not a cryptographic | ||
| 373 | + * boundary — a determined caller can still work around Object.freeze. | ||
| 374 | + * @param value - The value to deep-freeze | ||
| 375 | + * @returns The frozen value (same reference, now immutable) | ||
| 376 | + */ | ||
| 377 | +export function deepFreeze<T>(value: T): T { | ||
| 378 | + if (value === null || typeof value !== 'object') { | ||
| 379 | + return value; | ||
| 380 | + } | ||
| 381 | + if (Array.isArray(value)) { | ||
| 382 | + for (let i = 0; i < value.length; i++) { | ||
| 383 | + deepFreeze(value[i] as Object); | ||
| 384 | + } | ||
| 385 | + Object.freeze(value); | ||
| 386 | + return value; | ||
| 387 | + } | ||
| 388 | + const src: Record<string, Object> = value as Record<string, Object>; | ||
| 389 | + const keys: string[] = Object.keys(src); | ||
| 390 | + for (let i = 0; i < keys.length; i++) { | ||
| 391 | + deepFreeze(src[keys[i]]); | ||
| 392 | + } | ||
| 393 | + Object.freeze(value); | ||
| 394 | + return value; | ||
| 395 | +} | ||
| @@ -0,0 +1,195 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Common Types for A4P Protocol | ||
| 7 | + * | ||
| 8 | + * Shared interfaces and types used across the A4P SDK, | ||
| 9 | + * including request/response types and the error type thrown on failure. | ||
| 10 | + */ | ||
| 11 | + | ||
| 12 | +import { StructuredIntent } from './intent'; | ||
| 13 | +import { UserIdentity, AgentIdentity, ServiceProviderIdentity } from './identity'; | ||
| 14 | + | ||
| 15 | +/** | ||
| 16 | + * Request payload for creating a new Level 1 intent. | ||
| 17 | + */ | ||
| 18 | +export interface CreateIntentRequest { | ||
| 19 | + /** original intent conversation */ | ||
| 20 | + intentConversation: string; | ||
| 21 | + /** Human-readable summary of the intent */ | ||
| 22 | + intentSummary: string; | ||
| 23 | + /** Structured intent data containing action and constraints */ | ||
| 24 | + structuredIntent: StructuredIntent; | ||
| 25 | + /** Pre-assigned intent identifier (optional; generated when absent) */ | ||
| 26 | + intentId?: string; | ||
| 27 | +} | ||
| 28 | + | ||
| 29 | +/** | ||
| 30 | + * Context required for issuing a Level 1 intent to Level 2. | ||
| 31 | + */ | ||
| 32 | +export interface IntentIssueContext { | ||
| 33 | + /** Identity of the user involved */ | ||
| 34 | + userIdentity: UserIdentity; | ||
| 35 | + /** Identity of the agent creating the intent */ | ||
| 36 | + agentIdentity: AgentIdentity; | ||
| 37 | + /** Identity of the service provider */ | ||
| 38 | + serviceProviderIdentity: ServiceProviderIdentity; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/** | ||
| 42 | + * Result of a signature verification operation. | ||
| 43 | + */ | ||
| 44 | +export interface VerificationResult { | ||
| 45 | + /** Whether the signature is valid */ | ||
| 46 | + valid: boolean; | ||
| 47 | + /** Verification result code (provider-specific numeric code) */ | ||
| 48 | + code: number; | ||
| 49 | + /** Human-readable result message */ | ||
| 50 | + message?: string; | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/** | ||
| 54 | + * A4P Protocol Error Codes. | ||
| 55 | + * | ||
| 56 | + * Standard error codes used across all A4P operations. | ||
| 57 | + * | ||
| 58 | + * Error code ranges: | ||
| 59 | + * - 0: Success | ||
| 60 | + * - 1001-1999: Parameter/Validation errors | ||
| 61 | + * - 2001-2999: Signature/Verification errors | ||
| 62 | + * - 3001-3999: State/Lifecycle errors | ||
| 63 | + * - 4001-4999: Execution/Limit errors | ||
| 64 | + * - 5001-5999: Serialization/HTTP errors | ||
| 65 | + * - 6001-6999: System/Internal errors | ||
| 66 | + */ | ||
| 67 | +export enum A4pErrorCode { | ||
| 68 | + /** Operation completed successfully */ | ||
| 69 | + A4P_SUCCESS = 0, | ||
| 70 | + | ||
| 71 | + /** Request parameter is invalid or missing */ | ||
| 72 | + A4P_INVALID_PARAMETER = 1001, | ||
| 73 | + /** Protocol version is not supported */ | ||
| 74 | + A4P_UNSUPPORTED_VERSION = 1002, | ||
| 75 | + /** Identifier already exists (e.g. a duplicate execution ID or order ID) */ | ||
| 76 | + A4P_DUPLICATE_ID = 1003, | ||
| 77 | + | ||
| 78 | + /** Signing operation failed */ | ||
| 79 | + A4P_SIGNING_FAIL = 2001, | ||
| 80 | + /** Signature verification failed */ | ||
| 81 | + A4P_VERIFY_FAIL = 2002, | ||
| 82 | + | ||
| 83 | + /** Intent or execution status does not allow this operation */ | ||
| 84 | + A4P_INVALID_STATUS = 3001, | ||
| 85 | + /** Timestamp has expired (exceeded validUntil) */ | ||
| 86 | + A4P_TIMESTAMP_EXPIRED = 3002, | ||
| 87 | + /** Timestamp is too early (before validFrom) */ | ||
| 88 | + A4P_TIMESTAMP_TOO_EARLY = 3003, | ||
| 89 | + | ||
| 90 | + /** Total execution count limit exceeded */ | ||
| 91 | + A4P_EXECUTION_COUNT_EXCEEDED = 4001, | ||
| 92 | + /** Total amount limit exceeded */ | ||
| 93 | + A4P_AMOUNT_EXCEEDED = 4002, | ||
| 94 | + /** Period count limit exceeded */ | ||
| 95 | + A4P_PERIOD_COUNT_EXCEEDED = 4003, | ||
| 96 | + /** Period execution count limit exceeded */ | ||
| 97 | + A4P_PERIOD_EXECUTION_COUNT_EXCEEDED = 4004, | ||
| 98 | + /** Cart does not match the intent's authorized resource order template */ | ||
| 99 | + A4P_CART_MISMATCH = 4005, | ||
| 100 | + /** Single order amount limit exceeded */ | ||
| 101 | + A4P_SINGLE_ORDER_AMOUNT_EXCEEDED = 4006, | ||
| 102 | + /** Cart product is outside the authorized whitelist (scope violation) */ | ||
| 103 | + A4P_PRODUCT_NOT_AUTHORIZED = 4007, | ||
| 104 | + | ||
| 105 | + /** Serialization failed */ | ||
| 106 | + A4P_SERIALIZE_FAIL = 5001, | ||
| 107 | + /** Deserialization failed */ | ||
| 108 | + A4P_DESERIALIZE_FAIL = 5002, | ||
| 109 | + | ||
| 110 | + /** Unknown or unexpected internal error */ | ||
| 111 | + A4P_INTERNAL_ERROR = 6001 | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/** | ||
| 115 | + * The fixed message for an A4P error code: every A4pError thrown with a | ||
| 116 | + * given code carries exactly this message. Failure-specific causes (which | ||
| 117 | + * field failed validation, what the underlying error was) are recorded | ||
| 118 | + * via hilog at the throw site instead of being embedded in the message. | ||
| 119 | + * @param code - The A4P error code to look up | ||
| 120 | + * @returns The fixed human-readable message for the code | ||
| 121 | + */ | ||
| 122 | +export function a4pErrorMessage(code: A4pErrorCode): string { | ||
| 123 | + switch (code) { | ||
| 124 | + case A4pErrorCode.A4P_SUCCESS: | ||
| 125 | + return 'Operation completed successfully'; | ||
| 126 | + case A4pErrorCode.A4P_INVALID_PARAMETER: | ||
| 127 | + return 'Invalid parameter'; | ||
| 128 | + case A4pErrorCode.A4P_UNSUPPORTED_VERSION: | ||
| 129 | + return 'Unsupported version'; | ||
| 130 | + case A4pErrorCode.A4P_DUPLICATE_ID: | ||
| 131 | + return 'Duplicate ID'; | ||
| 132 | + case A4pErrorCode.A4P_SIGNING_FAIL: | ||
| 133 | + return 'Signing failed'; | ||
| 134 | + case A4pErrorCode.A4P_VERIFY_FAIL: | ||
| 135 | + return 'Verification failed'; | ||
| 136 | + case A4pErrorCode.A4P_INVALID_STATUS: | ||
| 137 | + return 'Invalid status'; | ||
| 138 | + case A4pErrorCode.A4P_TIMESTAMP_EXPIRED: | ||
| 139 | + return 'Timestamp expired'; | ||
| 140 | + case A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY: | ||
| 141 | + return 'Timestamp too early'; | ||
| 142 | + case A4pErrorCode.A4P_EXECUTION_COUNT_EXCEEDED: | ||
| 143 | + return 'Execution count exceeded'; | ||
| 144 | + case A4pErrorCode.A4P_AMOUNT_EXCEEDED: | ||
| 145 | + return 'Amount exceeded'; | ||
| 146 | + case A4pErrorCode.A4P_PERIOD_COUNT_EXCEEDED: | ||
| 147 | + return 'Period count exceeded'; | ||
| 148 | + case A4pErrorCode.A4P_PERIOD_EXECUTION_COUNT_EXCEEDED: | ||
| 149 | + return 'Period execution count exceeded'; | ||
| 150 | + case A4pErrorCode.A4P_CART_MISMATCH: | ||
| 151 | + return 'Cart does not match the authorized resource'; | ||
| 152 | + case A4pErrorCode.A4P_SINGLE_ORDER_AMOUNT_EXCEEDED: | ||
| 153 | + return 'Single order amount exceeded'; | ||
| 154 | + case A4pErrorCode.A4P_PRODUCT_NOT_AUTHORIZED: | ||
| 155 | + return 'Product not authorized'; | ||
| 156 | + case A4pErrorCode.A4P_SERIALIZE_FAIL: | ||
| 157 | + return 'Serialization failed'; | ||
| 158 | + case A4pErrorCode.A4P_DESERIALIZE_FAIL: | ||
| 159 | + return 'Deserialization failed'; | ||
| 160 | + case A4pErrorCode.A4P_INTERNAL_ERROR: | ||
| 161 | + return 'Unexpected internal error'; | ||
| 162 | + default: | ||
| 163 | + return 'Unexpected internal error'; | ||
| 164 | + } | ||
| 165 | +} | ||
| 166 | + | ||
| 167 | +/** | ||
| 168 | + * Error thrown by all A4P operations on failure. Follows the HarmonyOS | ||
| 169 | + * BusinessError shape (see @ohos.base): it extends Error and carries a | ||
| 170 | + * numeric `code` (an A4pErrorCode), so callers may treat it as a | ||
| 171 | + * BusinessError<number> — the compatibility is structural, no explicit | ||
| 172 | + * implements needed. The message is fixed per code (see a4pErrorMessage) | ||
| 173 | + * — identical codes always carry identical messages. The specific cause | ||
| 174 | + * of a failure is recorded via hilog at the throw site, never embedded in | ||
| 175 | + * the message. The `code` field replaces the old A4pResult result-wrapper | ||
| 176 | + * convention: APIs now return data directly and throw A4pError on | ||
| 177 | + * failure. The class is module-internal: it is not exported from | ||
| 178 | + * Index.ets, so consumers catch the thrown error structurally as a | ||
| 179 | + * BusinessError<number> — A4pErrorCode is the only error-related export. | ||
| 180 | + */ | ||
| 181 | +export class A4pError extends Error { | ||
| 182 | + /** A4P error code, see A4pErrorCode */ | ||
| 183 | + readonly code: A4pErrorCode; | ||
| 184 | + | ||
| 185 | + /** | ||
| 186 | + * @param code - The A4P error code; the message is derived from it | ||
| 187 | + */ | ||
| 188 | + constructor(code: A4pErrorCode) { | ||
| 189 | + // Error message is not writable in ArkTS subclasses; set via the base | ||
| 190 | + // constructor so `e.message` and `e.toString()` behave as expected. | ||
| 191 | + super(a4pErrorMessage(code)); | ||
| 192 | + this.name = 'A4pError'; | ||
| 193 | + this.code = code; | ||
| 194 | + } | ||
| 195 | +} | ||
| @@ -0,0 +1,61 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Constraint Models | ||
| 7 | + * | ||
| 8 | + * Defines constraint types for intent execution in the A4P protocol. | ||
| 9 | + */ | ||
| 10 | + | ||
| 11 | +/** | ||
| 12 | + * Payment constraints for an intent: per-order and total amount limits, | ||
| 13 | + * validity window, execution count cap, and per-period execution limits. | ||
| 14 | + * `singleOrderMaxAmount` and `maxExecuteCount` are optional (absent means | ||
| 15 | + * no cap of that kind); the period rule (`anchorTime`/`periodSeconds`/ | ||
| 16 | + * `maxExecutionCountPerPeriod`) is all-or-nothing — a periodic intent | ||
| 17 | + * provides all three, a non-periodic intent omits all three. | ||
| 18 | + */ | ||
| 19 | +export interface PaymentConstraints { | ||
| 20 | + /** | ||
| 21 | + * Maximum amount allowed per single order (in cents); must be a positive | ||
| 22 | + * integer when present — absent means no per-order amount cap | ||
| 23 | + */ | ||
| 24 | + singleOrderMaxAmount?: number; | ||
| 25 | + /** Maximum total amount across all non-canceled executions (in cents); must be a positive integer */ | ||
| 26 | + totalMaxAmount: number; | ||
| 27 | + /** Currency code for the amounts (e.g., "CNY", "USD") */ | ||
| 28 | + currency: string; | ||
| 29 | + | ||
| 30 | + /** Earliest allowed execution time (milliseconds since epoch); must be a non-negative integer */ | ||
| 31 | + validFrom: number; | ||
| 32 | + /** Latest allowed execution time (milliseconds since epoch); must be a non-negative integer */ | ||
| 33 | + validUntil: number; | ||
| 34 | + /** | ||
| 35 | + * Maximum number of non-canceled executions (an explicit cancel releases | ||
| 36 | + * a slot); must be a positive integer when present — absent means no | ||
| 37 | + * execution count cap | ||
| 38 | + */ | ||
| 39 | + maxExecuteCount?: number; | ||
| 40 | + /** | ||
| 41 | + * Anchor time for period calculation (milliseconds since epoch); provided | ||
| 42 | + * together with periodSeconds and maxExecutionCountPerPeriod, or all | ||
| 43 | + * three omitted. Must not be later than validFrom: reservations happen at | ||
| 44 | + * now >= validFrom, so a later anchor would give pre-anchor reservations | ||
| 45 | + * negative period indexes, each with a fresh per-period budget | ||
| 46 | + */ | ||
| 47 | + anchorTime?: number; | ||
| 48 | + /** | ||
| 49 | + * Period duration in seconds; provided together with anchorTime and | ||
| 50 | + * maxExecutionCountPerPeriod, or all three omitted. Capped at | ||
| 51 | + * 9007199254740 (MAX_SAFE_INTEGER / 1000): the millisecond conversion | ||
| 52 | + * used for period indexes must stay a safe integer | ||
| 53 | + */ | ||
| 54 | + periodSeconds?: number; | ||
| 55 | + /** | ||
| 56 | + * Maximum number of non-canceled executions allowed per period; must be a | ||
| 57 | + * positive integer when present; provided together with anchorTime and | ||
| 58 | + * periodSeconds, or all three omitted | ||
| 59 | + */ | ||
| 60 | + maxExecutionCountPerPeriod?: number; | ||
| 61 | +} | ||
| @@ -0,0 +1,149 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Execution Models | ||
| 7 | + * | ||
| 8 | + * Defines execution status, records, and context types | ||
| 9 | + * for tracking intent execution state in the A4P protocol. | ||
| 10 | + */ | ||
| 11 | + | ||
| 12 | +import { IntentActionType, IntentL3 } from './intent'; | ||
| 13 | +import { CartItem } from './product'; | ||
| 14 | + | ||
| 15 | +/** | ||
| 16 | + * Represents a payment order. | ||
| 17 | + */ | ||
| 18 | +export interface Order { | ||
| 19 | + /** | ||
| 20 | + * Unique order identifier; doubles as the payment idempotency key — | ||
| 21 | + * createExecution rejects an orderId already present in the context's | ||
| 22 | + * ledger (canceled records included) | ||
| 23 | + */ | ||
| 24 | + orderId: string; | ||
| 25 | + /** | ||
| 26 | + * Payment amount in cents; must be a positive integer. Caller-declared: | ||
| 27 | + * validated only against the signed amount caps, never reconciled with | ||
| 28 | + * the cart — Product carries no price — so binding the amount to the | ||
| 29 | + * products' actual prices is the responsibility of the party holding | ||
| 30 | + * the authoritative product catalog (see createExecution) | ||
| 31 | + */ | ||
| 32 | + amount: number; | ||
| 33 | + /** Currency code (e.g., "CNY", "USD") */ | ||
| 34 | + currency: string; | ||
| 35 | + /** Shopping cart contents */ | ||
| 36 | + cartItems: CartItem[]; | ||
| 37 | + /** Order creation timestamp (milliseconds since epoch); must be a non-negative integer */ | ||
| 38 | + timestamp: number; | ||
| 39 | +} | ||
| 40 | + | ||
| 41 | +/** | ||
| 42 | + * An execution requested against an activated intent: reserved via | ||
| 43 | + * createExecution and recorded in the ledger as an ExecutionRecord. | ||
| 44 | + */ | ||
| 45 | +export interface Execution { | ||
| 46 | + /** Action to perform; must match the authorized intent's action */ | ||
| 47 | + action: IntentActionType; | ||
| 48 | + /** Unique execution identifier */ | ||
| 49 | + id?: string; | ||
| 50 | + /** Execution content (order details) */ | ||
| 51 | + executionContent: Order; | ||
| 52 | +} | ||
| 53 | + | ||
| 54 | +/** | ||
| 55 | + * Status of an intent's overall execution lifecycle. | ||
| 56 | + */ | ||
| 57 | +export enum IntentExecutionStatus { | ||
| 58 | + /** Intent is active and can accept executions */ | ||
| 59 | + ACTIVE = 'ACTIVE', | ||
| 60 | + /** Intent quota is consumed; no further executions can be reserved */ | ||
| 61 | + CONSUMED = 'CONSUMED', | ||
| 62 | + /** Intent has been revoked */ | ||
| 63 | + REVOKED = 'REVOKED', | ||
| 64 | + /** Intent has expired */ | ||
| 65 | + EXPIRED = 'EXPIRED' | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +/** | ||
| 69 | + * Status of an individual execution. | ||
| 70 | + */ | ||
| 71 | +export enum ExecutionStatus { | ||
| 72 | + /** Execution is pending */ | ||
| 73 | + PENDING = 'PENDING', | ||
| 74 | + /** Execution is complete */ | ||
| 75 | + COMPLETED = 'COMPLETED', | ||
| 76 | + /** Execution is canceled */ | ||
| 77 | + CANCELED = 'CANCELED' | ||
| 78 | +} | ||
| 79 | + | ||
| 80 | +/** | ||
| 81 | + * Record of a single execution within an intent. | ||
| 82 | + */ | ||
| 83 | +export interface ExecutionRecord { | ||
| 84 | + /** Unique execution identifier */ | ||
| 85 | + executionId: string; | ||
| 86 | + /** Current status of the execution */ | ||
| 87 | + status: ExecutionStatus; | ||
| 88 | + /** Period index of the reservation; present only for periodic intents */ | ||
| 89 | + periodIndex?: number; | ||
| 90 | + /** Timestamp when execution was reserved (always present) */ | ||
| 91 | + reservedAt: number; | ||
| 92 | + /** Timestamp when execution was completed (only when status is COMPLETED) */ | ||
| 93 | + completedAt?: number; | ||
| 94 | + /** Timestamp when execution was canceled (only when status is CANCELED) */ | ||
| 95 | + canceledAt?: number; | ||
| 96 | + /** The execution that was reserved */ | ||
| 97 | + execution: Execution; | ||
| 98 | +} | ||
| 99 | + | ||
| 100 | +/** | ||
| 101 | + * Accounting snapshot of an execution context, derived from the | ||
| 102 | + * payment constraints and the executions ledger (never maintained by | ||
| 103 | + * hand; see internal/accounting.ts). Fields whose cap does not apply are | ||
| 104 | + * omitted: `periodIndex`/`leftPeriodExecutionCount` for non-periodic | ||
| 105 | + * intents, `leftExecutionCount` when the intent carries no | ||
| 106 | + * `maxExecuteCount` cap. | ||
| 107 | + */ | ||
| 108 | +export interface PaymentExecutionInfo { | ||
| 109 | + /** Index of the period containing the evaluation instant; periodic intents only */ | ||
| 110 | + periodIndex?: number; | ||
| 111 | + /** Executions still allowed in the current period (an explicit cancel releases a slot); periodic intents only */ | ||
| 112 | + leftPeriodExecutionCount?: number; | ||
| 113 | + /** | ||
| 114 | + * Executions still allowed against the count cap (an explicit cancel | ||
| 115 | + * releases a slot); omitted when the intent carries no maxExecuteCount cap | ||
| 116 | + */ | ||
| 117 | + leftExecutionCount?: number; | ||
| 118 | + /** Amount still allowed against the total amount cap (non-canceled records only) */ | ||
| 119 | + leftAmount: number; | ||
| 120 | +} | ||
| 121 | + | ||
| 122 | +/** | ||
| 123 | + * Execution context for an activated intent. | ||
| 124 | + * Tracks the state of all executions for an intent. | ||
| 125 | + */ | ||
| 126 | +export interface IntentExecutionContext { | ||
| 127 | + /** Context version */ | ||
| 128 | + version: string; | ||
| 129 | + /** Intent identifier */ | ||
| 130 | + intentId: string; | ||
| 131 | + /** The authorized Level 3 intent */ | ||
| 132 | + authorizedIntent: IntentL3; | ||
| 133 | + /** Current execution status */ | ||
| 134 | + status: IntentExecutionStatus; | ||
| 135 | + /** | ||
| 136 | + * Activation instant (milliseconds since epoch), stamped by activateIntent | ||
| 137 | + * as the reservation floor: createExecution rejects an evaluation instant | ||
| 138 | + * earlier than it — no execution may predate the context itself | ||
| 139 | + */ | ||
| 140 | + activatedTime: number; | ||
| 141 | + /** | ||
| 142 | + * List of execution records (append-only ledger; canceled records stay in | ||
| 143 | + * it). The execution count is derived from the non-canceled records; it is | ||
| 144 | + * not materialized as a separate field. | ||
| 145 | + */ | ||
| 146 | + executions: ExecutionRecord[]; | ||
| 147 | + /** Accounting snapshot derived from the constraints and the ledger (see PaymentExecutionInfo and internal/accounting.ts) */ | ||
| 148 | + executionInfo: PaymentExecutionInfo; | ||
| 149 | +} | ||
| @@ -0,0 +1,56 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Identity Models | ||
| 7 | + * | ||
| 8 | + * Defines the identities attached to an issued (L2) intent: the paying | ||
| 9 | + * user, the agent acting on their behalf, and the service provider; plus | ||
| 10 | + * the environment of the user's signing device (recorded on L3). | ||
| 11 | + */ | ||
| 12 | + | ||
| 13 | +/** | ||
| 14 | + * Identity of the paying user, as attested by an identity provider. | ||
| 15 | + */ | ||
| 16 | +export interface UserIdentity { | ||
| 17 | + /** Identifier of the identity provider attesting this identity */ | ||
| 18 | + identityProvider: string; | ||
| 19 | + /** User identifier, unique within the provider */ | ||
| 20 | + id: string; | ||
| 21 | + /** Additional identity information (JSON string); optional, absent means none */ | ||
| 22 | + additionalInfo?: string; | ||
| 23 | +} | ||
| 24 | + | ||
| 25 | +/** | ||
| 26 | + * Identity of the agent creating the intent and acting for the user. | ||
| 27 | + */ | ||
| 28 | +export interface AgentIdentity { | ||
| 29 | + /** Identifier of the identity provider attesting this identity */ | ||
| 30 | + identityProvider: string; | ||
| 31 | + /** Agent identifier, unique within the provider */ | ||
| 32 | + id: string; | ||
| 33 | + /** Additional identity information (JSON string); optional, absent means none */ | ||
| 34 | + additionalInfo?: string; | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/** | ||
| 38 | + * Identity of the service provider processing the payment. | ||
| 39 | + */ | ||
| 40 | +export interface ServiceProviderIdentity { | ||
| 41 | + /** Service provider identifier */ | ||
| 42 | + id: string; | ||
| 43 | + /** Additional identity information (JSON string); optional, absent means none */ | ||
| 44 | + additionalInfo?: string; | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/** | ||
| 48 | + * Environment of the user's device at signing time, recorded on the | ||
| 49 | + * Level 3 intent. | ||
| 50 | + */ | ||
| 51 | +export interface SigningEnv { | ||
| 52 | + /** Device information (e.g. model and OS version) */ | ||
| 53 | + device: object; | ||
| 54 | + /** Application information (e.g. name and version) */ | ||
| 55 | + app: object; | ||
| 56 | +} | ||
| @@ -0,0 +1,126 @@ | |||
| 1 | +/* | ||
| 2 | + * Copyright (c) Huawei Technologies Co., Ltd. 2026. All rights reserved. | ||
| 3 | + */ | ||
| 4 | + | ||
| 5 | +/** | ||
| 6 | + * Intent Lifecycle Models | ||
| 7 | + * | ||
| 8 | + * Defines the core data structures for the A4P intent lifecycle: | ||
| 9 | + * - L1: Agent-created intent | ||
| 10 | + * - L2: Issued intent (with user/agent/service provider identities) | ||
| 11 | + * - L3: User-signed intent (authorized for execution) | ||
| 12 | + */ | ||
| 13 | + | ||
| 14 | +import { PaymentConstraints } from './constraint'; | ||
| 15 | +import { UserIdentity, AgentIdentity, ServiceProviderIdentity, SigningEnv } from './identity'; | ||
| 16 | +import { ShoppingItems } from './product'; | ||
| 17 | + | ||
| 18 | +/** | ||
| 19 | + * Actions an intent can authorize. | ||
| 20 | + */ | ||
| 21 | +export enum IntentActionType { | ||
| 22 | + /** Agent payment: purchase of whitelisted products under payment constraints */ | ||
| 23 | + AI_PAY = 'AI_PAY', | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +/** | ||
| 27 | + * Signature algorithms supported for intent signing. | ||
| 28 | + */ | ||
| 29 | +export enum AlgorithmType { | ||
| 30 | + /** RSA signature with a 3072-bit key */ | ||
| 31 | + RSA3072 = 'RSA3072', | ||
| 32 | +} | ||
| 33 | + | ||
| 34 | +/** | ||
| 35 | + * Structured intent data defining the action, the authorized resource, | ||
| 36 | + * and the payment constraints. | ||
| 37 | + */ | ||
| 38 | +export interface StructuredIntent { | ||
| 39 | + /** Action to be performed */ | ||
| 40 | + action: IntentActionType; | ||
| 41 | + /** Resource being acted upon (the authorized purchase whitelist) */ | ||
| 42 | + resource: ShoppingItems; | ||
| 43 | + /** Payment constraints for this intent */ | ||
| 44 | + constraints: PaymentConstraints; | ||
| 45 | +} | ||
| 46 | + | ||
| 47 | +/** | ||
| 48 | + * Detached signature metadata attached to each intent level: the algorithm | ||
| 49 | + * and key identifier used to sign this level, plus the signature itself. | ||
| 50 | + * None of these fields are part of the signed bytes. | ||
| 51 | + */ | ||
| 52 | +export interface SignatureInfo { | ||
| 53 | + /** Signing algorithm used; detached metadata, not covered by the signature (see sign) */ | ||
| 54 | + alg: AlgorithmType; | ||
| 55 | + /** Key index used for signing; detached metadata, not covered by the signature (see sign) */ | ||
| 56 | + keyIdentifier: string; | ||
| 57 | + /** | ||
| 58 | + * Signer's signature (base64url-encoded, unpadded) over the canonical | ||
| 59 | + * JSON of the intent with the top-level `sign` object removed entirely. | ||
| 60 | + * `alg`/`keyIdentifier` sit inside that removed object, so they are NOT | ||
| 61 | + * covered by the signature: verification reads them before verifying and | ||
| 62 | + * cannot rely on the signature to authenticate them — the verifier | ||
| 63 | + * contract (key resolution from `keyIdentifier`, `alg` bound to the key | ||
| 64 | + * type) is the defense against alg/key confusion. | ||
| 65 | + */ | ||
| 66 | + sign: string; | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/** | ||
| 70 | + * Level 1 Intent - Created by an agent. | ||
| 71 | + * This is the initial state of an intent before issuance. | ||
| 72 | + */ | ||
| 73 | +export interface IntentL1 { | ||
| 74 | + /** Intent version */ | ||
| 75 | + version: string; | ||
| 76 | + /** Unique intent identifier */ | ||
| 77 | + intentId: string; | ||
| 78 | + /** Intent conversation configuration */ | ||
| 79 | + intentConversation: string; | ||
| 80 | + /** Human-readable intent summary */ | ||
| 81 | + intentSummary: string; | ||
| 82 | + /** Structured intent data */ | ||
| 83 | + structuredIntent: StructuredIntent; | ||
| 84 | + /** Creation timestamp (milliseconds since epoch); must be a non-negative integer */ | ||
| 85 | + timestamp: number; | ||
| 86 | + /** Agent's signing information, including the signature over this intent */ | ||
| 87 | + sign?: SignatureInfo; | ||
| 88 | +} | ||
| 89 | + | ||
| 90 | +/** | ||
| 91 | + * Level 2 Intent - Issued with identities. | ||
| 92 | + * Created when a Level 1 intent is issued with user, agent, and service provider information. | ||
| 93 | + */ | ||
| 94 | +export interface IntentL2 { | ||
| 95 | + /** Intent version */ | ||
| 96 | + version: string; | ||
| 97 | + /** The original Level 1 intent */ | ||
| 98 | + intentL1: IntentL1; | ||
| 99 | + /** User identity */ | ||
| 100 | + userIdentity: UserIdentity; | ||
| 101 | + /** Agent identity */ | ||
| 102 | + agentIdentity: AgentIdentity; | ||
| 103 | + /** Service provider identity */ | ||
| 104 | + serviceProviderIdentity: ServiceProviderIdentity; | ||
| 105 | + /** Issuance timestamp (milliseconds since epoch); must be a non-negative integer no earlier than the embedded intentL1's timestamp */ | ||
| 106 | + timestamp: number; | ||
| 107 | + /** Server's signing information, including the signature over this intent */ | ||
| 108 | + sign?: SignatureInfo; | ||
| 109 | +} | ||
| 110 | + | ||
| 111 | +/** | ||
| 112 | + * Level 3 Intent - User-signed and authorized. | ||
| 113 | + * Created when a user signs a Level 2 intent, authorizing execution. | ||
| 114 | + */ | ||
| 115 | +export interface IntentL3 { | ||
| 116 | + /** Intent version */ | ||
| 117 | + version: string; | ||
| 118 | + /** The Level 2 intent */ | ||
| 119 | + intentL2: IntentL2; | ||
| 120 | + /** Signing environment information */ | ||
| 121 | + signingEnv: SigningEnv; | ||
| 122 | + /** Signing timestamp (milliseconds since epoch); must be a non-negative integer no earlier than the embedded intentL2's timestamp */ | ||
| 123 | + timestamp: number; | ||
| 124 | + /** User's signing information, including the signature over this intent */ | ||
| 125 | + sign?: SignatureInfo; | ||
| 126 | +} | ||