Merged
refactor(java-sdk): 对齐公开 API 并完善文档与示例 #386
machuanAdd on 17 days ago
refactor(java-sdk): 对齐公开 API 并完善文档与示例 #386
Merged
Total: 41 files changed+2712-649
| @@ -1,9 +1,18 @@ | |||
| 1 | # A4P Java SDK | 1 | # A4P Java SDK |
| 2 | 2 | ||
| 3 | +[Public API and usage contract](docs/API.md) | [公开 API 与使用约束](docs/API_zh.md) | ||
| 4 | + | ||
| 3 | English | [简体中文](./README_zh.md) | 5 | English | [简体中文](./README_zh.md) |
| 4 | 6 | ||
| 5 | -Java 17 implementation of the A4P payment-intent protocol, ported from the ArkTS SDK in | 7 | +Java 17 implementation of the A4P payment-intent protocol. |
| 6 | -[PR #130](https://github.com/openJiuwen-ai/agent-protocol/pull/130). | 8 | + |
| 9 | +## Quick build | ||
| 10 | + | ||
| 11 | +```sh | ||
| 12 | +bash A4P-java-sdk/scripts/build.sh build # Explicitly compile and package | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +Build artifacts are located at `A4P-java-sdk/target/a4p-java-sdk-*.jar`. | ||
| 7 | 16 | ||
| 8 | ## Build and test | 17 | ## Build and test |
| 9 | 18 | ||
| @@ -15,67 +24,93 @@ mvn test | |||
| 15 | mvn package | 24 | mvn package |
| 16 | ``` | 25 | ``` |
| 17 | 26 | ||
| 18 | -### Build script | 27 | +### Generate English API documentation |
| 19 | 28 | ||
| 20 | -The scripts require Bash (for example, Linux, WSL or Git Bash on Windows). From the | 29 | +From the repository root, run: |
| 21 | -repository root, run: | ||
| 22 | 30 | ||
| 23 | ```sh | 31 | ```sh |
| 24 | -bash A4P-java-sdk/scripts/build.sh # Default: build | 32 | +mvn -f A4P-java-sdk/pom.xml javadoc:javadoc |
| 25 | -bash A4P-java-sdk/scripts/build.sh build # Explicit build mode | 33 | +``` |
| 34 | + | ||
| 35 | +Open `A4P-java-sdk/target/site/apidocs/index.html` to browse the English documentation. | ||
| 36 | +A full JDK 17+ (including `javadoc`) and Maven 3.9+ are required; the first run downloads plugins. | ||
| 37 | +Generated pages cover the public API (including nested types), excluding tests and the standalone examples module. | ||
| 38 | +Missing comments do not prevent the build; malformed Javadoc or broken references cause generation to fail. | ||
| 39 | + | ||
| 40 | +`mvn package` automatically generates and attaches the English `target/a4p-java-sdk-0.1.0-javadoc.jar`. | ||
| 41 | +To run tests, package the SDK, and generate HTML documentation together: | ||
| 42 | + | ||
| 43 | +```sh | ||
| 44 | +mvn -f A4P-java-sdk/pom.xml clean verify javadoc:javadoc | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +When changing an API, update its English source comments in the same change. When public usage or build instructions change, | ||
| 48 | +also update `docs/API.md`, `docs/API_zh.md`, and the corresponding READMEs. | ||
| 49 | +Generated files under `target/` do not need to be edited manually or committed. | ||
| 50 | + | ||
| 51 | +### Build script | ||
| 52 | + | ||
| 53 | +The script requires Bash (for example, Linux, WSL, or Git Bash on Windows). From the repository root, run: | ||
| 54 | + | ||
| 55 | +```sh | ||
| 56 | +bash A4P-java-sdk/scripts/build.sh # Default: build mode | ||
| 57 | +bash A4P-java-sdk/scripts/build.sh build # Explicitly compile and package | ||
| 26 | bash A4P-java-sdk/scripts/build.sh ut # Run unit tests only | 58 | bash A4P-java-sdk/scripts/build.sh ut # Run unit tests only |
| 59 | +bash A4P-java-sdk/scripts/build.sh docs # Generate Javadoc documentation | ||
| 27 | bash A4P-java-sdk/scripts/build.sh --help | 60 | bash A4P-java-sdk/scripts/build.sh --help |
| 28 | ``` | 61 | ``` |
| 29 | 62 | ||
| 30 | -`build` runs `clean package` with `-Dmaven.test.skip=true`, skipping both test | 63 | +- `build` runs `clean package` with `-Dmaven.test.skip=true`, skipping both compilation and execution of test code. |
| 31 | -compilation and execution. The JAR is written to | 64 | + The artifact is `A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`. |
| 32 | -`A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`. `ut` runs `clean test`, requires tests to | 65 | +- `ut` runs `clean test`, requires tests to be present, and returns a failure if tests fail. It does not package a JAR; |
| 33 | -be present and fails on test failures; it does not package the JAR. Surefire reports | 66 | + Surefire test reports are located at `A4P-java-sdk/target/surefire-reports/`. |
| 34 | -are written to `A4P-java-sdk/target/surefire-reports/`. Both modes clean `target/` | 67 | +- `docs` generates documentation using Javadoc. |
| 35 | -before running and return Maven's exit code. | ||
| 36 | 68 | ||
| 37 | -Additional Maven options go after the mode, for example: | 69 | +The `build` and `ut` modes clean `target/` first; `docs` does not. All modes return Maven's exit code. |
| 70 | + | ||
| 71 | +Place additional Maven arguments after the script's mode selection, for example: | ||
| 38 | 72 | ||
| 39 | ```sh | 73 | ```sh |
| 40 | bash A4P-java-sdk/scripts/build.sh build -o | 74 | bash A4P-java-sdk/scripts/build.sh build -o |
| 41 | -bash A4P-java-sdk/scripts/build.sh ut -Dtest=Rsa3072Test | 75 | +mvn -f A4P-java-sdk/examples/pom.xml test |
| 42 | ``` | 76 | ``` |
| 43 | 77 | ||
| 44 | -`-o` uses Maven's offline mode, so the required dependencies and plugins must already | 78 | +`-o` enables Maven's offline mode; required dependencies and plugins must already be cached. The script locates `pom.xml` |
| 45 | -be cached. The script locates `pom.xml` relative to itself, independently of the | 79 | +relative to itself, independently of the caller's working directory. |
| 46 | -caller's working directory. | ||
| 47 | 80 | ||
| 48 | ### UT script with CI reports | 81 | ### UT script with CI reports |
| 49 | 82 | ||
| 50 | -To run unit tests and generate CI reports, execute the following from the repository | 83 | +To run unit tests and generate CI reports, run the following command from the repository root. The script locates the |
| 51 | -root. The script locates the repository root relative to itself, independently of | 84 | +repository root relative to itself, independently of the caller's working directory. You can override the default |
| 52 | -the caller's working directory. Optionally set `WORKSPACE` to an absolute repository | 85 | +by setting `WORKSPACE` to the absolute path of the repository root. |
| 53 | -root to override this default. | ||
| 54 | 86 | ||
| 55 | ```sh | 87 | ```sh |
| 56 | bash A4P-java-sdk/scripts/ut.sh | 88 | bash A4P-java-sdk/scripts/ut.sh |
| 57 | ``` | 89 | ``` |
| 58 | 90 | ||
| 59 | -This script requires Git, Maven and standard shell utilities, including `grep` with | 91 | +The script requires Git, Maven, and standard shell utilities, including `grep` with `-P` support (for example, GNU grep). |
| 60 | -`-P` support (for example, GNU grep). It runs `mvn clean test` and returns Maven's | 92 | +It runs `mvn clean test` and returns Maven's exit code (`0` for `PASS`, nonzero for `FAILED`). |
| 61 | -exit code (`0` for `PASS`, nonzero for `FAILED`). Reports are written under | 93 | +Reports are written to `outputs/` under the resolved repository root (`$WORKSPACE/outputs/` when overridden): |
| 62 | -`outputs/` under the resolved repository root (`$WORKSPACE/outputs/` when overridden): | ||
| 63 | 94 | ||
| 64 | | File | Contents | | 95 | | File | Contents | |
| 65 | | --- | --- | | 96 | | --- | --- | |
| 66 | | `ut.log` | Maven test log | | 97 | | `ut.log` | Maven test log | |
| 67 | | `unit_test_report.html` | Test counts and the last 200 log lines | | 98 | | `unit_test_report.html` | Test counts and the last 200 log lines | |
| 68 | -| `junit.xml` | Combined JUnit XML, generated when Surefire XML reports exist | | 99 | +| `junit.xml` | Combined JUnit XML, generated only when Surefire XML reports exist | |
| 69 | -| `ut.json` | Status, Maven exit code and report link | | 100 | +| `ut.json` | Status, Maven exit code, and report links | |
| 70 | 101 | ||
| 71 | -Optional environment variables `PR_ID` (default `0`) and `OBS_BUCKET` (default | 102 | +Optional environment variables `PR_ID` (default `0`) and `OBS_BUCKET` (default `openjiuwen-ci`) configure |
| 72 | -`openjiuwen-ci`) control the report link in `ut.json`. The script generates local | 103 | +report links in `ut.json`. The script only generates local reports; CI must upload them separately to the linked OBS locations. |
| 73 | -reports; uploading them to the linked OBS location is a separate CI step. | ||
| 74 | 104 | ||
| 75 | -The artifact coordinates are `io.openjiuwen:a4p-java-sdk:0.1.0`. | 105 | +### Build dependencies |
| 76 | -Jackson handles JSON; JUnit 5 is test-only. No web framework is required. | ||
| 77 | 106 | ||
| 78 | -`jackson-databind` (2.20.1 here) is the only runtime dependency; JUnit 5 is `test` scope. | 107 | +The artifact coordinates are `io.openjiuwen:a4p-java-sdk:0.1.0`. Jackson handles JSON; JUnit 5 is used only for testing. No web framework is required. |
| 108 | + | ||
| 109 | +`jackson-databind` (2.20.1 here) is the only runtime dependency; JUnit 5 has `test` scope. | ||
| 110 | + | ||
| 111 | +## Run the example program | ||
| 112 | + | ||
| 113 | +The example program depends on the external Java SDK: | ||
| 79 | 114 | ||
| 80 | ```xml | 115 | ```xml |
| 81 | <dependency> | 116 | <dependency> |
| @@ -85,107 +120,57 @@ Jackson handles JSON; JUnit 5 is test-only. No web framework is required. | |||
| 85 | </dependency> | 120 | </dependency> |
| 86 | ``` | 121 | ``` |
| 87 | 122 | ||
| 88 | -Run `io.openjiuwen.a4p.examples.PaymentExample` from an IDE, or: | 123 | +First run `mvn -f A4P-java-sdk/pom.xml install` to build the SDK, then run `io.openjiuwen.a4p.examples.PaymentExample` from the standalone examples module: |
| 89 | 124 | ||
| 90 | ```sh | 125 | ```sh |
| 91 | -mvn compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample" | 126 | +mvn -f A4P-java-sdk/examples/pom.xml compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample" |
| 92 | ``` | 127 | ``` |
| 93 | 128 | ||
| 94 | -The exec plugin is not declared in `pom.xml`, so that command resolves it from Maven | 129 | +The exec plugin is not declared in `pom.xml`, so this command resolves it from Maven Central on first use and requires network access. |
| 95 | -Central on first use and therefore needs network access. | ||
| 96 | 130 | ||
| 97 | -The example uses separate agent, intent-center and user RSA-3072 key pairs. It creates, | 131 | +The example uses separate Agent, intent center, and user RSA-3072 key pairs to demonstrate creating, issuing, authorizing, activating, verifying, reserving, and completing a payment. |
| 98 | -issues, authorizes, activates, verifies, reserves and completes a payment. | ||
| 99 | 132 | ||
| 100 | ## API | 133 | ## API |
| 101 | 134 | ||
| 102 | -| Specification | Java | | 135 | +For detailed API documentation, see [docs/API.md](docs/API.md). |
| 103 | -| --- | --- | | ||
| 104 | -| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, long now])` returns `A4pResult<IntentL1>` | | ||
| 105 | -| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, long now])` returns `A4pResult<IntentL2>` | | ||
| 106 | -| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, long now])` returns `A4pResult<IntentL3>` | | ||
| 107 | -| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, long now])` returns `A4pResult<IntentExecutionContext>` | | ||
| 108 | -| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` returns `A4pResult<VerificationResult>` | | ||
| 109 | -| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` / `A4p.revokeIntent(IntentExecutionContext, long now)` returns `A4pResult<IntentExecutionContext>` | | ||
| 110 | -| `createExecution / completeExecution / cancelExecution` | Static methods on `A4p`, returning `A4pResult<IntentExecutionContext>` | | ||
| 111 | -| `A4pResult<T>` | `A4pResult`: `success()`, `data()`, `code()` (`long`), `message()` | | ||
| 112 | -| `A4pException` | `A4pException`, thrown only by value-returning helpers and for SDK defects | | ||
| 113 | -| `A4pErrorCode` | `code()`, `message()`, and `fromCode(int)` for turning a result code back into a constant | | ||
| 114 | -| `A4pIntentCodec` | `A4pIntentCodec.standard()`; `serializeIntentL1/L2/L3` and `serializeIntentExecutionContext` return `String`, and each `deserialize…` counterpart returns `A4pResult` | | ||
| 115 | -| `Signer / SignatureVerifier` | Functional interfaces; `Signer.sign(byte[])` returns a `SignatureInfo` | | ||
| 116 | -| `Rsa3072` | Optional adapter: `Rsa3072.signer(String, PrivateKey)` and `Rsa3072.verifier(Map<String, PublicKey>)` | | ||
| 117 | -| `CanonicalJson` | Canonical helpers used when signing: `stringify`, `toSignableBytes`, `encodeUtf8`/`decodeUtf8`, `base64UrlEncode`/`base64UrlDecode`, `MAX_SAFE_INTEGER` | | ||
| 118 | -| Typed union (`StructuredIntent`, `Execution`, `executionInfo`) | `JsonNode` payloads; `PaymentProfile` converts AI_PAY payloads to and from records | | ||
| 119 | -| Data model | Immutable records and enums in `Models` | | ||
| 120 | 136 | ||
| 121 | -`[long now]` marks the explicit-clock overload described below. | 137 | +To use the classes and functions defined in the SDK, import: |
| 122 | - | ||
| 123 | -The records and enums are nested in `Models`; `A4p`, `A4pResult`, `A4pException`, | ||
| 124 | -`A4pErrorCode`, `A4pIntentCodec`, `IntentExecutionContext`, `PaymentProfile` and `Rsa3072` | ||
| 125 | -are top-level classes, so both imports are needed: | ||
| 126 | 138 | ||
| 127 | ```java | 139 | ```java |
| 128 | import io.openjiuwen.a4p.*; | 140 | import io.openjiuwen.a4p.*; |
| 129 | import io.openjiuwen.a4p.Models.*; | 141 | import io.openjiuwen.a4p.Models.*; |
| 130 | ``` | 142 | ``` |
| 131 | 143 | ||
| 132 | -Build AI_PAY payloads through `PaymentProfile`. The sketch below shows the shape of the | 144 | +Build AI_PAY payloads through the `PaymentProfile` helper class. The following snippet illustrates the calls; see |
| 133 | -calls; `io.openjiuwen.a4p.examples.PaymentExample` is the complete, compiling version, | 145 | +`io.openjiuwen.a4p.examples.PaymentExample` for a complete, compilable version that also sets up the key pairs and the L1/L2/L3 chain. |
| 134 | -which also sets up the key pairs, the L1/L2/L3 chain and canonical serialization. | ||
| 135 | 146 | ||
| 136 | ```java | 147 | ```java |
| 137 | -// Activate an intent that the agent created and the intent center issued and signed. | 148 | +// Activate an intent created by the Agent, issued by the intent center and signed by the user. |
| 138 | -SignatureVerifier userVerifier = Rsa3072.verifier(Map.of("user", userPublicKey)); | ||
| 139 | A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now); | 149 | A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now); |
| 140 | -if (!activated.success()) { /* branch on activated.code() */ } | 150 | +if (!activated.success()) { throw new IllegalStateException("Activation failed: " + activated.code()); } |
| 141 | IntentExecutionContext context = activated.data(); | 151 | IntentExecutionContext context = activated.data(); |
| 142 | 152 | ||
| 143 | -// Reserve, then complete, one order against the activated intent. | 153 | +// Reserve an order against the activated intent, then complete it. |
| 144 | Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now); | 154 | Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now); |
| 145 | Execution execution = PaymentProfile.execution("execution-1", order); | 155 | Execution execution = PaymentProfile.execution("execution-1", order); |
| 146 | A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now); | 156 | A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now); |
| 147 | -if (!reserved.success()) { /* branch on reserved.code(), then persist the context */ } | 157 | +// Persist context even on failure: the reservation attempt may mark it EXPIRED. |
| 158 | +if (!reserved.success()) { throw new IllegalStateException("Reservation failed: " + reserved.code()); } | ||
| 159 | +// Perform the external payment; complete only after success, or cancel on failure. | ||
| 148 | A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now); | 160 | A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now); |
| 149 | 161 | ||
| 162 | +if (!completed.success()) { throw new IllegalStateException("Completion failed: " + completed.code()); } | ||
| 163 | + | ||
| 150 | PaymentExecutionInfo info = PaymentProfile.executionInfo(context); | 164 | PaymentExecutionInfo info = PaymentProfile.executionInfo(context); |
| 151 | ``` | 165 | ``` |
| 152 | 166 | ||
| 153 | -A failed `createExecution` can still have moved the context to `EXPIRED`, so persist the | 167 | +Use `new A4pIntentCodec()` for serialization and restoration. Persist the context after activation and every update, and serialize database read-update-write cycles for each intent in a transaction. Context JSON is for local persistence only; restoration does not verify signatures or storage integrity. |
| 154 | -context after every call. `serializeIntentExecutionContext` / | ||
| 155 | -`deserializeIntentExecutionContext` | ||
| 156 | -on `A4pIntentCodec` provide the persisted form; deserialization re-validates the stored L3 | ||
| 157 | -(without re-verifying the user signature), checks that the ledger respects the authorized | ||
| 158 | -constraints, and requires `executionInfo` to match the ledger. It also requires a reachable | ||
| 159 | -state: each `reservedAt` lies within `[validFrom, validUntil]`, `completedAt`/`canceledAt` | ||
| 160 | -are not earlier than `reservedAt`, and the status is `CONSUMED` exactly when nothing is | ||
| 161 | -pending and the global quota is used up (`REVOKED` and `EXPIRED` accept any ledger). | ||
| 162 | - | ||
| 163 | -Optional fields use `null`; absent optional fields are omitted from signed JSON. Explicit | ||
| 164 | -`null` values inside AI_PAY payloads are rejected. Monetary values are positive integers in | ||
| 165 | -the application's agreed minor unit. All protocol numbers are integers limited to the | ||
| 166 | -JavaScript safe-integer range; values that are not integers must be carried as strings. | ||
| 167 | - | ||
| 168 | -Lifecycle/execution methods have both a system-clock overload and an explicit | ||
| 169 | -`long now` overload (epoch milliseconds). An explicit `now` must be a non-negative | ||
| 170 | -safe integer and is validated before anything else. Production code must supply a | ||
| 171 | -trusted clock, never a client-provided timestamp. Order timestamps do not determine | ||
| 172 | -quota periods or authorization validity. | ||
| 173 | - | ||
| 174 | -Required strings must be non-blank (using the JavaScript `trim()` whitespace set). A | ||
| 175 | -product needs a non-blank seller ID and at least one of `spuId`/`skuId`. A periodic rule | ||
| 176 | -requires `anchorTime <= validFrom` and `periodSeconds <= 9007199254740`. Chain timestamps | ||
| 177 | -are monotonic: `L1.timestamp <= L2.timestamp <= L3.timestamp`. Activation requires | ||
| 178 | -`L3.timestamp <= now <= validUntil` (`A4P_INVALID_PARAMETER` / `A4P_TIMESTAMP_EXPIRED`); an | ||
| 179 | -intent that is not yet valid can be activated, and reservations before `validFrom` fail with | ||
| 180 | -`A4P_TIMESTAMP_TOO_EARLY`. Length limits and | ||
| 181 | -sensitive-data filtering of `intentConversation` are the Agent's responsibility. | ||
| 182 | 168 | ||
| 183 | ### Result codes | 169 | ### Result codes |
| 184 | 170 | ||
| 185 | -Callers branch on `code()`; `message()` is a fixed diagnostic text, and the values come | 171 | +The following values come from `A4pErrorCode`, shared with the ArkTS SDK. `0` indicates success; any other value indicates a protocol failure. |
| 186 | -from `A4pErrorCode`, shared with the ArkTS SDK. `0` means success and every other value is | 172 | +`A4pErrorCode.fromCode(int)` resolves a code back to its constant; |
| 187 | -a protocol failure. `A4pErrorCode.fromCode(int)` resolves a code back to its constant and | 173 | +unknown values map to `A4P_INTERNAL_ERROR` (cast the `long` returned by `code()` to `int` when calling it). |
| 188 | -maps an unknown value to `A4P_INTERNAL_ERROR` (cast the `long` returned by `code()`). | ||
| 189 | 174 | ||
| 190 | | Code | Constant | Meaning | | 175 | | Code | Constant | Meaning | |
| 191 | | --- | --- | --- | | 176 | | --- | --- | --- | |
| @@ -198,120 +183,36 @@ maps an unknown value to `A4P_INTERNAL_ERROR` (cast the `long` returned by `code | |||
| 198 | | 3001 | `A4P_INVALID_STATUS` | Invalid status | | 183 | | 3001 | `A4P_INVALID_STATUS` | Invalid status | |
| 199 | | 3002 | `A4P_TIMESTAMP_EXPIRED` | Timestamp expired | | 184 | | 3002 | `A4P_TIMESTAMP_EXPIRED` | Timestamp expired | |
| 200 | | 3003 | `A4P_TIMESTAMP_TOO_EARLY` | Timestamp too early | | 185 | | 3003 | `A4P_TIMESTAMP_TOO_EARLY` | Timestamp too early | |
| 201 | -| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | Execution count exceeded | | 186 | +| 4001 | `A4P_EXECUTION_COUNT_EXCEEDED` | Execution count limit exceeded | |
| 202 | -| 4002 | `A4P_AMOUNT_EXCEEDED` | Amount exceeded | | 187 | +| 4002 | `A4P_AMOUNT_EXCEEDED` | Amount limit exceeded | |
| 203 | -| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | Reserved for ArkTS error-code compatibility; not returned by Java (per-period execution limits use 4004) | | 188 | +| 4003 | `A4P_PERIOD_COUNT_EXCEEDED` | Reserved for ArkTS error-code compatibility; Java does not currently return this code (per-period execution count limits use 4004) | |
| 204 | -| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | Period execution count exceeded | | 189 | +| 4004 | `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | Per-period execution count limit exceeded | |
| 205 | -| 4005 | `A4P_CART_MISMATCH` | Cart does not match the authorized template | | 190 | +| 4005 | `A4P_CART_MISMATCH` | Cart does not match the authorized order template | |
| 206 | -| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | Single order amount exceeded | | 191 | +| 4006 | `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | Single-order amount limit exceeded | |
| 207 | | 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | Product not authorized | | 192 | | 4007 | `A4P_PRODUCT_NOT_AUTHORIZED` | Product not authorized | |
| 208 | | 5001 | `A4P_SERIALIZE_FAIL` | Serialization failed | | 193 | | 5001 | `A4P_SERIALIZE_FAIL` | Serialization failed | |
| 209 | | 5002 | `A4P_DESERIALIZE_FAIL` | Deserialization failed | | 194 | | 5002 | `A4P_DESERIALIZE_FAIL` | Deserialization failed | |
| 210 | | 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error | | 195 | | 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error | |
| 211 | 196 | ||
| 212 | -`2001` and `2002` also cover the optional adapter: `Rsa3072` returns `2002` for a rejected | ||
| 213 | -signature, and a `Signer`/`SignatureVerifier` that throws is mapped to the same codes by | ||
| 214 | -the SDK, as described below. | ||
| 215 | - | ||
| 216 | -## Execution semantics | ||
| 217 | - | ||
| 218 | -- Pending and completed records consume amount and execution-count quotas; explicit cancellation releases them. | ||
| 219 | -- Each whitelist group is a per-order template: every execution buys exactly one listed product at exactly the group's `quantity`, in any cart order. Quantities do not accumulate across executions. | ||
| 220 | -- Duplicate products within a group and products shared across groups are rejected with `1001` when validating an intent. | ||
| 221 | -- Products outside the whitelist fail with `4007` before template checks. Wrong cart size, repeated groups, and wrong quantities fail with `A4P_CART_MISMATCH` (`4005`). | ||
| 222 | -- `Execution` has no `version` field; `PaymentProfile.execution(id, order)` constructs it. | ||
| 223 | -- Execution and order IDs remain reserved after cancellation; duplicates fail with `1003`. | ||
| 224 | -- Reservation checks run in order: request structure; action and currency; context status; validity and activation floors; expiry; duplicate IDs; count, single-order amount, total amount, cart template, and period quotas. | ||
| 225 | -- `revokeIntent(context)` uses the system clock; `revokeIntent(context, now)` accepts an explicit non-negative safe integer. Status is checked before the activation floor; an earlier instant fails with `3003`. Revocation permits pending completion/cancellation. | ||
| 226 | -- A reservation past `validUntil` marks the context EXPIRED, even though the call fails. | ||
| 227 | - Pending records can still be completed or canceled in EXPIRED status. | ||
| 228 | -- Reservation rejects `now < activatedTime`; completion/cancellation reject `now < reservedAt`, with `A4P_TIMESTAMP_TOO_EARLY` (3003). | ||
| 229 | -- A rejected finalization leaves the record pending. | ||
| 230 | -- An ACTIVE intent becomes CONSUMED after a completion leaves no pending record and either | ||
| 231 | - the count cap is reached or the remaining amount is 0. REVOKED and EXPIRED are terminal. | ||
| 232 | -- `executionInfo()` always includes `leftAmount`. It includes `leftExecutionCount` only with a | ||
| 233 | - count cap, and `periodIndex` / `leftPeriodExecutionCount` only for periodic intents. | ||
| 234 | - The Java `PaymentExecutionInfo` record represents inapplicable figures as `null`; they are | ||
| 235 | - omitted from context JSON so ArkTS can deserialize it. | ||
| 236 | -- Context operations synchronize validation and updates. This protects threads | ||
| 237 | - sharing one context, **not** multiple processes or independently activated copies. | ||
| 238 | -- `A4pIntentCodec.standard()` returns a stateless shared singleton, so one instance can | ||
| 239 | - serve every thread. | ||
| 240 | - | ||
| 241 | -The ledger is in-memory. The intent center must persist the context inside a database | ||
| 242 | -transaction locked by `intentId`, prevent replay of the same `intentId`, and bind keys to | ||
| 243 | -identities. Activation checks the outer user signature; `verifyIntentAuthenticity` checks | ||
| 244 | -the L3 chain and the intent center's L2 signature, not the user signature, and does not | ||
| 245 | -depend on the context status. | ||
| 246 | - | ||
| 247 | -## Wire format and security | ||
| 248 | - | ||
| 249 | -See [canonical JSON specification](docs/canonical-json-spec.md). JSON field names follow the | ||
| 250 | -specification (`intentConversation`, `resources`, `UserIdentity.id`), every enum is | ||
| 251 | -serialized by name (`"AI_PAY"`, `"CONSUMED"`, `"PENDING"`), and the protocol version is | ||
| 252 | -`1.0`. HTTP bindings are not part of this SDK until the specification settles them. | ||
| 253 | - | ||
| 254 | -Each level's signature covers the level without its whole `sign` object, so that level's | ||
| 255 | -`alg` and `keyIdentifier` are not part of its own signed bytes; the next level's signature | ||
| 256 | -covers them. This is the specified design. `alg` must be `RSA3072`. Verifiers must resolve | ||
| 257 | -keys exclusively from a trusted registry and bind each key to allowed algorithms; never | ||
| 258 | -trust the incoming `alg`. | ||
| 259 | - | ||
| 260 | -`Rsa3072` is an optional working adapter using JCA `SHA256withRSA` (PKCS#1 v1.5), | ||
| 261 | -3072-bit RSA keys and unpadded Base64URL. Its `VerificationResult.code` is `0` on success | ||
| 262 | -and `2002` on failure, with the reason in `message`. Its factories throw | ||
| 263 | -`A4pException(A4P_INVALID_PARAMETER)` for a missing trust map, a blank key identifier or a | ||
| 264 | -missing or non-3072-bit key. Peers must agree on this suite or | ||
| 265 | -supply matching `Signer`/`SignatureVerifier` implementations. Any verifier must return a | ||
| 266 | -`VerificationResult` whose `valid` is true exactly when `code` is `0`; an inconsistent | ||
| 267 | -result is treated as a verification failure. | ||
| 268 | - | ||
| 269 | -Intent records and nested payloads are immutable; `JsonNode` payloads are copied on the | ||
| 270 | -way in and out. The Java port also rejects duplicate JSON keys, unknown model fields, | ||
| 271 | -invalid UTF-8, fractional integer fields, numeric enum values, scalar coercions and invalid | ||
| 272 | -callback results instead of silently normalizing security-sensitive input. | ||
| 273 | - | ||
| 274 | ## Version and compatibility | 197 | ## Version and compatibility |
| 275 | 198 | ||
| 276 | -The protocol version is `1.0` (`A4p.PROTOCOL_VERSION`). Every level this SDK creates is | 199 | +- Current protocol version: `1.0` (`A4p.PROTOCOL_VERSION`) |
| 277 | -stamped with that constant, and each step validates the levels it receives, rejecting a | 200 | +- Java SDK build version: `0.1.0` |
| 278 | -mismatch with `A4P_UNSUPPORTED_VERSION`. The port implements the same wire | ||
| 279 | -format as the ArkTS SDK (`A4P-arkts-sdk/`) it came from, and the canonical-vector tests | ||
| 280 | -keep the two in step, so intents and persisted contexts are interchangeable across the | ||
| 281 | -two SDKs as long as both use the canonical JSON rules and the same signature suite. The | ||
| 282 | -artifact version is `0.1.0`; protocol compatibility is governed by the `version` | ||
| 283 | -field, not by the artifact version. | ||
| 284 | - | ||
| 285 | -## Known limitations | ||
| 286 | - | ||
| 287 | -- The ledger is in-memory and per-context. Durability, locked persistence, replay | ||
| 288 | - prevention and key-to-identity binding belong to the intent center. | ||
| 289 | -- Synchronization covers threads that share one `IntentExecutionContext`, not several | ||
| 290 | - processes or independently activated copies of the same `intentId`. | ||
| 291 | -- HTTP bindings are out of scope until the specification settles them; only in-process | ||
| 292 | - calls and canonical JSON serialization are provided. | ||
| 293 | -- `Rsa3072` is one agreed suite rather than a negotiation; peers must either use it or | ||
| 294 | - supply matching `Signer`/`SignatureVerifier` implementations. | ||
| 295 | -- `verifyIntentAuthenticity` deliberately does not verify the user signature. | ||
| 296 | -- The port is stricter than the protocol minimum in places (duplicate JSON keys, unknown | ||
| 297 | - fields, numeric enums, scalar coercions) so that security-sensitive input is never | ||
| 298 | - silently normalized. The alignment documents below record what changed, and why. | ||
| 299 | 201 | ||
| 300 | ## More documentation | 202 | ## More documentation |
| 301 | 203 | ||
| 302 | -Additional reference documents live under `docs/`: | 204 | +Reference documents are located in `docs/`: |
| 303 | 205 | ||
| 304 | | Document | Contents | | 206 | | Document | Contents | |
| 305 | | --- | --- | | 207 | | --- | --- | |
| 306 | -| [canonical-json-spec.md](docs/canonical-json-spec.md) | Canonical JSON and Base64URL rules behind every signature. | | 208 | +| [API.md](docs/API.md) | Detailed API documentation | |
| 209 | +| [serialization_and_signature_rules.md](docs/serialization_and_signature_rules.md) | Serialization and signature rules | | ||
| 307 | 210 | ||
| 308 | ## Tests | 211 | ## Tests |
| 309 | 212 | ||
| 310 | -Tests cover lifecycle, quota rollback, order idempotency, one-to-one cart matching, check | 213 | +Tests cover lifecycle, quota rollback, order idempotency, one-to-one cart matching, check ordering, expiry finalization, |
| 311 | -ordering, expiry finalization, terminal states, consumption, whitelist checks, period | 214 | +terminal states, consumption, whitelist validation, period boundaries, blank and structural validation, the result model, |
| 312 | -boundaries, blank/structural validation, the result model, the typed-union payloads, wire | 215 | +typed-union payloads, wire-format names and enum encoding, concurrent reservations, canonical vectors, detached signature |
| 313 | -names and enum encoding, concurrent reservations, canonical vectors, detached signature | 216 | +metadata, malformed input, verifier result consistency, execution-context persistence and restoration (including reachable |
| 314 | -metadata, malformed input, verifier result consistency, execution-context persistence and | 217 | +states and record timestamps), and real RSA signature verification and tampering detection. The digest signer in the test |
| 315 | -restore (including reachable status and record timestamps) and real RSA signature | 218 | +fixtures is only a deterministic test double and must not be used for authorization. |
| 316 | -verification/tampering. The digest signer in the test fixtures is only a deterministic | ||
| 317 | -test double and must not be used for authorization. | ||
| @@ -1,8 +1,18 @@ | |||
| 1 | # A4P Java SDK | 1 | # A4P Java SDK |
| 2 | 2 | ||
| 3 | +[公开 API 与使用约束](docs/API_zh.md) | [Public API and usage contract](docs/API.md) | ||
| 4 | + | ||
| 3 | [English](./README.md) | 简体中文 | 5 | [English](./README.md) | 简体中文 |
| 4 | 6 | ||
| 5 | -A4P 支付意图协议的 Java 17 实现,移植自 [PR #130](https://github.com/openJiuwen-ai/agent-protocol/pull/130) 中的 ArkTS SDK。 | 7 | +A4P 支付意图协议的 Java 17 实现 |
| 8 | + | ||
| 9 | +## 快速构建 | ||
| 10 | + | ||
| 11 | +```sh | ||
| 12 | +bash A4P-java-sdk/scripts/build.sh build # 显式指定编译打包 | ||
| 13 | +``` | ||
| 14 | + | ||
| 15 | +构建产物位于 A4P-java-sdk/target/a4p-java-sdk-*.jar | ||
| 6 | 16 | ||
| 7 | ## 构建与测试 | 17 | ## 构建与测试 |
| 8 | 18 | ||
| @@ -14,6 +24,30 @@ mvn test | |||
| 14 | mvn package | 24 | mvn package |
| 15 | ``` | 25 | ``` |
| 16 | 26 | ||
| 27 | +### 生成英文 API 文档 | ||
| 28 | + | ||
| 29 | +在仓库根目录执行: | ||
| 30 | + | ||
| 31 | +```sh | ||
| 32 | +mvn -f A4P-java-sdk/pom.xml javadoc:javadoc | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +打开 `A4P-java-sdk/target/site/apidocs/index.html` 浏览英文文档。 | ||
| 36 | +需要完整 JDK 17+(含 `javadoc`)及 Maven 3.9+;首次执行需要下载插件。 | ||
| 37 | +生成页面展示公开 API(含嵌套类型),不包含测试和独立示例模块。 | ||
| 38 | +缺失注释不会阻止构建;错误的 Javadoc 语法或失效引用会使生成失败。 | ||
| 39 | + | ||
| 40 | +`mvn package` 会自动生成并附带英文 `target/a4p-java-sdk-0.1.0-javadoc.jar`。 | ||
| 41 | +同时执行测试、SDK 打包及 HTML 生成: | ||
| 42 | + | ||
| 43 | +```sh | ||
| 44 | +mvn -f A4P-java-sdk/pom.xml clean verify javadoc:javadoc | ||
| 45 | +``` | ||
| 46 | + | ||
| 47 | +修改 API 时,在同一次变更中同步更新英文源码注释;公开用法或构建方式变化时, | ||
| 48 | +再更新 `docs/API.md`、`docs/API_zh.md` 和相应 README。 | ||
| 49 | +`target/` 下的生成文件无需手工修改或提交。 | ||
| 50 | + | ||
| 17 | ### 编译脚本 | 51 | ### 编译脚本 |
| 18 | 52 | ||
| 19 | 脚本需要 Bash 环境(例如 Linux、WSL 或 Windows 上的 Git Bash)。在仓库根目录执行: | 53 | 脚本需要 Bash 环境(例如 Linux、WSL 或 Windows 上的 Git Bash)。在仓库根目录执行: |
| @@ -22,19 +56,23 @@ mvn package | |||
| 22 | bash A4P-java-sdk/scripts/build.sh # 默认使用 build 模式 | 56 | bash A4P-java-sdk/scripts/build.sh # 默认使用 build 模式 |
| 23 | bash A4P-java-sdk/scripts/build.sh build # 显式指定编译打包 | 57 | bash A4P-java-sdk/scripts/build.sh build # 显式指定编译打包 |
| 24 | bash A4P-java-sdk/scripts/build.sh ut # 仅运行单元测试 | 58 | bash A4P-java-sdk/scripts/build.sh ut # 仅运行单元测试 |
| 59 | +bash A4P-java-sdk/scripts/build.sh docs # 生成 javadoc 文档 | ||
| 25 | bash A4P-java-sdk/scripts/build.sh --help | 60 | bash A4P-java-sdk/scripts/build.sh --help |
| 26 | ``` | 61 | ``` |
| 27 | 62 | ||
| 28 | -`build` 使用 `-Dmaven.test.skip=true` 执行 `clean package`,跳过测试代码的编译与执行, | 63 | +- `build` 使用 `-Dmaven.test.skip=true` 执行 `clean package`,跳过测试代码的编译与执行, |
| 29 | -产物为 `A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`。`ut` 执行 `clean test`, | 64 | +产物为 `A4P-java-sdk/target/a4p-java-sdk-0.1.0.jar`。 |
| 30 | -要求存在测试,测试失败时返回失败,不打包 JAR;Surefire 测试报告位于 | 65 | +- `ut` 执行 `clean test`,要求存在测试,测试失败时返回失败,不打包 JAR;Surefire 测试报告位于 |
| 31 | -`A4P-java-sdk/target/surefire-reports/`。两种模式都会先清理 `target/`,并返回 Maven 的退出码。 | 66 | +`A4P-java-sdk/target/surefire-reports/`。 |
| 67 | +- `docs` 使用 javadoc 生成文档 | ||
| 32 | 68 | ||
| 33 | -额外的 Maven 参数放在模式之后,例如: | 69 | +`build` 和 `ut` 模式会先清理 `target/`,`docs` 不会。所有模式均返回 Maven 的退出码。 |
| 70 | + | ||
| 71 | +额外的 Maven 参数放在脚本选择运行模式之后,例如: | ||
| 34 | 72 | ||
| 35 | ```sh | 73 | ```sh |
| 36 | bash A4P-java-sdk/scripts/build.sh build -o | 74 | bash A4P-java-sdk/scripts/build.sh build -o |
| 37 | -bash A4P-java-sdk/scripts/build.sh ut -Dtest=Rsa3072Test | 75 | +mvn -f A4P-java-sdk/examples/pom.xml test |
| 38 | ``` | 76 | ``` |
| 39 | 77 | ||
| 40 | `-o` 表示 Maven 离线模式,所需依赖和插件必须已缓存。脚本根据自身位置定位 `pom.xml`, | 78 | `-o` 表示 Maven 离线模式,所需依赖和插件必须已缓存。脚本根据自身位置定位 `pom.xml`, |
| @@ -63,10 +101,16 @@ bash A4P-java-sdk/scripts/ut.sh | |||
| 63 | 可选环境变量 `PR_ID`(默认 `0`)与 `OBS_BUCKET`(默认 `openjiuwen-ci`)用于配置 | 101 | 可选环境变量 `PR_ID`(默认 `0`)与 `OBS_BUCKET`(默认 `openjiuwen-ci`)用于配置 |
| 64 | `ut.json` 中的报告链接。脚本只生成本地报告,上传到链接对应的 OBS 位置需由 CI 另行完成。 | 102 | `ut.json` 中的报告链接。脚本只生成本地报告,上传到链接对应的 OBS 位置需由 CI 另行完成。 |
| 65 | 103 | ||
| 104 | +### 构建依赖 | ||
| 105 | + | ||
| 66 | 构件坐标为 `io.openjiuwen:a4p-java-sdk:0.1.0`。JSON 由 Jackson 处理;JUnit 5 仅用于测试。不需要任何 Web 框架。 | 106 | 构件坐标为 `io.openjiuwen:a4p-java-sdk:0.1.0`。JSON 由 Jackson 处理;JUnit 5 仅用于测试。不需要任何 Web 框架。 |
| 67 | 107 | ||
| 68 | `jackson-databind`(此处为 2.20.1)是唯一的运行时依赖,JUnit 5 为 `test` 作用域。 | 108 | `jackson-databind`(此处为 2.20.1)是唯一的运行时依赖,JUnit 5 为 `test` 作用域。 |
| 69 | 109 | ||
| 110 | +## 运行示例程序 | ||
| 111 | + | ||
| 112 | +示例程序依赖外部的 java SDK | ||
| 113 | + | ||
| 70 | ```xml | 114 | ```xml |
| 71 | <dependency> | 115 | <dependency> |
| 72 | <groupId>io.openjiuwen</groupId> | 116 | <groupId>io.openjiuwen</groupId> |
| @@ -75,10 +119,10 @@ bash A4P-java-sdk/scripts/ut.sh | |||
| 75 | </dependency> | 119 | </dependency> |
| 76 | ``` | 120 | ``` |
| 77 | 121 | ||
| 78 | -可在 IDE 中运行 `io.openjiuwen.a4p.examples.PaymentExample`,或执行: | 122 | +先运行 `mvn -f A4P-java-sdk/pom.xml install` 构建 SDK,再从独立示例模块运行 `io.openjiuwen.a4p.examples.PaymentExample`: |
| 79 | 123 | ||
| 80 | ```sh | 124 | ```sh |
| 81 | -mvn compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample" | 125 | +mvn -f A4P-java-sdk/examples/pom.xml compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample" |
| 82 | ``` | 126 | ``` |
| 83 | 127 | ||
| 84 | `pom.xml` 中并未声明 exec 插件,因此该命令首次执行时会从 Maven 中央仓库解析该插件,需要有网络访问。 | 128 | `pom.xml` 中并未声明 exec 插件,因此该命令首次执行时会从 Maven 中央仓库解析该插件,需要有网络访问。 |
| @@ -87,81 +131,44 @@ mvn compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java "-Dexec.mainClass=io. | |||
| 87 | 131 | ||
| 88 | ## API | 132 | ## API |
| 89 | 133 | ||
| 90 | -| 规范 | Java | | 134 | +详细的 API 请见 [docs/API_zh.md](docs/API_zh.md) |
| 91 | -| --- | --- | | ||
| 92 | -| `createIntent` | `A4p.createIntent(CreateIntentRequest, Signer[, long now])` 返回 `A4pResult<IntentL1>` | | ||
| 93 | -| `issueIntent` | `A4p.issueIntent(IntentL1, SignatureVerifier, IntentIssueContext, Signer[, long now])` 返回 `A4pResult<IntentL2>` | | ||
| 94 | -| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, long now])` 返回 `A4pResult<IntentL3>` | | ||
| 95 | -| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, long now])` 返回 `A4pResult<IntentExecutionContext>` | | ||
| 96 | -| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` 返回 `A4pResult<VerificationResult>` | | ||
| 97 | -| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` / `A4p.revokeIntent(IntentExecutionContext, long now)` 返回 `A4pResult<IntentExecutionContext>` | | ||
| 98 | -| `createExecution / completeExecution / cancelExecution` | `A4p` 上的静态方法,返回 `A4pResult<IntentExecutionContext>` | | ||
| 99 | -| `A4pResult<T>` | `A4pResult`:`success()`、`data()`、`code()`(`long`)、`message()` | | ||
| 100 | -| `A4pException` | `A4pException`,仅由返回值型辅助方法以及 SDK 缺陷抛出 | | ||
| 101 | -| `A4pErrorCode` | `code()`、`message()`,以及把结果码还原为常量的 `fromCode(int)` | | ||
| 102 | -| `A4pIntentCodec` | `A4pIntentCodec.standard()`;`serializeIntentL1/L2/L3` 与 `serializeIntentExecutionContext` 返回 `String`,对应的每个 `deserialize…` 返回 `A4pResult` | | ||
| 103 | -| `Signer / SignatureVerifier` | 函数式接口;`Signer.sign(byte[])` 返回 `SignatureInfo` | | ||
| 104 | -| `Rsa3072` | 可选适配器:`Rsa3072.signer(String, PrivateKey)` 与 `Rsa3072.verifier(Map<String, PublicKey>)` | | ||
| 105 | -| `CanonicalJson` | 签名时使用的规范化辅助方法:`stringify`、`toSignableBytes`、`encodeUtf8`/`decodeUtf8`、`base64UrlEncode`/`base64UrlDecode`、`MAX_SAFE_INTEGER` | | ||
| 106 | -| 类型联合(`StructuredIntent`、`Execution`、`executionInfo`) | `JsonNode` 载荷;`PaymentProfile` 在 AI_PAY 载荷与记录之间相互转换 | | ||
| 107 | -| 数据模型 | `Models` 中的不可变 record 与枚举 | | ||
| 108 | 135 | ||
| 109 | -`[long now]` 表示下文中说明的显式时钟重载。 | 136 | +若要使用 SDK 中定义的类和函数,用以下方式导入: |
| 110 | - | ||
| 111 | -这些 record 与枚举嵌套在 `Models` 中;`A4p`、`A4pResult`、`A4pException`、`A4pErrorCode`、 | ||
| 112 | -`A4pIntentCodec`、`IntentExecutionContext`、`PaymentProfile` 与 `Rsa3072` 是顶层类,因此两个 import 都需要: | ||
| 113 | 137 | ||
| 114 | ```java | 138 | ```java |
| 115 | import io.openjiuwen.a4p.*; | 139 | import io.openjiuwen.a4p.*; |
| 116 | import io.openjiuwen.a4p.Models.*; | 140 | import io.openjiuwen.a4p.Models.*; |
| 117 | ``` | 141 | ``` |
| 118 | 142 | ||
| 119 | -AI_PAY 载荷请通过 `PaymentProfile` 构造。下面的片段展示调用形态;完整可编译的版本见 | 143 | +AI_PAY 载荷请通过 `PaymentProfile` 辅助类构造。下面的片段展示调用形态;完整可编译的版本见 |
| 120 | -`io.openjiuwen.a4p.examples.PaymentExample`,其中还包含密钥对、L1/L2/L3 链以及规范化序列化的搭建过程。 | 144 | +`io.openjiuwen.a4p.examples.PaymentExample`,其中还包含密钥对、L1/L2/L3 链的搭建过程。 |
| 121 | 145 | ||
| 122 | ```java | 146 | ```java |
| 123 | -// 激活一个由 Agent 创建、意图中心签发并签名的意图。 | 147 | +// 激活一个由 Agent 创建、意图中心签发、用户签名的意图。 |
| 124 | -SignatureVerifier userVerifier = Rsa3072.verifier(Map.of("user", userPublicKey)); | ||
| 125 | A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now); | 148 | A4pResult<IntentExecutionContext> activated = A4p.activateIntent(authorizedIntent, userVerifier, now); |
| 126 | -if (!activated.success()) { /* 依据 activated.code() 分支处理 */ } | 149 | +if (!activated.success()) { throw new IllegalStateException("Activation failed: " + activated.code()); } |
| 127 | IntentExecutionContext context = activated.data(); | 150 | IntentExecutionContext context = activated.data(); |
| 128 | 151 | ||
| 129 | // 针对已激活的意图预留一笔订单,然后完成它。 | 152 | // 针对已激活的意图预留一笔订单,然后完成它。 |
| 130 | Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now); | 153 | Order order = new Order("order-1", 3000L, "CNY", List.of(new CartItem(product, 1L)), now); |
| 131 | Execution execution = PaymentProfile.execution("execution-1", order); | 154 | Execution execution = PaymentProfile.execution("execution-1", order); |
| 132 | A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now); | 155 | A4pResult<IntentExecutionContext> reserved = A4p.createExecution(context, execution, now); |
| 133 | -if (!reserved.success()) { /* 依据 reserved.code() 分支处理,然后持久化 context */ } | 156 | +// 即使失败也须持久化 context:预留尝试可能将其置为 EXPIRED。 |
| 157 | +if (!reserved.success()) { throw new IllegalStateException("Reservation failed: " + reserved.code()); } | ||
| 158 | +// 执行对外支付;成功后完成预留,失败则取消预留。 | ||
| 134 | A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now); | 159 | A4pResult<IntentExecutionContext> completed = A4p.completeExecution(context, execution.id(), now); |
| 135 | 160 | ||
| 161 | +if (!completed.success()) { throw new IllegalStateException("Completion failed: " + completed.code()); } | ||
| 162 | + | ||
| 136 | PaymentExecutionInfo info = PaymentProfile.executionInfo(context); | 163 | PaymentExecutionInfo info = PaymentProfile.executionInfo(context); |
| 137 | ``` | 164 | ``` |
| 138 | 165 | ||
| 139 | -失败的 `createExecution` 仍可能已把 context 置为 `EXPIRED`,因此每次调用后都要持久化 context。 | 166 | +使用 `new A4pIntentCodec()` 序列化与恢复。激活后和每次更新后均须持久化 Context,并在事务中串行执行同一意图的数据库读取、更新与写回。Context JSON 仅用于本地持久化;恢复不会验证签名或存储完整性。 |
| 140 | -`A4pIntentCodec` 上的 `serializeIntentExecutionContext` / `deserializeIntentExecutionContext` | ||
| 141 | -提供持久化形式;反序列化会重新校验存储的 L3(不重新验证用户签名),检查账本是否符合已授权约束, | ||
| 142 | -并要求 `executionInfo` 与账本一致。它还要求状态可达:每个 `reservedAt` 落在 `[validFrom, validUntil]` 内, | ||
| 143 | -`completedAt`/`canceledAt` 不早于 `reservedAt`,并且当且仅当没有待处理记录且全局配额已用尽时状态为 | ||
| 144 | -`CONSUMED`(`REVOKED` 与 `EXPIRED` 接受任意账本)。 | ||
| 145 | - | ||
| 146 | -可选字段使用 `null`;缺席的可选字段不会出现在签名 JSON 中。AI_PAY 载荷内显式的 `null` 会被拒绝。 | ||
| 147 | -金额是应用约定的最小货币单位下的正整数。所有协议数值都是限制在 JavaScript 安全整数范围内的整数; | ||
| 148 | -不是整数的值必须以字符串承载。 | ||
| 149 | - | ||
| 150 | -生命周期与执行方法都同时提供系统时钟重载与显式的 `long now` 重载(epoch 毫秒)。显式 `now` | ||
| 151 | -必须是非负安全整数,并且在其他校验之前最先被验证。生产代码必须提供可信时钟,绝不能使用客户端 | ||
| 152 | -提供的时间戳。订单时间戳不决定配额周期,也不决定授权有效期。 | ||
| 153 | - | ||
| 154 | -必填字符串不能为空白(使用 JavaScript `trim()` 的空白字符集)。一个商品需要非空白的 seller ID, | ||
| 155 | -并且 `spuId`/`skuId` 至少提供一个。周期规则要求 `anchorTime <= validFrom` 且 | ||
| 156 | -`periodSeconds <= 9007199254740`。链上时间戳单调:`L1.timestamp <= L2.timestamp <= L3.timestamp`。 | ||
| 157 | -激活要求 `L3.timestamp <= now <= validUntil`(`A4P_INVALID_PARAMETER` / `A4P_TIMESTAMP_EXPIRED`); | ||
| 158 | -尚未生效的意图可以被激活,而在 `validFrom` 之前的预留会以 `A4P_TIMESTAMP_TOO_EARLY` 失败。 | ||
| 159 | -`intentConversation` 的长度限制与敏感数据过滤由 Agent 负责。 | ||
| 160 | 167 | ||
| 161 | ### 结果码 | 168 | ### 结果码 |
| 162 | 169 | ||
| 163 | -调用方依据 `code()` 分支处理;`message()` 是固定的诊断文本,取值来自与 ArkTS SDK 共用的 | 170 | +下面的取值来自与 ArkTS SDK 共用的 `A4pErrorCode`。`0` 表示成功,其他任何值都是协议失败。 |
| 164 | -`A4pErrorCode`。`0` 表示成功,其他任何值都是协议失败。`A4pErrorCode.fromCode(int)` 把码还原为常量, | 171 | +`A4pErrorCode.fromCode(int)` 把码还原为常量, |
| 165 | 未知值映射为 `A4P_INTERNAL_ERROR`(调用时需把 `code()` 返回的 `long` 转成 `int`)。 | 172 | 未知值映射为 `A4P_INTERNAL_ERROR`(调用时需把 `code()` 返回的 `long` 转成 `int`)。 |
| 166 | 173 | ||
| 167 | | 码 | 常量 | 含义 | | 174 | | 码 | 常量 | 含义 | |
| @@ -186,78 +193,10 @@ PaymentExecutionInfo info = PaymentProfile.executionInfo(context); | |||
| 186 | | 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 | | 193 | | 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 | |
| 187 | | 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 | | 194 | | 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 | |
| 188 | 195 | ||
| 189 | -`2001` 与 `2002` 也覆盖可选适配器:`Rsa3072` 对签名被拒返回 `2002`,抛出异常的 | ||
| 190 | -`Signer`/`SignatureVerifier` 会被 SDK 映射为同样的码,详见下文。 | ||
| 191 | - | ||
| 192 | -## 执行语义 | ||
| 193 | - | ||
| 194 | -- 待处理和已完成记录占用金额及执行次数;显式取消释放配额。 | ||
| 195 | -- 白名单是每笔订单的固定模板:每个分组恰好购买一种商品,数量必须等于分组的 `quantity`。数量不跨执行累计,购物车顺序不限。 | ||
| 196 | -- 意图校验拒绝组内重复商品及跨组重叠商品,返回 `1001`。 | ||
| 197 | -- 未授权商品优先返回 `4007`;购物车长度、分组覆盖或数量不匹配统一返回 `A4P_CART_MISMATCH`(`4005`)。 | ||
| 198 | -- `Execution` 已移除 `version`,使用 `PaymentProfile.execution(id, order)` 构造。 | ||
| 199 | -- 执行 ID 和订单 ID 在取消后仍不能复用,重复时返回 `1003`。 | ||
| 200 | -- 预留按请求结构、动作和币种、状态、有效期及激活时间下限、过期、重复 ID、次数、单笔金额、总金额、购物车模板、周期额度的顺序校验。 | ||
| 201 | -- `revokeIntent(context)` 使用系统时间;`revokeIntent(context, now)` 支持指定非负安全整数时间。先检查状态,再检查激活时间下限,时间倒退返回 `3003`。 | ||
| 202 | -- 完成和取消时间早于记录的 `reservedAt` 时返回 `3003`。 | ||
| 203 | -- 撤销会阻止预留,但允许对待处理记录执行完成/取消。 | ||
| 204 | -- 超过 `validUntil` 的预留会把 context 标记为 EXPIRED,尽管该次调用失败。待处理记录在 EXPIRED 状态下 | ||
| 205 | - 仍可被完成或取消。 | ||
| 206 | -- 创建执行时,`now` 早于上下文的 `activatedTime` 会返回 `A4P_TIMESTAMP_TOO_EARLY`(3003)。 | ||
| 207 | -- 完成或取消被拒绝时,记录保持待处理。 | ||
| 208 | -- 当一次完成操作之后不再有待处理记录,且要么达到次数上限、要么剩余金额为 0 时,ACTIVE 意图变为 | ||
| 209 | - CONSUMED。REVOKED 与 EXPIRED 是终态。 | ||
| 210 | -- `executionInfo()` 始终包含 `leftAmount`;有次数上限时才包含 `leftExecutionCount`, | ||
| 211 | - 周期意图才包含 `periodIndex` 和 `leftPeriodExecutionCount`。Java 的 | ||
| 212 | - `PaymentExecutionInfo` 记录中,不适用数值仍为 `null`;上下文 JSON 会省略这些字段,供 ArkTS 解析。 | ||
| 213 | -- context 操作对校验与更新加锁。这保护共享同一个 context 的线程,而**不**保护多个进程或各自独立激活 | ||
| 214 | - 的副本。 | ||
| 215 | -- `A4pIntentCodec.standard()` 返回无状态的共享单例,因此一个实例可以服务所有线程。 | ||
| 216 | - | ||
| 217 | -账本位于内存中。意图中心必须在以 `intentId` 加锁的数据库事务中持久化 context,防止同一个 `intentId` | ||
| 218 | -被重放,并把密钥与身份绑定。激活会校验最外层的用户签名;`verifyIntentAuthenticity` 校验 L3 链与意图 | ||
| 219 | -中心的 L2 签名,不校验用户签名,也不依赖 context 状态。 | ||
| 220 | - | ||
| 221 | -## 线格式与安全 | ||
| 222 | - | ||
| 223 | -参见 [canonical JSON 规范](docs/canonical-json-spec.md)。JSON 字段名遵循规范 | ||
| 224 | -(`intentConversation`、`resources`、`UserIdentity.id`),每个枚举都按名称序列化 | ||
| 225 | -(`"AI_PAY"`、`"CONSUMED"`、`"PENDING"`),协议版本为 `1.0`。在规范确定它们之前,HTTP 绑定不属于本 SDK。 | ||
| 226 | - | ||
| 227 | -每一层的签名覆盖该层除去整个 `sign` 对象之后的内容,因此该层自己的 `alg` 与 `keyIdentifier` | ||
| 228 | -不在其自身签名字节内;它们由下一层的签名覆盖。这是规范规定的设计。`alg` 必须是 `RSA3072`。 | ||
| 229 | -验证方必须只从可信注册表中解析密钥,并把每个密钥绑定到允许的算法;绝不要信任传入的 `alg`。 | ||
| 230 | - | ||
| 231 | -`Rsa3072` 是一个可选但可用的适配器,使用 JCA `SHA256withRSA`(PKCS#1 v1.5)、3072 位 RSA 密钥 | ||
| 232 | -和无填充的 Base64URL。其 `VerificationResult.code` 成功为 `0`、失败为 `2002`,失败原因放在 | ||
| 233 | -`message` 中。缺失信任映射表、空白密钥标识符或缺失/非 3072 位密钥时,其工厂方法抛出 | ||
| 234 | -`A4pException(A4P_INVALID_PARAMETER)`。对端必须就该套件达成一致,或提供相匹配的 | ||
| 235 | -`Signer`/`SignatureVerifier` 实现。任何验证器返回的 `VerificationResult` 都必须在 `code` 为 `0` | ||
| 236 | -时恰好令 `valid` 为 true;结果不一致时按验证失败处理。 | ||
| 237 | - | ||
| 238 | -意图记录与嵌套载荷不可变;`JsonNode` 载荷在进出时都会被复制。该 Java 移植还拒绝重复的 JSON 键、 | ||
| 239 | -未知的模型字段、非法 UTF-8、带小数的整数字段、数值型枚举值、标量强制转换以及非法的回调结果, | ||
| 240 | -而不是静默地规范化安全敏感输入。 | ||
| 241 | - | ||
| 242 | ## 版本与兼容性 | 196 | ## 版本与兼容性 |
| 243 | 197 | ||
| 244 | -协议版本是 `1.0`(`A4p.PROTOCOL_VERSION`)。本 SDK 创建的每一层都写入该常量,每一步都会校验所收到的 | 198 | +- 当前协议版本: `1.0`(`A4p.PROTOCOL_VERSION`) |
| 245 | -各层,不一致时以 `A4P_UNSUPPORTED_VERSION` 拒绝。该移植与它所来自的 ArkTS SDK(`A4P-arkts-sdk/`) | 199 | +- java SDK 构建版本: `0.1.0` |
| 246 | -实现相同的线格式,canonical-vector 测试让两者保持一致,因此在双方都使用 canonical JSON 规则与同一 | ||
| 247 | -签名套件的前提下,意图与持久化的 context 可以在两个 SDK 之间互换。构件版本为 `0.1.0`; | ||
| 248 | -协议兼容性由 `version` 字段决定,而不是由构件版本决定。 | ||
| 249 | - | ||
| 250 | -## 已知限制 | ||
| 251 | - | ||
| 252 | -- 账本是内存内的、以单个 context 为粒度。持久化、加锁写入、防重放以及密钥与身份的绑定都由意图中心负责。 | ||
| 253 | -- 同步只覆盖共享同一个 `IntentExecutionContext` 的线程,不覆盖多个进程,也不覆盖同一个 `intentId` | ||
| 254 | - 各自独立激活的副本。 | ||
| 255 | -- 在规范确定之前,HTTP 绑定不在范围内;仅提供进程内调用与 canonical JSON 序列化。 | ||
| 256 | -- `Rsa3072` 是约定好的一个套件,而非协商结果;对端要么使用它,要么提供相匹配的 | ||
| 257 | - `Signer`/`SignatureVerifier` 实现。 | ||
| 258 | -- `verifyIntentAuthenticity` 有意不校验用户签名。 | ||
| 259 | -- 该移植在若干处比协议最低要求更严格(重复 JSON 键、未知字段、数值枚举、标量强制转换),以确保安全 | ||
| 260 | - 敏感输入永远不会被静默规范化。下文的对齐文档记录了改了什么以及为什么。 | ||
| 261 | 200 | ||
| 262 | ## 更多文档 | 201 | ## 更多文档 |
| 263 | 202 | ||
| @@ -265,7 +204,8 @@ PaymentExecutionInfo info = PaymentProfile.executionInfo(context); | |||
| 265 | 204 | ||
| 266 | | 文档 | 内容 | | 205 | | 文档 | 内容 | |
| 267 | | --- | --- | | 206 | | --- | --- | |
| 268 | -| [canonical-json-spec.md](docs/canonical-json-spec.md) | 每次签名背后的 canonical JSON 与 Base64URL 规则。 | | 207 | +| [API_zh.md](docs/API_zh.md) | API 详细说明 | |
| 208 | +| [serialization_and_signature_rules_zh.md](docs/serialization_and_signature_rules_zh.md) | 序列化与签名规则 | | ||
| 269 | 209 | ||
| 270 | ## 测试 | 210 | ## 测试 |
| 271 | 211 | ||
| @@ -0,0 +1,242 @@ | |||
| 1 | +# Java SDK public API | ||
| 2 | + | ||
| 3 | +[English](API.md) | [简体中文](API_zh.md) | ||
| 4 | + | ||
| 5 | +This reference describes the current public API in `io.openjiuwen.a4p`, targeting Java 17 and A4P Core `1.0` (`A4p.PROTOCOL_VERSION`). The supported action type is `AI_PAY`. | ||
| 6 | + | ||
| 7 | +## Imports and lifecycle | ||
| 8 | + | ||
| 9 | +```java | ||
| 10 | +import io.openjiuwen.a4p.*; | ||
| 11 | +import io.openjiuwen.a4p.Models.*; | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +Protocol records and enums are nested in `Models`; importing `A4p` alone does not import them. `A4p` provides static lifecycle operations, `PaymentProfile` constructs and decodes payment payloads, and `new A4pIntentCodec()` provides canonical JSON serialization and restoration. | ||
| 15 | + | ||
| 16 | +```text | ||
| 17 | +createIntent → issueIntent → signIntent → activateIntent | ||
| 18 | + ↓ | ||
| 19 | + createExecution | ||
| 20 | + ↓ | ||
| 21 | + completeExecution / cancelExecution | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +Create and restore layered intents and execution contexts through SDK APIs. Applications may construct request, identity, environment and payment input records. Do not repeat the same operation for the same Intent or Execution; lifecycle operations must be called in order. One Context can process multiple distinct Executions. Queries and serialization can be repeated. | ||
| 25 | + | ||
| 26 | +The SDK reserves and accounts for authorization; the application performs the external payment and then completes or cancels its reservation. Persist the activated context and every subsequent update. Serialize each intent's database read-update-write cycle in a transaction; synchronization on one in-memory context does not coordinate multiple restored copies or processes. A failed reservation can set the supplied context to EXPIRED: persist that context even though the failure result has no data. | ||
| 27 | + | ||
| 28 | +## Results and exceptions | ||
| 29 | + | ||
| 30 | +Lifecycle methods and deserializers return `A4pResult<T>`. Check `success()` before reading `data()`: success has non-null data and code `0`; failure has null data and a nonzero code. Branch on numeric codes rather than message text. The public result constructor throws `IllegalArgumentException` for inconsistent success/data/code combinations. `toString()` excludes business payloads. | ||
| 31 | + | ||
| 32 | +Serialization, payment helpers and model normalization can throw `A4pException`; inspect `code()` for its `A4pErrorCode`. Unexpected runtime defects in result-returning operations surface as `A4pException(A4P_INTERNAL_ERROR)` rather than ordinary failure results. | ||
| 33 | + | ||
| 34 | +`verifyIntentAuthenticity` has two result levels: `result.success()` means the SDK call succeeded, while `result.data().valid()` is the issuer-verification verdict. A consistent negative verdict can be returned inside a successful SDK result. | ||
| 35 | + | ||
| 36 | +## Timestamp rules | ||
| 37 | + | ||
| 38 | +All timestamps and explicit `now` arguments are Unix epoch milliseconds. Overloads without `now` use `System.currentTimeMillis()`; explicit clocks must be trusted. Numeric protocol values are integers within ±9007199254740991; timestamps are non-negative. Amounts and quantities are positive integers. Amount units are application-defined minor currency units. | ||
| 39 | + | ||
| 40 | +| Operation | Time requirements | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `issueIntent` | `now >= L1.timestamp`; otherwise `A4P_INVALID_PARAMETER`. | | ||
| 43 | +| `signIntent` | `now >= L2.timestamp` and `now <= validUntil`; otherwise invalid parameter or expired. These checks precede verification and signing. | | ||
| 44 | +| `activateIntent` | `now >= L3.timestamp` and `now <= validUntil`; otherwise invalid parameter or expired. Stores `activatedTime = now`. | | ||
| 45 | +| `createExecution` | `now >= activatedTime` and `validFrom <= now <= validUntil`. Too early returns 3003; expiration returns 3002 and can mark the context EXPIRED. | | ||
| 46 | +| `completeExecution`, `cancelExecution` | `now >= reservedAt`; otherwise 3003. Existing reservations can be finalized after expiry or revocation. | | ||
| 47 | +| `revokeIntent` | `now >= activatedTime`; otherwise 3003. No authorization validity-window restriction. | | ||
| 48 | + | ||
| 49 | +Signing and activation before `validFrom` are allowed. Equal timestamps and both validity boundaries are allowed. `Order.timestamp` is validated as a timestamp but does not determine reservation validity or quota periods. Reading context status does not automatically evaluate expiry. | ||
| 50 | + | ||
| 51 | +## Function reference | ||
| 52 | + | ||
| 53 | +| Type | Signature | Behavior | | ||
| 54 | +| --- | --- | --- | | ||
| 55 | +| `A4p` | `static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner)` | Create and agent-sign L1; generate intentId when omitted. | | ||
| 56 | +| `A4p` | `static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner, long now)` | Create and agent-sign L1; generate intentId when omitted. | | ||
| 57 | +| `A4p` | `static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier, IntentIssueContext context, Signer serverSigner)` | Validate L1 and its agent signature, bind identities and server-sign L2. | | ||
| 58 | +| `A4p` | `static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier, IntentIssueContext context, Signer serverSigner, long now)` | Validate L1 and its agent signature, bind identities and server-sign L2. | | ||
| 59 | +| `A4p` | `static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier, SigningEnv environment, Signer userSigner)` | Verify the L2 server signature, attach the signing environment and user-sign L3. Checks both L2 and L1 versions. Requires `now >= L2.timestamp` (`A4P_INVALID_PARAMETER` if earlier) and `now <= validUntil` (`A4P_TIMESTAMP_EXPIRED`, 3002, if later) before verification or user signing. Signing before `validFrom` is allowed; `createExecution` rejects early reservations with `A4P_TIMESTAMP_TOO_EARLY` (3003). Uses the system clock for `now`. | | ||
| 60 | +| `A4p` | `static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier, SigningEnv environment, Signer userSigner, long now)` | Verify the L2 server signature, attach the signing environment and user-sign L3. Checks both L2 and L1 versions. Requires `now >= L2.timestamp` (`A4P_INVALID_PARAMETER` if earlier) and `now <= validUntil` (`A4P_TIMESTAMP_EXPIRED`, 3002, if later) before verification or user signing. Signing before `validFrom` is allowed; `createExecution` rejects early reservations with `A4P_TIMESTAMP_TOO_EARLY` (3003). | | ||
| 61 | +| `A4p` | `static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier)` | Verify the L3 user signature and create an ACTIVE context with activatedTime. | | ||
| 62 | +| `A4p` | `static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier, long now)` | Verify the L3 user signature and create an ACTIVE context with activatedTime. | | ||
| 63 | +| `A4p` | `static A4pResult<VerificationResult> verifyIntentAuthenticity(IntentL3 intent, SignatureVerifier issuerVerifier)` | Check chain structure, versions and the L2 issuer signature; return the verification verdict without checking the user signature. | | ||
| 64 | +| `A4p` | `static A4pResult<IntentExecutionContext> revokeIntent(IntentExecutionContext context)` | Revoke an ACTIVE context; existing pending executions may still be completed or canceled. | | ||
| 65 | +| `A4p` | `static A4pResult<IntentExecutionContext> revokeIntent(IntentExecutionContext context, long now)` | Revoke an ACTIVE context; existing pending executions may still be completed or canceled. | | ||
| 66 | +| `A4p` | `static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context, Execution execution)` | Check validity, status, unique IDs, order and quotas; append a PENDING reservation and refresh accounting. | | ||
| 67 | +| `A4p` | `static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context, Execution execution, long now)` | Check validity, status, unique IDs, order and quotas; append a PENDING reservation and refresh accounting. | | ||
| 68 | +| `A4p` | `static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context, String executionId)` | Complete a pending execution and refresh current-period executionInfo; consume an active context when global quota is exhausted and no execution is pending. | | ||
| 69 | +| `A4p` | `static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context, String executionId, long now)` | Complete a pending execution and refresh current-period executionInfo; consume an active context when global quota is exhausted and no execution is pending. | | ||
| 70 | +| `A4p` | `static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context, String executionId)` | Cancel a pending execution, release its quotas and refresh accounting while retaining the ledger record. | | ||
| 71 | +| `A4p` | `static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context, String executionId, long now)` | Cancel a pending execution, release its quotas and refresh accounting while retaining the ledger record. | | ||
| 72 | +| `A4pErrorCode` | `int code()` | Read the result code or exception error code. | | ||
| 73 | +| `A4pErrorCode` | `String message()` | Read the diagnostic message (SDK-generated results use fixed English messages). | | ||
| 74 | +| `A4pErrorCode` | `static A4pErrorCode fromCode(int code)` | Map a numeric code to its enum; unknown codes map to internal error. | | ||
| 75 | +| `A4pException` | `A4pException(A4pErrorCode code)` | Construct a runtime exception with a code and optional message and cause. | | ||
| 76 | +| `A4pException` | `A4pException(A4pErrorCode code, String message, Throwable cause)` | Construct a runtime exception with a code and optional message and cause. | | ||
| 77 | +| `A4pException` | `A4pErrorCode code()` | Read the result code or exception error code. | | ||
| 78 | +| `A4pIntentCodec` | `A4pIntentCodec()` | Construct the public, reusable canonical JSON codec. | | ||
| 79 | +| `A4pIntentCodec` | `String serializeIntentL1(IntentL1 intentL1)` | Serialize IntentL1 as canonical JSON. | | ||
| 80 | +| `A4pIntentCodec` | `A4pResult<IntentL1> deserializeIntentL1(String serialized)` | Restore from local JSON with structural checks; this does not replace signature or integrity verification. | | ||
| 81 | +| `A4pIntentCodec` | `String serializeIntentL2(IntentL2 intentL2)` | Serialize IntentL2 as canonical JSON. | | ||
| 82 | +| `A4pIntentCodec` | `A4pResult<IntentL2> deserializeIntentL2(String serialized)` | Restore from local JSON with structural checks; this does not replace signature or integrity verification. | | ||
| 83 | +| `A4pIntentCodec` | `String serializeIntentL3(IntentL3 intentL3)` | Serialize IntentL3 as canonical JSON. | | ||
| 84 | +| `A4pIntentCodec` | `A4pResult<IntentL3> deserializeIntentL3(String serialized)` | Restore from local JSON with structural checks; this does not replace signature or integrity verification. | | ||
| 85 | +| `A4pIntentCodec` | `String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext)` | Serialize IntentExecutionContext as canonical JSON. | | ||
| 86 | +| `A4pIntentCodec` | `A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized)` | Restore from local JSON with structural checks; this does not replace signature or integrity verification. | | ||
| 87 | +| `A4pResult` | `boolean success()` | Read the success flag. | | ||
| 88 | +| `A4pResult` | `T data()` | Read success data, or null on failure. | | ||
| 89 | +| `A4pResult` | `long code()` | Read the result code or exception error code. | | ||
| 90 | +| `A4pResult` | `String message()` | Read the diagnostic message (SDK-generated results use fixed English messages). | | ||
| 91 | +| `A4pResult` | `String toString()` | Return a result summary without business payloads. | | ||
| 92 | +| `A4pResult` | `A4pResult(boolean success, T data, long code, String message)` | Construct a result; success requires non-null data and code 0, failure requires null data and a nonzero code. | | ||
| 93 | +| `IntentExecutionContext` | `long activatedTime()` | Read the activation timestamp in epoch milliseconds, preserved across serialization. | | ||
| 94 | +| `IntentExecutionContext` | `String version()` | Read the protocol version. | | ||
| 95 | +| `IntentExecutionContext` | `String intentId()` | Read the associated intent identifier. | | ||
| 96 | +| `IntentExecutionContext` | `IntentL3 authorizedIntent()` | Read the authorized L3 snapshot. | | ||
| 97 | +| `IntentExecutionContext` | `synchronized IntentExecutionStatus status()` | Read the intent execution status. | | ||
| 98 | +| `IntentExecutionContext` | `synchronized List<ExecutionRecord> executions()` | Read an immutable ledger snapshot. | | ||
| 99 | +| `IntentExecutionContext` | `synchronized JsonNode executionInfo()` | Read the accounting snapshot; reads do not advance its period, execution calls refresh it. | | ||
| 100 | +| `PaymentProfile` | `static StructuredIntent structuredIntent(ShoppingItems resources, PaymentConstraints constraints)` | Wrap payment resources and constraints as an AI_PAY structured intent. | | ||
| 101 | +| `PaymentProfile` | `static Execution execution(String id, Order order)` | Wrap an order as an AI_PAY execution request. | | ||
| 102 | +| `PaymentProfile` | `static ShoppingItems resources(StructuredIntent intent)` | Read and decode AI_PAY resources. | | ||
| 103 | +| `PaymentProfile` | `static PaymentConstraints constraints(StructuredIntent intent)` | Read and decode AI_PAY constraints. | | ||
| 104 | +| `PaymentProfile` | `static Order order(Execution execution)` | Read and decode the payment order in an execution. | | ||
| 105 | +| `PaymentProfile` | `static PaymentExecutionInfo executionInfo(IntentExecutionContext context)` | Read the accounting snapshot; reads do not advance its period, execution calls refresh it. | | ||
| 106 | +| `SignatureVerifier` | `VerificationResult verify(byte[] data, SignatureInfo signature) throws Exception` | Verify SDK-provided bytes and signature and return VerificationResult. | | ||
| 107 | +| `Signer` | `SignatureInfo sign(byte[] data) throws Exception` | Sign the SDK-provided bytes and return SignatureInfo. | | ||
| 108 | + | ||
| 109 | +## Public data types | ||
| 110 | + | ||
| 111 | +All rows below are nested in `io.openjiuwen.a4p.Models`, for example `io.openjiuwen.a4p.Models.IntentL1`. Fields are listed in canonical constructor order; accessors have the component name, such as `order.amount()`. | ||
| 112 | + | ||
| 113 | +| Type | Description and fields | | ||
| 114 | +| --- | --- | | ||
| 115 | +| `io.openjiuwen.a4p.Models.SellerInfo` | Seller identifier; `String id` | | ||
| 116 | +| `io.openjiuwen.a4p.Models.SpuSkuInfo` | Product SPU/SKU identifiers; `String spuId, String skuId` | | ||
| 117 | +| `io.openjiuwen.a4p.Models.Product` | Seller and product identity; `SellerInfo seller, SpuSkuInfo spusku` | | ||
| 118 | +| `io.openjiuwen.a4p.Models.CartItem` | Cart product and quantity; `Product product, Long quantity` | | ||
| 119 | +| `io.openjiuwen.a4p.Models.ItemWhiteList` | Allowed products and quantity; `List<Product> whiteList, Long quantity` | | ||
| 120 | +| `io.openjiuwen.a4p.Models.ShoppingItems` | Payment resource whitelist; `List<ItemWhiteList> itemsWhiteList` | | ||
| 121 | +| `io.openjiuwen.a4p.Models.PaymentConstraints` | Amount, currency, validity, execution-count and period limits; `Long singleOrderMaxAmount, Long totalMaxAmount, String currency, Long validFrom, Long validUntil, Long maxExecutionCount, Long anchorTime, Long periodSeconds, Long maxExecutionCountPerPeriod` | | ||
| 122 | +| `io.openjiuwen.a4p.Models.Order` | Order identifier, amount, currency, products and timestamp; `String orderId, Long amount, String currency, List<CartItem> cartItems, Long timestamp` | | ||
| 123 | +| `io.openjiuwen.a4p.Models.PaymentExecutionInfo` | Remaining quotas and snapshot period; `Long leftExecutionCount, long leftAmount, Long periodIndex, Long leftPeriodExecutionCount` | | ||
| 124 | +| `io.openjiuwen.a4p.Models.StructuredIntent` | Action and associated resources and constraints; `IntentActionType action, JsonNode resources, JsonNode constraints` | | ||
| 125 | +| `io.openjiuwen.a4p.Models.UserIdentity` | User identity; `String identityProvider, String id, String additionalInfo` | | ||
| 126 | +| `io.openjiuwen.a4p.Models.AgentIdentity` | Agent identity; `String identityProvider, String id, String additionalInfo` | | ||
| 127 | +| `io.openjiuwen.a4p.Models.ServiceProviderIdentity` | Service provider identity; `String id, String additionalInfo` | | ||
| 128 | +| `io.openjiuwen.a4p.Models.SigningEnv` | Signing device and app environment; `Map<String, Object> device, Map<String, Object> app` | | ||
| 129 | +| `io.openjiuwen.a4p.Models.SignatureInfo` | Algorithm, key identifier and signature; `String alg, String keyIdentifier, String sign` | | ||
| 130 | +| `io.openjiuwen.a4p.Models.CreateIntentRequest` | Input for creating L1; `String intentConversation, String intentSummary, StructuredIntent structuredIntent, String intentId` | | ||
| 131 | +| `io.openjiuwen.a4p.Models.IntentIssueContext` | Identity context input for issuing L2; `UserIdentity userIdentity, AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity` | | ||
| 132 | +| `io.openjiuwen.a4p.Models.VerificationResult` | Verification validity, code and message; `boolean valid, long code, String message` | | ||
| 133 | +| `io.openjiuwen.a4p.Models.IntentL1` | Agent-created level-one intent; `String version, String intentId, String intentConversation, String intentSummary, StructuredIntent structuredIntent, Long timestamp, SignatureInfo sign` | | ||
| 134 | +| `io.openjiuwen.a4p.Models.IntentL2` | Server-issued level-two intent; `String version, IntentL1 intentL1, UserIdentity userIdentity, AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity, Long timestamp, SignatureInfo sign` | | ||
| 135 | +| `io.openjiuwen.a4p.Models.IntentL3` | User-signed level-three intent; `String version, IntentL2 intentL2, SigningEnv signingEnv, Long timestamp, SignatureInfo sign` | | ||
| 136 | +| `io.openjiuwen.a4p.Models.Execution` | Execution request and action payload; `IntentActionType action, String id, JsonNode executionContent` | | ||
| 137 | +| `io.openjiuwen.a4p.Models.ExecutionRecord` | Ledger record for reservation, completion or cancellation; `String executionId, ExecutionStatus status, IntentActionType action, JsonNode executionContent, Long periodIndex, long reservedAt, Long completedAt, Long canceledAt` | | ||
| 138 | +| `io.openjiuwen.a4p.Models.IntentActionType` | `AI_PAY` | | ||
| 139 | +| `io.openjiuwen.a4p.Models.AlgorithmType` | `RSA3072` | | ||
| 140 | +| `io.openjiuwen.a4p.Models.IntentExecutionStatus` | `ACTIVE, CONSUMED, REVOKED, EXPIRED` | | ||
| 141 | +| `io.openjiuwen.a4p.Models.ExecutionStatus` | `PENDING, COMPLETED, CANCELED` | | ||
| 142 | + | ||
| 143 | +Records expose canonical constructors and standard `equals`, `hashCode` and `toString`. `SignatureInfo` also accepts `(AlgorithmType alg, String keyIdentifier, String sign)`. Enums expose `values()` and `valueOf(String)`. Collections are copied, environment maps are normalized and frozen, and JSON payload accessors return defensive copies. Record construction does not replace lifecycle validation. `IntentExecutionContext` has no public constructor; obtain it through activation or the codec. | ||
| 144 | + | ||
| 145 | +## Payment input and cart matching | ||
| 146 | + | ||
| 147 | +`PaymentProfile.structuredIntent(resources, constraints)` and `PaymentProfile.execution(id, order)` wrap typed records as action-selected JSON. They do not replace lifecycle validation. Java `null` omits optional record fields from canonical JSON; payment payload decoders reject explicit JSON null values, including nested nulls. | ||
| 148 | + | ||
| 149 | +- `totalMaxAmount`, `currency`, `validFrom` and `validUntil` are required; `validFrom <= validUntil`. `singleOrderMaxAmount` and `maxExecutionCount` are optional positive limits. The order currency must exactly equal the authorized currency. | ||
| 150 | +- `anchorTime`, `periodSeconds` and `maxExecutionCountPerPeriod` must be supplied together or all omitted. `anchorTime <= validFrom`; `periodSeconds` is positive, measured in seconds and at most 9007199254740. Violations return `A4P_INVALID_PARAMETER`. | ||
| 151 | +- Whitelist groups and each group's alternatives must be nonempty. Groups form an AND template; products within a group are OR alternatives. Every product must be unique across the entire whitelist, including within a group. | ||
| 152 | +- Each execution must contain exactly one cart entry per group, with exactly that group's quantity. Quantity is a per-execution template, not a lifetime product quota. Missing groups, repeated groups or wrong quantities return `A4P_CART_MISMATCH` (4005). Unauthorized products return `A4P_PRODUCT_NOT_AUTHORIZED` (4007) and are checked before cart shape. | ||
| 153 | +- Product matching compares the complete seller/SPU/SKU record exactly. Seller ID is required; at least one of SPU or SKU must be present and nonblank. Omission of an identifier is not a wildcard. | ||
| 154 | +- Conversation and summary must be nonblank. Conversation length limits and sensitive-data filtering are the agent application's responsibility. Issuance requires trusted user, agent and service-provider identities; signing requires non-null device and app maps. | ||
| 155 | + | ||
| 156 | +## State and accounting | ||
| 157 | + | ||
| 158 | +| State | Meaning | | ||
| 159 | +| --- | --- | | ||
| 160 | +| Context `ACTIVE` | Accepts new reservations subject to time and quota checks. | | ||
| 161 | +| Context `CONSUMED` | Global amount or count quota exhausted with no PENDING records; set when completing the final pending execution of an ACTIVE context. | | ||
| 162 | +| Context `REVOKED` | Explicitly revoked; rejects new reservations and allows existing PENDING records to be completed or canceled. | | ||
| 163 | +| Context `EXPIRED` | Marked by an expired reservation attempt; rejects new reservations and allows existing PENDING records to be completed or canceled. | | ||
| 164 | +| Execution `PENDING` | Reserves amount, global count and original-period count. | | ||
| 165 | +| Execution `COMPLETED` | Retains quota usage; cannot be finalized again. | | ||
| 166 | +| Execution `CANCELED` | Releases quota usage and retains the record; cannot be finalized again. | | ||
| 167 | + | ||
| 168 | +Revocation requires ACTIVE. Finalizing records in REVOKED or EXPIRED contexts preserves that context status. A full period alone does not make a context CONSUMED. Execution IDs and order IDs are unique within a context and remain unavailable for reuse after cancellation. A null execution ID requests UUID generation; read the generated ID from the resulting ledger. | ||
| 169 | + | ||
| 170 | +Periodic accounting uses `floor((now - anchorTime) / (periodSeconds * 1000))`. `ExecutionRecord.periodIndex` is assigned at reservation and never moved by completion or cancellation. Pending and completed records occupy quotas; canceled records do not. Finalizing in a later period refreshes that period's snapshot while retaining the original reservation period and completed global usage. Canceling an old-period reservation does not reduce current-period usage. | ||
| 171 | + | ||
| 172 | +`executionInfo()` is a snapshot, refreshed at activation and successful reservation/completion/cancellation. Reads and revocation do not advance its period. Unconfigured optional quotas are null in `PaymentExecutionInfo` and omitted from context JSON. | ||
| 173 | + | ||
| 174 | +## Signing and verification callbacks | ||
| 175 | + | ||
| 176 | +Implement `Signer` and `SignatureVerifier` using application-owned key infrastructure. The SDK supplies canonical UTF-8 JSON bytes: object keys are sorted, array order is preserved and insignificant whitespace is omitted. Only the current layer's outer `sign` field is removed; embedded layer signatures remain covered. Sign the supplied bytes directly. | ||
| 177 | + | ||
| 178 | +Return `SignatureInfo` with `alg`, a trusted key identifier and an unpadded Base64URL signature. Resolve verification keys and their bound algorithm through a trusted registry: the outer signature metadata is not covered by its own layer's signature. Callback exceptions or invalid signer metadata map to `A4P_SIGNING_FAIL`. Verifier exceptions, null verdicts, or disagreement between `valid` and `code == 0` map to `A4P_VERIFY_FAIL`. Lifecycle operations requiring a positive verdict also map a negative verdict to `A4P_VERIFY_FAIL`. | ||
| 179 | + | ||
| 180 | +| API | Cryptographic verification performed | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `issueIntent` | L1 agent signature. | | ||
| 183 | +| `signIntent` | L2 intent-center signature. | | ||
| 184 | +| `activateIntent` | L3 user signature. | | ||
| 185 | +| `verifyIntentAuthenticity` | L2 issuer signature, after chain structure and version checks; does not verify the user signature or current execution eligibility. | | ||
| 186 | +| Deserializers | Structural validation only; no cryptographic signature verification. | | ||
| 187 | + | ||
| 188 | +See [Serialization and signature rules](serialization_and_signature_rules.md). | ||
| 189 | + | ||
| 190 | +## Serialization and persistence | ||
| 191 | + | ||
| 192 | +`A4pIntentCodec` is a public concrete class with a public no-argument constructor. Use the provided codec directly; no application implementation or factory is required. | ||
| 193 | + | ||
| 194 | +```java | ||
| 195 | +A4pIntentCodec codec = new A4pIntentCodec(); | ||
| 196 | +String json = codec.serializeIntentExecutionContext(context); | ||
| 197 | +A4pResult<IntentExecutionContext> restored = | ||
| 198 | + codec.deserializeIntentExecutionContext(json); | ||
| 199 | +if (!restored.success()) { | ||
| 200 | + throw new IllegalStateException("Restore failed: " + restored.code()); | ||
| 201 | +} | ||
| 202 | +IntentExecutionContext restoredContext = restored.data(); | ||
| 203 | +``` | ||
| 204 | + | ||
| 205 | +The same codec supports L1, L2 and L3 serialization and restoration. Context JSON contains `version`, `intentId`, `authorizedIntent`, `activatedTime`, `status`, `executionInfo` and `executions`. Serialization takes a consistent context snapshot under its lock. Parsing rejects duplicate keys and trailing tokens; structural validation failures may return specific protocol errors rather than only 5002. Intent deserializers check structure; context restoration additionally checks supported versions, activation time, ledger constraints, reachable status and accounting consistency. | ||
| 206 | + | ||
| 207 | +Restoration does not authenticate stored data or reverify signatures. Protect persistence integrity at the application level where required. Context JSON is for local persistence only and must not be used as a network message. Old contexts without the required `activatedTime` cannot be restored directly; use an application-controlled trusted migration, or a new authorization lifecycle without resetting existing authorization usage. | ||
| 208 | + | ||
| 209 | +## Result codes | ||
| 210 | + | ||
| 211 | +| Enum | Code | Message | | ||
| 212 | +| --- | --- | --- | | ||
| 213 | +| `A4P_SUCCESS` | 0 | Operation completed successfully | | ||
| 214 | +| `A4P_INVALID_PARAMETER` | 1001 | Invalid parameter | | ||
| 215 | +| `A4P_UNSUPPORTED_VERSION` | 1002 | Unsupported version | | ||
| 216 | +| `A4P_DUPLICATE_ID` | 1003 | Duplicate ID | | ||
| 217 | +| `A4P_SIGNING_FAIL` | 2001 | Signing failed | | ||
| 218 | +| `A4P_VERIFY_FAIL` | 2002 | Verification failed | | ||
| 219 | +| `A4P_INVALID_STATUS` | 3001 | Invalid status | | ||
| 220 | +| `A4P_TIMESTAMP_EXPIRED` | 3002 | Timestamp expired | | ||
| 221 | +| `A4P_TIMESTAMP_TOO_EARLY` | 3003 | Timestamp too early | | ||
| 222 | +| `A4P_EXECUTION_COUNT_EXCEEDED` | 4001 | Execution count exceeded | | ||
| 223 | +| `A4P_AMOUNT_EXCEEDED` | 4002 | Amount exceeded | | ||
| 224 | +| `A4P_PERIOD_COUNT_EXCEEDED` | 4003 | Period count exceeded | | ||
| 225 | +| `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | 4004 | Period execution count exceeded | | ||
| 226 | +| `A4P_CART_MISMATCH` | 4005 | Cart does not match the authorized resource | | ||
| 227 | +| `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | 4006 | Single order amount exceeded | | ||
| 228 | +| `A4P_PRODUCT_NOT_AUTHORIZED` | 4007 | Product not authorized | | ||
| 229 | +| `A4P_SERIALIZE_FAIL` | 5001 | Serialization failed | | ||
| 230 | +| `A4P_DESERIALIZE_FAIL` | 5002 | Deserialization failed | | ||
| 231 | +| `A4P_INTERNAL_ERROR` | 6001 | Unexpected internal error | | ||
| 232 | + | ||
| 233 | +Code 4003 is retained for ArkTS compatibility; Java uses 4004 for per-period execution-count limits. | ||
| 234 | + | ||
| 235 | +## Usage contract | ||
| 236 | + | ||
| 237 | +1. Create or restore all Intent and Context structures through SDK APIs. Hand-assembled lifecycle structures may cause undefined behavior. Applications may construct the documented request, identity, environment and order input models. | ||
| 238 | +2. Follow the lifecycle: createIntent → issueIntent → signIntent → activateIntent → createExecution → completeExecution or cancelExecution. An ACTIVE Context may be revoked. | ||
| 239 | +3. Do not repeat the same lifecycle step for an Intent, activation/revocation for a Context, or reservation/finalization for an Execution. An ACTIVE Context may process distinct Executions; reads and serialization may be repeated. | ||
| 240 | +4. Persist the Context after activateIntent and every other API returning a Context. A failed createExecution may change its status to EXPIRED, so persist the current Context as well. Persistence is the caller's responsibility. | ||
| 241 | +5. The SDK does not protect persisted Contexts against tampering or verify their integrity. Add caller-side verification where required; structural checks during deserialization are not security integrity checks. | ||
| 242 | +6. Serialized Contexts are for local persistence only and must not be transmitted as network messages. | ||
| @@ -0,0 +1,242 @@ | |||
| 1 | +# Java SDK 公开 API | ||
| 2 | + | ||
| 3 | +[English](API.md) | [简体中文](API_zh.md) | ||
| 4 | + | ||
| 5 | +本文对应当前 `io.openjiuwen.a4p` 包的公开 API,要求 Java 17,支持 A4P Core `1.0`(`A4p.PROTOCOL_VERSION`)。当前支持的 action 类型为 `AI_PAY`。 | ||
| 6 | + | ||
| 7 | +## 导入与生命周期 | ||
| 8 | + | ||
| 9 | +```java | ||
| 10 | +import io.openjiuwen.a4p.*; | ||
| 11 | +import io.openjiuwen.a4p.Models.*; | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +协议 record 和枚举嵌套于 `Models`,仅导入 `A4p` 不会导入它们。`A4p` 提供静态生命周期方法,`PaymentProfile` 用于构造和解析支付载荷,`new A4pIntentCodec()` 提供规范 JSON 序列化与恢复能力。 | ||
| 15 | + | ||
| 16 | +```text | ||
| 17 | +createIntent → issueIntent → signIntent → activateIntent | ||
| 18 | + ↓ | ||
| 19 | + createExecution | ||
| 20 | + ↓ | ||
| 21 | + completeExecution / cancelExecution | ||
| 22 | +``` | ||
| 23 | + | ||
| 24 | +各层 Intent 和执行 Context 应通过 SDK 接口创建或恢复;应用可自行构造请求、身份、环境和支付输入 record。禁止对同一个 Intent 或 Execution 重复调用相同的接口,管理生命周期的函数必须按顺序调用。同一个 Context 可以处理多个不同的 Execution。查询与序列化可重复调用。 | ||
| 25 | + | ||
| 26 | +SDK 负责授权预留和额度记账,应用负责实际对外支付,再根据支付结果完成或取消预留。activateIntent 调用后及每次更新后均须持久化 Context。同一意图的数据库读取、更新、写回应在事务中串行执行;单个内存 Context 的同步不能协调多个恢复副本或进程。预留失败也可能将传入 Context 改为 EXPIRED:即使失败结果没有 data,也须保存该 Context。 | ||
| 27 | + | ||
| 28 | +## 返回结果与异常 | ||
| 29 | + | ||
| 30 | +生命周期方法和反序列化方法返回 `A4pResult<T>`。先检查 `success()`,再读取 `data()`:成功时数据非空、结果码为 `0`;失败时数据为 null、结果码非零。业务判断应使用数值结果码。公开结果构造器在 success/data/code 不一致时抛出 `IllegalArgumentException`。`toString()` 不包含业务载荷。 | ||
| 31 | + | ||
| 32 | +序列化、支付辅助方法和模型规范化可能抛出 `A4pException`,可通过 `code()` 读取 `A4pErrorCode`。返回结果的方法遇到非预期运行时缺陷时会抛出 `A4pException(A4P_INTERNAL_ERROR)`,而非返回普通失败结果。 | ||
| 33 | + | ||
| 34 | +`verifyIntentAuthenticity` 有两层结果:`result.success()` 表示 SDK 调用成功,`result.data().valid()` 才是签发方验签结论。可能存在即使函数返回成功,但是验签结果为非法的情况。 | ||
| 35 | + | ||
| 36 | +## 时间戳规则 | ||
| 37 | + | ||
| 38 | +所有时间戳和显式 `now` 参数均为 Unix epoch 毫秒。省略 `now` 的重载使用 `System.currentTimeMillis()`;显式时间必须来自可信时钟。协议数值为 ±9007199254740991 范围内的整数;时间戳非负,金额与数量为正整数。金额使用应用约定的货币最小单位。 | ||
| 39 | + | ||
| 40 | +| 操作 | 时间要求 | | ||
| 41 | +| --- | --- | | ||
| 42 | +| `issueIntent` | `now >= L1.timestamp`,否则返回 `A4P_INVALID_PARAMETER`。 | | ||
| 43 | +| `signIntent` | `now >= L2.timestamp` 且 `now <= validUntil`,否则返回参数无效或过期;时间检查先于验签和签名。 | | ||
| 44 | +| `activateIntent` | `now >= L3.timestamp` 且 `now <= validUntil`,否则返回参数无效或过期;保存 `activatedTime = now`。 | | ||
| 45 | +| `createExecution` | `now >= activatedTime` 且 `validFrom <= now <= validUntil`;过早返回 3003,过期返回 3002,并可能将 Context 置为 EXPIRED。 | | ||
| 46 | +| `completeExecution`、`cancelExecution` | `now >= reservedAt`,否则返回 3003;过期或撤销后仍可终结已有预留。 | | ||
| 47 | +| `revokeIntent` | `now >= activatedTime`,否则返回 3003;不受授权有效期窗口限制。 | | ||
| 48 | + | ||
| 49 | +允许在 `validFrom` 前签名和激活,允许相同时间戳,有效期两端均包含在内。`Order.timestamp` 会作为时间戳校验,但不决定预留有效性或额度周期。读取 Context 状态不会自动判断是否过期。 | ||
| 50 | + | ||
| 51 | +## 函数接口 | ||
| 52 | + | ||
| 53 | +| 类型 | 签名 | 说明 | | ||
| 54 | +| --- | --- | --- | | ||
| 55 | +| `A4p` | `static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner)` | 创建并签名 L1;请求可省略 intentId,由 SDK 生成。 | | ||
| 56 | +| `A4p` | `static A4pResult<IntentL1> createIntent(CreateIntentRequest request, Signer agentSigner, long now)` | 创建并签名 L1;请求可省略 intentId,由 SDK 生成。 | | ||
| 57 | +| `A4p` | `static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier, IntentIssueContext context, Signer serverSigner)` | 校验 L1 和 Agent 签名,绑定身份后由服务端签发 L2。 | | ||
| 58 | +| `A4p` | `static A4pResult<IntentL2> issueIntent(IntentL1 intent, SignatureVerifier agentVerifier, IntentIssueContext context, Signer serverSigner, long now)` | 校验 L1 和 Agent 签名,绑定身份后由服务端签发 L2。 | | ||
| 59 | +| `A4p` | `static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier, SigningEnv environment, Signer userSigner)` | 验证 L2 服务端签名,绑定签名环境并生成用户签名的 L3。校验 L2 和内嵌 L1 的版本;要求 `now >= L2.timestamp`(否则返回 `A4P_INVALID_PARAMETER`)且 `now <= validUntil`(否则返回 `A4P_TIMESTAMP_EXPIRED`,3002),时间校验先于验签和用户签名。允许在 `validFrom` 前提前签署;生效前预留由 `createExecution` 返回 `A4P_TIMESTAMP_TOO_EARLY`(3003)。省略 `now` 时使用系统时间。 | | ||
| 60 | +| `A4p` | `static A4pResult<IntentL3> signIntent(IntentL2 intent, SignatureVerifier serverVerifier, SigningEnv environment, Signer userSigner, long now)` | 验证 L2 服务端签名,绑定签名环境并生成用户签名的 L3。校验 L2 和内嵌 L1 的版本;要求 `now >= L2.timestamp`(否则返回 `A4P_INVALID_PARAMETER`)且 `now <= validUntil`(否则返回 `A4P_TIMESTAMP_EXPIRED`,3002),时间校验先于验签和用户签名。允许在 `validFrom` 前提前签署;生效前预留由 `createExecution` 返回 `A4P_TIMESTAMP_TOO_EARLY`(3003)。 | | ||
| 61 | +| `A4p` | `static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier)` | 验证 L3 用户签名并创建 ACTIVE Context,记录 activatedTime。 | | ||
| 62 | +| `A4p` | `static A4pResult<IntentExecutionContext> activateIntent(IntentL3 intent, SignatureVerifier userVerifier, long now)` | 验证 L3 用户签名并创建 ACTIVE Context,记录 activatedTime。 | | ||
| 63 | +| `A4p` | `static A4pResult<VerificationResult> verifyIntentAuthenticity(IntentL3 intent, SignatureVerifier issuerVerifier)` | 验证意图链结构、版本和 L2 签发方签名,返回验证结果;不验证用户签名。 | | ||
| 64 | +| `A4p` | `static A4pResult<IntentExecutionContext> revokeIntent(IntentExecutionContext context)` | 将 ACTIVE Context 撤销为 REVOKED;已有 PENDING Execution仍可完成或取消。 | | ||
| 65 | +| `A4p` | `static A4pResult<IntentExecutionContext> revokeIntent(IntentExecutionContext context, long now)` | 将 ACTIVE Context 撤销为 REVOKED;已有 PENDING Execution仍可完成或取消。 | | ||
| 66 | +| `A4p` | `static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context, Execution execution)` | 校验有效期、状态、唯一 ID、订单及额度,追加 PENDING 预留并刷新额度。 | | ||
| 67 | +| `A4p` | `static A4pResult<IntentExecutionContext> createExecution(IntentExecutionContext context, Execution execution, long now)` | 校验有效期、状态、唯一 ID、订单及额度,追加 PENDING 预留并刷新额度。 | | ||
| 68 | +| `A4p` | `static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context, String executionId)` | 完成指定 PENDING Execution,刷新当前周期 executionInfo;额度耗尽且无待处理Execution时变为 CONSUMED。 | | ||
| 69 | +| `A4p` | `static A4pResult<IntentExecutionContext> completeExecution(IntentExecutionContext context, String executionId, long now)` | 完成指定 PENDING Execution,刷新当前周期 executionInfo;额度耗尽且无待处理Execution时变为 CONSUMED。 | | ||
| 70 | +| `A4p` | `static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context, String executionId)` | 取消指定 PENDING Execution,释放其占用额度并刷新信息;账本记录保留。 | | ||
| 71 | +| `A4p` | `static A4pResult<IntentExecutionContext> cancelExecution(IntentExecutionContext context, String executionId, long now)` | 取消指定 PENDING Execution,释放其占用额度并刷新信息;账本记录保留。 | | ||
| 72 | +| `A4pErrorCode` | `int code()` | 读取结果码或异常对应的错误码。 | | ||
| 73 | +| `A4pErrorCode` | `String message()` | 读取诊断说明(SDK 生成的结果使用固定英文消息)。 | | ||
| 74 | +| `A4pErrorCode` | `static A4pErrorCode fromCode(int code)` | 将整数结果码映射为枚举;未知值映射为内部错误。 | | ||
| 75 | +| `A4pException` | `A4pException(A4pErrorCode code)` | 构建携带错误码的运行时异常,可提供消息与原因。 | | ||
| 76 | +| `A4pException` | `A4pException(A4pErrorCode code, String message, Throwable cause)` | 构建携带错误码的运行时异常,可提供消息与原因。 | | ||
| 77 | +| `A4pException` | `A4pErrorCode code()` | 读取结果码或异常对应的错误码。 | | ||
| 78 | +| `A4pIntentCodec` | `A4pIntentCodec()` | 创建公开、可复用的规范 JSON 编解码器。 | | ||
| 79 | +| `A4pIntentCodec` | `String serializeIntentL1(IntentL1 intentL1)` | 将 IntentL1 序列化为规范 JSON。 | | ||
| 80 | +| `A4pIntentCodec` | `A4pResult<IntentL1> deserializeIntentL1(String serialized)` | 从本地 JSON 恢复并进行结构校验;不代替签名验证或防篡改检查。 | | ||
| 81 | +| `A4pIntentCodec` | `String serializeIntentL2(IntentL2 intentL2)` | 将 IntentL2 序列化为规范 JSON。 | | ||
| 82 | +| `A4pIntentCodec` | `A4pResult<IntentL2> deserializeIntentL2(String serialized)` | 从本地 JSON 恢复并进行结构校验;不代替签名验证或防篡改检查。 | | ||
| 83 | +| `A4pIntentCodec` | `String serializeIntentL3(IntentL3 intentL3)` | 将 IntentL3 序列化为规范 JSON。 | | ||
| 84 | +| `A4pIntentCodec` | `A4pResult<IntentL3> deserializeIntentL3(String serialized)` | 从本地 JSON 恢复并进行结构校验;不代替签名验证或防篡改检查。 | | ||
| 85 | +| `A4pIntentCodec` | `String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext)` | 将 IntentExecutionContext 序列化为规范 JSON。 | | ||
| 86 | +| `A4pIntentCodec` | `A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized)` | 从本地 JSON 恢复并进行结构校验;不代替签名验证或防篡改检查。 | | ||
| 87 | +| `A4pResult` | `boolean success()` | 读取操作成功标志。 | | ||
| 88 | +| `A4pResult` | `T data()` | 读取成功数据;失败时为 null。 | | ||
| 89 | +| `A4pResult` | `long code()` | 读取结果码或异常对应的错误码。 | | ||
| 90 | +| `A4pResult` | `String message()` | 读取诊断说明(SDK 生成的结果使用固定英文消息)。 | | ||
| 91 | +| `A4pResult` | `String toString()` | 返回不包含业务数据的结果摘要。 | | ||
| 92 | +| `A4pResult` | `A4pResult(boolean success, T data, long code, String message)` | 构造结果;成功要求数据非空且结果码为 0,失败要求数据为空且结果码非 0。 | | ||
| 93 | +| `IntentExecutionContext` | `long activatedTime()` | 读取激活时的毫秒时间戳,序列化与恢复时保留。 | | ||
| 94 | +| `IntentExecutionContext` | `String version()` | 读取协议版本。 | | ||
| 95 | +| `IntentExecutionContext` | `String intentId()` | 读取关联意图标识。 | | ||
| 96 | +| `IntentExecutionContext` | `IntentL3 authorizedIntent()` | 读取已授权 L3 快照。 | | ||
| 97 | +| `IntentExecutionContext` | `synchronized IntentExecutionStatus status()` | 读取意图执行状态。 | | ||
| 98 | +| `IntentExecutionContext` | `synchronized List<ExecutionRecord> executions()` | 读取只读账本快照。 | | ||
| 99 | +| `IntentExecutionContext` | `synchronized JsonNode executionInfo()` | 读取额度快照;读取本身不会推进周期,执行接口调用会刷新。 | | ||
| 100 | +| `PaymentProfile` | `static StructuredIntent structuredIntent(ShoppingItems resources, PaymentConstraints constraints)` | 将支付资源与约束封装为 AI_PAY 结构化意图。 | | ||
| 101 | +| `PaymentProfile` | `static Execution execution(String id, Order order)` | 将订单封装为 AI_PAY 执行请求。 | | ||
| 102 | +| `PaymentProfile` | `static ShoppingItems resources(StructuredIntent intent)` | 读取并解析 AI_PAY 资源。 | | ||
| 103 | +| `PaymentProfile` | `static PaymentConstraints constraints(StructuredIntent intent)` | 读取并解析 AI_PAY 约束。 | | ||
| 104 | +| `PaymentProfile` | `static Order order(Execution execution)` | 读取并解析Execution中的支付订单。 | | ||
| 105 | +| `PaymentProfile` | `static PaymentExecutionInfo executionInfo(IntentExecutionContext context)` | 读取额度快照;读取本身不会推进周期,执行接口调用会刷新。 | | ||
| 106 | +| `SignatureVerifier` | `VerificationResult verify(byte[] data, SignatureInfo signature) throws Exception` | 验证 SDK 提供的字节与签名,返回 VerificationResult。 | | ||
| 107 | +| `Signer` | `SignatureInfo sign(byte[] data) throws Exception` | 对 SDK 提供的待签名字节签名并返回 SignatureInfo。 | | ||
| 108 | + | ||
| 109 | +## 公开数据类型 | ||
| 110 | + | ||
| 111 | +下表类型均嵌套于 `io.openjiuwen.a4p.Models`,如 `io.openjiuwen.a4p.Models.IntentL1`。字段按规范构造器参数顺序列出;访问器与字段同名,例如 `order.amount()`。 | ||
| 112 | + | ||
| 113 | +| 类型 | 说明及字段 | | ||
| 114 | +| --- | --- | | ||
| 115 | +| `io.openjiuwen.a4p.Models.SellerInfo` | 商家标识; `String id` | | ||
| 116 | +| `io.openjiuwen.a4p.Models.SpuSkuInfo` | 商品 SPU/SKU 标识; `String spuId, String skuId` | | ||
| 117 | +| `io.openjiuwen.a4p.Models.Product` | 商家与商品标识; `SellerInfo seller, SpuSkuInfo spusku` | | ||
| 118 | +| `io.openjiuwen.a4p.Models.CartItem` | 购物车商品与数量; `Product product, Long quantity` | | ||
| 119 | +| `io.openjiuwen.a4p.Models.ItemWhiteList` | 允许的商品集合与数量; `List<Product> whiteList, Long quantity` | | ||
| 120 | +| `io.openjiuwen.a4p.Models.ShoppingItems` | 支付资源白名单; `List<ItemWhiteList> itemsWhiteList` | | ||
| 121 | +| `io.openjiuwen.a4p.Models.PaymentConstraints` | 金额、币种、有效期、次数与周期限制; `Long singleOrderMaxAmount, Long totalMaxAmount, String currency, Long validFrom, Long validUntil, Long maxExecutionCount, Long anchorTime, Long periodSeconds, Long maxExecutionCountPerPeriod` | | ||
| 122 | +| `io.openjiuwen.a4p.Models.Order` | 订单标识、金额、币种、商品与时间戳; `String orderId, Long amount, String currency, List<CartItem> cartItems, Long timestamp` | | ||
| 123 | +| `io.openjiuwen.a4p.Models.PaymentExecutionInfo` | 剩余额度与快照周期; `Long leftExecutionCount, long leftAmount, Long periodIndex, Long leftPeriodExecutionCount` | | ||
| 124 | +| `io.openjiuwen.a4p.Models.StructuredIntent` | 动作及对应资源与约束; `IntentActionType action, JsonNode resources, JsonNode constraints` | | ||
| 125 | +| `io.openjiuwen.a4p.Models.UserIdentity` | 用户身份; `String identityProvider, String id, String additionalInfo` | | ||
| 126 | +| `io.openjiuwen.a4p.Models.AgentIdentity` | Agent 身份; `String identityProvider, String id, String additionalInfo` | | ||
| 127 | +| `io.openjiuwen.a4p.Models.ServiceProviderIdentity` | 服务方身份; `String id, String additionalInfo` | | ||
| 128 | +| `io.openjiuwen.a4p.Models.SigningEnv` | 签名设备与应用环境; `Map<String, Object> device, Map<String, Object> app` | | ||
| 129 | +| `io.openjiuwen.a4p.Models.SignatureInfo` | 算法、密钥标识与签名; `String alg, String keyIdentifier, String sign` | | ||
| 130 | +| `io.openjiuwen.a4p.Models.CreateIntentRequest` | 创建 L1 的输入; `String intentConversation, String intentSummary, StructuredIntent structuredIntent, String intentId` | | ||
| 131 | +| `io.openjiuwen.a4p.Models.IntentIssueContext` | 签发 L2 的身份上下文输入; `UserIdentity userIdentity, AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity` | | ||
| 132 | +| `io.openjiuwen.a4p.Models.VerificationResult` | 验证有效性、结果码与说明; `boolean valid, long code, String message` | | ||
| 133 | +| `io.openjiuwen.a4p.Models.IntentL1` | Agent 创建的一级意图; `String version, String intentId, String intentConversation, String intentSummary, StructuredIntent structuredIntent, Long timestamp, SignatureInfo sign` | | ||
| 134 | +| `io.openjiuwen.a4p.Models.IntentL2` | 服务端签发的二级意图; `String version, IntentL1 intentL1, UserIdentity userIdentity, AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity, Long timestamp, SignatureInfo sign` | | ||
| 135 | +| `io.openjiuwen.a4p.Models.IntentL3` | 用户签名的三级意图; `String version, IntentL2 intentL2, SigningEnv signingEnv, Long timestamp, SignatureInfo sign` | | ||
| 136 | +| `io.openjiuwen.a4p.Models.Execution` | 执行请求及动作内容; `IntentActionType action, String id, JsonNode executionContent` | | ||
| 137 | +| `io.openjiuwen.a4p.Models.ExecutionRecord` | 预留、完成或取消的账本记录; `String executionId, ExecutionStatus status, IntentActionType action, JsonNode executionContent, Long periodIndex, long reservedAt, Long completedAt, Long canceledAt` | | ||
| 138 | +| `io.openjiuwen.a4p.Models.IntentActionType` | `AI_PAY` | | ||
| 139 | +| `io.openjiuwen.a4p.Models.AlgorithmType` | `RSA3072` | | ||
| 140 | +| `io.openjiuwen.a4p.Models.IntentExecutionStatus` | `ACTIVE, CONSUMED, REVOKED, EXPIRED` | | ||
| 141 | +| `io.openjiuwen.a4p.Models.ExecutionStatus` | `PENDING, COMPLETED, CANCELED` | | ||
| 142 | + | ||
| 143 | +record 提供规范构造器和标准 `equals`、`hashCode`、`toString`。`SignatureInfo` 另有 `(AlgorithmType alg, String keyIdentifier, String sign)` 构造器;枚举提供 `values()` 和 `valueOf(String)`。集合会复制,环境 Map 会规范化并冻结,JSON 载荷访问器返回防御性副本。构造 record 不代替生命周期校验。`IntentExecutionContext` 无公开构造器,应通过激活或编解码器获取。 | ||
| 144 | + | ||
| 145 | +## 支付输入与购物车匹配 | ||
| 146 | + | ||
| 147 | +`PaymentProfile.structuredIntent(resources, constraints)` 和 `PaymentProfile.execution(id, order)` 将类型化 record 封装为按动作区分的 JSON,不代替生命周期校验。Java `null` 表示省略可选 record 字段;支付载荷解码器拒绝显式 JSON null,包括嵌套 null。 | ||
| 148 | + | ||
| 149 | +- `totalMaxAmount`、`currency`、`validFrom`、`validUntil` 必填,且 `validFrom <= validUntil`;`singleOrderMaxAmount` 和 `maxExecutionCount` 为可选正整数限制。订单币种必须与授权币种完全一致。 | ||
| 150 | +- `anchorTime`、`periodSeconds`、`maxExecutionCountPerPeriod` 必须一起提供或一起省略;`anchorTime <= validFrom`,`periodSeconds` 为正整数秒,最大为 9007199254740。不满足时返回 `A4P_INVALID_PARAMETER`。 | ||
| 151 | +- 白名单组及每组候选商品均不能为空。组间为 AND,每组候选商品为 OR。整个白名单中的商品必须唯一,同组内也不得重复。 | ||
| 152 | +- 每次执行必须为每组提供且仅提供一条购物车条目,数量与该组声明值完全相同。数量是单次执行模板,不是商品的累计额度。缺组、重复匹配同组或数量不符返回 `A4P_CART_MISMATCH`(4005);未授权商品返回 `A4P_PRODUCT_NOT_AUTHORIZED`(4007),且先于购物车形状检查。 | ||
| 153 | +- 商品按完整 seller/SPU/SKU record 精确匹配。商家 ID 必填,SPU 和 SKU 至少提供一个非空白标识;省略某个标识不表示通配。 | ||
| 154 | +- 对话和摘要不能为空白;对话长度限制及敏感信息过滤由 Agent 应用负责。签发时须提供可信的用户、Agent 和服务方身份;签名时 device 与 app Map 均不可为 null。 | ||
| 155 | + | ||
| 156 | +## 状态与额度记账 | ||
| 157 | + | ||
| 158 | +| 状态 | 含义 | | ||
| 159 | +| --- | --- | | ||
| 160 | +| Context `ACTIVE` | 在时间和额度允许时接受新预留。 | | ||
| 161 | +| Context `CONSUMED` | 总金额或总次数额度耗尽,且无 PENDING Execution;完成 ACTIVE Context 的最后一个待处理 Execution 时设置。 | | ||
| 162 | +| Context `REVOKED` | 已主动撤销;拒绝新预留,允许完成或取消已有 PENDING Execution。 | | ||
| 163 | +| Context `EXPIRED` | 由过期预留尝试设置;拒绝新预留,允许完成或取消已有 PENDING Execution。 | | ||
| 164 | +| Execution `PENDING` | 占用金额、总次数及原预留周期的次数额度。 | | ||
| 165 | +| Execution `COMPLETED` | 保留额度占用,不可再次终结。 | | ||
| 166 | +| Execution `CANCELED` | 释放额度并保留记录,不可再次终结。 | | ||
| 167 | + | ||
| 168 | +撤销接口 revokeIntent 要求 Context 为 ACTIVE。在 REVOKED 或 EXPIRED Context 中 completeExecution/cancelExecution 调用不会改变该 Context 状态。仅当周期次数耗尽时不会变成 CONSUMED。Execution ID 和 Order ID 在 Context 内唯一,取消后仍不可复用。Execution ID 为 null 时生成 UUID,可从更新后的账本读取。 | ||
| 169 | + | ||
| 170 | +周期(Period)下标为 `floor((now - anchorTime) / (periodSeconds * 1000))`。`ExecutionRecord.periodIndex` 在预留时确定,完成或取消不会改变其所属周期。PENDING 和 COMPLETED 占用额度,CANCELED 不占用。跨周期终结会刷新求值时所在周期的快照,但保留原预留周期及已完成Execution的全局用量;取消旧周期预留不会减少当前周期用量。 | ||
| 171 | + | ||
| 172 | +`executionInfo()` 是额度快照,在激活和成功预留、完成、取消时刷新。读取和撤销不会推进其周期。未配置的可选额度在 `PaymentExecutionInfo` 中为 null,在 Context JSON 中省略。 | ||
| 173 | + | ||
| 174 | +## 签名与验签回调 | ||
| 175 | + | ||
| 176 | +使用应用自身的密钥设施实现 `Signer` 和 `SignatureVerifier`。SDK 提供规范 UTF-8 JSON 字节:对象键排序、数组顺序保留、不含无意义空白。仅去除当前层最外侧 `sign` 字段,内嵌层签名仍被覆盖;应直接签署 SDK 提供的字节。 | ||
| 177 | + | ||
| 178 | +返回的 `SignatureInfo` 应包含 `alg`、可信密钥标识和无填充 Base64URL 签名。验签时应通过可信注册表解析密钥及其绑定算法;最外层签名元数据不被本层签名覆盖。签名回调异常或签名元数据无效映射为 `A4P_SIGNING_FAIL`。验签回调异常、返回 null 或 `valid` 与 `code == 0` 不一致映射为 `A4P_VERIFY_FAIL`。要求验签通过的生命周期方法也会将否定结论映射为 `A4P_VERIFY_FAIL`。 | ||
| 179 | + | ||
| 180 | +| API | 密码学验证 | | ||
| 181 | +| --- | --- | | ||
| 182 | +| `issueIntent` | L1 Agent 签名。 | | ||
| 183 | +| `signIntent` | L2 意图中心签名。 | | ||
| 184 | +| `activateIntent` | L3 用户签名。 | | ||
| 185 | +| `verifyIntentAuthenticity` | 检查链结构和版本后验证 L2 签发方签名;不验证用户签名,也不判断当前能否执行。 | | ||
| 186 | +| 反序列化方法 | 仅结构校验,不验证密码学签名。 | | ||
| 187 | + | ||
| 188 | +可以参考 [序列化与签名规则](serialization_and_signature_rules_zh.md) | ||
| 189 | + | ||
| 190 | +## 序列化与持久化 | ||
| 191 | + | ||
| 192 | +`A4pIntentCodec` 是带公开无参构造器的公开具体类,可直接使用,无须应用自行实现或查找工厂。 | ||
| 193 | + | ||
| 194 | +```java | ||
| 195 | +A4pIntentCodec codec = new A4pIntentCodec(); | ||
| 196 | +String json = codec.serializeIntentExecutionContext(context); | ||
| 197 | +A4pResult<IntentExecutionContext> restored = | ||
| 198 | + codec.deserializeIntentExecutionContext(json); | ||
| 199 | +if (!restored.success()) { | ||
| 200 | + throw new IllegalStateException("Restore failed: " + restored.code()); | ||
| 201 | +} | ||
| 202 | +IntentExecutionContext restoredContext = restored.data(); | ||
| 203 | +``` | ||
| 204 | + | ||
| 205 | +同一个编解码器支持 L1、L2、L3 的序列化与恢复。Context JSON 包含 `version`、`intentId`、`authorizedIntent`、`activatedTime`、`status`、`executionInfo`、`executions`。序列化在 Context 锁内取得一致快照。解析拒绝重复键和尾随 token;结构校验失败可能返回具体协议错误,而非统一返回 5002。Intent 反序列化检查结构;Context 恢复还检查支持的版本、激活时间、账本约束、状态可达性和额度一致性。 | ||
| 206 | + | ||
| 207 | +恢复不会认证持久化数据,也不会重新验签。需要时由应用保护存储完整性。Context JSON 仅用于本地持久化,不得作为网络消息。缺少必填 `activatedTime` 的旧 Context 无法直接恢复;应使用应用控制的可信迁移,或启动新的授权生命周期,同时避免重置已有授权用量。 | ||
| 208 | + | ||
| 209 | +## 结果码 | ||
| 210 | + | ||
| 211 | +| 枚举 | 数值 | 消息 | | ||
| 212 | +| --- | --- | --- | | ||
| 213 | +| `A4P_SUCCESS` | 0 | Operation completed successfully | | ||
| 214 | +| `A4P_INVALID_PARAMETER` | 1001 | Invalid parameter | | ||
| 215 | +| `A4P_UNSUPPORTED_VERSION` | 1002 | Unsupported version | | ||
| 216 | +| `A4P_DUPLICATE_ID` | 1003 | Duplicate ID | | ||
| 217 | +| `A4P_SIGNING_FAIL` | 2001 | Signing failed | | ||
| 218 | +| `A4P_VERIFY_FAIL` | 2002 | Verification failed | | ||
| 219 | +| `A4P_INVALID_STATUS` | 3001 | Invalid status | | ||
| 220 | +| `A4P_TIMESTAMP_EXPIRED` | 3002 | Timestamp expired | | ||
| 221 | +| `A4P_TIMESTAMP_TOO_EARLY` | 3003 | Timestamp too early | | ||
| 222 | +| `A4P_EXECUTION_COUNT_EXCEEDED` | 4001 | Execution count exceeded | | ||
| 223 | +| `A4P_AMOUNT_EXCEEDED` | 4002 | Amount exceeded | | ||
| 224 | +| `A4P_PERIOD_COUNT_EXCEEDED` | 4003 | Period count exceeded | | ||
| 225 | +| `A4P_PERIOD_EXECUTION_COUNT_EXCEEDED` | 4004 | Period execution count exceeded | | ||
| 226 | +| `A4P_CART_MISMATCH` | 4005 | Cart does not match the authorized resource | | ||
| 227 | +| `A4P_SINGLE_ORDER_AMOUNT_EXCEEDED` | 4006 | Single order amount exceeded | | ||
| 228 | +| `A4P_PRODUCT_NOT_AUTHORIZED` | 4007 | Product not authorized | | ||
| 229 | +| `A4P_SERIALIZE_FAIL` | 5001 | Serialization failed | | ||
| 230 | +| `A4P_DESERIALIZE_FAIL` | 5002 | Deserialization failed | | ||
| 231 | +| `A4P_INTERNAL_ERROR` | 6001 | Unexpected internal error | | ||
| 232 | + | ||
| 233 | +4003 为兼容 ArkTS 保留,Java 使用 4004 表示周期执行次数超限。 | ||
| 234 | + | ||
| 235 | +## 使用约束 | ||
| 236 | + | ||
| 237 | +1. 所有 Intent 和 Context 结构必须通过 SDK 接口创建或恢复,禁止自行组装,否则可能产生未定义行为。请求、身份、环境与订单等输入模型可按下文构造。 | ||
| 238 | +2. 必须按生命周期顺序调用:createIntent → issueIntent → signIntent → activateIntent → createExecution → completeExecution 或 cancelExecution;可撤销 ACTIVE Context。 | ||
| 239 | +3. 同一个 Intent 的同一生命周期步骤、同一个 Context 的激活/撤销步骤以及同一执行的预留/终结步骤不得重复调用。一个 ACTIVE Context 可处理多个不同执行;只读查询与序列化可以重复。 | ||
| 240 | +4. activateIntent 及其他返回 Context 的接口返回后必须持久化 Context。createExecution 失败时也可能把状态改为 EXPIRED,仍须持久化当前 Context。持久化不是 SDK 自动完成的。 | ||
| 241 | +5. SDK 不负责持久化 Context 的防篡改或完整性验证;需要该能力时由调用方自行校验。反序列化中的格式检查不代表安全完整性校验。 | ||
| 242 | +6. 序列化 Context 只能用于本地持久化,不应作为消息通过网络传输。 | ||
| @@ -1,42 +0,0 @@ | |||
| 1 | -# Canonical JSON and signed bytes | ||
| 2 | - | ||
| 3 | -Reference: PR #334 | ||
| 4 | - | ||
| 5 | -1. Object keys are sorted lexicographically by UTF-16 code units (Java | ||
| 6 | - `String.compareTo`, equivalent to JavaScript's default string sort and to RFC 8785). | ||
| 7 | -2. Array order is preserved. There is no whitespace between tokens. | ||
| 8 | -3. Numbers must be finite integers in `[-9007199254740991, 9007199254740991]`. | ||
| 9 | - They use decimal notation without a fractional part or exponent. Negative zero | ||
| 10 | - becomes `0`. Amounts and timestamps are subject to additional model validation. | ||
| 11 | - Every protocol number is an integer by design; a value that is not an integer must | ||
| 12 | - be carried as a string. | ||
| 13 | -4. Quotes, backslashes and control characters use JSON escapes. Characters below | ||
| 14 | - U+0020 without a short escape use lowercase `\u00xx`; other Unicode characters | ||
| 15 | - are emitted directly, with no normalization. Unpaired surrogates are rejected. | ||
| 16 | -5. Java record fields with `null` represent absent optional properties and are | ||
| 17 | - omitted. Null values inside explicit JSON maps and lists remain `null`. Enums are | ||
| 18 | - rendered by name, for example `"AI_PAY"`. | ||
| 19 | -6. Signing removes only the complete top-level property named `sign`, canonicalizes | ||
| 20 | - the remaining object, and encodes it as UTF-8 without a byte-order mark. It does | ||
| 21 | - not recursively remove nested signatures. The level's own `alg` and `keyIdentifier` | ||
| 22 | - are therefore not part of that level's signed bytes; the next level's signature | ||
| 23 | - covers them. This is the specified design (API specification §4.6.2). | ||
| 24 | -7. Signature bytes use RFC 4648 Base64URL without padding. Decoders reject padding, | ||
| 25 | - non-URL-safe characters and nonzero unused trailing bits. | ||
| 26 | - | ||
| 27 | -Examples: | ||
| 28 | - | ||
| 29 | -```text | ||
| 30 | -{"b":1,"a":2} -> {"a":2,"b":1} | ||
| 31 | -[3,1,2] -> [3,1,2] | ||
| 32 | -{"10":1,"2":2} -> {"10":1,"2":2} | ||
| 33 | -9007199254740991 -> 9007199254740991 | ||
| 34 | -{"sign":"outer","nested":{"sign":"inner"}} | ||
| 35 | -signed bytes -> {"nested":{"sign":"inner"}} | ||
| 36 | -``` | ||
| 37 | - | ||
| 38 | -`CanonicalJson.stringify` accepts JSON maps/lists/primitives, Jackson `JsonNode` trees | ||
| 39 | -and SDK model records and enums. Arbitrary Java objects, non-string map keys, cycles and | ||
| 40 | -excessive nesting fail with `A4P_SERIALIZE_FAIL`. Deserialization requires an object of | ||
| 41 | -the expected model, rejects unknown properties, numeric enum values and explicit nulls | ||
| 42 | -inside AI_PAY payloads, and validates every nested signature and constraint. | ||
| @@ -0,0 +1,212 @@ | |||
| 1 | +# Serialization and Signature Rules | ||
| 2 | + | ||
| 3 | +A4P uses JSON as the serialization format for Intents. To ensure that implementations in different languages, such as Java and ArkTS, generate identical signature inputs, the object to be signed must be serialized deterministically before signing or signature verification. | ||
| 4 | + | ||
| 5 | +## JSON Canonicalization | ||
| 6 | + | ||
| 7 | +A4P uses the [RFC 8785](https://www.rfc-editor.org/info/rfc8785/) JSON Canonicalization Scheme (JCS) for JSON canonicalization. Signers and verifiers must generate the bytes to be signed using the same canonicalization rules. | ||
| 8 | + | ||
| 9 | +JCS canonicalization meets the following requirements: | ||
| 10 | + | ||
| 11 | +* JSON object fields are sorted deterministically according to JCS rules, with nested objects processed recursively; | ||
| 12 | +* JSON arrays retain their original element order; canonicalization must not reorder array elements; | ||
| 13 | +* Whitespace that does not affect semantics is omitted; | ||
| 14 | +* String contents retain their original Unicode data, without additional Unicode normalization; | ||
| 15 | +* JSON objects must not contain duplicate field names; | ||
| 16 | +* The canonicalized JSON is encoded as UTF-8 to produce the `byte[]` to be signed. | ||
| 17 | + | ||
| 18 | +A4P additionally restricts all numeric values to integers in the inclusive range `-9007199254740991` to `9007199254740991`. This applies recursively, including numbers in `SigningEnv.device` and `SigningEnv.app`. Fractional values, non-finite values and integers outside this range are rejected. Field-specific validation may impose stricter limits, such as non-negative timestamps and positive amounts. | ||
| 19 | + | ||
| 20 | +Note: JSON in HTTP messages does not need to be canonicalized and can be transmitted directly. The receiver should first parse the JSON, then regenerate canonicalized bytes according to the rules above for signature verification. Therefore, field order and formatting whitespace in HTTP messages do not affect signature verification. | ||
| 21 | + | ||
| 22 | +Examples: | ||
| 23 | + | ||
| 24 | +```text | ||
| 25 | +{"b":1,"a":2} -> {"a":2,"b":1} | ||
| 26 | +[3,1,2] -> [3,1,2] | ||
| 27 | +{"10":1,"2":2} -> {"10":1,"2":2} | ||
| 28 | +9007199254740991 -> 9007199254740991 | ||
| 29 | +1.5 -> rejected: not an integer | ||
| 30 | +9007199254740992 -> rejected: outside the safe integer range | ||
| 31 | +{"sign":"outer","nested":{"sign":"inner"}} | ||
| 32 | +signed bytes -> {"nested":{"sign":"inner"}} | ||
| 33 | +``` | ||
| 34 | + | ||
| 35 | +Canonicalization is implemented internally by the Java SDK. Use the public `A4pIntentCodec` for serialization; signing callbacks receive the canonical bytes directly. | ||
| 36 | + | ||
| 37 | +## Serialization/Deserialization API | ||
| 38 | + | ||
| 39 | +This API converts Intent protocol objects to and from their standard serialized representations. Signing requires serialization/deserialization through the interfaces provided by the following class. | ||
| 40 | + | ||
| 41 | +```java | ||
| 42 | +public class A4pIntentCodec { | ||
| 43 | + | ||
| 44 | + String serializeIntentL1( | ||
| 45 | + IntentL1 intentL1 | ||
| 46 | + ); | ||
| 47 | + | ||
| 48 | + A4pResult<IntentL1> deserializeIntentL1( | ||
| 49 | + String serialized | ||
| 50 | + ); | ||
| 51 | + | ||
| 52 | + String serializeIntentL2( | ||
| 53 | + IntentL2 intentL2 | ||
| 54 | + ); | ||
| 55 | + | ||
| 56 | + A4pResult<IntentL2> deserializeIntentL2( | ||
| 57 | + String serialized | ||
| 58 | + ); | ||
| 59 | + | ||
| 60 | + String serializeIntentL3( | ||
| 61 | + IntentL3 intentL3 | ||
| 62 | + ); | ||
| 63 | + | ||
| 64 | + A4pResult<IntentL3> deserializeIntentL3( | ||
| 65 | + String serialized | ||
| 66 | + ); | ||
| 67 | + | ||
| 68 | + String serializeIntentExecutionContext( | ||
| 69 | + IntentExecutionContext intentExecutionContext | ||
| 70 | + ); | ||
| 71 | + | ||
| 72 | + A4pResult<IntentExecutionContext> deserializeIntentExecutionContext( | ||
| 73 | + String serialized | ||
| 74 | + ); | ||
| 75 | +} | ||
| 76 | +``` | ||
| 77 | + | ||
| 78 | +All serialization APIs accept protocol objects that have already been constructed within the SDK. | ||
| 79 | + | ||
| 80 | +Deserialization APIs handle external input and therefore consistently return `A4pResult<T>` to represent errors such as invalid formats and unsupported versions. | ||
| 81 | + | ||
| 82 | +## Signature Coverage at Each Layer | ||
| 83 | + | ||
| 84 | +The `sign` field in each of the three Intent layers is a `SignatureInfo` object (containing `alg`, `keyIdentifier`, and `sign`). Each layer's signature covers the entire object at that layer except its own `sign` field (the entire `SignatureInfo` object). Fields at that layer, such as `timestamp`, are included in the signed content. | ||
| 85 | + | ||
| 86 | +The `alg` and `keyIdentifier` fields in a layer's own `SignatureInfo` are excluded from that layer's signed content. This is intentional: they are covered by the next signature—the complete `SignatureInfo` objects of L1 and L2 are included in the signature inputs of L2 and L3, respectively. The outermost L3 `alg` and `keyIdentifier` fields are not protected by a signature. The verifier must retrieve the key from a trusted registry using only `keyIdentifier` and use the algorithm bound to that key; it must not trust the `alg` value in the message. | ||
| 87 | + | ||
| 88 | +```text | ||
| 89 | +L1 signature input = Canonicalize(IntentL1 excluding L1.sign) | ||
| 90 | + | ||
| 91 | +L2 signature input = Canonicalize(IntentL2 excluding L2.sign) | ||
| 92 | + Includes the complete IntentL1, including L1.sign | ||
| 93 | + | ||
| 94 | +L3 signature input = Canonicalize(IntentL3 excluding L3.sign) | ||
| 95 | + Includes the complete IntentL2, including L1.sign and L2.sign | ||
| 96 | +``` | ||
| 97 | + | ||
| 98 | +Example of signature coverage for a single layer: | ||
| 99 | + | ||
| 100 | +```json | ||
| 101 | +{"sign":"outer","nested":{"sign":"inner"}} | ||
| 102 | +signed bytes -> {"nested":{"sign":"inner"}} | ||
| 103 | +``` | ||
| 104 | + | ||
| 105 | +## Signing and Signature Verification | ||
| 106 | + | ||
| 107 | +The recommended asymmetric cryptographic algorithm for `alg` is **RSA3072**. | ||
| 108 | + | ||
| 109 | +The signing process is as follows: | ||
| 110 | + | ||
| 111 | +```text | ||
| 112 | +Intent (sign is empty) | ||
| 113 | + ↓ | ||
| 114 | +Remove the current layer's sign field (the entire SignatureInfo) | ||
| 115 | + ↓ | ||
| 116 | +JCS Canonicalize | ||
| 117 | + ↓ | ||
| 118 | +UTF-8 bytes | ||
| 119 | + ↓ | ||
| 120 | +Signer.sign(bytes) | ||
| 121 | + ↓ | ||
| 122 | +Write the returned SignatureInfo (alg / keyIdentifier / sign) to the current layer's sign field | ||
| 123 | +``` | ||
| 124 | + | ||
| 125 | +Note 1: `Signer.sign()` returns a `SignatureInfo` object whose `sign` field is the signature bytes **encoded as Base64URL without padding**. The SDK validates the returned value (`alg` must be a defined algorithm, and `keyIdentifier` and `sign` must be non-blank). An invalid value is treated as a signing failure. | ||
| 126 | + | ||
| 127 | +The signature verification process is as follows: | ||
| 128 | + | ||
| 129 | +```text | ||
| 130 | +Intent (with sign) | ||
| 131 | + ↓ | ||
| 132 | +Read the current layer's sign (SignatureInfo) | ||
| 133 | + ↓ | ||
| 134 | +Remove the current layer's sign field | ||
| 135 | + ↓ | ||
| 136 | +JCS Canonicalize | ||
| 137 | + ↓ | ||
| 138 | +UTF-8 bytes | ||
| 139 | + ↓ | ||
| 140 | +SignatureVerifier.verify( | ||
| 141 | + bytes, | ||
| 142 | + signatureInfo | ||
| 143 | +) | ||
| 144 | + ↓ | ||
| 145 | +Return VerificationResult | ||
| 146 | +``` | ||
| 147 | + | ||
| 148 | +Note 2: `SignatureVerifier` is responsible for resolving a trusted key using `keyIdentifier`, checking that `alg` matches the key type, and decoding `sign` from Base64URL without padding before verifying the signature. | ||
| 149 | + | ||
| 150 | +### RSA3072: L1 Signing and Verification Example | ||
| 151 | + | ||
| 152 | +The following program uses [`Rsa3072.java`](../examples/src/main/java/io/openjiuwen/a4p/examples/Rsa3072.java) from the standalone examples module to create an Agent signer and verifier. `A4p.createIntent` generates the canonicalized L1 bytes to be signed, calls the Agent's `Signer`, and writes the returned signature to `L1.sign`. `A4p.issueIntent` calls the Agent's `SignatureVerifier` to verify this signature and generates L2 only after verification succeeds. Callers do not need to serialize L1 or remove the `sign` field manually. | ||
| 153 | + | ||
| 154 | +```java | ||
| 155 | +package io.openjiuwen.a4p.examples; | ||
| 156 | + | ||
| 157 | +import io.openjiuwen.a4p.A4p; | ||
| 158 | +import io.openjiuwen.a4p.A4pResult; | ||
| 159 | +import io.openjiuwen.a4p.PaymentProfile; | ||
| 160 | +import io.openjiuwen.a4p.Signer; | ||
| 161 | +import io.openjiuwen.a4p.SignatureVerifier; | ||
| 162 | +import io.openjiuwen.a4p.Models.*; | ||
| 163 | +import java.security.KeyPairGenerator; | ||
| 164 | +import java.util.List; | ||
| 165 | +import java.util.Map; | ||
| 166 | + | ||
| 167 | +public final class Rsa3072SignVerifyExample { | ||
| 168 | + public static void main(String[] args) throws Exception { | ||
| 169 | + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); | ||
| 170 | + generator.initialize(3072); | ||
| 171 | + var agentKeys = generator.generateKeyPair(); | ||
| 172 | + var centerKeys = generator.generateKeyPair(); | ||
| 173 | + | ||
| 174 | + Signer agentSigner = Rsa3072.signer("agent-key-1", agentKeys.getPrivate()); | ||
| 175 | + SignatureVerifier agentVerifier = Rsa3072.verifier( | ||
| 176 | + Map.of("agent-key-1", agentKeys.getPublic())); | ||
| 177 | + Signer centerSigner = Rsa3072.signer("center-key-1", centerKeys.getPrivate()); | ||
| 178 | + | ||
| 179 | + long now = System.currentTimeMillis(); | ||
| 180 | + Product product = new Product(new SellerInfo("shop"), new SpuSkuInfo("book", "paperback")); | ||
| 181 | + PaymentConstraints constraints = new PaymentConstraints( | ||
| 182 | + 5000L, 10000L, "CNY", now, now + 60_000L, 2L, null, null, null); | ||
| 183 | + CreateIntentRequest request = new CreateIntentRequest( | ||
| 184 | + "Buy two books", "Book purchase authorization", | ||
| 185 | + PaymentProfile.structuredIntent( | ||
| 186 | + new ShoppingItems(List.of(new ItemWhiteList(List.of(product), 2L))), | ||
| 187 | + constraints), | ||
| 188 | + null); | ||
| 189 | + | ||
| 190 | + // The SDK canonicalizes L1, calls agentSigner, and populates L1.sign. | ||
| 191 | + IntentL1 l1 = requireSuccess(A4p.createIntent(request, agentSigner, now)); | ||
| 192 | + System.out.println("L1 signed, key ID: " + l1.sign().keyIdentifier()); | ||
| 193 | + | ||
| 194 | + IntentIssueContext identities = new IntentIssueContext( | ||
| 195 | + new UserIdentity("example", "user-1", null), | ||
| 196 | + new AgentIdentity("example", "agent-1", null), | ||
| 197 | + new ServiceProviderIdentity("shop", null)); | ||
| 198 | + // The SDK verifies L1.sign; on success, centerSigner issues L2. | ||
| 199 | + IntentL2 l2 = requireSuccess(A4p.issueIntent(l1, agentVerifier, identities, centerSigner, now)); | ||
| 200 | + System.out.println("L1 signature verified, L2 generated: " + l2.version()); | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + private static <T> T requireSuccess(A4pResult<T> result) { | ||
| 204 | + if (!result.success()) { | ||
| 205 | + throw new IllegalStateException(result.code() + " " + result.message()); | ||
| 206 | + } | ||
| 207 | + return result.data(); | ||
| 208 | + } | ||
| 209 | +} | ||
| 210 | +``` | ||
| 211 | + | ||
| 212 | +`keyIdentifier` must map to the correct public key in the verifier's trusted public key registry. The two key pairs in the example are for demonstration only; in production, each party manages its own keys. | ||
| @@ -0,0 +1,217 @@ | |||
| 1 | +# 序列化与签名规则 | ||
| 2 | + | ||
| 3 | +A4P 使用 JSON 作为 Intent 的序列化格式。为保证 Java、ArkTS 等不同语言实现能够生成一致的签名输入,签名和验签前必须对待签名对象进行确定性序列化。 | ||
| 4 | + | ||
| 5 | +## JSON 规范化 | ||
| 6 | + | ||
| 7 | +A4P 的 JSON 规范化采用 [RFC 8785](https://www.rfc-editor.org/info/rfc8785/) JSON Canonicalization Scheme(JCS)。签名方和验签方必须基于同一规范化规则生成待签名字节。 | ||
| 8 | + | ||
| 9 | +JCS 规范化处理满足以下要求: | ||
| 10 | + | ||
| 11 | +* JSON Object 的字段按照 JCS 规则进行确定性排序,并递归处理嵌套 Object; | ||
| 12 | + | ||
| 13 | +* JSON Array 保持元素原有顺序,禁止因规范化改变数组元素顺序; | ||
| 14 | + | ||
| 15 | +* 不输出对语义无影响的空白字符; | ||
| 16 | + | ||
| 17 | +* 字符串内容保持原始 Unicode 数据,不额外进行 Unicode Normalization; | ||
| 18 | + | ||
| 19 | +* JSON 对象中不得包含重复字段名; | ||
| 20 | + | ||
| 21 | +* 规范化后的 JSON 使用 UTF\-8 编码转换为待签名 `byte[]`; | ||
| 22 | + | ||
| 23 | +A4P 额外要求所有数值必须为整数,且处于闭区间 `-9007199254740991` 至 `9007199254740991` 内。此限制递归适用,包括 `SigningEnv.device` 和 `SigningEnv.app` 中的数值。小数、非有限数值和超出范围的整数均被拒绝。字段校验可能施加更严格限制,例如时间戳非负、金额为正。 | ||
| 24 | + | ||
| 25 | +注:HTTP 报文中的 JSON 无需规范化,可直接传输。接收方应先解析 JSON,再按照上述规则重新生成规范化字节用于验签,因此 HTTP 报文的字段顺序和格式化空白不影响签名验证。 | ||
| 26 | + | ||
| 27 | +样例: | ||
| 28 | + | ||
| 29 | +```text | ||
| 30 | +{"b":1,"a":2} -> {"a":2,"b":1} | ||
| 31 | +[3,1,2] -> [3,1,2] | ||
| 32 | +{"10":1,"2":2} -> {"10":1,"2":2} | ||
| 33 | +9007199254740991 -> 9007199254740991 | ||
| 34 | +1.5 -> 拒绝:不是整数 | ||
| 35 | +9007199254740992 -> 拒绝:超出安全整数范围 | ||
| 36 | +{"sign":"outer","nested":{"sign":"inner"}} | ||
| 37 | +signed bytes -> {"nested":{"sign":"inner"}} | ||
| 38 | +``` | ||
| 39 | + | ||
| 40 | +规范化由 Java SDK 内部实现。序列化请使用公开的 `A4pIntentCodec`;签名回调直接接收规范化字节。 | ||
| 41 | + | ||
| 42 | +## 序列化/反序列化 API | ||
| 43 | + | ||
| 44 | +负责 Intent 协议对象与标准序列化表示之间的转换。签名时需要利用下面的类提供的接口进行序列化/反序列化 | ||
| 45 | + | ||
| 46 | +```java | ||
| 47 | +public class A4pIntentCodec { | ||
| 48 | + | ||
| 49 | + String serializeIntentL1( | ||
| 50 | + IntentL1 intentL1 | ||
| 51 | + ); | ||
| 52 | + | ||
| 53 | + A4pResult<IntentL1> deserializeIntentL1( | ||
| 54 | + String serialized | ||
| 55 | + ); | ||
| 56 | + | ||
| 57 | + String serializeIntentL2( | ||
| 58 | + IntentL2 intentL2 | ||
| 59 | + ); | ||
| 60 | + | ||
| 61 | + A4pResult<IntentL2> deserializeIntentL2( | ||
| 62 | + String serialized | ||
| 63 | + ); | ||
| 64 | + | ||
| 65 | + String serializeIntentL3( | ||
| 66 | + IntentL3 intentL3 | ||
| 67 | + ); | ||
| 68 | + | ||
| 69 | + A4pResult<IntentL3> deserializeIntentL3( | ||
| 70 | + String serialized | ||
| 71 | + ); | ||
| 72 | + | ||
| 73 | + String serializeIntentExecutionContext( | ||
| 74 | + IntentExecutionContext intentExecutionContext | ||
| 75 | + ); | ||
| 76 | + | ||
| 77 | + A4pResult<IntentExecutionContext> deserializeIntentExecutionContext( | ||
| 78 | + String serialized | ||
| 79 | + ); | ||
| 80 | +} | ||
| 81 | +``` | ||
| 82 | + | ||
| 83 | +序列化 API 的输入均为 SDK 内已经构造完成的协议对象。 | ||
| 84 | + | ||
| 85 | +反序列化 API 面向外部输入,因此统一返回 `A4pResult<T>`,用于表达非法格式、版本不支持等错误。 | ||
| 86 | + | ||
| 87 | +## 各层签名覆盖范围 | ||
| 88 | + | ||
| 89 | +三层 Intent 的 `sign` 字段均为 `SignatureInfo`(含 `alg`、`keyIdentifier`、`sign`)。每层签名覆盖该层除自身 `sign` 字段(整个 `SignatureInfo` 对象)以外的完整对象,`timestamp` 等本层字段均属于签名内容。 | ||
| 90 | + | ||
| 91 | +本层 `SignatureInfo` 中的 `alg`、`keyIdentifier` 不属于本层签名内容,这是有意的设计:它们由下一步的签名覆盖——L1、L2 的 `SignatureInfo` 分别完整包含在 L2、L3 的签名输入中;最外层 L3 的 `alg`、`keyIdentifier` 不受签名保护,验签方必须只按 `keyIdentifier` 从可信注册表获取密钥,并使用与该密钥绑定的算法,不得信任报文中的 `alg`。 | ||
| 92 | + | ||
| 93 | +```text | ||
| 94 | +L1 签名输入 = Canonicalize(IntentL1 excluding L1.sign) | ||
| 95 | + | ||
| 96 | +L2 签名输入 = Canonicalize(IntentL2 excluding L2.sign) | ||
| 97 | + 其中包含完整 IntentL1,包括 L1.sign | ||
| 98 | + | ||
| 99 | +L3 签名输入 = Canonicalize(IntentL3 excluding L3.sign) | ||
| 100 | + 其中包含完整 IntentL2,包括 L1.sign 和 L2.sign | ||
| 101 | +``` | ||
| 102 | + | ||
| 103 | +一层的签名范围样例如下: | ||
| 104 | + | ||
| 105 | +```json | ||
| 106 | +{"sign":"outer","nested":{"sign":"inner"}} | ||
| 107 | +signed bytes -> {"nested":{"sign":"inner"}} | ||
| 108 | +``` | ||
| 109 | + | ||
| 110 | +## 签名与验签流程 | ||
| 111 | + | ||
| 112 | +`alg`推荐采用 **RSA3072** 非对称加密算法。 | ||
| 113 | + | ||
| 114 | +签名流程如下: | ||
| 115 | + | ||
| 116 | +```text | ||
| 117 | +Intent(sign 为空) | ||
| 118 | + ↓ | ||
| 119 | +移除当前层 sign 字段(整个 SignatureInfo) | ||
| 120 | + ↓ | ||
| 121 | +JCS Canonicalize | ||
| 122 | + ↓ | ||
| 123 | +UTF-8 bytes | ||
| 124 | + ↓ | ||
| 125 | +Signer.sign(bytes) | ||
| 126 | + ↓ | ||
| 127 | +返回的 SignatureInfo(alg / keyIdentifier / sign)写入当前层 sign | ||
| 128 | +``` | ||
| 129 | + | ||
| 130 | +注1:`Signer.sign()` 返回 `SignatureInfo`,其中 `sign` 是签名字节经 **Base64URL 编码(不含 padding)** 得到的字符串。SDK 会校验返回值(`alg` 为已定义的算法、`keyIdentifier` 与 `sign` 非空白),不合法时按签名失败处理。 | ||
| 131 | + | ||
| 132 | +验签流程如下: | ||
| 133 | + | ||
| 134 | +```text | ||
| 135 | +Intent(包含 sign) | ||
| 136 | + ↓ | ||
| 137 | +读取当前层 sign(SignatureInfo) | ||
| 138 | + ↓ | ||
| 139 | +移除当前层 sign 字段 | ||
| 140 | + ↓ | ||
| 141 | +JCS Canonicalize | ||
| 142 | + ↓ | ||
| 143 | +UTF-8 bytes | ||
| 144 | + ↓ | ||
| 145 | +SignatureVerifier.verify( | ||
| 146 | + bytes, | ||
| 147 | + signatureInfo | ||
| 148 | +) | ||
| 149 | + ↓ | ||
| 150 | +输出 VerificationResult | ||
| 151 | +``` | ||
| 152 | + | ||
| 153 | +注2:`SignatureVerifier` 负责按 `keyIdentifier` 解析可信密钥、校验 `alg` 与密钥类型匹配,并将 `sign` 按 Base64URL(不含 padding)解码后验签。 | ||
| 154 | + | ||
| 155 | +### RSA3072:L1 签名与验签样例 | ||
| 156 | + | ||
| 157 | +下面的程序使用独立示例模块中的 [`Rsa3072.java`](../examples/src/main/java/io/openjiuwen/a4p/examples/Rsa3072.java) 创建 Agent 签名器和验签器。`A4p.createIntent` 会生成 L1 的规范化待签名字节、调用 Agent 的 `Signer`,并把返回的签名写入 `L1.sign`;`A4p.issueIntent` 会调用 Agent 的 `SignatureVerifier` 验证这个签名,验证通过后才生成 L2。调用方无需手动序列化 L1 或移除 `sign` 字段。 | ||
| 158 | + | ||
| 159 | +```java | ||
| 160 | +package io.openjiuwen.a4p.examples; | ||
| 161 | + | ||
| 162 | +import io.openjiuwen.a4p.A4p; | ||
| 163 | +import io.openjiuwen.a4p.A4pResult; | ||
| 164 | +import io.openjiuwen.a4p.PaymentProfile; | ||
| 165 | +import io.openjiuwen.a4p.Signer; | ||
| 166 | +import io.openjiuwen.a4p.SignatureVerifier; | ||
| 167 | +import io.openjiuwen.a4p.Models.*; | ||
| 168 | +import java.security.KeyPairGenerator; | ||
| 169 | +import java.util.List; | ||
| 170 | +import java.util.Map; | ||
| 171 | + | ||
| 172 | +public final class Rsa3072SignVerifyExample { | ||
| 173 | + public static void main(String[] args) throws Exception { | ||
| 174 | + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); | ||
| 175 | + generator.initialize(3072); | ||
| 176 | + var agentKeys = generator.generateKeyPair(); | ||
| 177 | + var centerKeys = generator.generateKeyPair(); | ||
| 178 | + | ||
| 179 | + Signer agentSigner = Rsa3072.signer("agent-key-1", agentKeys.getPrivate()); | ||
| 180 | + SignatureVerifier agentVerifier = Rsa3072.verifier( | ||
| 181 | + Map.of("agent-key-1", agentKeys.getPublic())); | ||
| 182 | + Signer centerSigner = Rsa3072.signer("center-key-1", centerKeys.getPrivate()); | ||
| 183 | + | ||
| 184 | + long now = System.currentTimeMillis(); | ||
| 185 | + Product product = new Product(new SellerInfo("shop"), new SpuSkuInfo("book", "paperback")); | ||
| 186 | + PaymentConstraints constraints = new PaymentConstraints( | ||
| 187 | + 5000L, 10000L, "CNY", now, now + 60_000L, 2L, null, null, null); | ||
| 188 | + CreateIntentRequest request = new CreateIntentRequest( | ||
| 189 | + "购买两本书", "购买书籍授权", | ||
| 190 | + PaymentProfile.structuredIntent( | ||
| 191 | + new ShoppingItems(List.of(new ItemWhiteList(List.of(product), 2L))), | ||
| 192 | + constraints), | ||
| 193 | + null); | ||
| 194 | + | ||
| 195 | + // SDK 规范化 L1、调用 agentSigner,并填充 L1.sign。 | ||
| 196 | + IntentL1 l1 = requireSuccess(A4p.createIntent(request, agentSigner, now)); | ||
| 197 | + System.out.println("L1 已签名,密钥 ID: " + l1.sign().keyIdentifier()); | ||
| 198 | + | ||
| 199 | + IntentIssueContext identities = new IntentIssueContext( | ||
| 200 | + new UserIdentity("example", "user-1", null), | ||
| 201 | + new AgentIdentity("example", "agent-1", null), | ||
| 202 | + new ServiceProviderIdentity("shop", null)); | ||
| 203 | + // SDK 验证 L1.sign;成功后由 centerSigner 签发 L2。 | ||
| 204 | + IntentL2 l2 = requireSuccess(A4p.issueIntent(l1, agentVerifier, identities, centerSigner, now)); | ||
| 205 | + System.out.println("L1 签名验证通过,已生成 L2: " + l2.version()); | ||
| 206 | + } | ||
| 207 | + | ||
| 208 | + private static <T> T requireSuccess(A4pResult<T> result) { | ||
| 209 | + if (!result.success()) { | ||
| 210 | + throw new IllegalStateException(result.code() + " " + result.message()); | ||
| 211 | + } | ||
| 212 | + return result.data(); | ||
| 213 | + } | ||
| 214 | +} | ||
| 215 | +``` | ||
| 216 | + | ||
| 217 | +`keyIdentifier` 必须在验签方可信公钥表中对应到正确公钥。上例的两个密钥对仅用于演示,实际业务由各方管理自己的密钥。 | ||
| @@ -0,0 +1 @@ | |||
| 1 | +target/ | ||
| @@ -0,0 +1,16 @@ | |||
| 1 | +# Java SDK examples | ||
| 2 | + | ||
| 3 | +This is a separate Maven artifact. `Rsa3072` and `PaymentExample` live in | ||
| 4 | +`io.openjiuwen.a4p.examples` and are not included in the A4P Java SDK JAR. | ||
| 5 | + | ||
| 6 | +From the repository root: | ||
| 7 | + | ||
| 8 | +```sh | ||
| 9 | +mvn -f A4P-java-sdk/pom.xml install | ||
| 10 | +mvn -f A4P-java-sdk/examples/pom.xml test | ||
| 11 | +mvn -f A4P-java-sdk/examples/pom.xml compile org.codehaus.mojo:exec-maven-plugin:3.6.3:java -Dexec.mainClass=io.openjiuwen.a4p.examples.PaymentExample | ||
| 12 | +``` | ||
| 13 | + | ||
| 14 | +The RSA implementation is an example of the public `Signer` and | ||
| 15 | +`SignatureVerifier` interfaces. Applications should supply implementations | ||
| 16 | +appropriate for their own key management. | ||
| @@ -0,0 +1,20 @@ | |||
| 1 | +<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" | ||
| 2 | + xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd"> | ||
| 3 | + <modelVersion>4.0.0</modelVersion> | ||
| 4 | + <groupId>io.openjiuwen</groupId> | ||
| 5 | + <artifactId>a4p-java-sdk-examples</artifactId> | ||
| 6 | + <version>0.1.0</version> | ||
| 7 | + <properties><maven.compiler.release>17</maven.compiler.release></properties> | ||
| 8 | + <dependencies> | ||
| 9 | + <dependency> | ||
| 10 | + <groupId>io.openjiuwen</groupId><artifactId>a4p-java-sdk</artifactId><version>0.1.0</version> | ||
| 11 | + </dependency> | ||
| 12 | + <dependency> | ||
| 13 | + <groupId>org.junit.jupiter</groupId><artifactId>junit-jupiter</artifactId><version>5.14.1</version><scope>test</scope> | ||
| 14 | + </dependency> | ||
| 15 | + </dependencies> | ||
| 16 | + <build><plugins> | ||
| 17 | + <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-compiler-plugin</artifactId><version>3.14.1</version></plugin> | ||
| 18 | + <plugin><groupId>org.apache.maven.plugins</groupId><artifactId>maven-surefire-plugin</artifactId><version>3.5.4</version></plugin> | ||
| 19 | + </plugins></build> | ||
| 20 | +</project> | ||
RA4P-java-sdk/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java→A4P-java-sdk/examples/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java+2-1
| @@ -42,7 +42,8 @@ public final class PaymentExample { | |||
| 42 | unwrap(A4p.completeExecution(context, execution.id(), now)); | 42 | unwrap(A4p.completeExecution(context, execution.id(), now)); |
| 43 | System.out.println("Intent: " + context.intentId() + " (" + context.status() + ")"); | 43 | System.out.println("Intent: " + context.intentId() + " (" + context.status() + ")"); |
| 44 | System.out.println("Remaining amount: " + PaymentProfile.executionInfo(context).leftAmount()); | 44 | System.out.println("Remaining amount: " + PaymentProfile.executionInfo(context).leftAmount()); |
| 45 | - System.out.println(A4pIntentCodec.standard().serializeIntentL3(authorized)); | 45 | + A4pIntentCodec codec = new A4pIntentCodec(); |
| 46 | + unwrap(codec.deserializeIntentExecutionContext(codec.serializeIntentExecutionContext(context))); | ||
| 46 | } | 47 | } |
| 47 | 48 | ||
| 48 | private static <Value> Value unwrap(A4pResult<Value> result) { | 49 | private static <Value> Value unwrap(A4pResult<Value> result) { |
RA4P-java-sdk/src/main/java/io/openjiuwen/a4p/Rsa3072.java→A4P-java-sdk/examples/src/main/java/io/openjiuwen/a4p/examples/Rsa3072.java+30-8
| @@ -1,4 +1,6 @@ | |||
| 1 | -package io.openjiuwen.a4p; | 1 | +package io.openjiuwen.a4p.examples; |
| 2 | + | ||
| 3 | +import io.openjiuwen.a4p.*; | ||
| 2 | 4 | ||
| 3 | import io.openjiuwen.a4p.Models.*; | 5 | import io.openjiuwen.a4p.Models.*; |
| 4 | import java.security.PrivateKey; | 6 | import java.security.PrivateKey; |
| @@ -7,29 +9,30 @@ import java.security.Signature; | |||
| 7 | import java.security.interfaces.RSAKey; | 9 | import java.security.interfaces.RSAKey; |
| 8 | import java.util.HashMap; | 10 | import java.util.HashMap; |
| 9 | import java.util.Map; | 11 | import java.util.Map; |
| 12 | +import java.util.Base64; | ||
| 10 | 13 | ||
| 11 | public final class Rsa3072 { | 14 | public final class Rsa3072 { |
| 12 | private Rsa3072() {} | 15 | private Rsa3072() {} |
| 13 | 16 | ||
| 14 | public static Signer signer(String keyIdentifier, PrivateKey privateKey) { | 17 | public static Signer signer(String keyIdentifier, PrivateKey privateKey) { |
| 15 | - Validation.text(keyIdentifier); | 18 | + requireText(keyIdentifier); |
| 16 | requireKey(privateKey); | 19 | requireKey(privateKey); |
| 17 | return data -> { | 20 | return data -> { |
| 18 | Signature signer = Signature.getInstance("SHA256withRSA"); | 21 | Signature signer = Signature.getInstance("SHA256withRSA"); |
| 19 | signer.initSign(privateKey); | 22 | signer.initSign(privateKey); |
| 20 | signer.update(data); | 23 | signer.update(data); |
| 21 | return new SignatureInfo(AlgorithmType.RSA3072, keyIdentifier, | 24 | return new SignatureInfo(AlgorithmType.RSA3072, keyIdentifier, |
| 22 | - CanonicalJson.base64UrlEncode(signer.sign())); | 25 | + Base64.getUrlEncoder().withoutPadding().encodeToString(signer.sign())); |
| 23 | }; | 26 | }; |
| 24 | } | 27 | } |
| 25 | 28 | ||
| 26 | // Codes follow the A4pErrorCode set; message names the reason for diagnostics only. | 29 | // Codes follow the A4pErrorCode set; message names the reason for diagnostics only. |
| 27 | public static SignatureVerifier verifier(Map<String, PublicKey> trustedKeys) { | 30 | public static SignatureVerifier verifier(Map<String, PublicKey> trustedKeys) { |
| 28 | - Validation.present(trustedKeys); | 31 | + require(trustedKeys != null); |
| 29 | // Copied into a HashMap first, which admits nulls, so they are rejected as A4pException. | 32 | // Copied into a HashMap first, which admits nulls, so they are rejected as A4pException. |
| 30 | Map<String, PublicKey> copy = new HashMap<>(trustedKeys); | 33 | Map<String, PublicKey> copy = new HashMap<>(trustedKeys); |
| 31 | copy.forEach((keyIdentifier, key) -> { | 34 | copy.forEach((keyIdentifier, key) -> { |
| 32 | - Validation.text(keyIdentifier); | 35 | + requireText(keyIdentifier); |
| 33 | requireKey(key); | 36 | requireKey(key); |
| 34 | }); | 37 | }); |
| 35 | Map<String, PublicKey> keys = Map.copyOf(copy); | 38 | Map<String, PublicKey> keys = Map.copyOf(copy); |
| @@ -42,7 +45,8 @@ public final class Rsa3072 { | |||
| 42 | Signature verifier = Signature.getInstance("SHA256withRSA"); | 45 | Signature verifier = Signature.getInstance("SHA256withRSA"); |
| 43 | verifier.initVerify(keys.get(info.keyIdentifier())); | 46 | verifier.initVerify(keys.get(info.keyIdentifier())); |
| 44 | verifier.update(data); | 47 | verifier.update(data); |
| 45 | - if (verifier.verify(CanonicalJson.base64UrlDecode(info.sign()))) { | 48 | + byte[] signatureBytes = decodeCanonicalSignature(info.sign()); |
| 49 | + if (verifier.verify(signatureBytes)) { | ||
| 46 | return new VerificationResult(true, A4pErrorCode.A4P_SUCCESS.code(), null); | 50 | return new VerificationResult(true, A4pErrorCode.A4P_SUCCESS.code(), null); |
| 47 | } | 51 | } |
| 48 | return rejected("INVALID_SIGNATURE"); | 52 | return rejected("INVALID_SIGNATURE"); |
| @@ -56,8 +60,26 @@ public final class Rsa3072 { | |||
| 56 | return new VerificationResult(false, A4pErrorCode.A4P_VERIFY_FAIL.code(), reason); | 60 | return new VerificationResult(false, A4pErrorCode.A4P_VERIFY_FAIL.code(), reason); |
| 57 | } | 61 | } |
| 58 | 62 | ||
| 63 | + private static byte[] decodeCanonicalSignature(String encoded) { | ||
| 64 | + if (encoded == null || !encoded.matches("[A-Za-z0-9_-]+")) { | ||
| 65 | + throw new IllegalArgumentException("Invalid Base64URL signature"); | ||
| 66 | + } | ||
| 67 | + byte[] decoded = Base64.getUrlDecoder().decode(encoded); | ||
| 68 | + if (!Base64.getUrlEncoder().withoutPadding().encodeToString(decoded).equals(encoded)) { | ||
| 69 | + throw new IllegalArgumentException("Noncanonical Base64URL signature"); | ||
| 70 | + } | ||
| 71 | + return decoded; | ||
| 72 | + } | ||
| 73 | + | ||
| 74 | + private static void requireText(String value) { | ||
| 75 | + require(value != null && !value.isBlank()); | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + private static void require(boolean valid) { | ||
| 79 | + if (!valid) { throw new A4pException(A4pErrorCode.A4P_INVALID_PARAMETER); } | ||
| 80 | + } | ||
| 81 | + | ||
| 59 | private static void requireKey(Object key) { | 82 | private static void requireKey(Object key) { |
| 60 | - Validation.require(key instanceof RSAKey rsa && rsa.getModulus().bitLength() == 3072, | 83 | + require(key instanceof RSAKey rsa && rsa.getModulus().bitLength() == 3072); |
| 61 | - A4pErrorCode.A4P_INVALID_PARAMETER); | ||
| 62 | } | 84 | } |
| 63 | } | 85 | } |
| @@ -0,0 +1,35 @@ | |||
| 1 | +package io.openjiuwen.a4p.examples; | ||
| 2 | + | ||
| 3 | +import io.openjiuwen.a4p.A4pErrorCode; | ||
| 4 | +import io.openjiuwen.a4p.A4pException; | ||
| 5 | +import io.openjiuwen.a4p.Models.SignatureInfo; | ||
| 6 | +import org.junit.jupiter.api.Test; | ||
| 7 | +import java.security.KeyPairGenerator; | ||
| 8 | +import java.util.Map; | ||
| 9 | +import static org.junit.jupiter.api.Assertions.*; | ||
| 10 | + | ||
| 11 | +class Rsa3072Test { | ||
| 12 | + @Test void paymentExampleRunsWithOnlyPublicSdkTypes() { | ||
| 13 | + assertDoesNotThrow(() -> PaymentExample.main(new String[0])); | ||
| 14 | + } | ||
| 15 | + | ||
| 16 | + @Test void signsAndVerifiesWithoutSdkInternalHelpers() throws Exception { | ||
| 17 | + KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA"); | ||
| 18 | + generator.initialize(3072); | ||
| 19 | + var keys = generator.generateKeyPair(); | ||
| 20 | + var signer = Rsa3072.signer("example", keys.getPrivate()); | ||
| 21 | + var verifier = Rsa3072.verifier(Map.of("example", keys.getPublic())); | ||
| 22 | + byte[] bytes = "example".getBytes(java.nio.charset.StandardCharsets.UTF_8); | ||
| 23 | + var signature = signer.sign(bytes); | ||
| 24 | + assertTrue(verifier.verify(bytes, signature).valid()); | ||
| 25 | + assertFalse(verifier.verify("changed".getBytes(java.nio.charset.StandardCharsets.UTF_8), signature).valid()); | ||
| 26 | + assertFalse(verifier.verify(bytes, new SignatureInfo(signature.alg(), signature.keyIdentifier(), | ||
| 27 | + signature.sign() + "=")).valid()); | ||
| 28 | + assertFalse(verifier.verify(bytes, new SignatureInfo(signature.alg(), "unknown", | ||
| 29 | + signature.sign())).valid()); | ||
| 30 | + generator.initialize(2048); | ||
| 31 | + var weak = generator.generateKeyPair(); | ||
| 32 | + assertEquals(A4pErrorCode.A4P_INVALID_PARAMETER, | ||
| 33 | + assertThrows(A4pException.class, () -> Rsa3072.signer("weak", weak.getPrivate())).code()); | ||
| 34 | + } | ||
| 35 | +} | ||
| @@ -24,6 +24,36 @@ | |||
| 24 | </dependencies> | 24 | </dependencies> |
| 25 | <build> | 25 | <build> |
| 26 | <plugins> | 26 | <plugins> |
| 27 | + <plugin> | ||
| 28 | + <groupId>org.apache.maven.plugins</groupId> | ||
| 29 | + <artifactId>maven-javadoc-plugin</artifactId> | ||
| 30 | + <version>3.12.0</version> | ||
| 31 | + <configuration> | ||
| 32 | + <encoding>UTF-8</encoding> | ||
| 33 | + <docencoding>UTF-8</docencoding> | ||
| 34 | + <charset>UTF-8</charset> | ||
| 35 | + <locale>en_US</locale> | ||
| 36 | + <show>public</show> | ||
| 37 | + <doclint>all,-missing</doclint> | ||
| 38 | + <failOnError>true</failOnError> | ||
| 39 | + <detectJavaApiLink>false</detectJavaApiLink> | ||
| 40 | + </configuration> | ||
| 41 | + <executions> | ||
| 42 | + <execution> | ||
| 43 | + <id>default-cli</id> | ||
| 44 | + <configuration> | ||
| 45 | + <outputDirectory>${project.build.directory}/site</outputDirectory> | ||
| 46 | + </configuration> | ||
| 47 | + </execution> | ||
| 48 | + <execution> | ||
| 49 | + <id>attach-javadocs</id> | ||
| 50 | + <phase>package</phase> | ||
| 51 | + <goals> | ||
| 52 | + <goal>jar</goal> | ||
| 53 | + </goals> | ||
| 54 | + </execution> | ||
| 55 | + </executions> | ||
| 56 | + </plugin> | ||
| 27 | <plugin> | 57 | <plugin> |
| 28 | <groupId>org.apache.maven.plugins</groupId> | 58 | <groupId>org.apache.maven.plugins</groupId> |
| 29 | <artifactId>maven-compiler-plugin</artifactId> | 59 | <artifactId>maven-compiler-plugin</artifactId> |
| @@ -34,7 +34,8 @@ class UtReport { | |||
| 34 | for (String key : List.of("os.name", "os.version", "java.version")) { | 34 | for (String key : List.of("os.name", "os.version", "java.version")) { |
| 35 | testEnvironment.put(key, new LinkedHashSet<>()); | 35 | testEnvironment.put(key, new LinkedHashSet<>()); |
| 36 | } | 36 | } |
| 37 | - Path reports = project.resolve("target/surefire-reports"); | 37 | + for (Path reports : List.of(project.resolve("target/surefire-reports"), |
| 38 | + project.resolve("examples/target/surefire-reports"))) { | ||
| 38 | if (Files.isDirectory(reports)) { | 39 | if (Files.isDirectory(reports)) { |
| 39 | List<Path> files; | 40 | List<Path> files; |
| 40 | try (var stream = Files.list(reports)) { | 41 | try (var stream = Files.list(reports)) { |
| @@ -91,6 +92,7 @@ class UtReport { | |||
| 91 | } | 92 | } |
| 92 | } | 93 | } |
| 93 | } | 94 | } |
| 95 | + } | ||
| 94 | Map<String, Long> counts = new LinkedHashMap<>(); | 96 | Map<String, Long> counts = new LinkedHashMap<>(); |
| 95 | for (String status : List.of("Passed", "Failed", "Skipped", "Error")) { | 97 | for (String status : List.of("Passed", "Failed", "Skipped", "Error")) { |
| 96 | counts.put(status, results.stream().filter(r -> r.status().equals(status)).count()); | 98 | counts.put(status, results.stream().filter(r -> r.status().equals(status)).count()); |
| @@ -3,9 +3,10 @@ | |||
| 3 | set -euo pipefail | 3 | set -euo pipefail |
| 4 | 4 | ||
| 5 | usage() { | 5 | usage() { |
| 6 | - echo "Usage: bash build.sh [build|ut] [additional Maven options]" | 6 | + echo "Usage: bash build.sh [build|ut|docs] [additional Maven options]" |
| 7 | echo " build Compile and package the JAR without compiling/running tests (default)." | 7 | echo " build Compile and package the JAR without compiling/running tests (default)." |
| 8 | echo " ut Compile and run unit tests without packaging the JAR." | 8 | echo " ut Compile and run unit tests without packaging the JAR." |
| 9 | + echo " docs Generate English HTML API documentation from Javadoc comments." | ||
| 9 | } | 10 | } |
| 10 | 11 | ||
| 11 | MODE="${1:-build}" | 12 | MODE="${1:-build}" |
| @@ -19,6 +20,9 @@ case "${MODE}" in | |||
| 19 | ut) | 20 | ut) |
| 20 | MAVEN_ARGS=(-DskipTests=false -Dmaven.test.skip=false -Dmaven.test.failure.ignore=false -DfailIfNoTests=true clean test) | 21 | MAVEN_ARGS=(-DskipTests=false -Dmaven.test.skip=false -Dmaven.test.failure.ignore=false -DfailIfNoTests=true clean test) |
| 21 | ;; | 22 | ;; |
| 23 | + docs) | ||
| 24 | + MAVEN_ARGS=(javadoc:javadoc) | ||
| 25 | + ;; | ||
| 22 | -h|--help) | 26 | -h|--help) |
| 23 | usage | 27 | usage |
| 24 | exit 0 | 28 | exit 0 |
| @@ -37,6 +41,12 @@ if ! command -v mvn >/dev/null 2>&1; then | |||
| 37 | exit 1 | 41 | exit 1 |
| 38 | fi | 42 | fi |
| 39 | 43 | ||
| 44 | +if [[ "$MODE" == "ut" ]]; then | ||
| 45 | + mvn --batch-mode --no-transfer-progress --file "${PROJECT_DIR}/pom.xml" "$@" "${MAVEN_ARGS[@]}" | ||
| 46 | + mvn --batch-mode --no-transfer-progress --file "${PROJECT_DIR}/pom.xml" "$@" install -DskipTests | ||
| 47 | + exec mvn --batch-mode --no-transfer-progress --file "${PROJECT_DIR}/examples/pom.xml" "$@" clean test -DskipTests=false -Dmaven.test.skip=false -Dmaven.test.failure.ignore=false -DfailIfNoTests=true | ||
| 48 | +fi | ||
| 49 | + | ||
| 40 | # Resolve the project independently of the caller's working directory. | 50 | # Resolve the project independently of the caller's working directory. |
| 41 | # Preserve Maven's exit code so compilation/test failures fail the CI job. | 51 | # Preserve Maven's exit code so compilation/test failures fail the CI job. |
| 42 | exec mvn --batch-mode --no-transfer-progress --show-version \ | 52 | exec mvn --batch-mode --no-transfer-progress --show-version \ |
| @@ -70,9 +70,18 @@ echo ">>> Report output: $HTML" | |||
| 70 | # --------------------------------------------------------------------------- | 70 | # --------------------------------------------------------------------------- |
| 71 | cd "$JAVA_PROJECT_DIR" | 71 | cd "$JAVA_PROJECT_DIR" |
| 72 | 72 | ||
| 73 | +# Remove both modules' old Surefire XML before any Maven command can fail. | ||
| 74 | +# UtReport reads only TEST-*.xml; keep other diagnostic files intact. | ||
| 75 | +for report_dir in "$JAVA_PROJECT_DIR/target/surefire-reports" "$JAVA_PROJECT_DIR/examples/target/surefire-reports"; do | ||
| 76 | + rm -f -- "$report_dir"/TEST-*.xml | ||
| 77 | +done | ||
| 78 | + | ||
| 73 | started_at=$(date +%s) | 79 | started_at=$(date +%s) |
| 74 | rc=0 | 80 | rc=0 |
| 75 | -mvn --batch-mode --no-transfer-progress clean test 2>&1 | tee "$LOG" || rc=${PIPESTATUS[0]} | 81 | +mvn --batch-mode --no-transfer-progress -f examples/pom.xml clean 2>&1 | tee "$LOG" || rc=${PIPESTATUS[0]} |
| 82 | +if [ "$rc" -eq 0 ]; then | ||
| 83 | + bash "$SCRIPT_DIR/build.sh" ut 2>&1 | tee -a "$LOG" || rc=${PIPESTATUS[0]} | ||
| 84 | +fi | ||
| 76 | 85 | ||
| 77 | # --------------------------------------------------------------------------- | 86 | # --------------------------------------------------------------------------- |
| 78 | # 5. 转换 Surefire 报告为标准 JUnit XML | 87 | # 5. 转换 Surefire 报告为标准 JUnit XML |
MA4P-java-sdk/src/main/java/io/openjiuwen/a4p/A4p.java+233-4File content is under review, please try again later
| @@ -1,38 +1,81 @@ | |||
| 1 | package io.openjiuwen.a4p; | 1 | package io.openjiuwen.a4p; |
| 2 | 2 | ||
| 3 | +/** | ||
| 4 | + * Defines stable numeric protocol result codes and their fixed diagnostic messages. | ||
| 5 | + * Use numeric codes for application decisions rather than matching message text. | ||
| 6 | + */ | ||
| 3 | public enum A4pErrorCode { | 7 | public enum A4pErrorCode { |
| 8 | + /** Operation completed successfully. Numeric code: 0. */ | ||
| 4 | A4P_SUCCESS(0, "Operation completed successfully"), | 9 | A4P_SUCCESS(0, "Operation completed successfully"), |
| 10 | + /** Invalid parameter. Numeric code: 1001. */ | ||
| 5 | A4P_INVALID_PARAMETER(1001, "Invalid parameter"), | 11 | A4P_INVALID_PARAMETER(1001, "Invalid parameter"), |
| 12 | + /** Unsupported version. Numeric code: 1002. */ | ||
| 6 | A4P_UNSUPPORTED_VERSION(1002, "Unsupported version"), | 13 | A4P_UNSUPPORTED_VERSION(1002, "Unsupported version"), |
| 14 | + /** Duplicate ID. Numeric code: 1003. */ | ||
| 7 | A4P_DUPLICATE_ID(1003, "Duplicate ID"), | 15 | A4P_DUPLICATE_ID(1003, "Duplicate ID"), |
| 16 | + /** Signing failed. Numeric code: 2001. */ | ||
| 8 | A4P_SIGNING_FAIL(2001, "Signing failed"), | 17 | A4P_SIGNING_FAIL(2001, "Signing failed"), |
| 18 | + /** Verification failed. Numeric code: 2002. */ | ||
| 9 | A4P_VERIFY_FAIL(2002, "Verification failed"), | 19 | A4P_VERIFY_FAIL(2002, "Verification failed"), |
| 20 | + /** Invalid status. Numeric code: 3001. */ | ||
| 10 | A4P_INVALID_STATUS(3001, "Invalid status"), | 21 | A4P_INVALID_STATUS(3001, "Invalid status"), |
| 22 | + /** Timestamp expired. Numeric code: 3002. */ | ||
| 11 | A4P_TIMESTAMP_EXPIRED(3002, "Timestamp expired"), | 23 | A4P_TIMESTAMP_EXPIRED(3002, "Timestamp expired"), |
| 24 | + /** Timestamp too early. Numeric code: 3003. */ | ||
| 12 | A4P_TIMESTAMP_TOO_EARLY(3003, "Timestamp too early"), | 25 | A4P_TIMESTAMP_TOO_EARLY(3003, "Timestamp too early"), |
| 26 | + /** Execution count exceeded. Numeric code: 4001. */ | ||
| 13 | A4P_EXECUTION_COUNT_EXCEEDED(4001, "Execution count exceeded"), | 27 | A4P_EXECUTION_COUNT_EXCEEDED(4001, "Execution count exceeded"), |
| 28 | + /** Amount exceeded. Numeric code: 4002. */ | ||
| 14 | A4P_AMOUNT_EXCEEDED(4002, "Amount exceeded"), | 29 | A4P_AMOUNT_EXCEEDED(4002, "Amount exceeded"), |
| 15 | // Retained for ArkTS error-code compatibility; Java uses 4004 for per-period execution limits. | 30 | // Retained for ArkTS error-code compatibility; Java uses 4004 for per-period execution limits. |
| 31 | + /** Period count exceeded. Numeric code: 4003. Reserved for ArkTS compatibility; Java uses code 4004 for periodic execution-count limits. */ | ||
| 16 | A4P_PERIOD_COUNT_EXCEEDED(4003, "Period count exceeded"), | 32 | A4P_PERIOD_COUNT_EXCEEDED(4003, "Period count exceeded"), |
| 33 | + /** Period execution count exceeded. Numeric code: 4004. */ | ||
| 17 | A4P_PERIOD_EXECUTION_COUNT_EXCEEDED(4004, "Period execution count exceeded"), | 34 | A4P_PERIOD_EXECUTION_COUNT_EXCEEDED(4004, "Period execution count exceeded"), |
| 35 | + /** Cart does not match the authorized resource. Numeric code: 4005. Includes missing groups, repeated groups and incorrect template quantities. */ | ||
| 18 | A4P_CART_MISMATCH(4005, "Cart does not match the authorized resource"), | 36 | A4P_CART_MISMATCH(4005, "Cart does not match the authorized resource"), |
| 37 | + /** Single order amount exceeded. Numeric code: 4006. */ | ||
| 19 | A4P_SINGLE_ORDER_AMOUNT_EXCEEDED(4006, "Single order amount exceeded"), | 38 | A4P_SINGLE_ORDER_AMOUNT_EXCEEDED(4006, "Single order amount exceeded"), |
| 39 | + /** Product not authorized. Numeric code: 4007. */ | ||
| 20 | A4P_PRODUCT_NOT_AUTHORIZED(4007, "Product not authorized"), | 40 | A4P_PRODUCT_NOT_AUTHORIZED(4007, "Product not authorized"), |
| 41 | + /** Serialization failed. Numeric code: 5001. */ | ||
| 21 | A4P_SERIALIZE_FAIL(5001, "Serialization failed"), | 42 | A4P_SERIALIZE_FAIL(5001, "Serialization failed"), |
| 43 | + /** Deserialization failed. Numeric code: 5002. */ | ||
| 22 | A4P_DESERIALIZE_FAIL(5002, "Deserialization failed"), | 44 | A4P_DESERIALIZE_FAIL(5002, "Deserialization failed"), |
| 45 | + /** Unexpected internal error. Numeric code: 6001. */ | ||
| 23 | A4P_INTERNAL_ERROR(6001, "Unexpected internal error"); | 46 | A4P_INTERNAL_ERROR(6001, "Unexpected internal error"); |
| 24 | 47 | ||
| 48 | + /** Protocol result or exception error code. */ | ||
| 25 | private final int code; | 49 | private final int code; |
| 50 | + /** Diagnostic text associated with the result code. */ | ||
| 26 | private final String message; | 51 | private final String message; |
| 27 | 52 | ||
| 53 | + /** | ||
| 54 | + * Associates a stable numeric code with its diagnostic message. | ||
| 55 | + * @param code protocol result code; zero means success | ||
| 56 | + * @param message diagnostic message | ||
| 57 | + */ | ||
| 28 | A4pErrorCode(int code, String message) { | 58 | A4pErrorCode(int code, String message) { |
| 29 | this.code = code; | 59 | this.code = code; |
| 30 | this.message = message; | 60 | this.message = message; |
| 31 | } | 61 | } |
| 32 | 62 | ||
| 63 | + /** | ||
| 64 | + * Returns the stable numeric protocol code. | ||
| 65 | + * @return protocol result code | ||
| 66 | + */ | ||
| 33 | public int code() { return code; } | 67 | public int code() { return code; } |
| 68 | + /** | ||
| 69 | + * Returns the fixed English diagnostic message. | ||
| 70 | + * @return diagnostic message | ||
| 71 | + */ | ||
| 34 | public String message() { return message; } | 72 | public String message() { return message; } |
| 35 | 73 | ||
| 74 | + /** | ||
| 75 | + * Finds the enum constant for a numeric code; unknown codes map to A4P_INTERNAL_ERROR. | ||
| 76 | + * @param code protocol result code; zero means success | ||
| 77 | + * @return matching constant, or A4P_INTERNAL_ERROR for an unknown code | ||
| 78 | + */ | ||
| 36 | public static A4pErrorCode fromCode(int code) { | 79 | public static A4pErrorCode fromCode(int code) { |
| 37 | for (A4pErrorCode value : values()) { | 80 | for (A4pErrorCode value : values()) { |
| 38 | if (value.code == code) { | 81 | if (value.code == code) { |
| @@ -1,16 +1,36 @@ | |||
| 1 | package io.openjiuwen.a4p; | 1 | package io.openjiuwen.a4p; |
| 2 | 2 | ||
| 3 | +/** | ||
| 4 | + * Reports a protocol error from throwing utility APIs or an unexpected SDK defect. | ||
| 5 | + * Lifecycle operations normally return protocol failures in A4pResult instead. | ||
| 6 | + * @see A4pResult | ||
| 7 | + */ | ||
| 3 | public final class A4pException extends RuntimeException { | 8 | public final class A4pException extends RuntimeException { |
| 9 | + /** Protocol result or exception error code. */ | ||
| 4 | private final A4pErrorCode code; | 10 | private final A4pErrorCode code; |
| 5 | 11 | ||
| 12 | + /** | ||
| 13 | + * Constructs a protocol exception with a result code and diagnostic information. | ||
| 14 | + * @param code protocol result code; zero means success | ||
| 15 | + */ | ||
| 6 | public A4pException(A4pErrorCode code) { | 16 | public A4pException(A4pErrorCode code) { |
| 7 | this(code, code.message(), null); | 17 | this(code, code.message(), null); |
| 8 | } | 18 | } |
| 9 | 19 | ||
| 20 | + /** | ||
| 21 | + * Constructs a protocol exception with a result code and diagnostic information. | ||
| 22 | + * @param code protocol result code; zero means success | ||
| 23 | + * @param message diagnostic message | ||
| 24 | + * @param cause underlying cause, or null | ||
| 25 | + */ | ||
| 10 | public A4pException(A4pErrorCode code, String message, Throwable cause) { | 26 | public A4pException(A4pErrorCode code, String message, Throwable cause) { |
| 11 | super(message, cause); | 27 | super(message, cause); |
| 12 | this.code = code; | 28 | this.code = code; |
| 13 | } | 29 | } |
| 14 | 30 | ||
| 31 | + /** | ||
| 32 | + * Returns the protocol error represented by this exception. | ||
| 33 | + * @return protocol error enum constant | ||
| 34 | + */ | ||
| 15 | public A4pErrorCode code() { return code; } | 35 | public A4pErrorCode code() { return code; } |
| 16 | } | 36 | } |
| @@ -1,23 +1,243 @@ | |||
| 1 | package io.openjiuwen.a4p; | 1 | package io.openjiuwen.a4p; |
| 2 | 2 | ||
| 3 | +import com.fasterxml.jackson.databind.JsonNode; | ||
| 3 | import io.openjiuwen.a4p.Models.*; | 4 | import io.openjiuwen.a4p.Models.*; |
| 5 | +import java.util.ArrayList; | ||
| 6 | +import java.util.LinkedHashMap; | ||
| 7 | +import java.util.List; | ||
| 8 | +import java.util.Map; | ||
| 9 | +import java.util.function.Consumer; | ||
| 10 | +import static io.openjiuwen.a4p.A4pErrorCode.*; | ||
| 4 | 11 | ||
| 5 | -public interface A4pIntentCodec { | 12 | +// Serializes to canonical JSON; deserialization parses strictly and validates the whole chain. |
| 6 | - String serializeIntentL1(IntentL1 intentL1); | 13 | +/** |
| 14 | + * Provides canonical JSON serialization and structural restoration checks. | ||
| 15 | + * Restoration validates layered intents, ledger reachability and accounting consistency, | ||
| 16 | + * but does not verify signatures or provide integrity protection for persisted data. | ||
| 17 | + */ | ||
| 18 | +public class A4pIntentCodec { | ||
【review】接口兼容性。将 A4pIntentCodec 从公开接口改为具体类,同时移除公开的 standard() 工厂并把 Rsa3072 移出 SDK,属于源码和二进制不兼容的公开 API 变更;当前 pom.xml 版本仍为 0.1.0,若该版本已对外发布,现有调用方升级后会编译失败。确认 0.1.0 是否已对外发布;若已发布,建议提升版本号并在 README 与 API 文档中补充迁移说明,或保留 standard() 兼容入口。 ![]() ![]() | |||
| 7 | 19 | ||
| 8 | - A4pResult<IntentL1> deserializeIntentL1(String serialized); | 20 | + // Wire form of a persisted context; reservedAt is boxed so a missing field is rejected instead of read as 0. |
| 21 | + /** | ||
| 22 | + * Represents persisted context fields; restoration checks consistency without authenticating the data. | ||
| 23 | + * @param version A4P Core protocol version | ||
| 24 | + * @param intentId globally unique intent identifier | ||
| 25 | + * @param authorizedIntent authorized L3 snapshot | ||
| 26 | + * @param status context execution state | ||
| 27 | + * @param executionInfo persisted quota snapshot | ||
| 28 | + * @param executions persisted execution ledger | ||
| 29 | + * @param activatedTime activation instant in Unix epoch milliseconds | ||
| 30 | + */ | ||
| 31 | + record ContextJson(String version, String intentId, IntentL3 authorizedIntent, IntentExecutionStatus status, | ||
| 32 | + JsonNode executionInfo, List<RecordJson> executions, Long activatedTime) {} | ||
| 9 | 33 | ||
| 10 | - String serializeIntentL2(IntentL2 intentL2); | 34 | + /** |
| 35 | + * Represents a persisted execution record; boxed reservedAt allows missing timestamps to be rejected. | ||
| 36 | + * @param executionId execution identifier, retained even after cancellation | ||
| 37 | + * @param status execution record state | ||
| 38 | + * @param action protocol action selecting the payload schema | ||
| 39 | + * @param executionContent action-specific JSON payload; AI_PAY contains an Order | ||
| 40 | + * @param periodIndex original reservation period, or null without periodic limits | ||
| 41 | + * @param reservedAt reservation instant in Unix epoch milliseconds | ||
| 42 | + * @param completedAt completion instant, present only for COMPLETED and not before reservedAt | ||
| 43 | + * @param canceledAt cancellation instant, present only for CANCELED and not before reservedAt | ||
| 44 | + */ | ||
| 45 | + record RecordJson(String executionId, ExecutionStatus status, IntentActionType action, | ||
| 46 | + JsonNode executionContent, Long periodIndex, Long reservedAt, | ||
| 47 | + Long completedAt, Long canceledAt) {} | ||
| 11 | 48 | ||
| 12 | - A4pResult<IntentL2> deserializeIntentL2(String serialized); | 49 | + /** |
| 50 | + * Constructs a reusable canonical intent codec. | ||
| 51 | + */ | ||
| 52 | + public A4pIntentCodec() {} | ||
🟡 Medium Priority 变更点:A4pIntentCodec.java:18 把原来的
建议:同步修改 docs/API.md、docs/API_zh.md、docs/serialization_and_signature_rules.md(_zh) 与 CodecConformanceCheck 中的说明,删除“接口/包内可见/无公开工厂”的旧描述,改为公开类 ![]() ![]() Incorrect? | |||
| 13 | 53 | ||
| 14 | - String serializeIntentL3(IntentL3 intentL3); | 54 | + /** |
| 55 | + * Serializes the SDK-created IntentL1 as canonical JSON. | ||
| 56 | + * @param intentL1 SDK-created first-layer intent | ||
| 57 | + * @return canonical JSON representation | ||
| 58 | + * @throws A4pException if the input cannot be serialized | ||
| 59 | + */ | ||
| 60 | + public String serializeIntentL1(IntentL1 intentL1) { return serialize(intentL1); } | ||
| 15 | 61 | ||
| 16 | - A4pResult<IntentL3> deserializeIntentL3(String serialized); | 62 | + /** |
| 63 | + * Serializes the SDK-created IntentL2 as canonical JSON. | ||
| 64 | + * @param intentL2 SDK-issued second-layer intent | ||
| 65 | + * @return canonical JSON representation | ||
| 66 | + * @throws A4pException if the input cannot be serialized | ||
| 67 | + */ | ||
| 68 | + public String serializeIntentL2(IntentL2 intentL2) { return serialize(intentL2); } | ||
| 17 | 69 | ||
| 18 | - String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext); | 70 | + /** |
| 71 | + * Serializes the SDK-created IntentL3 as canonical JSON. | ||
| 72 | + * @param intentL3 SDK-authorized third-layer intent | ||
| 73 | + * @return canonical JSON representation | ||
| 74 | + * @throws A4pException if the input cannot be serialized | ||
| 75 | + */ | ||
| 76 | + public String serializeIntentL3(IntentL3 intentL3) { return serialize(intentL3); } | ||
| 19 | 77 | ||
| 20 | - A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized); | 78 | + /** |
| 79 | + * Restores IntentL1 from JSON with structural and protocol validation. | ||
| 80 | + * Does not verify cryptographic signatures or authenticate persisted data. | ||
| 81 | + * @param serialized serialized local JSON representation | ||
| 82 | + * @return restored object or a protocol failure result | ||
| 83 | + */ | ||
| 84 | + public A4pResult<IntentL1> deserializeIntentL1(String serialized) { | ||
| 85 | + return decode(serialized, IntentL1.class, Validation::intentL1); | ||
| 86 | + } | ||
| 21 | 87 | ||
| 22 | - static A4pIntentCodec standard() { return CanonicalIntentCodec.INSTANCE; } | 88 | + /** |
| 89 | + * Restores IntentL2 from JSON with structural and protocol validation. | ||
| 90 | + * Does not verify cryptographic signatures or authenticate persisted data. | ||
| 91 | + * @param serialized serialized local JSON representation | ||
| 92 | + * @return restored object or a protocol failure result | ||
| 93 | + */ | ||
| 94 | + public A4pResult<IntentL2> deserializeIntentL2(String serialized) { | ||
| 95 | + return decode(serialized, IntentL2.class, Validation::intentL2); | ||
| 96 | + } | ||
| 97 | + | ||
| 98 | + /** | ||
| 99 | + * Restores IntentL3 from JSON with structural and protocol validation. | ||
| 100 | + * Does not verify cryptographic signatures or authenticate persisted data. | ||
| 101 | + * @param serialized serialized local JSON representation | ||
| 102 | + * @return restored object or a protocol failure result | ||
| 103 | + */ | ||
| 104 | + public A4pResult<IntentL3> deserializeIntentL3(String serialized) { | ||
| 105 | + return decode(serialized, IntentL3.class, Validation::intentL3); | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + /** | ||
| 109 | + * Serializes the SDK-created IntentExecutionContext as canonical JSON. | ||
| 110 | + * Context output is for local persistence only; callers provide storage integrity protection. | ||
| 111 | + * @param intentExecutionContext context for local persistence only | ||
| 112 | + * @return canonical JSON representation | ||
| 113 | + * @throws A4pException if the input cannot be serialized | ||
| 114 | + */ | ||
| 115 | + public String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext) { | ||
| 116 | + Validation.present(intentExecutionContext); | ||
| 117 | + Map<String, Object> fields = new LinkedHashMap<>(); | ||
| 118 | + // One lock for every field, so the ledger and executionInfo come from the same state. | ||
| 119 | + synchronized (intentExecutionContext) { | ||
| 120 | + fields.put("version", intentExecutionContext.version()); | ||
| 121 | + fields.put("intentId", intentExecutionContext.intentId()); | ||
| 122 | + fields.put("authorizedIntent", intentExecutionContext.authorizedIntent()); | ||
| 123 | + fields.put("activatedTime", intentExecutionContext.activatedTime()); | ||
| 124 | + fields.put("status", intentExecutionContext.status()); | ||
| 125 | + fields.put("executionInfo", intentExecutionContext.executionInfo()); | ||
| 126 | + fields.put("executions", intentExecutionContext.executions()); | ||
| 127 | + } | ||
| 128 | + return CanonicalJson.stringify(fields); | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + // The user signature is not re-verified; the stored L3 is checked like activateIntent's input otherwise. | ||
| 132 | + /** | ||
| 133 | + * Restores IntentExecutionContext from JSON with structural and protocol validation. | ||
| 134 | + * Does not verify cryptographic signatures or authenticate persisted data. | ||
| 135 | + * Checks activation time, ledger reachability and accounting consistency; older contexts without activatedTime are rejected. | ||
| 136 | + * @param serialized serialized local JSON representation | ||
| 137 | + * @return restored object or a protocol failure result | ||
| 138 | + */ | ||
| 139 | + public A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized) { | ||
| 140 | + return A4pResult.capture(() -> restore(parse(serialized, ContextJson.class))); | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + /** | ||
| 144 | + * Restores a context after checking activation time, layered intent structure, ledger constraints and accounting consistency. | ||
| 145 | + * Does not reverify user signatures or authenticate persistence. | ||
| 146 | + * @param wire parsed persistence representation | ||
| 147 | + * @return structurally validated execution context | ||
| 148 | + */ | ||
| 149 | + private static IntentExecutionContext restore(ContextJson wire) { | ||
| 150 | + Validation.present(wire); | ||
| 151 | + Validation.text(wire.version()); | ||
| 152 | + Validation.version(wire.version()); | ||
| 153 | + IntentL3 authorized = wire.authorizedIntent(); | ||
| 154 | + Validation.intentL3(authorized); | ||
| 155 | + Validation.versions(authorized); | ||
| 156 | + IntentL1 intent = authorized.intentL2().intentL1(); | ||
| 157 | + Validation.require(intent.intentId().equals(wire.intentId()), A4P_INVALID_PARAMETER); | ||
| 158 | + Validation.integer(wire.activatedTime(), false); | ||
| 159 | + Validation.require(wire.activatedTime() >= authorized.timestamp(), A4P_INVALID_PARAMETER); | ||
| 160 | + Validation.present(wire.status()); | ||
| 161 | + Validation.present(wire.executions()); | ||
| 162 | + List<IntentExecutionContext.Entry> ledger = new ArrayList<>(); | ||
| 163 | + for (RecordJson record : wire.executions()) { | ||
| 164 | + Validation.present(record); | ||
| 165 | + Validation.integer(record.reservedAt(), false); | ||
| 166 | + Validation.require(record.reservedAt() >= wire.activatedTime(), A4P_INVALID_PARAMETER); | ||
| 167 | + Order order = Validation.execution(new Execution(record.action(), record.executionId(), | ||
| 168 | + record.executionContent())); | ||
| 169 | + ledger.add(new IntentExecutionContext.Entry(new ExecutionRecord(record.executionId(), record.status(), | ||
| 170 | + record.action(), record.executionContent(), record.periodIndex(), record.reservedAt(), | ||
| 171 | + record.completedAt(), record.canceledAt()), order)); | ||
| 172 | + } | ||
| 173 | + Long period = period(wire.executionInfo(), PaymentProfile.constraints(intent.structuredIntent())); | ||
| 174 | + IntentExecutionContext context = new IntentExecutionContext(authorized, wire.status(), ledger, period, wire.activatedTime()); | ||
| 175 | + Validation.ledger(context); | ||
| 176 | + // executionInfo is derived state, so it must match what the restored ledger yields. | ||
| 177 | + Validation.require(context.executionInfo().equals(CanonicalJson.freezeNode(wire.executionInfo())), | ||
| 178 | + A4P_INVALID_PARAMETER); | ||
| 179 | + return context; | ||
| 180 | + } | ||
| 181 | + | ||
| 182 | + // The period executionInfo was last recomputed in depends on call times the ledger does not record. | ||
| 183 | + /** | ||
| 184 | + * Reads the stored accounting period and checks that it agrees with the configured periodic policy. | ||
| 185 | + * @param info quota accounting snapshot | ||
| 186 | + * @param constraints authorized AI_PAY payment limits | ||
| 187 | + * @return computed or stored accounting period, or null without periodic limits | ||
| 188 | + */ | ||
| 189 | + private static Long period(JsonNode info, PaymentConstraints constraints) { | ||
| 190 | + Validation.require(info != null && info.isObject(), A4P_INVALID_PARAMETER); | ||
| 191 | + JsonNode period = info.get("periodIndex"); | ||
| 192 | + if (period == null || period.isNull()) { | ||
| 193 | + Validation.require(constraints.anchorTime() == null, A4P_INVALID_PARAMETER); | ||
| 194 | + return null; | ||
| 195 | + } | ||
| 196 | + Validation.require(constraints.anchorTime() != null && period.isIntegralNumber() && period.canConvertToLong(), | ||
| 197 | + A4P_INVALID_PARAMETER); | ||
| 198 | + return period.longValue(); | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /** | ||
| 202 | + * Serializes a non-null protocol object as canonical JSON. | ||
| 203 | + * @param intent protocol intent to process | ||
| 204 | + * @return canonical JSON representation | ||
| 205 | + */ | ||
| 206 | + private static String serialize(Object intent) { | ||
| 207 | + Validation.present(intent); | ||
| 208 | + return CanonicalJson.stringify(intent); | ||
| 209 | + } | ||
| 210 | + | ||
| 211 | + /** | ||
| 212 | + * Parses a typed protocol value and captures structural validation failures as results. | ||
| 213 | + * @param <Value> decoded or copied value type | ||
| 214 | + * @param json JSON representation to parse | ||
| 215 | + * @param type target decoded value type | ||
| 216 | + * @param validate structural validation action | ||
| 217 | + * @return validated value or a protocol failure | ||
| 218 | + */ | ||
| 219 | + private static <Value> A4pResult<Value> decode(String json, Class<Value> type, Consumer<Value> validate) { | ||
| 220 | + return A4pResult.capture(() -> { | ||
| 221 | + Value value = parse(json, type); | ||
| 222 | + validate.accept(value); | ||
| 223 | + return value; | ||
| 224 | + }); | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + /** | ||
| 228 | + * Strictly parses JSON and converts it to the requested protocol representation. | ||
| 229 | + * @param <Value> decoded or copied value type | ||
| 230 | + * @param json JSON representation to parse | ||
| 231 | + * @param type target decoded value type | ||
| 232 | + * @return decoded or parsed value | ||
| 233 | + */ | ||
| 234 | + private static <Value> Value parse(String json, Class<Value> type) { | ||
| 235 | + Validation.require(json != null && !json.isEmpty(), A4P_INVALID_PARAMETER); | ||
| 236 | + Object parsed = CanonicalJson.parse(json); | ||
| 237 | + try { | ||
| 238 | + return CanonicalJson.MAPPER.convertValue(parsed, type); | ||
| 239 | + } catch (IllegalArgumentException error) { | ||
| 240 | + throw new A4pException(A4P_INVALID_PARAMETER); | ||
| 241 | + } | ||
| 242 | + } | ||
| 23 | } | 243 | } |
| @@ -3,12 +3,48 @@ package io.openjiuwen.a4p; | |||
| 3 | import java.util.function.Supplier; | 3 | import java.util.function.Supplier; |
| 4 | import static io.openjiuwen.a4p.A4pErrorCode.*; | 4 | import static io.openjiuwen.a4p.A4pErrorCode.*; |
| 5 | 5 | ||
| 6 | +/** | ||
| 7 | + * Represents a successful value or a protocol failure. | ||
| 8 | + * Check success() before accessing data(). Success has non-null data and code zero; | ||
| 9 | + * failure has null data and a nonzero code. SDK-generated messages are fixed diagnostics. | ||
| 10 | + * @param <T> successful payload type | ||
| 11 | + * @see A4pErrorCode | ||
| 12 | + */ | ||
| 6 | public final class A4pResult<T> { | 13 | public final class A4pResult<T> { |
| 14 | + /** Whether this result contains a successful payload. */ | ||
| 7 | private final boolean success; | 15 | private final boolean success; |
| 16 | + /** Successful business payload, or null on failure. */ | ||
| 8 | private final T data; | 17 | private final T data; |
| 18 | + /** Protocol result or exception error code. */ | ||
| 9 | private final long code; | 19 | private final long code; |
| 20 | + /** Diagnostic text associated with the result code. */ | ||
| 10 | private final String message; | 21 | private final String message; |
| 11 | 22 | ||
| 23 | + /** | ||
| 24 | + * Constructs a result with the supplied status, payload and diagnostic information. | ||
| 25 | + * @param success whether the result represents success | ||
| 26 | + * @param data successful payload, or null for a failure | ||
| 27 | + * @param code protocol result code; zero means success | ||
| 28 | + * @param message diagnostic message | ||
| 29 | + * @throws IllegalArgumentException if status, payload and numeric code are inconsistent | ||
| 30 | + */ | ||
| 31 | + public A4pResult(boolean success, T data, long code, String message) { | ||
| 32 | + if (success ? data == null || code != A4P_SUCCESS.code() | ||
| 33 | + : data != null || code == A4P_SUCCESS.code()) { | ||
| 34 | + throw new IllegalArgumentException("Inconsistent A4pResult fields"); | ||
| 35 | + } | ||
| 36 | + this.success = success; | ||
| 37 | + this.data = data; | ||
| 38 | + this.code = code; | ||
| 39 | + this.message = message; | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + /** | ||
| 43 | + * Constructs a result with the supplied status, payload and diagnostic information. | ||
| 44 | + * @param success whether the result represents success | ||
| 45 | + * @param data successful payload, or null for a failure | ||
| 46 | + * @param code protocol result code; zero means success | ||
| 47 | + */ | ||
| 12 | private A4pResult(boolean success, T data, A4pErrorCode code) { | 48 | private A4pResult(boolean success, T data, A4pErrorCode code) { |
| 13 | this.success = success; | 49 | this.success = success; |
| 14 | this.data = data; | 50 | this.data = data; |
| @@ -16,26 +52,65 @@ public final class A4pResult<T> { | |||
| 16 | this.message = code.message(); | 52 | this.message = code.message(); |
| 17 | } | 53 | } |
| 18 | 54 | ||
| 19 | - public static <T> A4pResult<T> ok(T data) { | 55 | + /** |
| 56 | + * Builds a success result, mapping null payloads to an internal-error failure. | ||
| 57 | + * @param <T> successful payload type | ||
| 58 | + * @param data successful payload, or null for a failure | ||
| 59 | + * @return successful result, or internal-error failure for null data | ||
| 60 | + */ | ||
| 61 | + static <T> A4pResult<T> ok(T data) { | ||
| 20 | if (data == null) { return failure(A4P_INTERNAL_ERROR); } | 62 | if (data == null) { return failure(A4P_INTERNAL_ERROR); } |
| 21 | return new A4pResult<>(true, data, A4P_SUCCESS); | 63 | return new A4pResult<>(true, data, A4P_SUCCESS); |
| 22 | } | 64 | } |
| 23 | 65 | ||
| 24 | - public static <T> A4pResult<T> failure(A4pErrorCode code) { | 66 | + /** |
| 67 | + * Builds a failure result, mapping a missing or success error code to internal error. | ||
| 68 | + * @param <T> successful payload type | ||
| 69 | + * @param code protocol result code; zero means success | ||
| 70 | + * @return failure result with a nonzero error code | ||
| 71 | + */ | ||
| 72 | + static <T> A4pResult<T> failure(A4pErrorCode code) { | ||
| 25 | return new A4pResult<>(false, null, code == null || code == A4P_SUCCESS ? A4P_INTERNAL_ERROR : code); | 73 | return new A4pResult<>(false, null, code == null || code == A4P_SUCCESS ? A4P_INTERNAL_ERROR : code); |
| 26 | } | 74 | } |
| 27 | 75 | ||
| 76 | + /** | ||
| 77 | + * Reports whether this result contains a successful payload. | ||
| 78 | + * @return true if data is available | ||
| 79 | + */ | ||
| 28 | public boolean success() { return success; } | 80 | public boolean success() { return success; } |
| 81 | + /** | ||
| 82 | + * Returns the successful payload, or null on failure. | ||
| 83 | + * @return successful payload, or null | ||
| 84 | + */ | ||
| 29 | public T data() { return data; } | 85 | public T data() { return data; } |
| 86 | + /** | ||
| 87 | + * Returns the numeric protocol result code; zero indicates success. | ||
| 88 | + * @return protocol result code | ||
| 89 | + */ | ||
| 30 | public long code() { return code; } | 90 | public long code() { return code; } |
| 91 | + /** | ||
| 92 | + * Returns the diagnostic message associated with this result. | ||
| 93 | + * @return diagnostic message | ||
| 94 | + */ | ||
| 31 | public String message() { return message; } | 95 | public String message() { return message; } |
| 32 | 96 | ||
| 97 | + /** | ||
| 98 | + * Returns a diagnostic summary without including the business payload. | ||
| 99 | + * @return diagnostic summary excluding the business payload | ||
| 100 | + */ | ||
| 33 | @Override | 101 | @Override |
| 34 | public String toString() { | 102 | public String toString() { |
| 35 | return "A4pResult[success=" + success + ", code=" + code + ", message=" + message + "]"; | 103 | return "A4pResult[success=" + success + ", code=" + code + ", message=" + message + "]"; |
| 36 | } | 104 | } |
| 37 | 105 | ||
| 38 | // Protocol failures become results; anything else is an SDK defect and surfaces as A4pException. | 106 | // Protocol failures become results; anything else is an SDK defect and surfaces as A4pException. |
| 107 | + /** | ||
| 108 | + * Executes an operation and converts protocol exceptions into failure results. | ||
| 109 | + * Wraps unexpected runtime exceptions as internal SDK defects rather than hiding them as protocol failures. | ||
| 110 | + * @param <T> successful payload type | ||
| 111 | + * @param action operation to execute | ||
| 112 | + * @return successful result or captured protocol failure | ||
| 113 | + */ | ||
| 39 | static <T> A4pResult<T> capture(Supplier<T> action) { | 114 | static <T> A4pResult<T> capture(Supplier<T> action) { |
| 40 | try { | 115 | try { |
| 41 | return ok(action.get()); | 116 | return ok(action.get()); |
| @@ -4,9 +4,24 @@ import io.openjiuwen.a4p.Models.*; | |||
| 4 | import java.math.BigInteger; | 4 | import java.math.BigInteger; |
| 5 | import java.util.Objects; | 5 | import java.util.Objects; |
| 6 | 6 | ||
| 7 | +/** | ||
| 8 | + * Computes payment quota usage from the execution ledger. | ||
| 9 | + * PENDING and COMPLETED records occupy quota; CANCELED records release it. | ||
| 10 | + * Callers synchronize access to mutable contexts when computing or updating accounting. | ||
| 11 | + */ | ||
| 7 | final class Accounting { | 12 | final class Accounting { |
| 13 | + /** | ||
| 14 | + * Prevents instantiation of this utility class. | ||
| 15 | + */ | ||
| 8 | private Accounting() {} | 16 | private Accounting() {} |
| 9 | 17 | ||
| 18 | + /** | ||
| 19 | + * Computes floor((now - anchorTime) / (periodSeconds * 1000)), or null without periodic limits. | ||
| 20 | + * Uses arbitrary-precision intermediates to avoid overflow. | ||
| 21 | + * @param constraints authorized AI_PAY payment limits | ||
| 22 | + * @param now trusted non-negative Unix epoch milliseconds within the safe integer range | ||
| 23 | + * @return computed or stored accounting period, or null without periodic limits | ||
| 24 | + */ | ||
| 10 | static Long period(PaymentConstraints constraints, long now) { | 25 | static Long period(PaymentConstraints constraints, long now) { |
| 11 | if (constraints.anchorTime() == null) { return null; } | 26 | if (constraints.anchorTime() == null) { return null; } |
| 12 | BigInteger elapsed = BigInteger.valueOf(now).subtract(BigInteger.valueOf(constraints.anchorTime())); | 27 | BigInteger elapsed = BigInteger.valueOf(now).subtract(BigInteger.valueOf(constraints.anchorTime())); |
| @@ -16,23 +31,48 @@ final class Accounting { | |||
| 16 | ? quotient[0].subtract(BigInteger.ONE) : quotient[0]).longValueExact(); | 31 | ? quotient[0].subtract(BigInteger.ONE) : quotient[0]).longValueExact(); |
| 17 | } | 32 | } |
| 18 | 33 | ||
| 34 | + /** | ||
| 35 | + * Reports whether a ledger entry occupies quota; canceled entries do not. | ||
| 36 | + * @param entry ledger entry to evaluate | ||
| 37 | + * @return true if the record occupies quota | ||
| 38 | + */ | ||
| 19 | static boolean counted(IntentExecutionContext.Entry entry) { | 39 | static boolean counted(IntentExecutionContext.Entry entry) { |
| 20 | return entry.record().status() != ExecutionStatus.CANCELED; | 40 | return entry.record().status() != ExecutionStatus.CANCELED; |
| 21 | } | 41 | } |
| 22 | 42 | ||
| 43 | + /** | ||
| 44 | + * Counts pending and completed executions across all periods. | ||
| 45 | + * @param context activated intent and mutable execution ledger | ||
| 46 | + * @return number of pending and completed executions | ||
| 47 | + */ | ||
| 23 | static long count(IntentExecutionContext context) { | 48 | static long count(IntentExecutionContext context) { |
| 24 | return context.ledger().stream().filter(Accounting::counted).count(); | 49 | return context.ledger().stream().filter(Accounting::counted).count(); |
| 25 | } | 50 | } |
| 26 | 51 | ||
| 52 | + /** | ||
| 53 | + * Sums amounts reserved by pending and completed executions. | ||
| 54 | + * @param context activated intent and mutable execution ledger | ||
| 55 | + * @return total amount occupied by pending and completed records | ||
| 56 | + */ | ||
| 27 | static long amount(IntentExecutionContext context) { | 57 | static long amount(IntentExecutionContext context) { |
| 28 | return context.ledger().stream().filter(Accounting::counted).mapToLong(entry -> entry.order().amount()).sum(); | 58 | return context.ledger().stream().filter(Accounting::counted).mapToLong(entry -> entry.order().amount()).sum(); |
| 29 | } | 59 | } |
| 30 | 60 | ||
| 61 | + /** | ||
| 62 | + * Subtracts occupied amounts from the authorized total amount. | ||
| 63 | + * @param context activated intent and mutable execution ledger | ||
| 64 | + * @return remaining global amount | ||
| 65 | + */ | ||
| 31 | static long leftAmount(IntentExecutionContext context) { | 66 | static long leftAmount(IntentExecutionContext context) { |
| 32 | return context.constraints().totalMaxAmount() - amount(context); | 67 | return context.constraints().totalMaxAmount() - amount(context); |
| 33 | } | 68 | } |
| 34 | 69 | ||
| 35 | // The global quota is permanently used up and nothing is pending, so an ACTIVE intent becomes CONSUMED. | 70 | // The global quota is permanently used up and nothing is pending, so an ACTIVE intent becomes CONSUMED. |
| 71 | + /** | ||
| 72 | + * Tests whether global amount or count quota is exhausted with no pending executions. | ||
| 73 | + * @param context activated intent and mutable execution ledger | ||
| 74 | + * @return true if global quota is exhausted and no execution is pending | ||
| 75 | + */ | ||
| 36 | static boolean exhausted(IntentExecutionContext context) { | 76 | static boolean exhausted(IntentExecutionContext context) { |
| 37 | boolean pending = context.ledger().stream() | 77 | boolean pending = context.ledger().stream() |
| 38 | .anyMatch(entry -> entry.record().status() == ExecutionStatus.PENDING); | 78 | .anyMatch(entry -> entry.record().status() == ExecutionStatus.PENDING); |
| @@ -41,15 +81,32 @@ final class Accounting { | |||
| 41 | return !pending && (countUsedUp || leftAmount(context) == 0); | 81 | return !pending && (countUsedUp || leftAmount(context) == 0); |
| 42 | } | 82 | } |
| 43 | 83 | ||
| 84 | + /** | ||
| 85 | + * Counts quota-occupying reservations assigned to the specified original period. | ||
| 86 | + * @param context activated intent and mutable execution ledger | ||
| 87 | + * @param period accounting period index, or null when periodic limits are absent | ||
| 88 | + * @return occupied execution count in the specified period | ||
| 89 | + */ | ||
| 44 | static long periodCount(IntentExecutionContext context, Long period) { | 90 | static long periodCount(IntentExecutionContext context, Long period) { |
| 45 | return context.ledger().stream().filter(Accounting::counted) | 91 | return context.ledger().stream().filter(Accounting::counted) |
| 46 | .filter(entry -> Objects.equals(entry.record().periodIndex(), period)).count(); | 92 | .filter(entry -> Objects.equals(entry.record().periodIndex(), period)).count(); |
| 47 | } | 93 | } |
| 48 | 94 | ||
| 95 | + /** | ||
| 96 | + * Refreshes the quota snapshot for the trusted evaluation instant without moving reservations between periods. | ||
| 97 | + * @param context activated intent and mutable execution ledger | ||
| 98 | + * @param now trusted non-negative Unix epoch milliseconds within the safe integer range | ||
| 99 | + */ | ||
| 49 | static void recompute(IntentExecutionContext context, long now) { | 100 | static void recompute(IntentExecutionContext context, long now) { |
| 50 | context.executionInfo(executionInfo(context, period(context.constraints(), now))); | 101 | context.executionInfo(executionInfo(context, period(context.constraints(), now))); |
| 51 | } | 102 | } |
| 52 | 103 | ||
| 104 | + /** | ||
| 105 | + * Computes remaining global and per-period quotas; unconfigured optional quotas are null. | ||
| 106 | + * @param context activated intent and mutable execution ledger | ||
| 107 | + * @param period accounting period index, or null when periodic limits are absent | ||
| 108 | + * @return quota snapshot without advancing its period | ||
| 109 | + */ | ||
| 53 | static PaymentExecutionInfo executionInfo(IntentExecutionContext context, Long period) { | 110 | static PaymentExecutionInfo executionInfo(IntentExecutionContext context, Long period) { |
| 54 | PaymentConstraints constraints = context.constraints(); | 111 | PaymentConstraints constraints = context.constraints(); |
| 55 | return new PaymentExecutionInfo( | 112 | return new PaymentExecutionInfo( |
| @@ -1,141 +0,0 @@ | |||
| 1 | -package io.openjiuwen.a4p; | ||
| 2 | - | ||
| 3 | -import com.fasterxml.jackson.databind.JsonNode; | ||
| 4 | -import io.openjiuwen.a4p.Models.*; | ||
| 5 | -import java.util.ArrayList; | ||
| 6 | -import java.util.LinkedHashMap; | ||
| 7 | -import java.util.List; | ||
| 8 | -import java.util.Map; | ||
| 9 | -import java.util.function.Consumer; | ||
| 10 | -import static io.openjiuwen.a4p.A4pErrorCode.*; | ||
| 11 | - | ||
| 12 | -// Serializes to canonical JSON; deserialization parses strictly and validates the whole chain. | ||
| 13 | -final class CanonicalIntentCodec implements A4pIntentCodec { | ||
| 14 | - static final CanonicalIntentCodec INSTANCE = new CanonicalIntentCodec(); | ||
| 15 | - | ||
| 16 | - // Wire form of a persisted context; reservedAt is boxed so a missing field is rejected instead of read as 0. | ||
| 17 | - record ContextJson(String version, String intentId, IntentL3 authorizedIntent, IntentExecutionStatus status, | ||
| 18 | - JsonNode executionInfo, List<RecordJson> executions, Long activatedTime) {} | ||
| 19 | - | ||
| 20 | - record RecordJson(String executionId, ExecutionStatus status, IntentActionType action, | ||
| 21 | - JsonNode executionContent, Long periodIndex, Long reservedAt, | ||
| 22 | - Long completedAt, Long canceledAt) {} | ||
| 23 | - | ||
| 24 | - private CanonicalIntentCodec() {} | ||
| 25 | - | ||
| 26 | - @Override | ||
| 27 | - public String serializeIntentL1(IntentL1 intentL1) { return serialize(intentL1); } | ||
| 28 | - | ||
| 29 | - @Override | ||
| 30 | - public String serializeIntentL2(IntentL2 intentL2) { return serialize(intentL2); } | ||
| 31 | - | ||
| 32 | - @Override | ||
| 33 | - public String serializeIntentL3(IntentL3 intentL3) { return serialize(intentL3); } | ||
| 34 | - | ||
| 35 | - @Override | ||
| 36 | - public A4pResult<IntentL1> deserializeIntentL1(String serialized) { | ||
| 37 | - return decode(serialized, IntentL1.class, Validation::intentL1); | ||
| 38 | - } | ||
| 39 | - | ||
| 40 | - @Override | ||
| 41 | - public A4pResult<IntentL2> deserializeIntentL2(String serialized) { | ||
| 42 | - return decode(serialized, IntentL2.class, Validation::intentL2); | ||
| 43 | - } | ||
| 44 | - | ||
| 45 | - @Override | ||
| 46 | - public A4pResult<IntentL3> deserializeIntentL3(String serialized) { | ||
| 47 | - return decode(serialized, IntentL3.class, Validation::intentL3); | ||
| 48 | - } | ||
| 49 | - | ||
| 50 | - @Override | ||
| 51 | - public String serializeIntentExecutionContext(IntentExecutionContext intentExecutionContext) { | ||
| 52 | - Validation.present(intentExecutionContext); | ||
| 53 | - Map<String, Object> fields = new LinkedHashMap<>(); | ||
| 54 | - // One lock for every field, so the ledger and executionInfo come from the same state. | ||
| 55 | - synchronized (intentExecutionContext) { | ||
| 56 | - fields.put("version", intentExecutionContext.version()); | ||
| 57 | - fields.put("intentId", intentExecutionContext.intentId()); | ||
| 58 | - fields.put("authorizedIntent", intentExecutionContext.authorizedIntent()); | ||
| 59 | - fields.put("activatedTime", intentExecutionContext.activatedTime()); | ||
| 60 | - fields.put("status", intentExecutionContext.status()); | ||
| 61 | - fields.put("executionInfo", intentExecutionContext.executionInfo()); | ||
| 62 | - fields.put("executions", intentExecutionContext.executions()); | ||
| 63 | - } | ||
| 64 | - return CanonicalJson.stringify(fields); | ||
| 65 | - } | ||
| 66 | - | ||
| 67 | - // The user signature is not re-verified; the stored L3 is checked like activateIntent's input otherwise. | ||
| 68 | - @Override | ||
| 69 | - public A4pResult<IntentExecutionContext> deserializeIntentExecutionContext(String serialized) { | ||
| 70 | - return A4pResult.capture(() -> restore(parse(serialized, ContextJson.class))); | ||
| 71 | - } | ||
| 72 | - | ||
| 73 | - private static IntentExecutionContext restore(ContextJson wire) { | ||
| 74 | - Validation.present(wire); | ||
| 75 | - Validation.text(wire.version()); | ||
| 76 | - Validation.version(wire.version()); | ||
| 77 | - IntentL3 authorized = wire.authorizedIntent(); | ||
| 78 | - Validation.intentL3(authorized); | ||
| 79 | - Validation.versions(authorized); | ||
| 80 | - IntentL1 intent = authorized.intentL2().intentL1(); | ||
| 81 | - Validation.require(intent.intentId().equals(wire.intentId()), A4P_INVALID_PARAMETER); | ||
| 82 | - Validation.integer(wire.activatedTime(), false); | ||
| 83 | - Validation.require(wire.activatedTime() >= authorized.timestamp(), A4P_INVALID_PARAMETER); | ||
| 84 | - Validation.present(wire.status()); | ||
| 85 | - Validation.present(wire.executions()); | ||
| 86 | - List<IntentExecutionContext.Entry> ledger = new ArrayList<>(); | ||
| 87 | - for (RecordJson record : wire.executions()) { | ||
| 88 | - Validation.present(record); | ||
| 89 | - Validation.integer(record.reservedAt(), false); | ||
| 90 | - Validation.require(record.reservedAt() >= wire.activatedTime(), A4P_INVALID_PARAMETER); | ||
| 91 | - Order order = Validation.execution(new Execution(record.action(), record.executionId(), | ||
| 92 | - record.executionContent())); | ||
| 93 | - ledger.add(new IntentExecutionContext.Entry(new ExecutionRecord(record.executionId(), record.status(), | ||
| 94 | - record.action(), record.executionContent(), record.periodIndex(), record.reservedAt(), | ||
| 95 | - record.completedAt(), record.canceledAt()), order)); | ||
| 96 | - } | ||
| 97 | - Long period = period(wire.executionInfo(), PaymentProfile.constraints(intent.structuredIntent())); | ||
| 98 | - IntentExecutionContext context = new IntentExecutionContext(authorized, wire.status(), ledger, period, wire.activatedTime()); | ||
| 99 | - Validation.ledger(context); | ||
| 100 | - // executionInfo is derived state, so it must match what the restored ledger yields. | ||
| 101 | - Validation.require(context.executionInfo().equals(CanonicalJson.freezeNode(wire.executionInfo())), | ||
| 102 | - A4P_INVALID_PARAMETER); | ||
| 103 | - return context; | ||
| 104 | - } | ||
| 105 | - | ||
| 106 | - // The period executionInfo was last recomputed in depends on call times the ledger does not record. | ||
| 107 | - private static Long period(JsonNode info, PaymentConstraints constraints) { | ||
| 108 | - Validation.require(info != null && info.isObject(), A4P_INVALID_PARAMETER); | ||
| 109 | - JsonNode period = info.get("periodIndex"); | ||
| 110 | - if (period == null || period.isNull()) { | ||
| 111 | - Validation.require(constraints.anchorTime() == null, A4P_INVALID_PARAMETER); | ||
| 112 | - return null; | ||
| 113 | - } | ||
| 114 | - Validation.require(constraints.anchorTime() != null && period.isIntegralNumber() && period.canConvertToLong(), | ||
| 115 | - A4P_INVALID_PARAMETER); | ||
| 116 | - return period.longValue(); | ||
| 117 | - } | ||
| 118 | - | ||
| 119 | - private static String serialize(Object intent) { | ||
| 120 | - Validation.present(intent); | ||
| 121 | - return CanonicalJson.stringify(intent); | ||
| 122 | - } | ||
| 123 | - | ||
| 124 | - private static <Value> A4pResult<Value> decode(String json, Class<Value> type, Consumer<Value> validate) { | ||
| 125 | - return A4pResult.capture(() -> { | ||
| 126 | - Value value = parse(json, type); | ||
| 127 | - validate.accept(value); | ||
| 128 | - return value; | ||
| 129 | - }); | ||
| 130 | - } | ||
| 131 | - | ||
| 132 | - private static <Value> Value parse(String json, Class<Value> type) { | ||
| 133 | - Validation.require(json != null && !json.isEmpty(), A4P_INVALID_PARAMETER); | ||
| 134 | - Object parsed = CanonicalJson.parse(json); | ||
| 135 | - try { | ||
| 136 | - return CanonicalJson.MAPPER.convertValue(parsed, type); | ||
| 137 | - } catch (IllegalArgumentException error) { | ||
| 138 | - throw new A4pException(A4P_INVALID_PARAMETER); | ||
| 139 | - } | ||
| 140 | - } | ||
| 141 | -} | ||
| @@ -29,8 +29,16 @@ import java.util.stream.Collectors; | |||
| 29 | 29 | ||
| 30 | import static io.openjiuwen.a4p.A4pErrorCode.*; | 30 | import static io.openjiuwen.a4p.A4pErrorCode.*; |
| 31 | 31 | ||
| 32 | -public final class CanonicalJson { | 32 | +/** |
| 33 | + * Implements deterministic protocol JSON and signing-byte normalization. | ||
| 34 | + * Object keys are sorted, array order is preserved, and insignificant whitespace is omitted. | ||
| 35 | + * Only safe integer numbers are supported; strings retain their Unicode data. | ||
| 36 | + * Parsing rejects duplicate keys and trailing tokens. Signing removes only the outer sign field. | ||
| 37 | + */ | ||
| 38 | +final class CanonicalJson { | ||
| 39 | + /** Largest integer exactly representable by JavaScript protocol peers. */ | ||
| 33 | public static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L; | 40 | public static final long MAX_SAFE_INTEGER = 9_007_199_254_740_991L; |
| 41 | + /** Strict shared mapper used for protocol JSON parsing and conversion. */ | ||
| 34 | static final JsonMapper MAPPER = JsonMapper.builder(JsonFactory.builder() | 42 | static final JsonMapper MAPPER = JsonMapper.builder(JsonFactory.builder() |
| 35 | .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) | 43 | .enable(StreamReadFeature.STRICT_DUPLICATE_DETECTION).build()) |
| 36 | .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) | 44 | .disable(MapperFeature.ALLOW_COERCION_OF_SCALARS) |
| @@ -40,8 +48,16 @@ public final class CanonicalJson { | |||
| 40 | .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) | 48 | .enable(DeserializationFeature.USE_BIG_DECIMAL_FOR_FLOATS) |
| 41 | .build(); | 49 | .build(); |
| 42 | 50 | ||
| 51 | + /** | ||
| 52 | + * Prevents instantiation of this utility class. | ||
| 53 | + */ | ||
| 43 | private CanonicalJson() {} | 54 | private CanonicalJson() {} |
| 44 | 55 | ||
| 56 | + /** | ||
| 57 | + * Serializes a supported protocol value as deterministic compact JSON with sorted object keys. | ||
| 58 | + * @param value value to validate or normalize | ||
| 59 | + * @return compact canonical JSON | ||
| 60 | + */ | ||
| 45 | public static String stringify(Object value) { | 61 | public static String stringify(Object value) { |
| 46 | try { | 62 | try { |
| 47 | return render(normalize(value, new IdentityHashMap<>(), 0)); | 63 | return render(normalize(value, new IdentityHashMap<>(), 0)); |
| @@ -52,6 +68,12 @@ public final class CanonicalJson { | |||
| 52 | } | 68 | } |
| 53 | } | 69 | } |
| 54 | 70 | ||
| 71 | + /** | ||
| 72 | + * Returns canonical UTF-8 bytes after removing only the outer sign field. | ||
| 73 | + * Embedded intent signatures remain covered by the enclosing signature. | ||
| 74 | + * @param intent protocol intent to process | ||
| 75 | + * @return canonical UTF-8 bytes excluding only the outer sign field | ||
| 76 | + */ | ||
| 55 | public static byte[] toSignableBytes(Object intent) { | 77 | public static byte[] toSignableBytes(Object intent) { |
| 56 | Object normalized = normalize(intent, new IdentityHashMap<>(), 0); | 78 | Object normalized = normalize(intent, new IdentityHashMap<>(), 0); |
| 57 | if (!(normalized instanceof Map<?, ?> fields)) { | 79 | if (!(normalized instanceof Map<?, ?> fields)) { |
| @@ -62,10 +84,20 @@ public final class CanonicalJson { | |||
| 62 | return encodeUtf8(stringify(unsigned)); | 84 | return encodeUtf8(stringify(unsigned)); |
| 63 | } | 85 | } |
| 64 | 86 | ||
| 87 | + /** | ||
| 88 | + * Encodes bytes as unpadded Base64URL. | ||
| 89 | + * @param data bytes to encode | ||
| 90 | + * @return unpadded Base64URL text | ||
| 91 | + */ | ||
| 65 | public static String base64UrlEncode(byte[] data) { | 92 | public static String base64UrlEncode(byte[] data) { |
| 66 | return Base64.getUrlEncoder().withoutPadding().encodeToString(data); | 93 | return Base64.getUrlEncoder().withoutPadding().encodeToString(data); |
| 67 | } | 94 | } |
| 68 | 95 | ||
| 96 | + /** | ||
| 97 | + * Decodes canonical unpadded Base64URL and rejects noncanonical or invalid encodings. | ||
| 98 | + * @param data canonical unpadded Base64URL text | ||
| 99 | + * @return decoded bytes | ||
| 100 | + */ | ||
| 69 | public static byte[] base64UrlDecode(String data) { | 101 | public static byte[] base64UrlDecode(String data) { |
| 70 | try { | 102 | try { |
| 71 | if (data == null || !data.matches("[A-Za-z0-9_-]*")) { | 103 | if (data == null || !data.matches("[A-Za-z0-9_-]*")) { |
| @@ -81,6 +113,11 @@ public final class CanonicalJson { | |||
| 81 | } | 113 | } |
| 82 | } | 114 | } |
| 83 | 115 | ||
| 116 | + /** | ||
| 117 | + * Encodes a string as UTF-8, rejecting malformed surrogate sequences. | ||
| 118 | + * @param data Unicode string to encode | ||
| 119 | + * @return strict UTF-8 encoding | ||
| 120 | + */ | ||
| 84 | public static byte[] encodeUtf8(String data) { | 121 | public static byte[] encodeUtf8(String data) { |
| 85 | try { | 122 | try { |
| 86 | ByteBuffer encoded = StandardCharsets.UTF_8.newEncoder() | 123 | ByteBuffer encoded = StandardCharsets.UTF_8.newEncoder() |
| @@ -93,6 +130,11 @@ public final class CanonicalJson { | |||
| 93 | } | 130 | } |
| 94 | } | 131 | } |
| 95 | 132 | ||
| 133 | + /** | ||
| 134 | + * Decodes UTF-8 strictly and rejects malformed byte sequences. | ||
| 135 | + * @param data UTF-8 bytes to decode | ||
| 136 | + * @return decoded Unicode string | ||
| 137 | + */ | ||
| 96 | public static String decodeUtf8(byte[] data) { | 138 | public static String decodeUtf8(byte[] data) { |
| 97 | try { | 139 | try { |
| 98 | return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) | 140 | return StandardCharsets.UTF_8.newDecoder().onMalformedInput(CodingErrorAction.REPORT) |
| @@ -102,6 +144,11 @@ public final class CanonicalJson { | |||
| 102 | } | 144 | } |
| 103 | } | 145 | } |
| 104 | 146 | ||
| 147 | + /** | ||
| 148 | + * Parses JSON with duplicate-key and trailing-token detection. | ||
| 149 | + * @param json JSON representation to parse | ||
| 150 | + * @return decoded or parsed value | ||
| 151 | + */ | ||
| 105 | static Object parse(String json) { | 152 | static Object parse(String json) { |
| 106 | try { | 153 | try { |
| 107 | return MAPPER.readValue(json, Object.class); | 154 | return MAPPER.readValue(json, Object.class); |
| @@ -110,12 +157,23 @@ public final class CanonicalJson { | |||
| 110 | } | 157 | } |
| 111 | } | 158 | } |
| 112 | 159 | ||
| 160 | + /** | ||
| 161 | + * Creates a recursively normalized immutable snapshot of a nullable map. | ||
| 162 | + * @param source map to snapshot, or null | ||
| 163 | + * @return immutable normalized map, or null | ||
| 164 | + * @throws A4pException if a value cannot be represented by canonical protocol JSON | ||
| 165 | + */ | ||
| 113 | @SuppressWarnings("unchecked") | 166 | @SuppressWarnings("unchecked") |
| 114 | static Map<String, Object> freezeMap(Map<String, Object> source) { | 167 | static Map<String, Object> freezeMap(Map<String, Object> source) { |
| 115 | return source == null ? null : (Map<String, Object>) normalize(source, new IdentityHashMap<>(), 0); | 168 | return source == null ? null : (Map<String, Object>) normalize(source, new IdentityHashMap<>(), 0); |
| 116 | } | 169 | } |
| 117 | 170 | ||
| 118 | // Deep copy that stores every integral number as a long, so equal payloads compare equal after a round trip. | 171 | // Deep copy that stores every integral number as a long, so equal payloads compare equal after a round trip. |
| 172 | + /** | ||
| 173 | + * Copies a JSON tree defensively and normalizes integral nodes representable as long. | ||
| 174 | + * @param node JSON tree to inspect or decode | ||
| 175 | + * @return defensive JSON copy, or null | ||
| 176 | + */ | ||
| 119 | static JsonNode freezeNode(JsonNode node) { | 177 | static JsonNode freezeNode(JsonNode node) { |
| 120 | if (node == null) { return null; } | 178 | if (node == null) { return null; } |
| 121 | if (node.isIntegralNumber() && node.canConvertToLong()) { return LongNode.valueOf(node.longValue()); } | 179 | if (node.isIntegralNumber() && node.canConvertToLong()) { return LongNode.valueOf(node.longValue()); } |
| @@ -132,6 +190,13 @@ public final class CanonicalJson { | |||
| 132 | return node.deepCopy(); | 190 | return node.deepCopy(); |
| 133 | } | 191 | } |
| 134 | 192 | ||
| 193 | + /** | ||
| 194 | + * Converts a JSON tree to normalized protocol scalars and immutable containers. | ||
| 195 | + * @param node JSON tree to inspect or decode | ||
| 196 | + * @param ancestors identity set used to detect reference cycles | ||
| 197 | + * @param depth current normalization nesting depth | ||
| 198 | + * @return normalized scalar or immutable container | ||
| 199 | + */ | ||
| 135 | private static Object normalizeNode(JsonNode node, IdentityHashMap<Object, Boolean> ancestors, int depth) { | 200 | private static Object normalizeNode(JsonNode node, IdentityHashMap<Object, Boolean> ancestors, int depth) { |
| 136 | if (node.isNull()) { return null; } | 201 | if (node.isNull()) { return null; } |
| 137 | if (node.isTextual()) { return node.textValue(); } | 202 | if (node.isTextual()) { return node.textValue(); } |
| @@ -151,6 +216,14 @@ public final class CanonicalJson { | |||
| 151 | throw new A4pException(A4P_SERIALIZE_FAIL); | 216 | throw new A4pException(A4P_SERIALIZE_FAIL); |
| 152 | } | 217 | } |
| 153 | 218 | ||
| 219 | + /** | ||
| 220 | + * Normalizes safe integers, protocol records and supported containers. | ||
| 221 | + * Rejects unsupported types, cyclic object graphs and nesting deeper than 100. | ||
| 222 | + * @param value value to validate or normalize | ||
| 223 | + * @param ancestors identity set used to detect reference cycles | ||
| 224 | + * @param depth current normalization nesting depth | ||
| 225 | + * @return normalized protocol value | ||
| 226 | + */ | ||
| 154 | private static Object normalize(Object value, IdentityHashMap<Object, Boolean> ancestors, int depth) { | 227 | private static Object normalize(Object value, IdentityHashMap<Object, Boolean> ancestors, int depth) { |
| 155 | if (depth > 100) { | 228 | if (depth > 100) { |
| 156 | throw new A4pException(A4P_SERIALIZE_FAIL); | 229 | throw new A4pException(A4P_SERIALIZE_FAIL); |
| @@ -214,6 +287,11 @@ public final class CanonicalJson { | |||
| 214 | } | 287 | } |
| 215 | } | 288 | } |
| 216 | 289 | ||
| 290 | + /** | ||
| 291 | + * Renders a normalized value as compact deterministic JSON. | ||
| 292 | + * @param value value to validate or normalize | ||
| 293 | + * @return compact JSON representation | ||
| 294 | + */ | ||
| 217 | private static String render(Object value) { | 295 | private static String render(Object value) { |
| 218 | if (value == null) { return "null"; } | 296 | if (value == null) { return "null"; } |
| 219 | if (value instanceof String text) { return quote(text); } | 297 | if (value instanceof String text) { return quote(text); } |
| @@ -228,6 +306,11 @@ public final class CanonicalJson { | |||
| 228 | return value.toString(); | 306 | return value.toString(); |
| 229 | } | 307 | } |
| 230 | 308 | ||
| 309 | + /** | ||
| 310 | + * Quotes a valid Unicode string using JSON escapes without Unicode normalization. | ||
| 311 | + * @param text string to quote | ||
| 312 | + * @return JSON string literal | ||
| 313 | + */ | ||
| 231 | private static String quote(String text) { | 314 | private static String quote(String text) { |
| 232 | encodeUtf8(text); | 315 | encodeUtf8(text); |
| 233 | StringBuilder result = new StringBuilder("\""); | 316 | StringBuilder result = new StringBuilder("\""); |
| @@ -7,13 +7,32 @@ import java.util.Set; | |||
| 7 | import static io.openjiuwen.a4p.A4pErrorCode.*; | 7 | import static io.openjiuwen.a4p.A4pErrorCode.*; |
| 8 | 8 | ||
| 9 | // Each execution buys exactly one product per disjoint whitelist group, at its declared quantity. | 9 | // Each execution buys exactly one product per disjoint whitelist group, at its declared quantity. |
| 10 | +/** | ||
| 11 | + * Validates exact one-to-one matching between cart entries and disjoint whitelist groups. | ||
| 12 | + * Each execution chooses one authorized product from every group at that group quantity. | ||
| 13 | + */ | ||
| 10 | final class CartMatching { | 14 | final class CartMatching { |
| 15 | + /** | ||
| 16 | + * Prevents instantiation of this utility class. | ||
| 17 | + */ | ||
| 11 | private CartMatching() {} | 18 | private CartMatching() {} |
| 12 | 19 | ||
| 20 | + /** | ||
| 21 | + * Checks exact product membership, including seller and SPU/SKU identity, in a whitelist group. | ||
| 22 | + * @param group authorized alternative-product group | ||
| 23 | + * @param product seller and SPU/SKU product identity | ||
| 24 | + * @return true if the exact product is in the group | ||
| 25 | + */ | ||
| 13 | static boolean matches(ItemWhiteList group, Product product) { | 26 | static boolean matches(ItemWhiteList group, Product product) { |
| 14 | return group.whiteList().contains(product); | 27 | return group.whiteList().contains(product); |
| 15 | } | 28 | } |
| 16 | 29 | ||
| 30 | + /** | ||
| 31 | + * Requires one cart product from each disjoint group with its exact template quantity. | ||
| 32 | + * Checks unauthorized products before cart shape to preserve protocol error precedence. | ||
| 33 | + * @param items cart entries to validate | ||
| 34 | + * @param groups disjoint authorized product groups | ||
| 35 | + */ | ||
| 17 | static void requireOneToOne(List<CartItem> items, List<ItemWhiteList> groups) { | 36 | static void requireOneToOne(List<CartItem> items, List<ItemWhiteList> groups) { |
| 18 | // Scope is checked before template shape, matching ArkTS error precedence. | 37 | // Scope is checked before template shape, matching ArkTS error precedence. |
| 19 | for (CartItem item : items) { | 38 | for (CartItem item : items) { |
| @@ -6,24 +6,60 @@ import io.openjiuwen.a4p.Models.*; | |||
| 6 | import java.util.ArrayList; | 6 | import java.util.ArrayList; |
| 7 | import java.util.List; | 7 | import java.util.List; |
| 8 | 8 | ||
| 9 | +/** | ||
| 10 | + * Maintains an authorized L3 intent, activation time, execution ledger and quota snapshot. | ||
| 11 | + * Obtain contexts through activation or a validated codec. Persist after every operation returning a context, | ||
| 12 | + * including failed reservations that mark it EXPIRED. Applications must serialize read-update-write cycles | ||
| 13 | + * for the same intent in a database transaction; in-memory synchronization alone is insufficient. | ||
| 14 | + * Quota snapshots change on execution operations, not on reads. Context JSON is for local persistence only | ||
| 15 | + * and requires application-level integrity protection where needed. | ||
| 16 | + * @see A4p | ||
| 17 | + */ | ||
| 9 | public final class IntentExecutionContext { | 18 | public final class IntentExecutionContext { |
| 19 | + /** Authorized L3 snapshot bound to this context. */ | ||
| 10 | private final IntentL3 authorizedIntent; | 20 | private final IntentL3 authorizedIntent; |
| 21 | + /** Activation instant in Unix epoch milliseconds. */ | ||
| 11 | private final long activatedTime; | 22 | private final long activatedTime; |
| 23 | + /** Decoded payment resource whitelist. */ | ||
| 12 | private final ShoppingItems resources; | 24 | private final ShoppingItems resources; |
| 25 | + /** Decoded payment constraints. */ | ||
| 13 | private final PaymentConstraints constraints; | 26 | private final PaymentConstraints constraints; |
| 27 | + /** Current intent execution state. */ | ||
| 14 | private IntentExecutionStatus status = IntentExecutionStatus.ACTIVE; | 28 | private IntentExecutionStatus status = IntentExecutionStatus.ACTIVE; |
| 29 | + /** Mutable ledger of reserved and finalized executions. */ | ||
| 15 | private final List<Entry> ledger = new ArrayList<>(); | 30 | private final List<Entry> ledger = new ArrayList<>(); |
| 31 | + /** Quota snapshot for the most recent accounting evaluation. */ | ||
| 16 | private PaymentExecutionInfo executionInfo; | 32 | private PaymentExecutionInfo executionInfo; |
| 17 | 33 | ||
| 18 | // A ledger record together with its parsed AI_PAY order. | 34 | // A ledger record together with its parsed AI_PAY order. |
| 35 | + /** | ||
| 36 | + * Pairs an execution ledger record with its decoded payment order. | ||
| 37 | + * @param record execution ledger record | ||
| 38 | + * @param order payment order | ||
| 39 | + */ | ||
| 19 | record Entry(ExecutionRecord record, Order order) {} | 40 | record Entry(ExecutionRecord record, Order order) {} |
| 20 | 41 | ||
| 42 | + /** | ||
| 43 | + * Initializes an execution context from an authorized L3 intent and activation time. | ||
| 44 | + * Restoration overloads retain the supplied ledger and recompute the stored accounting period. | ||
| 45 | + * @param authorizedIntent authorized L3 snapshot | ||
| 46 | + * @param now trusted non-negative Unix epoch milliseconds within the safe integer range | ||
| 47 | + */ | ||
| 21 | IntentExecutionContext(IntentL3 authorizedIntent, long now) { | 48 | IntentExecutionContext(IntentL3 authorizedIntent, long now) { |
| 22 | this(now, authorizedIntent); | 49 | this(now, authorizedIntent); |
| 23 | Accounting.recompute(this, now); | 50 | Accounting.recompute(this, now); |
| 24 | } | 51 | } |
| 25 | 52 | ||
| 26 | // Restores a persisted context; executionInfo is recomputed for the period it was last computed in. | 53 | // Restores a persisted context; executionInfo is recomputed for the period it was last computed in. |
| 54 | + /** | ||
| 55 | + * Initializes an execution context from an authorized L3 intent and activation time. | ||
| 56 | + * Restoration overloads retain the supplied ledger and recompute the stored accounting period. | ||
| 57 | + * @param authorizedIntent authorized L3 snapshot | ||
| 58 | + * @param status context execution state | ||
| 59 | + * @param ledger execution records paired with decoded orders | ||
| 60 | + * @param period accounting period index, or null when periodic limits are absent | ||
| 61 | + * @param activatedTime activation instant in Unix epoch milliseconds | ||
| 62 | + */ | ||
| 27 | IntentExecutionContext(IntentL3 authorizedIntent, IntentExecutionStatus status, List<Entry> ledger, | 63 | IntentExecutionContext(IntentL3 authorizedIntent, IntentExecutionStatus status, List<Entry> ledger, |
| 28 | Long period, long activatedTime) { | 64 | Long period, long activatedTime) { |
| 29 | this(activatedTime, authorizedIntent); | 65 | this(activatedTime, authorizedIntent); |
| @@ -32,6 +68,12 @@ public final class IntentExecutionContext { | |||
| 32 | this.executionInfo = Accounting.executionInfo(this, period); | 68 | this.executionInfo = Accounting.executionInfo(this, period); |
| 33 | } | 69 | } |
| 34 | 70 | ||
| 71 | + /** | ||
| 72 | + * Initializes an execution context from an authorized L3 intent and activation time. | ||
| 73 | + * Restoration overloads retain the supplied ledger and recompute the stored accounting period. | ||
| 74 | + * @param activatedTime activation instant in Unix epoch milliseconds | ||
| 75 | + * @param authorizedIntent authorized L3 snapshot | ||
| 76 | + */ | ||
| 35 | private IntentExecutionContext(long activatedTime, IntentL3 authorizedIntent) { | 77 | private IntentExecutionContext(long activatedTime, IntentL3 authorizedIntent) { |
| 36 | this.activatedTime = activatedTime; | 78 | this.activatedTime = activatedTime; |
| 37 | this.authorizedIntent = authorizedIntent; | 79 | this.authorizedIntent = authorizedIntent; |
| @@ -40,16 +82,44 @@ public final class IntentExecutionContext { | |||
| 40 | this.constraints = PaymentProfile.constraints(intent); | 82 | this.constraints = PaymentProfile.constraints(intent); |
| 41 | } | 83 | } |
| 42 | 84 | ||
| 43 | - /** Activation instant in epoch milliseconds, preserved by the context codec. */ | 85 | + /** |
| 86 | + * Returns the activation instant in epoch milliseconds, preserved across serialization. | ||
| 87 | + * @return activation instant in epoch milliseconds | ||
| 88 | + */ | ||
| 44 | public long activatedTime() { return activatedTime; } | 89 | public long activatedTime() { return activatedTime; } |
| 45 | 90 | ||
| 91 | + /** | ||
| 92 | + * Returns the supported protocol version. | ||
| 93 | + * @return protocol version | ||
| 94 | + */ | ||
| 46 | public String version() { return A4p.PROTOCOL_VERSION; } | 95 | public String version() { return A4p.PROTOCOL_VERSION; } |
| 96 | + /** | ||
| 97 | + * Returns the identifier of the authorized intent. | ||
| 98 | + * @return associated intent identifier | ||
| 99 | + */ | ||
| 47 | public String intentId() { return authorizedIntent.intentL2().intentL1().intentId(); } | 100 | public String intentId() { return authorizedIntent.intentL2().intentL1().intentId(); } |
| 101 | + /** | ||
| 102 | + * Returns the authorized L3 snapshot associated with this context. | ||
| 103 | + * @return authorized L3 snapshot | ||
| 104 | + */ | ||
| 48 | public IntentL3 authorizedIntent() { return authorizedIntent; } | 105 | public IntentL3 authorizedIntent() { return authorizedIntent; } |
| 106 | + /** | ||
| 107 | + * Returns the current execution status without evaluating expiry. | ||
| 108 | + * @return current context state | ||
| 109 | + */ | ||
| 49 | public synchronized IntentExecutionStatus status() { return status; } | 110 | public synchronized IntentExecutionStatus status() { return status; } |
| 111 | + /** | ||
| 112 | + * Returns an immutable snapshot of the execution ledger, including canceled records. | ||
| 113 | + * @return immutable ledger snapshot | ||
| 114 | + */ | ||
| 50 | public synchronized List<ExecutionRecord> executions() { return ledger.stream().map(Entry::record).toList(); } | 115 | public synchronized List<ExecutionRecord> executions() { return ledger.stream().map(Entry::record).toList(); } |
| 51 | 116 | ||
| 52 | // Typed union: the action selects the schema; read it as PaymentExecutionInfo via PaymentProfile. | 117 | // Typed union: the action selects the schema; read it as PaymentExecutionInfo via PaymentProfile. |
| 118 | + /** | ||
| 119 | + * Returns a defensive JSON snapshot of remaining quotas, omitting absent optional figures. | ||
| 120 | + * Reading does not advance the accounting period. | ||
| 121 | + * @return quota snapshot without advancing its period | ||
| 122 | + */ | ||
| 53 | public synchronized JsonNode executionInfo() { | 123 | public synchronized JsonNode executionInfo() { |
| 54 | ObjectNode fields = CanonicalJson.MAPPER.createObjectNode(); | 124 | ObjectNode fields = CanonicalJson.MAPPER.createObjectNode(); |
| 55 | fields.put("leftAmount", executionInfo.leftAmount()); | 125 | fields.put("leftAmount", executionInfo.leftAmount()); |
| @@ -65,10 +135,34 @@ public final class IntentExecutionContext { | |||
| 65 | return fields; | 135 | return fields; |
| 66 | } | 136 | } |
| 67 | 137 | ||
| 138 | + /** | ||
| 139 | + * Returns the current typed payment quota snapshot without advancing its period. | ||
| 140 | + * @return current typed quota snapshot | ||
| 141 | + */ | ||
| 68 | synchronized PaymentExecutionInfo paymentExecutionInfo() { return executionInfo; } | 142 | synchronized PaymentExecutionInfo paymentExecutionInfo() { return executionInfo; } |
| 143 | + /** | ||
| 144 | + * Replaces the internal context state; callers must hold the context lock. | ||
| 145 | + * @param status context execution state | ||
| 146 | + */ | ||
| 69 | void status(IntentExecutionStatus status) { this.status = status; } | 147 | void status(IntentExecutionStatus status) { this.status = status; } |
| 148 | + /** | ||
| 149 | + * Replaces the internal quota snapshot; callers must hold the context lock. | ||
| 150 | + * @param info quota accounting snapshot | ||
| 151 | + */ | ||
| 70 | void executionInfo(PaymentExecutionInfo info) { this.executionInfo = info; } | 152 | void executionInfo(PaymentExecutionInfo info) { this.executionInfo = info; } |
| 153 | + /** | ||
| 154 | + * Returns the mutable internal ledger; callers must coordinate context access. | ||
| 155 | + * @return mutable internal ledger | ||
| 156 | + */ | ||
| 71 | List<Entry> ledger() { return ledger; } | 157 | List<Entry> ledger() { return ledger; } |
| 158 | + /** | ||
| 159 | + * Returns the payment resources decoded from the authorized intent. | ||
| 160 | + * @return decoded payment resources | ||
| 161 | + */ | ||
| 72 | ShoppingItems resources() { return resources; } | 162 | ShoppingItems resources() { return resources; } |
| 163 | + /** | ||
| 164 | + * Returns the payment constraints decoded from the authorized intent. | ||
| 165 | + * @return decoded payment constraints | ||
| 166 | + */ | ||
| 73 | PaymentConstraints constraints() { return constraints; } | 167 | PaymentConstraints constraints() { return constraints; } |
| 74 | } | 168 | } |
| @@ -6,105 +6,391 @@ import java.util.Collections; | |||
| 6 | import java.util.List; | 6 | import java.util.List; |
| 7 | import java.util.Map; | 7 | import java.util.Map; |
| 8 | 8 | ||
| 9 | +/** | ||
| 10 | + * Contains the protocol records and enums used by the A4P Java SDK. | ||
| 11 | + * Record constructors describe data, but do not replace lifecycle validation or authorization. | ||
| 12 | + * Use A4p to create layered intents and PaymentProfile to construct AI_PAY payloads. | ||
| 13 | + * Amounts use application-defined minor currency units; protocol numbers are safe integers. | ||
| 14 | + * Optional components use null and are omitted from canonical record JSON. | ||
| 15 | + * Collections are copied, maps are frozen, and JSON payload accessors return defensive copies. | ||
| 16 | + * @see PaymentProfile | ||
| 17 | + */ | ||
| 9 | public final class Models { | 18 | public final class Models { |
| 19 | + /** | ||
| 20 | + * Prevents instantiation of this utility class. | ||
| 21 | + */ | ||
| 10 | private Models() {} | 22 | private Models() {} |
| 11 | 23 | ||
| 12 | // Every enum is serialized by name, e.g. "AI_PAY". | 24 | // Every enum is serialized by name, e.g. "AI_PAY". |
| 13 | - public enum IntentActionType { AI_PAY } | 25 | + /** |
| 26 | + * Defines supported action discriminators; enum names are serialized as strings. | ||
| 27 | + */ | ||
| 28 | + public enum IntentActionType { | ||
| 29 | + /** Authorizes AI-initiated payment using the payment resource and constraint schemas. */ | ||
| 30 | + AI_PAY | ||
| 31 | + } | ||
| 14 | 32 | ||
| 15 | - public enum AlgorithmType { RSA3072 } | 33 | + /** |
| 34 | + * Defines supported signature algorithm identifiers. | ||
| 35 | + */ | ||
| 36 | + public enum AlgorithmType { | ||
| 37 | + /** Identifies the RSA-3072 signing algorithm supported by this protocol version. */ | ||
| 38 | + RSA3072 | ||
| 39 | + } | ||
| 16 | 40 | ||
| 17 | - public enum IntentExecutionStatus { ACTIVE, CONSUMED, REVOKED, EXPIRED } | 41 | + /** |
| 42 | + * Defines context states: ACTIVE accepts reservations; CONSUMED has exhausted global quota with no pending records. | ||
| 43 | + * REVOKED and EXPIRED reject new reservations but allow finalization of existing pending records. | ||
| 44 | + */ | ||
| 45 | + public enum IntentExecutionStatus { | ||
| 46 | + /** Accepts new reservations within the validity window and remaining quotas. */ | ||
| 47 | + ACTIVE, | ||
| 48 | + /** Has exhausted a global quota and has no pending executions. */ | ||
| 49 | + CONSUMED, | ||
| 50 | + /** Rejects new reservations while allowing existing pending records to be finalized. */ | ||
| 51 | + REVOKED, | ||
| 52 | + /** Rejects new reservations after expiry while allowing pending records to be finalized. */ | ||
| 53 | + EXPIRED | ||
| 54 | + } | ||
| 18 | 55 | ||
| 19 | - public enum ExecutionStatus { PENDING, COMPLETED, CANCELED } | 56 | + /** |
| 57 | + * Defines execution states: PENDING occupies quota, COMPLETED retains usage, and CANCELED releases usage. | ||
| 58 | + */ | ||
| 59 | + public enum ExecutionStatus { | ||
| 60 | + /** Reserves amount and execution-count quotas while awaiting an external outcome. */ | ||
| 61 | + PENDING, | ||
| 62 | + /** Confirms execution and retains occupied quotas. */ | ||
| 63 | + COMPLETED, | ||
| 64 | + /** Releases occupied quotas while retaining the record and its identifiers. */ | ||
| 65 | + CANCELED | ||
| 66 | + } | ||
| 20 | 67 | ||
| 21 | // AI_PAY payload types; PaymentProfile maps them to and from the JsonNode fields below. | 68 | // AI_PAY payload types; PaymentProfile maps them to and from the JsonNode fields below. |
| 69 | + /** | ||
| 70 | + * Identifies the authorized seller. | ||
| 71 | + * @param id nonblank identity identifier | ||
| 72 | + */ | ||
| 22 | public record SellerInfo(String id) {} | 73 | public record SellerInfo(String id) {} |
| 74 | + /** | ||
| 75 | + * Identifies a product by SPU, SKU or both; at least one identifier must be nonblank. | ||
| 76 | + * @param spuId SPU identifier; optional when skuId is present | ||
| 77 | + * @param skuId SKU identifier; optional when spuId is present | ||
| 78 | + */ | ||
| 23 | public record SpuSkuInfo(String spuId, String skuId) {} | 79 | public record SpuSkuInfo(String spuId, String skuId) {} |
| 80 | + /** | ||
| 81 | + * Combines seller and product identifiers for exact whitelist matching. | ||
| 82 | + * @param seller authorized seller identity | ||
| 83 | + * @param spusku SPU and SKU product identity | ||
| 84 | + */ | ||
| 24 | public record Product(SellerInfo seller, SpuSkuInfo spusku) {} | 85 | public record Product(SellerInfo seller, SpuSkuInfo spusku) {} |
| 86 | + /** | ||
| 87 | + * Specifies one selected product and its positive per-order quantity. | ||
| 88 | + * @param product seller and SPU/SKU product identity | ||
| 89 | + * @param quantity positive quantity required for each execution | ||
| 90 | + */ | ||
| 25 | public record CartItem(Product product, Long quantity) {} | 91 | public record CartItem(Product product, Long quantity) {} |
| 26 | 92 | ||
| 27 | // Per-execution template quantity, not a lifetime quota. Products must be unique across all groups. | 93 | // Per-execution template quantity, not a lifetime quota. Products must be unique across all groups. |
| 94 | + /** | ||
| 95 | + * Defines alternative products (OR) and the exact quantity required for this group in each execution. | ||
| 96 | + * Groups form an AND template, and products must be disjoint across groups; quantities are not lifetime quotas. | ||
| 97 | + * @param whiteList alternative authorized products in this group | ||
| 98 | + * @param quantity positive quantity required for each execution | ||
| 99 | + */ | ||
| 28 | public record ItemWhiteList(List<Product> whiteList, Long quantity) { | 100 | public record ItemWhiteList(List<Product> whiteList, Long quantity) { |
| 101 | + /** | ||
| 102 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 103 | + * @param whiteList alternative authorized products in this group | ||
| 104 | + * @param quantity positive quantity required for each execution | ||
| 105 | + */ | ||
| 29 | public ItemWhiteList { whiteList = snapshot(whiteList); } | 106 | public ItemWhiteList { whiteList = snapshot(whiteList); } |
| 30 | } | 107 | } |
| 31 | 108 | ||
| 109 | + /** | ||
| 110 | + * Defines all required payment whitelist groups (AND); each execution selects one product from every group. | ||
| 111 | + * @param itemsWhiteList all required, mutually disjoint whitelist groups | ||
| 112 | + */ | ||
| 32 | public record ShoppingItems(List<ItemWhiteList> itemsWhiteList) { | 113 | public record ShoppingItems(List<ItemWhiteList> itemsWhiteList) { |
| 114 | + /** | ||
| 115 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 116 | + * @param itemsWhiteList all required, mutually disjoint whitelist groups | ||
| 117 | + */ | ||
| 33 | public ShoppingItems { itemsWhiteList = snapshot(itemsWhiteList); } | 118 | public ShoppingItems { itemsWhiteList = snapshot(itemsWhiteList); } |
| 34 | } | 119 | } |
| 35 | 120 | ||
| 121 | + /** | ||
| 122 | + * Defines AI_PAY amount, currency, validity and execution-count limits. | ||
| 123 | + * Amounts are positive integers in application-defined minor currency units. | ||
| 124 | + * Periodic settings must be supplied together or all omitted; anchorTime must be at or before validFrom, | ||
| 125 | + * and periodSeconds must be positive and no greater than 9007199254740. | ||
| 126 | + * @param singleOrderMaxAmount optional positive amount cap for each order | ||
| 127 | + * @param totalMaxAmount positive global authorized amount cap | ||
| 128 | + * @param currency nonblank currency shared by constraints and orders | ||
| 129 | + * @param validFrom inclusive authorization start in Unix epoch milliseconds | ||
| 130 | + * @param validUntil inclusive authorization end in Unix epoch milliseconds | ||
| 131 | + * @param maxExecutionCount optional positive global count cap | ||
| 132 | + * @param anchorTime optional period anchor in epoch milliseconds, no later than validFrom | ||
| 133 | + * @param periodSeconds optional positive period length in seconds | ||
| 134 | + * @param maxExecutionCountPerPeriod optional positive count cap for each period | ||
| 135 | + */ | ||
| 36 | public record PaymentConstraints(Long singleOrderMaxAmount, Long totalMaxAmount, String currency, | 136 | public record PaymentConstraints(Long singleOrderMaxAmount, Long totalMaxAmount, String currency, |
| 37 | Long validFrom, Long validUntil, Long maxExecutionCount, | 137 | Long validFrom, Long validUntil, Long maxExecutionCount, |
| 38 | Long anchorTime, Long periodSeconds, Long maxExecutionCountPerPeriod) {} | 138 | Long anchorTime, Long periodSeconds, Long maxExecutionCountPerPeriod) {} |
| 39 | 139 | ||
| 140 | + /** | ||
| 141 | + * Describes a payment order and its cart. | ||
| 142 | + * The trusted SDK evaluation clock, rather than this order timestamp, controls validity and quota periods. | ||
| 143 | + * @param orderId nonblank payment idempotency key, unique within the context even after cancellation | ||
| 144 | + * @param amount positive payment amount in application-defined minor currency units | ||
| 145 | + * @param currency nonblank currency shared by constraints and orders | ||
| 146 | + * @param cartItems one selected product per whitelist group at its declared quantity | ||
| 147 | + * @param timestamp order timestamp in epoch milliseconds; not the trusted quota clock | ||
| 148 | + */ | ||
| 40 | public record Order(String orderId, Long amount, String currency, List<CartItem> cartItems, Long timestamp) { | 149 | public record Order(String orderId, Long amount, String currency, List<CartItem> cartItems, Long timestamp) { |
| 150 | + /** | ||
| 151 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 152 | + * @param orderId nonblank payment idempotency key, unique within the context even after cancellation | ||
| 153 | + * @param amount positive payment amount in application-defined minor currency units | ||
| 154 | + * @param currency nonblank currency shared by constraints and orders | ||
| 155 | + * @param cartItems one selected product per whitelist group at its declared quantity | ||
| 156 | + * @param timestamp order timestamp in epoch milliseconds; not the trusted quota clock | ||
| 157 | + */ | ||
| 41 | public Order { cartItems = snapshot(cartItems); } | 158 | public Order { cartItems = snapshot(cartItems); } |
| 42 | } | 159 | } |
| 43 | 160 | ||
| 44 | // Non-applicable figures are null in Java and omitted from context JSON. | 161 | // Non-applicable figures are null in Java and omitted from context JSON. |
| 162 | + /** | ||
| 163 | + * Captures remaining quotas after subtracting PENDING and COMPLETED usage. | ||
| 164 | + * Optional figures are null when unconfigured. Reads do not refresh this snapshot or its period. | ||
| 165 | + * @param leftExecutionCount remaining global count, or null when unconfigured | ||
| 166 | + * @param leftAmount remaining global amount after pending and completed reservations | ||
| 167 | + * @param periodIndex snapshot period, or null without periodic limits | ||
| 168 | + * @param leftPeriodExecutionCount remaining count for the snapshot period, or null when unconfigured | ||
| 169 | + */ | ||
| 45 | public record PaymentExecutionInfo(Long leftExecutionCount, long leftAmount, Long periodIndex, | 170 | public record PaymentExecutionInfo(Long leftExecutionCount, long leftAmount, Long periodIndex, |
| 46 | Long leftPeriodExecutionCount) {} | 171 | Long leftPeriodExecutionCount) {} |
| 47 | 172 | ||
| 48 | // Typed union: the action selects the schema of resources and constraints. | 173 | // Typed union: the action selects the schema of resources and constraints. |
| 174 | + /** | ||
| 175 | + * Selects resources and constraints schemas by action; AI_PAY uses the payment profile. | ||
| 176 | + * JSON inputs and returned payloads are copied defensively. | ||
| 177 | + * @param action protocol action selecting the payload schema | ||
| 178 | + * @param resources authorized AI_PAY shopping whitelist payload | ||
| 179 | + * @param constraints authorized AI_PAY payment limits | ||
| 180 | + */ | ||
| 49 | public record StructuredIntent(IntentActionType action, JsonNode resources, JsonNode constraints) { | 181 | public record StructuredIntent(IntentActionType action, JsonNode resources, JsonNode constraints) { |
| 182 | + /** | ||
| 183 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 184 | + * @param action protocol action selecting the payload schema | ||
| 185 | + * @param resources authorized AI_PAY shopping whitelist payload | ||
| 186 | + * @param constraints authorized AI_PAY payment limits | ||
| 187 | + */ | ||
| 50 | public StructuredIntent { | 188 | public StructuredIntent { |
| 51 | resources = CanonicalJson.freezeNode(resources); | 189 | resources = CanonicalJson.freezeNode(resources); |
| 52 | constraints = CanonicalJson.freezeNode(constraints); | 190 | constraints = CanonicalJson.freezeNode(constraints); |
| 53 | } | 191 | } |
| 54 | 192 | ||
| 193 | + /** | ||
| 194 | + * Returns a defensive copy of this record payload. | ||
| 195 | + * @return defensive JSON copy of the resources payload | ||
| 196 | + */ | ||
| 55 | @Override | 197 | @Override |
| 56 | public JsonNode resources() { return CanonicalJson.freezeNode(resources); } | 198 | public JsonNode resources() { return CanonicalJson.freezeNode(resources); } |
| 57 | 199 | ||
| 200 | + /** | ||
| 201 | + * Returns a defensive copy of this record payload. | ||
| 202 | + * @return defensive JSON copy of the constraints payload | ||
| 203 | + */ | ||
| 58 | @Override | 204 | @Override |
| 59 | public JsonNode constraints() { return CanonicalJson.freezeNode(constraints); } | 205 | public JsonNode constraints() { return CanonicalJson.freezeNode(constraints); } |
| 60 | } | 206 | } |
| 61 | 207 | ||
| 208 | + /** | ||
| 209 | + * Identifies the user through a trusted identity provider. | ||
| 210 | + * @param identityProvider trusted identity provider identifier | ||
| 211 | + * @param id nonblank identity identifier | ||
| 212 | + * @param additionalInfo optional additional identity information | ||
| 213 | + */ | ||
| 62 | public record UserIdentity(String identityProvider, String id, String additionalInfo) {} | 214 | public record UserIdentity(String identityProvider, String id, String additionalInfo) {} |
| 215 | + /** | ||
| 216 | + * Identifies the agent through a trusted identity provider. | ||
| 217 | + * @param identityProvider trusted identity provider identifier | ||
| 218 | + * @param id nonblank identity identifier | ||
| 219 | + * @param additionalInfo optional additional identity information | ||
| 220 | + */ | ||
| 63 | public record AgentIdentity(String identityProvider, String id, String additionalInfo) {} | 221 | public record AgentIdentity(String identityProvider, String id, String additionalInfo) {} |
| 222 | + /** | ||
| 223 | + * Identifies the service provider bound by the intent center. | ||
| 224 | + * @param id nonblank identity identifier | ||
| 225 | + * @param additionalInfo optional additional identity information | ||
| 226 | + */ | ||
| 64 | public record ServiceProviderIdentity(String id, String additionalInfo) {} | 227 | public record ServiceProviderIdentity(String id, String additionalInfo) {} |
| 65 | 228 | ||
| 229 | + /** | ||
| 230 | + * Captures user signing device and application information as immutable normalized maps. | ||
| 231 | + * @param device signing device information | ||
| 232 | + * @param app signing application information | ||
| 233 | + */ | ||
| 66 | public record SigningEnv(Map<String, Object> device, Map<String, Object> app) { | 234 | public record SigningEnv(Map<String, Object> device, Map<String, Object> app) { |
| 235 | + /** | ||
| 236 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 237 | + * @param device signing device information | ||
| 238 | + * @param app signing application information | ||
| 239 | + */ | ||
| 67 | public SigningEnv { | 240 | public SigningEnv { |
| 68 | device = CanonicalJson.freezeMap(device); | 241 | device = CanonicalJson.freezeMap(device); |
| 69 | app = CanonicalJson.freezeMap(app); | 242 | app = CanonicalJson.freezeMap(app); |
| 70 | } | 243 | } |
| 71 | } | 244 | } |
| 72 | 245 | ||
| 246 | + /** | ||
| 247 | + * Carries an algorithm name, key identifier and unpadded Base64URL signature. | ||
| 248 | + * The outer signature metadata is not signed by its own layer; verifiers must use trusted key bindings. | ||
| 249 | + * @param alg supported signature algorithm | ||
| 250 | + * @param keyIdentifier identifier used to resolve a trusted signing key | ||
| 251 | + * @param sign unpadded Base64URL signature bytes | ||
| 252 | + */ | ||
| 73 | public record SignatureInfo(String alg, String keyIdentifier, String sign) { | 253 | public record SignatureInfo(String alg, String keyIdentifier, String sign) { |
| 254 | + /** | ||
| 255 | + * Constructs signature metadata using the protocol enum name. | ||
| 256 | + * @param alg supported signature algorithm | ||
| 257 | + * @param keyIdentifier identifier used to resolve a trusted signing key | ||
| 258 | + * @param sign unpadded Base64URL signature bytes | ||
| 259 | + */ | ||
| 74 | public SignatureInfo(AlgorithmType alg, String keyIdentifier, String sign) { | 260 | public SignatureInfo(AlgorithmType alg, String keyIdentifier, String sign) { |
| 75 | this(alg == null ? null : alg.name(), keyIdentifier, sign); | 261 | this(alg == null ? null : alg.name(), keyIdentifier, sign); |
| 76 | } | 262 | } |
| 77 | } | 263 | } |
| 78 | 264 | ||
| 265 | + /** | ||
| 266 | + * Supplies the conversation, display summary and structured authorization for creating L1. | ||
| 267 | + * The agent enforces conversation length and sensitive-data filtering before submission. | ||
| 268 | + * @param intentConversation nonblank original conversation; length and sensitive-data filtering are the agent responsibility | ||
| 269 | + * @param intentSummary nonblank summary displayed for authorization | ||
| 270 | + * @param structuredIntent action-selected resources and constraints | ||
| 271 | + * @param intentId optional globally unique identifier; null requests UUID generation | ||
| 272 | + */ | ||
| 79 | public record CreateIntentRequest(String intentConversation, String intentSummary, | 273 | public record CreateIntentRequest(String intentConversation, String intentSummary, |
| 80 | StructuredIntent structuredIntent, String intentId) {} | 274 | StructuredIntent structuredIntent, String intentId) {} |
| 275 | + /** | ||
| 276 | + * Supplies trusted identities for issuing L2; this is not an activated execution context. | ||
| 277 | + * @param userIdentity trusted user identity | ||
| 278 | + * @param agentIdentity trusted agent identity | ||
| 279 | + * @param serviceProviderIdentity trusted service provider identity | ||
| 280 | + */ | ||
| 81 | public record IntentIssueContext(UserIdentity userIdentity, AgentIdentity agentIdentity, | 281 | public record IntentIssueContext(UserIdentity userIdentity, AgentIdentity agentIdentity, |
| 82 | ServiceProviderIdentity serviceProviderIdentity) {} | 282 | ServiceProviderIdentity serviceProviderIdentity) {} |
| 283 | + /** | ||
| 284 | + * Represents a verification verdict; valid must be true exactly when code is zero. | ||
| 285 | + * @param valid true exactly when the verification code is zero | ||
| 286 | + * @param code protocol result code; zero means success | ||
| 287 | + * @param message diagnostic message | ||
| 288 | + */ | ||
| 83 | public record VerificationResult(boolean valid, long code, String message) {} | 289 | public record VerificationResult(boolean valid, long code, String message) {} |
| 290 | + /** | ||
| 291 | + * Represents the agent-created first authorization layer. | ||
| 292 | + * Obtain authorized lifecycle objects through A4p; constructing a record does not authorize execution. | ||
| 293 | + * @param version A4P Core protocol version | ||
| 294 | + * @param intentId globally unique intent identifier | ||
| 295 | + * @param intentConversation nonblank original conversation; length and sensitive-data filtering are the agent responsibility | ||
| 296 | + * @param intentSummary nonblank summary displayed for authorization | ||
| 297 | + * @param structuredIntent action-selected resources and constraints | ||
| 298 | + * @param timestamp Unix epoch milliseconds | ||
| 299 | + * @param sign signature metadata for this layer | ||
| 300 | + */ | ||
| 84 | public record IntentL1(String version, String intentId, String intentConversation, String intentSummary, | 301 | public record IntentL1(String version, String intentId, String intentConversation, String intentSummary, |
| 85 | StructuredIntent structuredIntent, Long timestamp, SignatureInfo sign) {} | 302 | StructuredIntent structuredIntent, Long timestamp, SignatureInfo sign) {} |
| 303 | + /** | ||
| 304 | + * Represents the intent-center-issued second layer, embedding the complete signed L1 and trusted identities. | ||
| 305 | + * @param version A4P Core protocol version | ||
| 306 | + * @param intentL1 SDK-created first-layer intent | ||
| 307 | + * @param userIdentity trusted user identity | ||
| 308 | + * @param agentIdentity trusted agent identity | ||
| 309 | + * @param serviceProviderIdentity trusted service provider identity | ||
| 310 | + * @param timestamp Unix epoch milliseconds | ||
| 311 | + * @param sign signature metadata for this layer | ||
| 312 | + */ | ||
| 86 | public record IntentL2(String version, IntentL1 intentL1, UserIdentity userIdentity, | 313 | public record IntentL2(String version, IntentL1 intentL1, UserIdentity userIdentity, |
| 87 | AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity, | 314 | AgentIdentity agentIdentity, ServiceProviderIdentity serviceProviderIdentity, |
| 88 | Long timestamp, SignatureInfo sign) {} | 315 | Long timestamp, SignatureInfo sign) {} |
| 316 | + /** | ||
| 317 | + * Represents the user-signed third layer, embedding the complete signed L2 and signing environment. | ||
| 318 | + * @param version A4P Core protocol version | ||
| 319 | + * @param intentL2 SDK-issued second-layer intent | ||
| 320 | + * @param signingEnv user-device signing environment | ||
| 321 | + * @param timestamp Unix epoch milliseconds | ||
| 322 | + * @param sign signature metadata for this layer | ||
| 323 | + */ | ||
| 89 | public record IntentL3(String version, IntentL2 intentL2, SigningEnv signingEnv, | 324 | public record IntentL3(String version, IntentL2 intentL2, SigningEnv signingEnv, |
| 90 | Long timestamp, SignatureInfo sign) {} | 325 | Long timestamp, SignatureInfo sign) {} |
| 91 | 326 | ||
| 327 | + /** | ||
| 328 | + * Requests an action-specific execution; AI_PAY executionContent contains an Order. | ||
| 329 | + * A missing ID is generated during reservation, and JSON payloads are copied defensively. | ||
| 330 | + * @param action protocol action selecting the payload schema | ||
| 331 | + * @param id optional execution identifier; null requests generation during reservation | ||
| 332 | + * @param executionContent action-specific JSON payload; AI_PAY contains an Order | ||
| 333 | + */ | ||
| 92 | public record Execution(IntentActionType action, String id, JsonNode executionContent) { | 334 | public record Execution(IntentActionType action, String id, JsonNode executionContent) { |
| 335 | + /** | ||
| 336 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 337 | + * @param action protocol action selecting the payload schema | ||
| 338 | + * @param id optional execution identifier; null requests generation during reservation | ||
| 339 | + * @param executionContent action-specific JSON payload; AI_PAY contains an Order | ||
| 340 | + */ | ||
| 93 | public Execution { executionContent = CanonicalJson.freezeNode(executionContent); } | 341 | public Execution { executionContent = CanonicalJson.freezeNode(executionContent); } |
| 94 | 342 | ||
| 343 | + /** | ||
| 344 | + * Returns a defensive copy of this record payload. | ||
| 345 | + * @return defensive JSON copy of the execution payload | ||
| 346 | + */ | ||
| 95 | @Override | 347 | @Override |
| 96 | public JsonNode executionContent() { return CanonicalJson.freezeNode(executionContent); } | 348 | public JsonNode executionContent() { return CanonicalJson.freezeNode(executionContent); } |
| 97 | } | 349 | } |
| 98 | 350 | ||
| 351 | + /** | ||
| 352 | + * Records a reservation and its terminal outcome. | ||
| 353 | + * The reservation period remains fixed across completion or cancellation in later periods. | ||
| 354 | + * Canceled records retain their identifiers but release quotas; JSON payloads are copied defensively. | ||
| 355 | + * @param executionId execution identifier, retained even after cancellation | ||
| 356 | + * @param status execution record state | ||
| 357 | + * @param action protocol action selecting the payload schema | ||
| 358 | + * @param executionContent action-specific JSON payload; AI_PAY contains an Order | ||
| 359 | + * @param periodIndex original reservation period, or null without periodic limits | ||
| 360 | + * @param reservedAt reservation instant in Unix epoch milliseconds | ||
| 361 | + * @param completedAt completion instant, present only for COMPLETED and not before reservedAt | ||
| 362 | + * @param canceledAt cancellation instant, present only for CANCELED and not before reservedAt | ||
| 363 | + */ | ||
| 99 | public record ExecutionRecord(String executionId, ExecutionStatus status, IntentActionType action, | 364 | public record ExecutionRecord(String executionId, ExecutionStatus status, IntentActionType action, |
| 100 | JsonNode executionContent, Long periodIndex, long reservedAt, | 365 | JsonNode executionContent, Long periodIndex, long reservedAt, |
| 101 | Long completedAt, Long canceledAt) { | 366 | Long completedAt, Long canceledAt) { |
| 367 | + /** | ||
| 368 | + * Constructs a defensive snapshot of the supplied record components. | ||
| 369 | + * @param executionId execution identifier, retained even after cancellation | ||
| 370 | + * @param status execution record state | ||
| 371 | + * @param action protocol action selecting the payload schema | ||
| 372 | + * @param executionContent action-specific JSON payload; AI_PAY contains an Order | ||
| 373 | + * @param periodIndex original reservation period, or null without periodic limits | ||
| 374 | + * @param reservedAt reservation instant in Unix epoch milliseconds | ||
| 375 | + * @param completedAt completion instant, present only for COMPLETED and not before reservedAt | ||
| 376 | + * @param canceledAt cancellation instant, present only for CANCELED and not before reservedAt | ||
| 377 | + */ | ||
| 102 | public ExecutionRecord { executionContent = CanonicalJson.freezeNode(executionContent); } | 378 | public ExecutionRecord { executionContent = CanonicalJson.freezeNode(executionContent); } |
| 103 | 379 | ||
| 380 | + /** | ||
| 381 | + * Returns a defensive copy of this record payload. | ||
| 382 | + * @return defensive JSON copy of the execution payload | ||
| 383 | + */ | ||
| 104 | @Override | 384 | @Override |
| 105 | public JsonNode executionContent() { return CanonicalJson.freezeNode(executionContent); } | 385 | public JsonNode executionContent() { return CanonicalJson.freezeNode(executionContent); } |
| 106 | } | 386 | } |
| 107 | 387 | ||
| 388 | + /** | ||
| 389 | + * Copies a nullable list into an unmodifiable snapshot. | ||
| 390 | + * @param <Value> decoded or copied value type | ||
| 391 | + * @param values list to snapshot or validate | ||
| 392 | + * @return unmodifiable list copy, or null for null input | ||
| 393 | + */ | ||
| 108 | private static <Value> List<Value> snapshot(List<Value> values) { | 394 | private static <Value> List<Value> snapshot(List<Value> values) { |
| 109 | return values == null ? null : Collections.unmodifiableList(new ArrayList<>(values)); | 395 | return values == null ? null : Collections.unmodifiableList(new ArrayList<>(values)); |
| 110 | } | 396 | } |
MA4P-java-sdk/src/main/java/io/openjiuwen/a4p/Validation.java+102-0File content is under review, please try again later


【review】测试覆盖。新增的 examples 模块未接入 scripts/ut.sh 和 build.sh;这两个脚本只在 A4P-java-sdk 目录执行 mvn clean test,因此新增的 Rsa3072Test 以及完整支付流程示例测试在 CI 中不会被执行,真实 RSA 集成测试存在失效风险。在 UT 流程中先执行 mvn -f A4P-java-sdk/pom.xml install -DskipTests,再执行 mvn -f A4P-java-sdk/examples/pom.xml test,或将两个模块聚合到同一 reactor 构建。