Merged
fix(a4p): 添加校验,调整成员名保持与java一致 #374
fix(a4p): 添加校验,调整成员名保持与java一致 #374
Merged
wangweizhenAdd on 19 days ago
Total: 20 files changed+619-234
@@ -63,7 +63,7 @@ namespaces, the `Signer` / `SignatureVerifier` interfaces, and the data models.
63| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` returns `IntentL3` |63| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` returns `IntentL3` |
64| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` returns `IntentExecutionContext` |64| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` returns `IntentExecutionContext` |
65| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` returns `VerificationResult` |65| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` returns `VerificationResult` |
66-| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` returns `IntentExecutionContext` |66+| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext[, now?])` returns `IntentExecutionContext` |
67| `createExecution / completeExecution / cancelExecution` | Functions on the `A4p` namespace, returning `IntentExecutionContext` |67| `createExecution / completeExecution / cancelExecution` | Functions on the `A4p` namespace, returning `IntentExecutionContext` |
68| Failure reporting | No result wrapper: APIs return data directly and throw a `BusinessError`-shaped error whose `code` is an `A4pErrorCode` (the concrete class is module-internal; catch structurally) |68| Failure reporting | No result wrapper: APIs return data directly and throw a `BusinessError`-shaped error whose `code` is an `A4pErrorCode` (the concrete class is module-internal; catch structurally) |
69| Codec | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` return `String`; each `deserialize…` counterpart validates the structure and returns the object |69| Codec | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` return `String`; each `deserialize…` counterpart validates the structure and returns the object |
@@ -103,8 +103,8 @@ described below), so persist the context after every call.
103`A4pCodec.serializeIntentExecutionContext` / `deserializeIntentExecutionContext` provide103`A4pCodec.serializeIntentExecutionContext` / `deserializeIntentExecutionContext` provide
104the persisted form; deserialization re-validates the whole stored structure — the104the persisted form; deserialization re-validates the whole stored structure — the
105authorized L3 chain, the `intentId` derivation, every ledger record (status-bound105authorized L3 chain, the `intentId` derivation, every ledger record (status-bound
106-finalization timestamps, `execution.id === executionId`, `periodIndex` presence matching106+finalization timestamps, a well-formed flat `action`/`executionContent`, `periodIndex`
107-the intent's periodicity) and the accounting snapshot (period figures and107+presence matching the intent's periodicity) and the accounting snapshot (period figures and
108`leftExecutionCount` present exactly when their caps apply) — and re-freezes the108`leftExecutionCount` present exactly when their caps apply) — and re-freezes the
109authorization snapshot.109authorization snapshot.
110 110 
@@ -128,10 +128,14 @@ skuId is the whitelist matching key, and a product may appear at most once per g
128in at most one group. A period rule requires all of `anchorTime`, `periodSeconds` and128in at most one group. A period rule requires all of `anchorTime`, `periodSeconds` and
129`maxExecutionCountPerPeriod`, with `anchorTime <= validFrom` and129`maxExecutionCountPerPeriod`, with `anchorTime <= validFrom` and
130`periodSeconds <= 9007199254740`. Chain timestamps are monotonic:130`periodSeconds <= 9007199254740`. Chain timestamps are monotonic:
131-`L1.timestamp <= L2.timestamp <= L3.timestamp <= activation`. Activation applies no131+`L1.timestamp <= L2.timestamp <= L3.timestamp <= activation`. The validity window is
132-validity-window check: an intent can be activated before `validFrom` (and even after132+judged progressively as the chain approaches execution: issuance applies no window
133-`validUntil`); the window is enforced at reservation time, where an early reservation133+check; signing and activation refuse an instant past `validUntil` with
134-fails with `A4P_TIMESTAMP_TOO_EARLY`. Length limits and sensitive-data filtering of134+`A4P_TIMESTAMP_EXPIRED` (an L3 or a context created there could never reserve) but
135+permit one before `validFrom`, the intent simply waiting for the window to open; the
136+full window — both ends plus the `activatedTime` floor — is enforced at reservation
137+time, where an early reservation fails with `A4P_TIMESTAMP_TOO_EARLY` and a late one
138+flips the context to EXPIRED. Length limits and sensitive-data filtering of
135`intentConversation` are the Agent's responsibility.139`intentConversation` are the Agent's responsibility.
136 140 
137### Result codes141### Result codes
@@ -163,8 +167,9 @@ Callers branch on the numeric `code`; the message is a fixed diagnostic text per
163| 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error |167| 6001 | `A4P_INTERNAL_ERROR` | Unexpected internal error |
164 168 
165`2001` and `2002` also cover the crypto boundary: a `Signer`/`SignatureVerifier` that169`2001` and `2002` also cover the crypto boundary: a `Signer`/`SignatureVerifier` that
166-throws, returns nothing, or returns a malformed result is mapped to these codes by the170+throws, returns nothing, or returns a malformed or self-contradictory result (`valid`
167-SDK, so raw exceptions never leak through the lifecycle APIs.171+true with a non-success code, or `valid` false with code `0`) is mapped to these codes
172+by the SDK, so raw exceptions never leak through the lifecycle APIs.
168 173 
169## Execution semantics174## Execution semantics
170 175 
@@ -196,19 +201,22 @@ SDK, so raw exceptions never leak through the lifecycle APIs.
196 either the count cap is reached or the amount budget is exhausted. REVOKED and201 either the count cap is reached or the amount budget is exhausted. REVOKED and
197 EXPIRED are terminal.202 EXPIRED are terminal.
198- `executionInfo` always provides `leftAmount`; `periodIndex`/`leftPeriodExecutionCount`203- `executionInfo` always provides `leftAmount`; `periodIndex`/`leftPeriodExecutionCount`
199- appear only for periodic intents and `leftExecutionCount` only when `maxExecuteCount`204+ appear only for periodic intents and `leftExecutionCount` only when `maxExecutionCount`
200 is present — non-applicable figures are omitted, not null. The snapshot is always205 is present — non-applicable figures are omitted, not null. The snapshot is always
201 re-derived from the ledger, never maintained by hand.206 re-derived from the ledger, never maintained by hand.
202-- The caller's execution object is never mutated: the id is resolved locally and lands207+- The caller's execution object is neither mutated nor aliased: the id is resolved
203- on the ledger's own deep copy after every check has passed. The ledger is append-only.208+ locally and stored as the record's `executionId`, and a deep copy of the execution
209+ content lands on the flat ledger record after every check has passed. The ledger is
210+ append-only.
204- Completion books no quota but re-derives the accounting snapshot at the evaluation211- Completion books no quota but re-derives the accounting snapshot at the evaluation
205 instant, so the period figures follow `now`, not the last ledger mutation.212 instant, so the period figures follow `now`, not the last ledger mutation.
206- The authorized intent is deep-cloned and deep-frozen at activation; execution checks213- The authorized intent is deep-cloned and deep-frozen at activation; execution checks
207 read the immutable snapshot while the ledger and figures stay mutable.214 read the immutable snapshot while the ledger and figures stay mutable.
208- Context operations carry no locks. That is safe in the ArkTS single-threaded runtime,215- Context operations carry no locks. That is safe in the ArkTS single-threaded runtime,
209 **not** across processes or independently activated copies of the same `intentId`.216 **not** across processes or independently activated copies of the same `intentId`.
210-- `verifyIntentAuthenticity` verifies the L3 chain and the server's L2 signature, not217+- `verifyIntentAuthenticity` structurally validates the whole L3 chain (its own `sign`,
211- the user signature, and does not depend on any context status.218+ `signingEnv`, `timestamp` and `version` included) and verifies the server's L2
219+ signature, not the user signature; it does not depend on any context status.
212 220 
213The ledger is in-memory. The integrating service (the intent center) must persist the221The ledger is in-memory. The integrating service (the intent center) must persist the
214context inside a database transaction locked by `intentId`, prevent replay of the same222context inside a database transaction locked by `intentId`, prevent replay of the same
@@ -222,7 +230,7 @@ UTF-16 code units, no whitespace, finite safe integers only, `undefined` omitted
222signing strips only the complete top-level `sign` property (nested chain signatures230signing strips only the complete top-level `sign` property (nested chain signatures
223stay), UTF-8 without BOM, and RFC 4648 Base64URL without padding, with the decoder231stay), UTF-8 without BOM, and RFC 4648 Base64URL without padding, with the decoder
224rejecting padding, non-URL-safe characters and nonzero unused trailing bits. JSON field232rejecting padding, non-URL-safe characters and nonzero unused trailing bits. JSON field
225-names are the interface property names (`intentConversation`, `structuredIntent.resource`,233+names are the interface property names (`intentConversation`, `structuredIntent.resources`,
226`userIdentity.id`), every enum is serialized by name (`"AI_PAY"`, `"CONSUMED"`,234`userIdentity.id`), every enum is serialized by name (`"AI_PAY"`, `"CONSUMED"`,
227`"PENDING"`), and the protocol version is `1.0`.235`"PENDING"`), and the protocol version is `1.0`.
228 236 
@@ -255,12 +263,6 @@ step validates the levels it receives, rejecting a mismatch (including mixed-ver
255chains) with `A4P_UNSUPPORTED_VERSION`. The HAR version is `1.0.0`; protocol263chains) with `A4P_UNSUPPORTED_VERSION`. The HAR version is `1.0.0`; protocol
256compatibility is governed by the `version` field, not by the HAR version.264compatibility is governed by the `version` field, not by the HAR version.
257 265 
258-The Java port ([`A4P-java-sdk/`](../A4P-java-sdk)) was ported from this SDK and shares
259-the canonical JSON rules and the error-code table, but it follows the API
260-specification's newer field spellings (`resources` where this SDK signs `resource`, an
261-explicit `version` on `Execution`). Serialized intents are therefore not byte-identical
262-across the two SDKs; check the field names before exchanging wire data.
263- 
264## Known limitations266## Known limitations
265 267 
266- The ledger is in-memory and per-context. Durability, locked persistence, replay268- The ledger is in-memory and per-context. Durability, locked persistence, replay
@@ -273,8 +275,9 @@ across the two SDKs; check the field names before exchanging wire data.
273- `verifyIntentAuthenticity` deliberately does not verify the user signature.275- `verifyIntentAuthenticity` deliberately does not verify the user signature.
274- Deserialization is structural (JSON.parse semantics): unknown fields and duplicate276- Deserialization is structural (JSON.parse semantics): unknown fields and duplicate
275 JSON keys are not rejected, unlike the stricter Java port.277 JSON keys are not rejected, unlike the stricter Java port.
276-- Activation applies no validity-window check; the window is enforced at reservation278+- Signing and activation judge only the window's upper bound (`validUntil`); the
277- time (with the lazy EXPIRED flip).279+ window's opening (`validFrom`) and the lazy EXPIRED flip are left to reservation
280+ time.
278- Context operations are unsynchronized: safe in the single-threaded ArkTS runtime281- Context operations are unsynchronized: safe in the single-threaded ArkTS runtime
279 only, not across processes or independently activated copies.282 only, not across processes or independently activated copies.
280 283 
@@ -60,7 +60,7 @@ import { A4p, A4pCodec, A4pErrorCode } from 'a4p';
60| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` 返回 `IntentL3` |60| `signIntent` | `A4p.signIntent(IntentL2, SignatureVerifier, SigningEnv, Signer[, now?])` 返回 `IntentL3` |
61| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` 返回 `IntentExecutionContext` |61| `activateIntent` | `A4p.activateIntent(IntentL3, SignatureVerifier[, now?])` 返回 `IntentExecutionContext` |
62| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` 返回 `VerificationResult` |62| `verifyIntentAuthenticity` | `A4p.verifyIntentAuthenticity(IntentL3, SignatureVerifier)` 返回 `VerificationResult` |
63-| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext)` 返回 `IntentExecutionContext` |63+| `revokeIntent` | `A4p.revokeIntent(IntentExecutionContext[, now?])` 返回 `IntentExecutionContext` |
64| `createExecution / completeExecution / cancelExecution` | `A4p` 命名空间下的函数,返回 `IntentExecutionContext` |64| `createExecution / completeExecution / cancelExecution` | `A4p` 命名空间下的函数,返回 `IntentExecutionContext` |
65| 失败上报 | 无结果包装:API 直接返回数据,失败时抛出符合 `BusinessError` 形态的错误,`code` 为 `A4pErrorCode`(具体类为模块内部实现,按结构捕获) |65| 失败上报 | 无结果包装:API 直接返回数据,失败时抛出符合 `BusinessError` 形态的错误,`code` 为 `A4pErrorCode`(具体类为模块内部实现,按结构捕获) |
66| 编解码 | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` 返回 `String`;对应的每个 `deserialize…` 先做结构校验再返回对象 |66| 编解码 | `A4pCodec.serializeIntentL1/L2/L3/IntentExecutionContext` 返回 `String`;对应的每个 `deserialize…` 先做结构校验再返回对象 |
@@ -98,7 +98,7 @@ try {
98每次调用后都要持久化 context。`A4pCodec.serializeIntentExecutionContext` /98每次调用后都要持久化 context。`A4pCodec.serializeIntentExecutionContext` /
99`deserializeIntentExecutionContext` 提供持久化形式;反序列化会重新校验存储的完整结构99`deserializeIntentExecutionContext` 提供持久化形式;反序列化会重新校验存储的完整结构
100——已授权的 L3 链、`intentId` 的推导、每一条账本记录(与状态绑定的终结时间戳、100——已授权的 L3 链、`intentId` 的推导、每一条账本记录(与状态绑定的终结时间戳、
101-`execution.id === executionId`、`periodIndex` 的有无与意图周期性一致)以及记账快照101+结构合法的扁平 `action`/`executionContent`、`periodIndex` 的有无与意图周期性一致)以及记账快照
102(周期数值与 `leftExecutionCount` 恰在对应上限存在时出现)——并重新冻结授权快照。102(周期数值与 `leftExecutionCount` 恰在对应上限存在时出现)——并重新冻结授权快照。
103 103 
104可选字段用 `undefined` 表示;缺席的可选字段不会出现在签名 JSON 中。金额是应用约定的104可选字段用 `undefined` 表示;缺席的可选字段不会出现在签名 JSON 中。金额是应用约定的
@@ -117,10 +117,13 @@ seller id,且 `spuId`/`skuId` 至少提供一个非空白值;seller id + spu
117匹配键,一个商品在每个分组内至多出现一次,且至多属于一个分组。周期规则要求117匹配键,一个商品在每个分组内至多出现一次,且至多属于一个分组。周期规则要求
118`anchorTime`、`periodSeconds`、`maxExecutionCountPerPeriod` 三者同时提供,且118`anchorTime`、`periodSeconds`、`maxExecutionCountPerPeriod` 三者同时提供,且
119`anchorTime <= validFrom`、`periodSeconds <= 9007199254740`。链上时间戳单调:119`anchorTime <= validFrom`、`periodSeconds <= 9007199254740`。链上时间戳单调:
120-`L1.timestamp <= L2.timestamp <= L3.timestamp <= 激活时刻`。激活不做有效期窗口检查:120+`L1.timestamp <= L2.timestamp <= L3.timestamp <= 激活时刻`。有效期窗口随链路推进逐级
121-意图可以在 `validFrom` 之前(甚至 `validUntil` 之后)被激活;窗口在预留时才被强制,121+判定:签发不做窗口检查;签名与激活各自以 `A4P_TIMESTAMP_EXPIRED` 拒绝越过
122-早于窗口的预留以 `A4P_TIMESTAMP_TOO_EARLY` 失败。`intentConversation` 的长度限制与122+`validUntil` 的时刻(彼时生成的 L3 或 context 永远无法预留),但允许早于
123-敏感数据过滤由 Agent 负责。123+`validFrom`,意图只是等待窗口开启;完整窗口(两端加 `activatedTime` 下限)在预留时
124+强制。早于窗口的预留以 `A4P_TIMESTAMP_TOO_EARLY` 失败,越过 `validUntil` 的预留把
125+context 惰性置为 EXPIRED。`intentConversation` 的长度限制与敏感数据过滤由 Agent
126+负责。
124 127 
125### 结果码128### 结果码
126 129 
@@ -149,7 +152,8 @@ hilog 记录)。取值来自 `A4pErrorCode` 枚举。`0` 表示成功,其他
149| 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 |152| 5002 | `A4P_DESERIALIZE_FAIL` | 反序列化失败 |
150| 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 |153| 6001 | `A4P_INTERNAL_ERROR` | 意外的内部错误 |
151 154 
152-`2001` 与 `2002` 同样覆盖密码学边界:抛出异常、不返回结果或返回畸形结果的155+`2001` 与 `2002` 同样覆盖密码学边界:抛出异常、不返回结果,或返回畸形/自相矛盾结果
156+(`valid` 为真却携带非成功码,或 `valid` 为假却携带码 `0`)的
153`Signer`/`SignatureVerifier` 会被 SDK 映射为这两个码,原始异常不会穿透生命周期 API。157`Signer`/`SignatureVerifier` 会被 SDK 映射为这两个码,原始异常不会穿透生命周期 API。
154 158 
155## 执行语义159## 执行语义
@@ -175,17 +179,18 @@ hilog 记录)。取值来自 `A4pErrorCode` 枚举。`0` 表示成功,其他
175- 当一次完成操作之后不再有待处理记录,且要么达到次数上限、要么金额预算用尽时,ACTIVE179- 当一次完成操作之后不再有待处理记录,且要么达到次数上限、要么金额预算用尽时,ACTIVE
176 的 context 变为 CONSUMED。REVOKED 与 EXPIRED 是终态。180 的 context 变为 CONSUMED。REVOKED 与 EXPIRED 是终态。
177- `executionInfo` 始终给出 `leftAmount`;`periodIndex`/`leftPeriodExecutionCount` 仅在181- `executionInfo` 始终给出 `leftAmount`;`periodIndex`/`leftPeriodExecutionCount` 仅在
178- 周期意图上出现,`leftExecutionCount` 仅在存在 `maxExecuteCount` 时出现——不适用的数值182+ 周期意图上出现,`leftExecutionCount` 仅在存在 `maxExecutionCount` 时出现——不适用的数值
179 被省略而非置 null。快照始终由账本推导,从不手工维护。183 被省略而非置 null。快照始终由账本推导,从不手工维护。
180-- 调用方的 execution 对象不会被改动:ID 在本地解析,且只在全部检查通过后写入账本自己的184+- 调用方的 execution 对象既不会被改动也不会被别名引用:ID 在本地解析并存为记录的
181- 深拷贝。账本只追加。185+ `executionId`,执行内容的深拷贝则在全部检查通过后写入扁平的账本记录。账本只追加。
182- 完成操作不占用配额,但会按评估时刻重新推导记账快照,因此周期数值跟随 `now`,而不是186- 完成操作不占用配额,但会按评估时刻重新推导记账快照,因此周期数值跟随 `now`,而不是
183 最近一次账本变更。187 最近一次账本变更。
184- 已授权意图在激活时被深拷贝并深度冻结;执行检查读取不可变快照,而账本与数值保持188- 已授权意图在激活时被深拷贝并深度冻结;执行检查读取不可变快照,而账本与数值保持
185 可变。189 可变。
186- context 操作不加锁。这在 ArkTS 单线程运行时中是安全的,但**不**覆盖多个进程或同一个190- context 操作不加锁。这在 ArkTS 单线程运行时中是安全的,但**不**覆盖多个进程或同一个
187 `intentId` 各自独立激活的副本。191 `intentId` 各自独立激活的副本。
188-- `verifyIntentAuthenticity` 校验 L3 链与服务端的 L2 签名,不校验用户签名,也不依赖任何192+- `verifyIntentAuthenticity` 结构化校验整条 L3 链(含 L3 自身的 `sign`、`signingEnv`、
193+ `timestamp` 与 `version`)并验证服务端的 L2 签名,不校验用户签名,也不依赖任何
189 context 状态。194 context 状态。
190 195 
191账本位于内存中。接入方(意图中心)必须在以 `intentId` 加锁的数据库事务中持久化196账本位于内存中。接入方(意图中心)必须在以 `intentId` 加锁的数据库事务中持久化
@@ -198,7 +203,7 @@ context,防止同一个 `intentId` 被重放,并把密钥与身份绑定。
198UTF-16 码元排序、无空白、仅限有限安全整数、`undefined` 省略、签名时仅移除顶层完整的203UTF-16 码元排序、无空白、仅限有限安全整数、`undefined` 省略、签名时仅移除顶层完整的
199`sign` 属性(链上下层签名保留)、UTF-8 编码不带 BOM,以及 RFC 4648 无填充 Base64URL,204`sign` 属性(链上下层签名保留)、UTF-8 编码不带 BOM,以及 RFC 4648 无填充 Base64URL,
200解码端拒绝填充、非 URL 安全字符与非零的未用尾随位。JSON 字段名即接口属性名205解码端拒绝填充、非 URL 安全字符与非零的未用尾随位。JSON 字段名即接口属性名
201-(`intentConversation`、`structuredIntent.resource`、`userIdentity.id`),每个枚举都按206+(`intentConversation`、`structuredIntent.resources`、`userIdentity.id`),每个枚举都按
202名称序列化(`"AI_PAY"`、`"CONSUMED"`、`"PENDING"`),协议版本为 `1.0`。207名称序列化(`"AI_PAY"`、`"CONSUMED"`、`"PENDING"`),协议版本为 `1.0`。
203 208 
204每一层的签名覆盖该层除去整个 `sign` 对象之后的内容,因此该层自己的 `alg` 与209每一层的签名覆盖该层除去整个 `sign` 对象之后的内容,因此该层自己的 `alg` 与
@@ -225,11 +230,6 @@ Base64URL,以便与 Java SDK 的 `Rsa3072` 适配器互操作。
225(包括混合版本的链)时以 `A4P_UNSUPPORTED_VERSION` 拒绝。HAR 版本为 `1.0.0`;协议兼容230(包括混合版本的链)时以 `A4P_UNSUPPORTED_VERSION` 拒绝。HAR 版本为 `1.0.0`;协议兼容
226性由 `version` 字段决定,而不是由 HAR 版本决定。231性由 `version` 字段决定,而不是由 HAR 版本决定。
227 232 
228-Java 移植版([`A4P-java-sdk/`](../A4P-java-sdk))移植自本 SDK,与本文共享 canonical JSON
229-规则与错误码表,但它遵循 API 规范中更新的字段拼写(本 SDK 签名 `resource`,Java 侧为
230-`resources`;`Execution` 上多出显式的 `version` 字段)。因此两个 SDK 序列化出的意图并非
231-字节级一致;交换线格式数据前请先核对字段名。
232- 
233## 已知限制233## 已知限制
234 234 
235- 账本是内存内的、以单个 context 为粒度。持久化、加锁写入、防重放以及密钥与身份的绑定235- 账本是内存内的、以单个 context 为粒度。持久化、加锁写入、防重放以及密钥与身份的绑定
@@ -241,7 +241,8 @@ Java 移植版([`A4P-java-sdk/`](../A4P-java-sdk))移植自本 SDK,与本
241- `verifyIntentAuthenticity` 有意不校验用户签名。241- `verifyIntentAuthenticity` 有意不校验用户签名。
242- 反序列化是结构性的(JSON.parse 语义):不拒绝未知字段与重复 JSON 键,这一点不如242- 反序列化是结构性的(JSON.parse 语义):不拒绝未知字段与重复 JSON 键,这一点不如
243 Java 移植版严格。243 Java 移植版严格。
244-- 激活不做有效期窗口检查;窗口在预留时强制(伴随惰性的 EXPIRED 翻转)。244+- 签名与激活只判定窗口上界(`validUntil`);窗口的开启(`validFrom`)与惰性的 EXPIRED
245+ 翻转都留给预留阶段。
245- context 操作无同步保护:仅在 ArkTS 单线程运行时中安全,不覆盖多进程或各自独立激活的246- context 操作无同步保护:仅在 ArkTS 单线程运行时中安全,不覆盖多进程或各自独立激活的
246 副本。247 副本。
247 248 
@@ -58,14 +58,14 @@ authorizedIntent
58activatedTime58activatedTime
59executions59executions
60executionInfo60executionInfo
61-resource61+resources
62constraints62constraints
63singleOrderMaxAmount63singleOrderMaxAmount
64totalMaxAmount64totalMaxAmount
65currency65currency
66validFrom66validFrom
67validUntil67validUntil
68-maxExecuteCount68+maxExecutionCount
69anchorTime69anchorTime
70periodSeconds70periodSeconds
71maxExecutionCountPerPeriod71maxExecutionCountPerPeriod
@@ -81,7 +81,6 @@ cartItems
81orderId81orderId
82amount82amount
83executionContent83executionContent
84-execution
85executionId84executionId
86periodIndex85periodIndex
87reservedAt86reservedAt
@@ -67,14 +67,14 @@ authorizedIntent
67activatedTime67activatedTime
68executions68executions
69executionInfo69executionInfo
70-resource70+resources
71constraints71constraints
72singleOrderMaxAmount72singleOrderMaxAmount
73totalMaxAmount73totalMaxAmount
74currency74currency
75validFrom75validFrom
76validUntil76validUntil
77-maxExecuteCount77+maxExecutionCount
78anchorTime78anchorTime
79periodSeconds79periodSeconds
80maxExecutionCountPerPeriod80maxExecutionCountPerPeriod
@@ -90,7 +90,6 @@ cartItems
90orderId90orderId
91amount91amount
92executionContent92executionContent
93-execution
94executionId93executionId
95periodIndex94periodIndex
96reservedAt95reservedAt
@@ -45,14 +45,16 @@ function raise(err: A4pValidationFailure | null): void {
45 * verifiers are expected to report failure through VerificationResult, but45 * verifiers are expected to report failure through VerificationResult, but
46 * a throwing verifier must still surface as an A4pError per the46 * a throwing verifier must still surface as an A4pError per the
47 * throw-on-failure convention, never as a leaked raw exception. A verifier47 * throw-on-failure convention, never as a leaked raw exception. A verifier
48- * returning no result at all is treated the same way. The verdict itself48+ * returning no result at all is treated the same way. A verdict whose
49- * is returned as-is, whatever it says.49+ * parts agree is returned as-is; a self-contradictory one — `valid` true
50+ * with a non-success code, or `valid` false with the success code — is
51+ * not a verdict the SDK can trust or relay and is reported the same way.
50 * @param verifier - The verifier to invoke52 * @param verifier - The verifier to invoke
51 * @param data - The signed bytes to verify53 * @param data - The signed bytes to verify
52 * @param signature - The signature information to check54 * @param signature - The signature information to check
53 * @param who - Whose signature is being checked (for the logged detail)55 * @param who - Whose signature is being checked (for the logged detail)
54- * @returns The verifier's result56+ * @returns The verifier's result (present and self-consistent)
55- * @throws A4pError with A4P_VERIFY_FAIL when the verifier throws or returns no result57+ * @throws A4pError with A4P_VERIFY_FAIL when the verifier throws, returns no result, or returns a contradictory one
56 */58 */
57function runVerifier(verifier: SignatureVerifier, data: Uint8Array, signature: SignatureInfo,59function runVerifier(verifier: SignatureVerifier, data: Uint8Array, signature: SignatureInfo,
58 who: string): VerificationResult {60 who: string): VerificationResult {
@@ -68,6 +70,18 @@ function runVerifier(verifier: SignatureVerifier, data: Uint8Array, signature: S
68 if (!result) {70 if (!result) {
69 a4pThrow(A4pErrorCode.A4P_VERIFY_FAIL, who + ' signature verifier returned no result');71 a4pThrow(A4pErrorCode.A4P_VERIFY_FAIL, who + ' signature verifier returned no result');
70 }72 }
73+ // The verdict's parts must agree: code 0 is success, anything else a
74+ // failure, so a valid verdict carrying a failure code — or an invalid
75+ // one carrying the success code — is self-contradictory. Such a result
76+ // is a broken verifier's output, not a verdict to trust or relay, so it
77+ // is reported as a verification failure like the ones above.
78+ const contradictory: boolean = (result.valid && result.code !== A4pErrorCode.A4P_SUCCESS) ||
79+ (!result.valid && result.code === A4pErrorCode.A4P_SUCCESS);
80+ if (contradictory) {
81+ a4pThrow(A4pErrorCode.A4P_VERIFY_FAIL,
82+ who + ' signature verifier returned a contradictory result: valid is ' + result.valid +
83+ ' but code is ' + result.code);
84+ }
71 return result;85 return result;
72}86}
73 87 
@@ -143,10 +157,11 @@ export namespace A4p {
143 * `now` is the signing instant (epoch milliseconds) recorded in the157 * `now` is the signing instant (epoch milliseconds) recorded in the
144 * intent's `timestamp` field and thereby covered by the signature. Unlike158 * intent's `timestamp` field and thereby covered by the signature. Unlike
145 * the evaluation instant of the execution APIs it drives no decision —159 * the evaluation instant of the execution APIs it drives no decision —
146- * validity windows are judged at reservation time, not at signing time.160+ * creation applies no validity-window check; the window's upper bound is
147- * Defaults to the system clock; pass a fixed value in tests to make the161+ * first judged at L3 signing (see signIntent) and the full window at
148- * signed bytes reproducible. A provided `now` must be a non-negative162+ * reservation time. Defaults to the system clock; pass a fixed value in
149- * safe integer.163+ * tests to make the signed bytes reproducible. A provided `now` must be a
164+ * non-negative safe integer.
150 * @param { CreateIntentRequest } request - The create-intent request containing intent details and constraints.165 * @param { CreateIntentRequest } request - The create-intent request containing intent details and constraints.
151 * @param { Signer } agentSigner - The signer used to produce the agent's L1 signature.166 * @param { Signer } agentSigner - The signer used to produce the agent's L1 signature.
152 * @param { number } now - Optional signing instant in epoch milliseconds; defaults to Date.now().167 * @param { number } now - Optional signing instant in epoch milliseconds; defaults to Date.now().
@@ -262,6 +277,10 @@ export namespace A4p {
262 * authorization would violate the chain's monotonic timestamps, so it is277 * authorization would violate the chain's monotonic timestamps, so it is
263 * rejected here instead of producing an L3 that activateIntent (and every278 * rejected here instead of producing an L3 that activateIntent (and every
264 * other receiver validating the chain) would refuse.279 * other receiver validating the chain) would refuse.
280+ * It must not be later than the intent's `validUntil`: the user cannot
281+ * authorize an intent whose validity window has already closed — every
282+ * execution against it would be refused as expired — so a post-validUntil
283+ * signing instant is rejected here instead of producing a dead-end L3.
265 * The embedded L2 and the signing environment are deep copies — the284 * The embedded L2 and the signing environment are deep copies — the
266 * caller's objects are never aliased into the returned intent.285 * caller's objects are never aliased into the returned intent.
267 * @param { IntentL2 } intentL2 - The Level 2 intent to verify and sign.286 * @param { IntentL2 } intentL2 - The Level 2 intent to verify and sign.
@@ -274,6 +293,7 @@ export namespace A4p {
274 * @throws { BusinessError } 1002 - Unsupported version.293 * @throws { BusinessError } 1002 - Unsupported version.
275 * @throws { BusinessError } 2001 - Signing failed.294 * @throws { BusinessError } 2001 - Signing failed.
276 * @throws { BusinessError } 2002 - Verification failed.295 * @throws { BusinessError } 2002 - Verification failed.
296+ * @throws { BusinessError } 3002 - Timestamp expired.
277 * @throws { BusinessError } 5001 - Serialization failed.297 * @throws { BusinessError } 5001 - Serialization failed.
278 */298 */
279 export function signIntent(intentL2: IntentL2, serverVerifier: SignatureVerifier, signingEnv: SigningEnv,299 export function signIntent(intentL2: IntentL2, serverVerifier: SignatureVerifier, signingEnv: SigningEnv,
@@ -296,6 +316,10 @@ export namespace A4p {
296 'IntentL1 version ' + intentL2.intentL1.version + ' is not supported');316 'IntentL1 version ' + intentL2.intentL1.version + ' is not supported');
297 }317 }
298 318 
319+ // Check order is part of the contract: structure and versions are
320+ // judged before any clock verdict, so a malformed or mixed-version
321+ // chain is reported as such even when its validity window has also
322+ // lapsed.
299 // The user's signing stamp must not predate the issuance it authorizes323 // The user's signing stamp must not predate the issuance it authorizes
300 // (see issueIntent): reject the skewed clock here instead of signing a324 // (see issueIntent): reject the skewed clock here instead of signing a
301 // dead-end L3 that activation would always refuse.325 // dead-end L3 that activation would always refuse.
@@ -304,6 +328,15 @@ export namespace A4p {
304 a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER,328 a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER,
305 'Signing timestamp ' + timestamp + ' is earlier than intentL2.timestamp ' + intentL2.timestamp);329 'Signing timestamp ' + timestamp + ' is earlier than intentL2.timestamp ' + intentL2.timestamp);
306 }330 }
331+ // Nor may the stamp fall past the validity window being authorized:
332+ // an L3 signed after validUntil could never execute (every reservation
333+ // would be refused as expired), so the closed window is reported here
334+ // instead of at activation.
335+ const constraints: PaymentConstraints = intentL2.intentL1.structuredIntent.constraints;
336+ if (timestamp > constraints.validUntil) {
337+ a4pThrow(A4pErrorCode.A4P_TIMESTAMP_EXPIRED,
338+ 'Signing timestamp ' + timestamp + ' is after validUntil ' + constraints.validUntil);
339+ }
307 340 
308 const l2Data: Uint8Array = toSignableBytes(intentL2);341 const l2Data: Uint8Array = toSignableBytes(intentL2);
309 // validateIntentL2 guarantees sign is present (validateSignatureInfo342 // validateIntentL2 guarantees sign is present (validateSignatureInfo
@@ -362,7 +395,12 @@ export namespace A4p {
362 * earlier than the L3's own `timestamp` — the chain's395 * earlier than the L3's own `timestamp` — the chain's
363 * monotonic-timestamp rule (see issueIntent) applied to the activation396 * monotonic-timestamp rule (see issueIntent) applied to the activation
364 * step: no context can be created for an authorization that did not397 * step: no context can be created for an authorization that did not
365- * exist yet at that instant. Defaults398+ * exist yet at that instant. It must not be later than the intent's
399+ * `validUntil`: an intent whose validity window has already closed can
400+ * no longer be activated — every execution against it would be refused
401+ * as expired — so no context is created for it (an intent not yet valid,
402+ * in contrast, is activated and waits for validFrom).
403+ * Defaults
366 * to the system clock; pass the same value intended for the execution404 * to the system clock; pass the same value intended for the execution
367 * APIs to keep the activation snapshot and the first reservation in the405 * APIs to keep the activation snapshot and the first reservation in the
368 * same period. A provided `now` must be a non-negative safe integer.406 * same period. A provided `now` must be a non-negative safe integer.
@@ -373,6 +411,7 @@ export namespace A4p {
373 * @throws { BusinessError } 1001 - Invalid parameter.411 * @throws { BusinessError } 1001 - Invalid parameter.
374 * @throws { BusinessError } 1002 - Unsupported version.412 * @throws { BusinessError } 1002 - Unsupported version.
375 * @throws { BusinessError } 2002 - Verification failed.413 * @throws { BusinessError } 2002 - Verification failed.
414+ * @throws { BusinessError } 3002 - Timestamp expired.
376 * @throws { BusinessError } 5001 - Serialization failed.415 * @throws { BusinessError } 5001 - Serialization failed.
377 */416 */
378 export function activateIntent(intentL3: IntentL3, userVerifier: SignatureVerifier,417 export function activateIntent(intentL3: IntentL3, userVerifier: SignatureVerifier,
@@ -383,6 +422,10 @@ export namespace A4p {
383 raise(validateIntentL3(intentL3));422 raise(validateIntentL3(intentL3));
384 raise(checkChainVersions(intentL3));423 raise(checkChainVersions(intentL3));
385 424 
425+ // Check order is part of the contract: structure and versions are
426+ // judged before any clock verdict, so a malformed or mixed-version
427+ // chain is reported as such even when its validity window has also
428+ // lapsed.
386 // The activation instant must not predate the authorization it429 // The activation instant must not predate the authorization it
387 // activates (the monotonic rule issueIntent/signIntent enforce for430 // activates (the monotonic rule issueIntent/signIntent enforce for
388 // their stamps): a context created before the L3's signing timestamp431 // their stamps): a context created before the L3's signing timestamp
@@ -394,6 +437,17 @@ export namespace A4p {
394 a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER,437 a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER,
395 'Activation timestamp ' + nowMs + ' is earlier than intentL3.timestamp ' + intentL3.timestamp);438 'Activation timestamp ' + nowMs + ' is earlier than intentL3.timestamp ' + intentL3.timestamp);
396 }439 }
440+ const constraints: PaymentConstraints = intentL3.intentL2.intentL1.structuredIntent.constraints;
441+ // Nor may it fall past the validity window: a context created after
442+ // validUntil could never reserve (every createExecution would be
443+ // refused as expired), so the closed window is reported instead of
444+ // handing out a dead-end context. An intent not yet valid is
445+ // activated and waits for validFrom — reservations, not activation,
446+ // judge the window's opening.
447+ if (nowMs > constraints.validUntil) {
448+ a4pThrow(A4pErrorCode.A4P_TIMESTAMP_EXPIRED,
449+ 'Activation timestamp ' + nowMs + ' is after validUntil ' + constraints.validUntil);
450+ }
397 451 
398 const l3Data: Uint8Array = toSignableBytes(intentL3);452 const l3Data: Uint8Array = toSignableBytes(intentL3);
399 // validateIntentL3 guarantees sign is present (validateSignatureInfo453 // validateIntentL3 guarantees sign is present (validateSignatureInfo
@@ -401,7 +455,6 @@ export namespace A4p {
401 verifyOrThrow(userVerifier, l3Data, intentL3.sign as SignatureInfo, 'User');455 verifyOrThrow(userVerifier, l3Data, intentL3.sign as SignatureInfo, 'User');
402 456 
403 const intentId: string = intentL3.intentL2.intentL1.intentId;457 const intentId: string = intentL3.intentL2.intentL1.intentId;
404- const constraints: PaymentConstraints = intentL3.intentL2.intentL1.structuredIntent.constraints;
405 458 
406 const authorizedIntent: IntentL3 = deepFreeze(deepClone(intentL3));459 const authorizedIntent: IntentL3 = deepFreeze(deepClone(intentL3));
407 460 
@@ -427,19 +480,22 @@ export namespace A4p {
427 * activateIntent. See issueIntent for the detached480 * activateIntent. See issueIntent for the detached
428 * `alg`/`keyIdentifier` verification caveat.481 * `alg`/`keyIdentifier` verification caveat.
429 *482 *
430- * The L3 is only the carrier here: the sole L3-level check is that it483+ * The L3 is structurally validated as a whole before verification —
431- * contains the L2 — the L3's own `sign`, `signingEnv`, `timestamp`, and484+ * its own `sign`, `signingEnv`, `timestamp`, and `version` must be
432- * `version` are neither verified nor required. The embedded L2 (with its485+ * present and well-formed, exactly like any chain the SDK accepts —
433- * L1) is structurally validated and version-checked before verification,486+ * but its signature value is not verified here (that is activateIntent's
434- * and the signature is verified over the embedded L2's own bytes, so a487+ * job) and its version is not compared against the protocol version:
435- * tampered L2 carrying a signature over different bytes must fail.488+ * the carrier's version plays no role in the verdict. The signature is
489+ * verified over the embedded L2's own bytes, so a tampered L2 carrying
490+ * a signature over different bytes must fail.
436 *491 *
437 * Unlike the lifecycle APIs this is a pure query: the verifier's verdict492 * Unlike the lifecycle APIs this is a pure query: the verifier's verdict
438 * is the answer, so an invalid signature is returned as a493 * is the answer, so an invalid signature is returned as a
439 * VerificationResult with `valid: false` (carrying the verifier's own494 * VerificationResult with `valid: false` (carrying the verifier's own
440 * `code`/`message`) instead of being thrown. Structural problems495 * `code`/`message`) instead of being thrown. Structural problems
441- * (malformed L2 chain, unsupported L2/L1 version, serialization failure)496+ * (malformed L3/L2 chain, unsupported L2/L1 version, serialization
442- * and a throwing verifier still throw.497+ * failure), a throwing verifier, and a self-contradictory verdict
498+ * (see runVerifier) still throw.
443 * @param { IntentL3 } intentL3 - The Level 3 intent carrying the Level 2 intent to verify.499 * @param { IntentL3 } intentL3 - The Level 3 intent carrying the Level 2 intent to verify.
444 * @param { SignatureVerifier } serverVerifier - The verifier used to check the server's L2 signature.500 * @param { SignatureVerifier } serverVerifier - The verifier used to check the server's L2 signature.
445 * @returns { VerificationResult } The verifier's result, including invalid (`valid: false`) verdicts.501 * @returns { VerificationResult } The verifier's result, including invalid (`valid: false`) verdicts.
@@ -449,15 +505,16 @@ export namespace A4p {
449 * @throws { BusinessError } 5001 - Serialization failed.505 * @throws { BusinessError } 5001 - Serialization failed.
450 */506 */
451 export function verifyIntentAuthenticity(intentL3: IntentL3, serverVerifier: SignatureVerifier): VerificationResult {507 export function verifyIntentAuthenticity(intentL3: IntentL3, serverVerifier: SignatureVerifier): VerificationResult {
452- // The L3 is only the carrier here: its own (user) signature is508+ // The L3 is structurally validated as a whole: the carrier must be a
453- // activateIntent's to verify, not this query's — the sole L3-level509+ // well-formed chain (its own sign, signingEnv, timestamp, version
454- // requirement is that it contains the L2 whose signature is checked.510+ // included) exactly like the one activateIntent freezes. Its own
455- if (!intentL3 || !intentL3.intentL2) {511+ // (user) signature remains activateIntent's to verify, not this
456- a4pThrow(A4pErrorCode.A4P_INVALID_PARAMETER, 'intentL3 must contain the intentL2 to verify');512+ // query's — presence and shape are checked here, the value is not.
457- }513+ // validateIntentL3 also covers the embedded L2 (with its L1), so no
514+ // separate L2 validation is needed.
515+ raise(validateIntentL3(intentL3));
458 516 
459 const intentL2: IntentL2 = intentL3.intentL2;517 const intentL2: IntentL2 = intentL3.intentL2;
460- raise(validateIntentL2(intentL2));
461 // The verified chain is the L2 with its embedded L1: a mixed-version518 // The verified chain is the L2 with its embedded L1: a mixed-version
462 // chain is signature-valid but semantically unsupported. The carrier519 // chain is signature-valid but semantically unsupported. The carrier
463 // L3's version plays no role in the verdict.520 // L3's version plays no role in the verdict.
@@ -470,26 +527,53 @@ export namespace A4p {
470 }527 }
471 528 
472 const l2Data: Uint8Array = toSignableBytes(intentL2);529 const l2Data: Uint8Array = toSignableBytes(intentL2);
473- // validateIntentL2 guarantees sign is present (validateSignatureInfo530+ // validateIntentL3 guarantees the embedded L2's sign is present
474- // rejects a missing or blank one); the cast only satisfies the compiler.531+ // (validateSignatureInfo rejects a missing or blank one); the cast
532+ // only satisfies the compiler.
475 return runVerifier(serverVerifier, l2Data, intentL2.sign as SignatureInfo, 'Server');533 return runVerifier(serverVerifier, l2Data, intentL2.sign as SignatureInfo, 'Server');
476 }534 }
477 535 
478 /**536 /**
479 * Revokes the intent: no new executions may be reserved; pending ones537 * Revokes the intent: no new executions may be reserved; pending ones
480 * can still complete or cancel.538 * can still complete or cancel.
539+ * `now` is the revocation instant in epoch milliseconds. It is validated
540+ * but never recorded — the status flip carries no timestamp, so unlike
541+ * the completion/cancellation floors this one guards no persisted
542+ * field. Its reason is the protocol's own: the revocable object is the
543+ * activated context, which exists only from `activatedTime` on, so an
544+ * instant before it is refused (equality allowed). Beyond that floor
545+ * the clock plays no role — the intent's validity window is
546+ * deliberately not judged: revocation is an administrative kill-switch,
547+ * and an intent whose window already closed is revoked rather than
548+ * reported as expired. Defaults to the system clock. A provided `now`
549+ * must be a non-negative safe integer.
481 * @param { IntentExecutionContext } context - The execution context to revoke.550 * @param { IntentExecutionContext } context - The execution context to revoke.
551+ * @param { number } now - Optional revocation instant in epoch milliseconds; defaults to Date.now().
482 * @returns { IntentExecutionContext } The updated execution context with status set to REVOKED.552 * @returns { IntentExecutionContext } The updated execution context with status set to REVOKED.
483 * @throws { BusinessError } 1001 - Invalid parameter.553 * @throws { BusinessError } 1001 - Invalid parameter.
484 * @throws { BusinessError } 3001 - Invalid status.554 * @throws { BusinessError } 3001 - Invalid status.
555+ * @throws { BusinessError } 3003 - Timestamp too early.
485 */556 */
486- export function revokeIntent(context: IntentExecutionContext): IntentExecutionContext {557+ export function revokeIntent(context: IntentExecutionContext, now?: number): IntentExecutionContext {
487 raise(validateExecutionContext(context));558 raise(validateExecutionContext(context));
559+ if (now !== undefined) {
560+ raise(validateNow(now));
561+ }
488 if (context.status !== IntentExecutionStatus.ACTIVE) {562 if (context.status !== IntentExecutionStatus.ACTIVE) {
489 a4pThrow(A4pErrorCode.A4P_INVALID_STATUS,563 a4pThrow(A4pErrorCode.A4P_INVALID_STATUS,
490 'revokeIntent requires an active intent, current status: ' + context.status);564 'revokeIntent requires an active intent, current status: ' + context.status);
491 }565 }
492 566 
567+ const nowMs: number = now !== undefined ? now : Date.now();
568+ // The revocation instant is floored by the context's creation: the
569+ // revocable object exists only from activatedTime on. Unlike the
570+ // completion/cancellation floors this guards no persisted field —
571+ // the status flip carries no timestamp. Equality is allowed.
572+ if (nowMs < context.activatedTime) {
573+ a4pThrow(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY,
574+ 'Revocation timestamp ' + nowMs + ' is earlier than activatedTime ' + context.activatedTime);
575+ }
atomgit-bot
atomgit-botatomgit-bot19 days ago

🟡 Medium Priority

改动行:a4p.ts:542-545 新增“撤销瞬间不得早于 context.activatedTime”的检查,未传 now 时取 Date.now()。

证据链:JSDoc 自述该瞬间“只校验、永不记录”(status flip 不带时间戳),因此这条下限与 completeExecution/cancelExecution 的理由不同——后两者是为了避免写入 completedAt/canceledAt < reservedAt 的、restore 侧会判为损坏的记录;撤销没有任何持久化时间戳,检查通过与否不改变落库数据。而同一段 JSDoc 又说“撤销是管理型 kill-switch,其前置条件是 context 状态而非时钟”。

建议:去掉对 activatedTime 的下限校验(该瞬间不落库,校验无持久化收益),或仅在调用方显式传入 now 时执行比较,避免默认墙钟把撤销这个 kill-switch 卡住。

likedislike
Incorrect?
576+ 
493 context.status = IntentExecutionStatus.REVOKED;577 context.status = IntentExecutionStatus.REVOKED;
494 return context;578 return context;
495 }579 }
@@ -502,10 +586,10 @@ export namespace A4p {
502 * @returns A validation failure if the cart exceeds scope, or null if within scope586 * @returns A validation failure if the cart exceeds scope, or null if within scope
503 */587 */
504 function enforceWhitelistScope(context: IntentExecutionContext, cartItems: CartItem[]): A4pValidationFailure | null {588 function enforceWhitelistScope(context: IntentExecutionContext, cartItems: CartItem[]): A4pValidationFailure | null {
505- const resource: ShoppingItems = context.authorizedIntent.intentL2.intentL1.structuredIntent.resource;589+ const resources: ShoppingItems = context.authorizedIntent.intentL2.intentL1.structuredIntent.resources;
506 for (let i = 0; i < cartItems.length; i++) {590 for (let i = 0; i < cartItems.length; i++) {
507 const item = cartItems[i];591 const item = cartItems[i];
508- const whitelisted: boolean = resource.itemsWhiteList.some(592+ const whitelisted: boolean = resources.itemsWhiteList.some(
509 (group: ItemWhiteList) => group.whiteList.some((p: Product) => productMatches(p, item.product)));593 (group: ItemWhiteList) => group.whiteList.some((p: Product) => productMatches(p, item.product)));
510 if (!whitelisted) {594 if (!whitelisted) {
511 return new A4pValidationFailure(A4pErrorCode.A4P_PRODUCT_NOT_AUTHORIZED,595 return new A4pValidationFailure(A4pErrorCode.A4P_PRODUCT_NOT_AUTHORIZED,
@@ -538,7 +622,7 @@ export namespace A4p {
538 */622 */
539 function enforceTemplateMatch(context: IntentExecutionContext, cartItems: CartItem[]): A4pValidationFailure | null {623 function enforceTemplateMatch(context: IntentExecutionContext, cartItems: CartItem[]): A4pValidationFailure | null {
540 const groups: ItemWhiteList[] =624 const groups: ItemWhiteList[] =
541- context.authorizedIntent.intentL2.intentL1.structuredIntent.resource.itemsWhiteList;625+ context.authorizedIntent.intentL2.intentL1.structuredIntent.resources.itemsWhiteList;
542 if (cartItems.length !== groups.length) {626 if (cartItems.length !== groups.length) {
543 return new A4pValidationFailure(A4pErrorCode.A4P_CART_MISMATCH,627 return new A4pValidationFailure(A4pErrorCode.A4P_CART_MISMATCH,
544 'Cart has ' + cartItems.length + ' items but the authorized resource has ' + groups.length +628 'Cart has ' + cartItems.length + ' items but the authorized resource has ' + groups.length +
@@ -584,11 +668,13 @@ export namespace A4p {
584 /**668 /**
585 * Reserves an execution against the context: the order is validated669 * Reserves an execution against the context: the order is validated
586 * against the frozen authorization snapshot (scope, order template,670 * against the frozen authorization snapshot (scope, order template,
587- * amounts, caps, period), appended to the ledger as PENDING, and the671+ * amounts, caps, period), appended to the ledger as a flat PENDING
588- * quota figures are re-derived from the ledger. The caller's execution672+ * record (executionId, action, executionContent), and the quota
589- * object is never mutated — the id is resolved locally (generated when673+ * figures are re-derived from the ledger. The caller's execution
590- * absent) and lands on the ledger's own deep copy only after every674+ * object is neither mutated nor aliased — the id is resolved locally
591- * check has passed.675+ * (generated when absent) and stored as the record's executionId, and
676+ * the action plus a deep copy of the executionContent land on the
677+ * record only after every check has passed.
592 *678 *
593 * `orderId` is the payment idempotency key: a reservation whose orderId679 * `orderId` is the payment idempotency key: a reservation whose orderId
594 * is already present in the context's ledger — canceled records included680 * is already present in the context's ledger — canceled records included
@@ -648,9 +734,10 @@ export namespace A4p {
648 raise(validateNow(now));734 raise(validateNow(now));
649 }735 }
650 raise(validateExecution(execution));736 raise(validateExecution(execution));
651- // The caller's object is never mutated: the id is resolved locally737+ // The caller's object is never mutated or aliased: the id is resolved
652- // (generated when absent) and assigned to the ledger's own deep copy738+ // locally (generated when absent) and stored as the record's
653- // only after every check has passed.739+ // executionId; the content lands as the record's own deep copy only
740+ // after every check has passed.
654 const executionId: string = execution.id !== undefined ? execution.id : util.generateRandomUUID();741 const executionId: string = execution.id !== undefined ? execution.id : util.generateRandomUUID();
655 742 
656 // Checks run in a fixed order — request structure (above), parameter743 // Checks run in a fixed order — request structure (above), parameter
@@ -704,19 +791,19 @@ export namespace A4p {
704 // most once per context — canceled records included, so a canceled791 // most once per context — canceled records included, so a canceled
705 // reservation cannot be re-reserved under a fresh execution id.792 // reservation cannot be re-reserved under a fresh execution id.
706 const duplicateOrder: boolean = context.executions.some(793 const duplicateOrder: boolean = context.executions.some(
707- (r: ExecutionRecord) => r.execution.executionContent.orderId === execution.executionContent.orderId);794+ (r: ExecutionRecord) => r.executionContent.orderId === execution.executionContent.orderId);
708 if (duplicateOrder) {795 if (duplicateOrder) {
709 a4pThrow(A4pErrorCode.A4P_DUPLICATE_ID,796 a4pThrow(A4pErrorCode.A4P_DUPLICATE_ID,
710 'Order ID already exists: ' + execution.executionContent.orderId);797 'Order ID already exists: ' + execution.executionContent.orderId);
711 }798 }
712 // Optional caps: an absent cap means no limit of that kind, so the799 // Optional caps: an absent cap means no limit of that kind, so the
713 // check is skipped entirely.800 // check is skipped entirely.
714- const countCap: number | undefined = constraints.maxExecuteCount;801+ const countCap: number | undefined = constraints.maxExecutionCount;
715 if (countCap !== undefined) {802 if (countCap !== undefined) {
716 const executionCount: number = computeExecutionCount(context.executions);803 const executionCount: number = computeExecutionCount(context.executions);
717 if (executionCount >= countCap) {804 if (executionCount >= countCap) {
718 a4pThrow(A4pErrorCode.A4P_EXECUTION_COUNT_EXCEEDED,805 a4pThrow(A4pErrorCode.A4P_EXECUTION_COUNT_EXCEEDED,
719- 'Execution count ' + executionCount + ' reached maxExecuteCount ' + countCap);806+ 'Execution count ' + executionCount + ' reached maxExecutionCount ' + countCap);
720 }807 }
721 }808 }
722 809 
@@ -752,13 +839,17 @@ export namespace A4p {
752 }839 }
753 }840 }
754 841 
755- const storedExecution: Execution = deepClone(execution);842+ // The caller's object is never mutated and never aliased: the id is
756- storedExecution.id = executionId;843+ // resolved locally (generated when absent) and stored as the record's
844+ // executionId, while the action and a deep copy of the executionContent
845+ // land on the ledger's own flat record only after every check has
846+ // passed.
757 const record: ExecutionRecord = {847 const record: ExecutionRecord = {
758 executionId: executionId,848 executionId: executionId,
759 status: ExecutionStatus.PENDING,849 status: ExecutionStatus.PENDING,
850+ action: execution.action,
851+ executionContent: deepClone(execution.executionContent),
760 reservedAt: nowMs,852 reservedAt: nowMs,
761- execution: storedExecution,
762 };853 };
763 if (currentPeriodIndex !== undefined) {854 if (currentPeriodIndex !== undefined) {
764 record.periodIndex = currentPeriodIndex;855 record.periodIndex = currentPeriodIndex;
@@ -783,13 +874,17 @@ export namespace A4p {
783 * completion books no quota (a PENDING record already counts), but the874 * completion books no quota (a PENDING record already counts), but the
784 * evaluation instant moves, so the period figures (periodIndex,875 * evaluation instant moves, so the period figures (periodIndex,
785 * leftPeriodExecutionCount) are updated to the period containing the876 * leftPeriodExecutionCount) are updated to the period containing the
786- * completion instant.877+ * completion instant. It must not be earlier than the record's
878+ * `reservedAt`: a finalization predating its own reservation would
879+ * rewrite history (the ledger's timestamps are monotonic like the
880+ * chain's), so such a clock is rejected instead of persisted.
787 * @param { IntentExecutionContext } context - The execution context containing the pending execution.881 * @param { IntentExecutionContext } context - The execution context containing the pending execution.
788 * @param { string } executionId - The ID of the execution to mark completed.882 * @param { string } executionId - The ID of the execution to mark completed.
789 * @param { number } now - Optional completion timestamp in epoch milliseconds; defaults to Date.now().883 * @param { number } now - Optional completion timestamp in epoch milliseconds; defaults to Date.now().
790 * @returns { IntentExecutionContext } The updated execution context.884 * @returns { IntentExecutionContext } The updated execution context.
791 * @throws { BusinessError } 1001 - Invalid parameter.885 * @throws { BusinessError } 1001 - Invalid parameter.
792 * @throws { BusinessError } 3001 - Invalid status.886 * @throws { BusinessError } 3001 - Invalid status.
887+ * @throws { BusinessError } 3003 - Timestamp too early.
793 */888 */
794 export function completeExecution(context: IntentExecutionContext, executionId: string,889 export function completeExecution(context: IntentExecutionContext, executionId: string,
795 now?: number): IntentExecutionContext {890 now?: number): IntentExecutionContext {
@@ -813,6 +908,14 @@ export namespace A4p {
813 }908 }
814 909 
815 const nowMs: number = now !== undefined ? now : Date.now();910 const nowMs: number = now !== undefined ? now : Date.now();
911+ // Record timestamps are monotonic like the chain's: a completion can
912+ // never predate the reservation it finalizes. A clock stepped back past
913+ // reservedAt is refused here rather than persisted as a record that
914+ // restore-side validation would reject as corrupted.
915+ if (nowMs < record.reservedAt) {
916+ a4pThrow(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY,
917+ 'Completion timestamp ' + nowMs + ' is earlier than reservedAt ' + record.reservedAt);
maoqiming
maoqimingmaoqiming18 days ago

【review】错误码一致性。当 activatedTime <= now < reservedAt 时,Java 的 completeExecution 和 cancelExecution 返回 A4P_INVALID_PARAMETER,而 ArkTS 两条路径返回 A4P_TIMESTAMP_TOO_EARLY;同一输入的错误码仍不一致,持久化恢复校验也沿用该差异。请将该场景统一为 A4P_INVALID_PARAMETER,并同步恢复校验及完成、取消、反序列化测试,或先修改 Java 契约并补齐文档。

likedislike
wangweizhen
18 days ago Comments:
likedislike
918+ }
816 record.status = ExecutionStatus.COMPLETED;919 record.status = ExecutionStatus.COMPLETED;
817 record.completedAt = nowMs;920 record.completedAt = nowMs;
818 921 
@@ -829,14 +932,14 @@ export namespace A4p {
829 // settled ledger: the count cap is reached or the total amount budget932 // settled ledger: the count cap is reached or the total amount budget
830 // is exhausted, and every record is finalized (flipping while a record933 // is exhausted, and every record is finalized (flipping while a record
831 // is still PENDING would strand it — finalize APIs require a934 // is still PENDING would strand it — finalize APIs require a
832- // non-CONSUMED status). Without maxExecuteCount the count trigger is935+ // non-CONSUMED status). Without maxExecutionCount the count trigger is
833 // absent but the amount trigger remains (totalMaxAmount is always936 // absent but the amount trigger remains (totalMaxAmount is always
834 // present). A REVOKED or EXPIRED context keeps its status —937 // present). A REVOKED or EXPIRED context keeps its status —
835 // revocation/expiry is a fact about the intent's history, not erased938 // revocation/expiry is a fact about the intent's history, not erased
836 // by the ledger draining.939 // by the ledger draining.
837 const constraints: PaymentConstraints =940 const constraints: PaymentConstraints =
838 context.authorizedIntent.intentL2.intentL1.structuredIntent.constraints;941 context.authorizedIntent.intentL2.intentL1.structuredIntent.constraints;
839- const countCap: number | undefined = constraints.maxExecuteCount;942+ const countCap: number | undefined = constraints.maxExecutionCount;
840 const countReached: boolean = countCap !== undefined &&943 const countReached: boolean = countCap !== undefined &&
841 computeExecutionCount(context.executions) >= countCap;944 computeExecutionCount(context.executions) >= countCap;
842 const amountExhausted: boolean = computeAccumulatedAmount(context.executions) >= constraints.totalMaxAmount;945 const amountExhausted: boolean = computeAccumulatedAmount(context.executions) >= constraints.totalMaxAmount;
@@ -857,12 +960,17 @@ export namespace A4p {
857 * `now` is the evaluation instant in epoch milliseconds (see createExecution).960 * `now` is the evaluation instant in epoch milliseconds (see createExecution).
858 * Allowed when the context is ACTIVE, REVOKED, or EXPIRED (so pending961 * Allowed when the context is ACTIVE, REVOKED, or EXPIRED (so pending
859 * executions reserved before revocation or expiry can still be finalized).962 * executions reserved before revocation or expiry can still be finalized).
963+ * `now` must not be earlier than the record's `reservedAt`: a
964+ * finalization predating its own reservation would rewrite history (the
965+ * ledger's timestamps are monotonic like the chain's), so such a clock is
966+ * rejected instead of persisted.
860 * @param { IntentExecutionContext } context - The execution context containing the pending execution.967 * @param { IntentExecutionContext } context - The execution context containing the pending execution.
861 * @param { string } executionId - The ID of the execution to cancel.968 * @param { string } executionId - The ID of the execution to cancel.
862 * @param { number } now - Optional cancellation timestamp in epoch milliseconds; defaults to Date.now().969 * @param { number } now - Optional cancellation timestamp in epoch milliseconds; defaults to Date.now().
863 * @returns { IntentExecutionContext } The updated execution context with quota released.970 * @returns { IntentExecutionContext } The updated execution context with quota released.
864 * @throws { BusinessError } 1001 - Invalid parameter.971 * @throws { BusinessError } 1001 - Invalid parameter.
865 * @throws { BusinessError } 3001 - Invalid status.972 * @throws { BusinessError } 3001 - Invalid status.
973+ * @throws { BusinessError } 3003 - Timestamp too early.
866 */974 */
867 export function cancelExecution(context: IntentExecutionContext, executionId: string,975 export function cancelExecution(context: IntentExecutionContext, executionId: string,
868 now?: number): IntentExecutionContext {976 now?: number): IntentExecutionContext {
@@ -885,8 +993,14 @@ export namespace A4p {
885 a4pThrow(A4pErrorCode.A4P_INVALID_STATUS, 'Execution is not pending, current status: ' + record.status);993 a4pThrow(A4pErrorCode.A4P_INVALID_STATUS, 'Execution is not pending, current status: ' + record.status);
886 }994 }
887 995 
888- record.status = ExecutionStatus.CANCELED;
889 const nowMs: number = now !== undefined ? now : Date.now();996 const nowMs: number = now !== undefined ? now : Date.now();
997+ // Same monotonic rule as completeExecution: a cancellation predating
998+ // its own reservation is a rewound clock, not a fact to persist.
999+ if (nowMs < record.reservedAt) {
1000+ a4pThrow(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY,
1001+ 'Cancellation timestamp ' + nowMs + ' is earlier than reservedAt ' + record.reservedAt);
1002+ }
1003+ record.status = ExecutionStatus.CANCELED;
890 record.canceledAt = nowMs;1004 record.canceledAt = nowMs;
891 1005 
892 // Quota release happens by re-deriving from the ledger — the canceled1006 // Quota release happens by re-deriving from the ledger — the canceled
@@ -111,7 +111,7 @@ export function computeAccumulatedAmount(executions: ExecutionRecord[]): number
111 let sum: number = 0;111 let sum: number = 0;
112 for (let i = 0; i < executions.length; i++) {112 for (let i = 0; i < executions.length; i++) {
113 if (isCountedRecord(executions[i])) {113 if (isCountedRecord(executions[i])) {
114- sum += executions[i].execution.executionContent.amount;114+ sum += executions[i].executionContent.amount;
115 }115 }
116 }116 }
117 return sum;117 return sum;
@@ -121,7 +121,7 @@ export function computeAccumulatedAmount(executions: ExecutionRecord[]): number
121 * Derives the execution-info snapshot from the payment constraints and the121 * Derives the execution-info snapshot from the payment constraints and the
122 * executions ledger:122 * executions ledger:
123 * - fields whose cap does not apply are omitted: `leftExecutionCount` when123 * - fields whose cap does not apply are omitted: `leftExecutionCount` when
124- * the intent carries no `maxExecuteCount` cap, and the period figures124+ * the intent carries no `maxExecutionCount` cap, and the period figures
125 * (`periodIndex`, `leftPeriodExecutionCount`) for non-periodic intents;125 * (`periodIndex`, `leftPeriodExecutionCount`) for non-periodic intents;
126 * - all figures count only non-canceled records (an explicit cancel126 * - all figures count only non-canceled records (an explicit cancel
127 * releases the quota);127 * releases the quota);
@@ -136,7 +136,7 @@ export function computeExecutionInfo(constraints: PaymentConstraints, executions
136 const info: PaymentExecutionInfo = {136 const info: PaymentExecutionInfo = {
137 leftAmount: constraints.totalMaxAmount - computeAccumulatedAmount(executions)137 leftAmount: constraints.totalMaxAmount - computeAccumulatedAmount(executions)
138 };138 };
139- const countCap: number | undefined = constraints.maxExecuteCount;139+ const countCap: number | undefined = constraints.maxExecutionCount;
140 if (countCap !== undefined) {140 if (countCap !== undefined) {
141 info.leftExecutionCount = countCap - computeExecutionCount(executions);141 info.leftExecutionCount = countCap - computeExecutionCount(executions);
142 }142 }
@@ -90,7 +90,7 @@ function isValidAlgorithmType(alg: AlgorithmType): boolean {
90 90 
91/**91/**
92 * Validates a PaymentConstraints object: amounts, validity window, and the92 * Validates a PaymentConstraints object: amounts, validity window, and the
93- * period rule. Optional caps (`singleOrderMaxAmount`, `maxExecuteCount`)93+ * period rule. Optional caps (`singleOrderMaxAmount`, `maxExecutionCount`)
94 * are validated only when present; the period rule is all-or-nothing —94 * are validated only when present; the period rule is all-or-nothing —
95 * all three fields provided (periodic) or all three omitted95 * all three fields provided (periodic) or all three omitted
96 * (non-periodic), never partial.96 * (non-periodic), never partial.
@@ -114,8 +114,8 @@ function validatePaymentConstraints(pc: PaymentConstraints): Validation {
114 if (pc.validFrom > pc.validUntil) {114 if (pc.validFrom > pc.validUntil) {
115 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'validFrom must not be later than validUntil');115 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'validFrom must not be later than validUntil');
116 }116 }
117- if (pc.maxExecuteCount !== undefined && !isPositiveInteger(pc.maxExecuteCount)) {117+ if (pc.maxExecutionCount !== undefined && !isPositiveInteger(pc.maxExecutionCount)) {
118- return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'maxExecuteCount must be a positive integer');118+ return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'maxExecutionCount must be a positive integer');
119 }119 }
120 const hasAnchorTime: boolean = pc.anchorTime !== undefined;120 const hasAnchorTime: boolean = pc.anchorTime !== undefined;
121 const hasPeriodSeconds: boolean = pc.periodSeconds !== undefined;121 const hasPeriodSeconds: boolean = pc.periodSeconds !== undefined;
@@ -224,23 +224,23 @@ function validateItemWhiteList(group: ItemWhiteList, field: string): Validation
224}224}
225 225 
226/**226/**
227- * Validates the resource: a non-empty list of valid whitelist groups with227+ * Validates the resources: a non-empty list of valid whitelist groups with
228- * no product shared by two groups. The resource is an order template and228+ * no product shared by two groups. The resources are an order template and
229 * a cart item finds its group by product alone, so a product must229 * a cart item finds its group by product alone, so a product must
230 * uniquely determine its group.230 * uniquely determine its group.
231 */231 */
232-function validateShoppingItems(resource: ShoppingItems, field: string): Validation {232+function validateShoppingItems(resources: ShoppingItems, field: string): Validation {
233- if (!resource.itemsWhiteList || resource.itemsWhiteList.length === 0) {233+ if (!resources.itemsWhiteList || resources.itemsWhiteList.length === 0) {
234 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + '.itemsWhiteList must not be empty');234 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + '.itemsWhiteList must not be empty');
235 }235 }
236- for (let i = 0; i < resource.itemsWhiteList.length; i++) {236+ for (let i = 0; i < resources.itemsWhiteList.length; i++) {
237- const groupErr = validateItemWhiteList(resource.itemsWhiteList[i], field + '.itemsWhiteList[' + i + ']');237+ const groupErr = validateItemWhiteList(resources.itemsWhiteList[i], field + '.itemsWhiteList[' + i + ']');
238 if (groupErr) {238 if (groupErr) {
239 return groupErr;239 return groupErr;
240 }240 }
241 for (let j = 0; j < i; j++) {241 for (let j = 0; j < i; j++) {
242- const earlier: ItemWhiteList = resource.itemsWhiteList[j];242+ const earlier: ItemWhiteList = resources.itemsWhiteList[j];
243- const current: ItemWhiteList = resource.itemsWhiteList[i];243+ const current: ItemWhiteList = resources.itemsWhiteList[i];
244 for (let a = 0; a < current.whiteList.length; a++) {244 for (let a = 0; a < current.whiteList.length; a++) {
245 for (let b = 0; b < earlier.whiteList.length; b++) {245 for (let b = 0; b < earlier.whiteList.length; b++) {
246 if (productMatches(current.whiteList[a], earlier.whiteList[b])) {246 if (productMatches(current.whiteList[a], earlier.whiteList[b])) {
@@ -279,17 +279,17 @@ function validateCartItems(cartItems: CartItem[], field: string): Validation {
279 return null;279 return null;
280}280}
281 281 
282-/** Validates a StructuredIntent: action, resource, and constraints. */282+/** Validates a StructuredIntent: action, resources, and constraints. */
283function validateStructuredIntent(si: StructuredIntent): Validation {283function validateStructuredIntent(si: StructuredIntent): Validation {
284 if (!isValidIntentActionType(si.action)) {284 if (!isValidIntentActionType(si.action)) {
285 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.action must be a valid IntentActionType');285 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.action must be a valid IntentActionType');
286 }286 }
287- if (!si.resource) {287+ if (!si.resources) {
288- return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.resource must not be null');288+ return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.resources must not be null');
289 }289 }
290- const resourceErr = validateShoppingItems(si.resource, 'structuredIntent.resource');290+ const resourcesErr = validateShoppingItems(si.resources, 'structuredIntent.resources');
291- if (resourceErr) {291+ if (resourcesErr) {
292- return resourceErr;292+ return resourcesErr;
293 }293 }
294 if (!si.constraints) {294 if (!si.constraints) {
295 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.constraints must not be null');295 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, 'structuredIntent.constraints must not be null');
@@ -666,7 +666,8 @@ function isValidIntentExecutionStatus(status: IntentExecutionStatus): boolean {
666 * Validates an execution record: a non-blank executionId, a defined666 * Validates an execution record: a non-blank executionId, a defined
667 * status, a non-negative reservedAt, the status-bound finalization667 * status, a non-negative reservedAt, the status-bound finalization
668 * timestamps (completedAt on a COMPLETED record, canceledAt on a CANCELED668 * timestamps (completedAt on a COMPLETED record, canceledAt on a CANCELED
669- * one — and only there), and the embedded execution itself.669+ * one — and only there), and the flat reserved-execution fields (a valid
670+ * action and a well-formed executionContent).
670 * @param record - The execution record to validate671 * @param record - The execution record to validate
671 * @param field - The field path prefix for error messages672 * @param field - The field path prefix for error messages
672 * @returns A validation failure if invalid, or null if valid673 * @returns A validation failure if invalid, or null if valid
@@ -721,19 +722,31 @@ function validateExecutionRecord(record: ExecutionRecord, field: string): Valida
721 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,722 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,
722 field + '.canceledAt must be present only on a CANCELED record');723 field + '.canceledAt must be present only on a CANCELED record');
723 }724 }
724- if (!record.execution) {725+ // Record timestamps are monotonic like the chain's: a finalization can
725- return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + '.execution must not be null');726+ // never predate the reservation it finalizes (completeExecution and
727+ // cancelExecution reject such a clock), so a persisted record violating
728+ // it is corrupted data and fails with the code the offending operation
729+ // would have returned.
730+ if (record.completedAt !== undefined && record.completedAt < record.reservedAt) {
731+ return fail(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY,
732+ field + '.completedAt must not be earlier than ' + field + '.reservedAt');
726 }733 }
727- const execErr = validateExecution(record.execution);734+ if (record.canceledAt !== undefined && record.canceledAt < record.reservedAt) {
728- if (execErr) {735+ return fail(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY,
729- return execErr;736+ field + '.canceledAt must not be earlier than ' + field + '.reservedAt');
730 }737 }
731- // The record's key and the stored execution's id are the same id by738+ // The reserved execution's fields live flat on the record: a valid
732- // construction (createExecution resolves it once); a mismatch is739+ // action and a well-formed order, exactly like the execution
733- // corrupted data.740+ // createExecution received and validated the same way.
734- if (record.execution.id !== record.executionId) {741+ if (!isValidIntentActionType(record.action)) {
735- return fail(A4pErrorCode.A4P_INVALID_PARAMETER,742+ return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + '.action must be a valid IntentActionType');
736- field + '.execution.id must equal ' + field + '.executionId');743+ }
744+ if (!record.executionContent) {
745+ return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + '.executionContent must not be null');
746+ }
747+ const orderErr = validateOrder(record.executionContent);
748+ if (orderErr) {
749+ return orderErr;
737 }750 }
738 return null;751 return null;
739}752}
@@ -752,9 +765,10 @@ function validatePaymentExecutionInfo(info: PaymentExecutionInfo, field: string)
752 if (!info) {765 if (!info) {
753 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + ' must not be null');766 return fail(A4pErrorCode.A4P_INVALID_PARAMETER, field + ' must not be null');
754 }767 }
755- // The snapshot period index may be negative: activateIntent applies no768+ // The snapshot period index may be negative: activateIntent judges only
756- // validity-window check, so an activation before the anchor snapshots769+ // the window's upper bound (validUntil) and permits an instant before
757- // the pre-anchor period. Record indexes, in contrast, are reserved at770+ // validFrom, so an activation before the anchor snapshots the pre-anchor
771+ // period. Record indexes, in contrast, are reserved at
758 // now >= validFrom >= anchorTime and are never negative.772 // now >= validFrom >= anchorTime and are never negative.
759 if (info.periodIndex !== undefined && !isSafeInteger(info.periodIndex)) {773 if (info.periodIndex !== undefined && !isSafeInteger(info.periodIndex)) {
760 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,774 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,
@@ -782,7 +796,7 @@ function validatePaymentExecutionInfo(info: PaymentExecutionInfo, field: string)
782 * snapshot — including the cap-tied presence rules: records carry a796 * snapshot — including the cap-tied presence rules: records carry a
783 * periodIndex exactly when the intent is periodic, and the snapshot797 * periodIndex exactly when the intent is periodic, and the snapshot
784 * carries its period figures exactly when periodic and798 * carries its period figures exactly when periodic and
785- * leftExecutionCount exactly when the intent has a maxExecuteCount cap.799+ * leftExecutionCount exactly when the intent has a maxExecutionCount cap.
786 * Used by the codec when deserializing a context (see800 * Used by the codec when deserializing a context (see
787 * A4pCodec.deserializeIntentExecutionContext); the execution APIs keep801 * A4pCodec.deserializeIntentExecutionContext); the execution APIs keep
788 * the lighter presence-only validateExecutionContext.802 * the lighter presence-only validateExecutionContext.
@@ -857,14 +871,14 @@ export function validateIntentExecutionContext(context: IntentExecutionContext):
857 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,871 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,
858 'context.executionInfo.periodIndex and leftPeriodExecutionCount must be absent on a non-periodic intent');872 'context.executionInfo.periodIndex and leftPeriodExecutionCount must be absent on a non-periodic intent');
859 }873 }
860- const countCap: number | undefined = l1.structuredIntent.constraints.maxExecuteCount;874+ const countCap: number | undefined = l1.structuredIntent.constraints.maxExecutionCount;
861 if (countCap !== undefined && context.executionInfo.leftExecutionCount === undefined) {875 if (countCap !== undefined && context.executionInfo.leftExecutionCount === undefined) {
862 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,876 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,
863- 'context.executionInfo.leftExecutionCount must be present when the intent carries maxExecuteCount');877+ 'context.executionInfo.leftExecutionCount must be present when the intent carries maxExecutionCount');
864 }878 }
865 if (countCap === undefined && context.executionInfo.leftExecutionCount !== undefined) {879 if (countCap === undefined && context.executionInfo.leftExecutionCount !== undefined) {
866 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,880 return fail(A4pErrorCode.A4P_INVALID_PARAMETER,
867- 'context.executionInfo.leftExecutionCount must be absent when the intent carries no maxExecuteCount');881+ 'context.executionInfo.leftExecutionCount must be absent when the intent carries no maxExecutionCount');
868 }882 }
869 return null;883 return null;
870}884}
@@ -84,7 +84,7 @@ export enum A4pErrorCode {
84 A4P_INVALID_STATUS = 3001,84 A4P_INVALID_STATUS = 3001,
85 /** Timestamp has expired (exceeded validUntil) */85 /** Timestamp has expired (exceeded validUntil) */
86 A4P_TIMESTAMP_EXPIRED = 3002,86 A4P_TIMESTAMP_EXPIRED = 3002,
87- /** Timestamp is too early (before validFrom) */87+ /** Timestamp is too early (before validFrom, or before a record's reservedAt) */
88 A4P_TIMESTAMP_TOO_EARLY = 3003,88 A4P_TIMESTAMP_TOO_EARLY = 3003,
89 89 
90 /** Total execution count limit exceeded */90 /** Total execution count limit exceeded */
@@ -95,7 +95,7 @@ export enum A4pErrorCode {
95 A4P_PERIOD_COUNT_EXCEEDED = 4003,95 A4P_PERIOD_COUNT_EXCEEDED = 4003,
96 /** Period execution count limit exceeded */96 /** Period execution count limit exceeded */
97 A4P_PERIOD_EXECUTION_COUNT_EXCEEDED = 4004,97 A4P_PERIOD_EXECUTION_COUNT_EXCEEDED = 4004,
98- /** Cart does not match the intent's authorized resource order template */98+ /** Cart does not match the intent's authorized resources order template */
99 A4P_CART_MISMATCH = 4005,99 A4P_CART_MISMATCH = 4005,
100 /** Single order amount limit exceeded */100 /** Single order amount limit exceeded */
101 A4P_SINGLE_ORDER_AMOUNT_EXCEEDED = 4006,101 A4P_SINGLE_ORDER_AMOUNT_EXCEEDED = 4006,
@@ -11,7 +11,7 @@
11/**11/**
12 * Payment constraints for an intent: per-order and total amount limits,12 * Payment constraints for an intent: per-order and total amount limits,
13 * validity window, execution count cap, and per-period execution limits.13 * validity window, execution count cap, and per-period execution limits.
14- * `singleOrderMaxAmount` and `maxExecuteCount` are optional (absent means14+ * `singleOrderMaxAmount` and `maxExecutionCount` are optional (absent means
15 * no cap of that kind); the period rule (`anchorTime`/`periodSeconds`/15 * no cap of that kind); the period rule (`anchorTime`/`periodSeconds`/
16 * `maxExecutionCountPerPeriod`) is all-or-nothing — a periodic intent16 * `maxExecutionCountPerPeriod`) is all-or-nothing — a periodic intent
17 * provides all three, a non-periodic intent omits all three.17 * provides all three, a non-periodic intent omits all three.
@@ -36,7 +36,7 @@ export interface PaymentConstraints {
36 * a slot); must be a positive integer when present — absent means no36 * a slot); must be a positive integer when present — absent means no
37 * execution count cap37 * execution count cap
38 */38 */
39- maxExecuteCount?: number;39+ maxExecutionCount?: number;
40 /**40 /**
41 * Anchor time for period calculation (milliseconds since epoch); provided41 * Anchor time for period calculation (milliseconds since epoch); provided
42 * together with periodSeconds and maxExecutionCountPerPeriod, or all42 * together with periodSeconds and maxExecutionCountPerPeriod, or all
@@ -39,13 +39,15 @@ export interface Order {
39}39}
40 40 
41/**41/**
42- * An execution requested against an activated intent: reserved via42+ * An execution requested against an activated intent: the input to
43- * createExecution and recorded in the ledger as an ExecutionRecord.43+ * createExecution. The reserved ledger record stores its fields flat (see
44+ * ExecutionRecord): the resolved id becomes the record's `executionId`,
45+ * and `action`/`executionContent` are copied onto the record itself.
44 */46 */
45export interface Execution {47export interface Execution {
46 /** Action to perform; must match the authorized intent's action */48 /** Action to perform; must match the authorized intent's action */
47 action: IntentActionType;49 action: IntentActionType;
48- /** Unique execution identifier */50+ /** Unique execution identifier; resolved into the record's executionId (generated when absent) */
49 id?: string;51 id?: string;
50 /** Execution content (order details) */52 /** Execution content (order details) */
51 executionContent: Order;53 executionContent: Order;
@@ -85,6 +87,10 @@ export interface ExecutionRecord {
85 executionId: string;87 executionId: string;
86 /** Current status of the execution */88 /** Current status of the execution */
87 status: ExecutionStatus;89 status: ExecutionStatus;
90+ /** Action to perform; copied from the reserved execution (matches the authorized intent's action) */
91+ action: IntentActionType;
92+ /** Execution content (order details); a deep copy of the reserved execution's content */
93+ executionContent: Order;
maoqiming
maoqimingmaoqiming18 days ago

【review】接口兼容性。ArkTS 账本已改为在记录顶层序列化 action 和 executionContent,而本仓库的 Java SDK 仍将其放在 execution 子对象中,并额外校验 id 与 version;同一执行上下文在两端无法互相反序列化,也与 PR 宣称的字段名一致不符。请先确定唯一的线格式并同步两端模型、校验与编解码;若采用扁平格式,需同步 Java SDK,并增加双向 golden JSON 与 restore 互操作测试。

likedislike
wangweizhen
18 days ago Comments:
likedislike
88 /** Period index of the reservation; present only for periodic intents */94 /** Period index of the reservation; present only for periodic intents */
89 periodIndex?: number;95 periodIndex?: number;
90 /** Timestamp when execution was reserved (always present) */96 /** Timestamp when execution was reserved (always present) */
@@ -93,8 +99,6 @@ export interface ExecutionRecord {
93 completedAt?: number;99 completedAt?: number;
94 /** Timestamp when execution was canceled (only when status is CANCELED) */100 /** Timestamp when execution was canceled (only when status is CANCELED) */
95 canceledAt?: number;101 canceledAt?: number;
96- /** The execution that was reserved */
97- execution: Execution;
98}102}
99 103 
100/**104/**
@@ -103,7 +107,7 @@ export interface ExecutionRecord {
103 * hand; see internal/accounting.ts). Fields whose cap does not apply are107 * hand; see internal/accounting.ts). Fields whose cap does not apply are
104 * omitted: `periodIndex`/`leftPeriodExecutionCount` for non-periodic108 * omitted: `periodIndex`/`leftPeriodExecutionCount` for non-periodic
105 * intents, `leftExecutionCount` when the intent carries no109 * intents, `leftExecutionCount` when the intent carries no
106- * `maxExecuteCount` cap.110+ * `maxExecutionCount` cap.
107 */111 */
108export interface PaymentExecutionInfo {112export interface PaymentExecutionInfo {
109 /** Index of the period containing the evaluation instant; periodic intents only */113 /** Index of the period containing the evaluation instant; periodic intents only */
@@ -112,7 +116,7 @@ export interface PaymentExecutionInfo {
112 leftPeriodExecutionCount?: number;116 leftPeriodExecutionCount?: number;
113 /**117 /**
114 * Executions still allowed against the count cap (an explicit cancel118 * Executions still allowed against the count cap (an explicit cancel
115- * releases a slot); omitted when the intent carries no maxExecuteCount cap119+ * releases a slot); omitted when the intent carries no maxExecutionCount cap
116 */120 */
117 leftExecutionCount?: number;121 leftExecutionCount?: number;
118 /** Amount still allowed against the total amount cap (non-canceled records only) */122 /** Amount still allowed against the total amount cap (non-canceled records only) */
@@ -32,14 +32,14 @@ export enum AlgorithmType {
32}32}
33 33 
34/**34/**
35- * Structured intent data defining the action, the authorized resource,35+ * Structured intent data defining the action, the authorized resources,
36 * and the payment constraints.36 * and the payment constraints.
37 */37 */
38export interface StructuredIntent {38export interface StructuredIntent {
39 /** Action to be performed */39 /** Action to be performed */
40 action: IntentActionType;40 action: IntentActionType;
41- /** Resource being acted upon (the authorized purchase whitelist) */41+ /** Resources being acted upon (the authorized purchase whitelist) */
42- resource: ShoppingItems;42+ resources: ShoppingItems;
atomgit-bot
atomgit-botatomgit-bot19 days ago

🟠 High Priority

改动行:models/intent.ts:42 把 StructuredIntent.resource 改名为 resources(wire 字段名随之变成 resources,A4pCodec 的 canonical JSON 与签名都基于真实属性名)。但混淆保留名单仍是旧名:A4p-arkts-sdk/a4p/obfuscation-rules.txt:70 与 A4p-arkts-sdk/a4p/consumer-rules.txt:61 都只保留了 resource,没有 resources。

证据链:build-profile.json5 的 release buildOptionSet 打开了 obfuscation.enable,规则文件里 -enable-property-obfuscation + -keep-property-name(strict、区分大小写)是唯一保护;两个规则文件头部注释明确写着“每个 wire-visible 字段 MUST 在同一次改动中加入”。本 PR 只改了模型与代码,规则文件未动,属于典型的单边改名。

失效模式:debug/本地 UT 全部通过(属性名未被混淆),但 release HAR 里 resources 会被改名,产出的 L1/L2/L3 JSON key 变成例如 a,服务端/Java SDK 无法解析,且签名覆盖的字节与对端不一致导致验签失败;A4pCodec.test.ets 的 GoldenWireKeys 用例(注释自述是“混淆 tripwire”,要求对开启混淆的 release 包跑一遍)也会直接失败。

修复:把两个规则文件中的 resource 行替换为 resources(不要保留旧名,用户的同名 resource 属性无需保护),并检查同一处其余新字段。

建议:在 obfuscation-rules.txt 与 consumer-rules.txt 的 -keep-property-name 段中把 resource 改为 resources,与本字段改名保持同步(规则文件注释要求同一次改动内加入)。

likedislike
Incorrect?
43 /** Payment constraints for this intent */43 /** Payment constraints for this intent */
44 constraints: PaymentConstraints;44 constraints: PaymentConstraints;
45}45}
@@ -67,10 +67,10 @@ export interface ItemWhiteList {
67}67}
68 68 
69/**69/**
70- * Resource object of a structured intent: the whitelist groups that70+ * Resources object of a structured intent (the `resources` field): the
71- * together form the order template every AI_PAY execution must satisfy71+ * whitelist groups that together form the order template every AI_PAY
72- * — all groups must be purchased (AND), each group satisfied by any72+ * execution must satisfy — all groups must be purchased (AND), each
73- * one of its whitelisted products (OR).73+ * group satisfied by any one of its whitelisted products (OR).
74 *74 *
75 * The template binds products and quantities only: Product carries no75 * The template binds products and quantities only: Product carries no
76 * price, so the signed scope places no price terms on an order and the76 * price, so the signed scope places no price terms on an order and the
MA4P-arkts-sdk/a4p/src/ohosTest/ets/test/A4p.test.ets+249-70File content is under review, please try again later
@@ -121,7 +121,7 @@ export default function a4pCodecTest() {
121 timestamp: l1.timestamp,121 timestamp: l1.timestamp,
122 structuredIntent: {122 structuredIntent: {
123 constraints: l1.structuredIntent.constraints,123 constraints: l1.structuredIntent.constraints,
124- resource: l1.structuredIntent.resource,124+ resources: l1.structuredIntent.resources,
125 action: l1.structuredIntent.action125 action: l1.structuredIntent.action
126 },126 },
127 intentSummary: l1.intentSummary,127 intentSummary: l1.intentSummary,
@@ -274,7 +274,7 @@ export default function a4pCodecTest() {
274 intentSummary: l2.intentL1.intentSummary,274 intentSummary: l2.intentL1.intentSummary,
275 structuredIntent: {275 structuredIntent: {
276 action: l2.intentL1.structuredIntent.action,276 action: l2.intentL1.structuredIntent.action,
277- resource: l2.intentL1.structuredIntent.resource,277+ resources: l2.intentL1.structuredIntent.resources,
278 constraints: new CustomInfo() as Object as PaymentConstraints278 constraints: new CustomInfo() as Object as PaymentConstraints
279 },279 },
280 timestamp: l2.intentL1.timestamp,280 timestamp: l2.intentL1.timestamp,
@@ -654,6 +654,23 @@ export default function a4pCodecTest() {
654 });654 });
655 });655 });
656 656 
657+ it('deserialize_fails_whenCompletedAtBeforeReservedAt', 0, () => {
658+ // completeExecution/cancelExecution refuse a clock earlier than the
659+ // record's reservedAt, so a persisted record violating that
660+ // monotonic rule is corrupted data: restore fails with the code the
661+ // offending operation would have returned.
662+ const context = createExecutionContextWithLedger();
663+ const serialized = A4pCodec.serializeIntentExecutionContext(context);
664+ const obj: Record<string, Object> = JSON.parse(serialized);
665+ const executions: Record<string, Object>[] = obj['executions'] as Record<string, Object>[];
666+ const reservedAt: number = executions[0]['reservedAt'] as number;
667+ executions[0]['completedAt'] = reservedAt - 1;
668+ 
669+ expectThrows(A4pErrorCode.A4P_TIMESTAMP_TOO_EARLY, () => {
670+ A4pCodec.deserializeIntentExecutionContext(JSON.stringify(obj));
671+ });
672+ });
673+ 
657 it('deserialize_fails_whenPeriodicRecordLacksPeriodIndex', 0, () => {674 it('deserialize_fails_whenPeriodicRecordLacksPeriodIndex', 0, () => {
658 // The default test constraints are periodic, so every record must675 // The default test constraints are periodic, so every record must
659 // carry its period index.676 // carry its period index.
@@ -748,8 +765,12 @@ export default function a4pCodecTest() {
748 expect(j1).assertContain('"keyIdentifier":"key-001"');765 expect(j1).assertContain('"keyIdentifier":"key-001"');
749 expect(j1).assertContain('"sign":"');766 expect(j1).assertContain('"sign":"');
750 767 
751- // L1 structuredIntent: action, order template, constraints.768+ // L1 structuredIntent: action, order template, constraints. The
769+ // resources key is asserted both positively and negatively: the
770+ // wire name (Java-compatible) must never drift back to the old
771+ // singular form this SDK once signed.
752 expect(j1).assertContain('"action":"AI_PAY"');772 expect(j1).assertContain('"action":"AI_PAY"');
773+ expect(j1).assertContain('"resources":{');
753 expect(j1).assertContain('"itemsWhiteList":[');774 expect(j1).assertContain('"itemsWhiteList":[');
754 expect(j1).assertContain('"whiteList":[');775 expect(j1).assertContain('"whiteList":[');
755 expect(j1).assertContain('"quantity":1');776 expect(j1).assertContain('"quantity":1');
@@ -760,10 +781,11 @@ export default function a4pCodecTest() {
760 expect(j1).assertContain('"currency":"CNY"');781 expect(j1).assertContain('"currency":"CNY"');
761 expect(j1).assertContain('"validFrom":1699999940000');782 expect(j1).assertContain('"validFrom":1699999940000');
762 expect(j1).assertContain('"validUntil":1700003600000');783 expect(j1).assertContain('"validUntil":1700003600000');
763- expect(j1).assertContain('"maxExecuteCount":10');784+ expect(j1).assertContain('"maxExecutionCount":10');
764 expect(j1).assertContain('"anchorTime":1699999940000');785 expect(j1).assertContain('"anchorTime":1699999940000');
765 expect(j1).assertContain('"periodSeconds":3600');786 expect(j1).assertContain('"periodSeconds":3600');
766 expect(j1).assertContain('"maxExecutionCountPerPeriod":10');787 expect(j1).assertContain('"maxExecutionCountPerPeriod":10');
788+ expect(j1.indexOf('"resource":')).assertEqual(-1);
767 789 
768 // L2 embeds the full L1 (its signature included) and adds the790 // L2 embeds the full L1 (its signature included) and adds the
769 // three identities plus the server's sign metadata.791 // three identities plus the server's sign metadata.
@@ -125,7 +125,7 @@ export default function a4pHttpTest() {
125 intentSummary: l1.intentSummary,125 intentSummary: l1.intentSummary,
126 structuredIntent: {126 structuredIntent: {
127 action: l1.structuredIntent.action,127 action: l1.structuredIntent.action,
128- resource: l1.structuredIntent.resource,128+ resources: l1.structuredIntent.resources,
129 constraints: l1.structuredIntent.constraints129 constraints: l1.structuredIntent.constraints
130 },130 },
131 timestamp: l1.timestamp131 timestamp: l1.timestamp
@@ -130,6 +130,36 @@ export class NoResultVerifier implements SignatureVerifier {
130 }130 }
131}131}
132 132 
133+/**
134+ * Test verifier whose verdict contradicts itself, for exercising the
135+ * result-consistency guard: `valid` and `code` must agree (code 0 is
136+ * success, anything else a failure), or the verdict is a broken
137+ * verifier's output and must surface as A4P_VERIFY_FAIL instead of being
138+ * trusted or relayed.
139+ */
140+export class ContradictoryVerifier implements SignatureVerifier {
141+ /** Which contradiction to produce: a valid verdict with a failure code (true), or an invalid one with the success code (false) */
142+ private validWithFailureCode: boolean;
143+ 
144+ constructor(validWithFailureCode: boolean = true) {
145+ this.validWithFailureCode = validWithFailureCode;
146+ }
147+ 
148+ verify(_data: Uint8Array, _signatureInfo: SignatureInfo): VerificationResult {
149+ return this.validWithFailureCode
150+ ? {
151+ valid: true,
152+ code: A4pErrorCode.A4P_VERIFY_FAIL,
153+ message: 'Valid verdict carrying a failure code'
154+ }
155+ : {
156+ valid: false,
157+ code: A4pErrorCode.A4P_SUCCESS,
158+ message: 'Invalid verdict carrying the success code'
159+ };
160+ }
161+}
162+ 
133/**163/**
134 * Test signer that returns no result at all, for exercising the164 * Test signer that returns no result at all, for exercising the
135 * signer-result guard: a broken signer must surface as A4P_SIGNING_FAIL,165 * signer-result guard: a broken signer must surface as A4P_SIGNING_FAIL,
@@ -71,7 +71,7 @@ export function createTestPaymentConstraintsAround(now: number): PaymentConstrai
71 currency: 'CNY',71 currency: 'CNY',
72 validFrom: now - 60000,72 validFrom: now - 60000,
73 validUntil: now + 3600000,73 validUntil: now + 3600000,
74- maxExecuteCount: 10,74+ maxExecutionCount: 10,
75 anchorTime: now - 60000,75 anchorTime: now - 60000,
76 periodSeconds: 3600,76 periodSeconds: 3600,
77 maxExecutionCountPerPeriod: 1077 maxExecutionCountPerPeriod: 10
@@ -81,7 +81,7 @@ export function createTestPaymentConstraintsAround(now: number): PaymentConstrai
81export function createTestStructuredIntent(now: number): StructuredIntent {81export function createTestStructuredIntent(now: number): StructuredIntent {
82 return {82 return {
83 action: IntentActionType.AI_PAY,83 action: IntentActionType.AI_PAY,
84- resource: createTestShoppingItems(),84+ resources: createTestShoppingItems(),
85 constraints: createTestPaymentConstraintsAround(now)85 constraints: createTestPaymentConstraintsAround(now)
86 };86 };
87}87}
@@ -6,8 +6,8 @@
6# without opening DevEco Studio. Always cleans previous outputs first.6# without opening DevEco Studio. Always cleans previous outputs first.
7# The test HAP packaging step additionally requires java on PATH.7# The test HAP packaging step additionally requires java on PATH.
8#8#
9-# Output: A4P-arkts-sdk/build/default/outputs/default/a4p.har9+# Output: A4P-arkts-sdk/a4p/build/default/outputs/default/a4p.har
10-# A4P-arkts-sdk/build/default/outputs/ohosTest/a4p-ohosTest-unsigned.hap10+# A4P-arkts-sdk/a4p/build/default/outputs/ohosTest/a4p-ohosTest-unsigned.hap
11 11 
12set -euo pipefail12set -euo pipefail
13 13 
MREADME.md+11-1
@@ -6,7 +6,7 @@ English | [简体中文](./README_zh.md)
6 6 
7**Agent Protocol** provides protocol SDKs and a service registry for agent interoperability in the [openJiuwen](https://github.com/openJiuwen-ai) ecosystem. It helps developers connect agents to tools, communicate with remote agents, discover available services, route requests across LLM deployments, and enforce verifiable user authorization before sensitive operations.7**Agent Protocol** provides protocol SDKs and a service registry for agent interoperability in the [openJiuwen](https://github.com/openJiuwen-ai) ecosystem. It helps developers connect agents to tools, communicate with remote agents, discover available services, route requests across LLM deployments, and enforce verifiable user authorization before sensitive operations.
8 8 
9-An agent application needs more than a model and task logic: it needs a way to access external capabilities, locate suitable collaborators, exchange messages and task results, and constrain what it can execute on a user's behalf. This repository addresses these needs through six complementary components: **MCP C++ SDK**, **A2A C++ SDK**, **A2X Registry**, **A4P Python SDK**, **A4P Java SDK**, and **IntelliRouter**. Developers can choose individual components or combine them according to their integration needs.9+An agent application needs more than a model and task logic: it needs a way to access external capabilities, locate suitable collaborators, exchange messages and task results, and constrain what it can execute on a user's behalf. This repository addresses these needs through seven complementary components: **MCP C++ SDK**, **A2A C++ SDK**, **A2X Registry**, **A4P Python SDK**, **A4P Java SDK**, **A4P ArkTS SDK**, and **IntelliRouter**. Developers can choose individual components or combine them according to their integration needs.
10 10 
11## Core Capabilities11## Core Capabilities
12 12 
@@ -36,6 +36,12 @@ The A4P Java SDK is currently released as SDK version `0.1.0` and implements the
36 36 
37The SDK provides immutable models, canonical JSON serialization, execution-context serialization and restoration, pluggable signing and verification interfaces, and an optional RSA-3072 adapter. Its execution ledger is in memory; applications must provide durable storage, database locking, replay prevention and key-to-identity binding. See the [Java SDK guide](./A4P-java-sdk/README.md) for integration details.37The SDK provides immutable models, canonical JSON serialization, execution-context serialization and restoration, pluggable signing and verification interfaces, and an optional RSA-3072 adapter. Its execution ledger is in memory; applications must provide durable storage, database locking, replay prevention and key-to-identity binding. See the [Java SDK guide](./A4P-java-sdk/README.md) for integration details.
38 38 
39+### Payment-intent authorization with A4P ArkTS
40+ 
41+The A4P ArkTS SDK brings the payment-intent protocol to **HarmonyOS**, delivered as a HAR library (module name `a4p`) implementing wire-format version `1.0`. It covers the signed intent lifecycle (create → issue → authorize → activate), payment execution accounting against the frozen authorization snapshot, and the canonical JSON codec used for signing and persistence, with the same L1/L2/L3 signature chain for agent creation, intent-center issuance, and user authorization as the Java SDK.
42+ 
43+Cryptography is pluggable through `Signer` / `SignatureVerifier` interfaces — nothing is bundled, and adapters built on `@kit.CryptoArchitectureKit` interoperate with the Java SDK's `RSA3072` suite. The execution ledger is in memory; applications must provide durable storage, database locking, replay prevention, and key-to-identity binding. The Java SDK was ported from this SDK and shares its canonical JSON rules, error-code table, and wire field names. See the [ArkTS SDK guide](./A4P-arkts-sdk/README.md) for integration details.
44+ 
39### Intelligent LLM routing with IntelliRouter45### Intelligent LLM routing with IntelliRouter
40 46 
41IntelliRouter is a lightweight **LLM proxy SDK** that maps a single model name to multiple deployment endpoints and routes each request intelligently. It pools deployments across providers — OpenAI, Anthropic, Bedrock, DeepSeek, Gemini, and SiliconFlow, plus any OpenAI-compatible endpoint — and selects among them with pluggable strategies: SimpleShuffle, LowestLatency, TagBased, TokenAware, RateLimitAware, Adaptive, OrderedFailover, and TagFiltered.47IntelliRouter is a lightweight **LLM proxy SDK** that maps a single model name to multiple deployment endpoints and routes each request intelligently. It pools deployments across providers — OpenAI, Anthropic, Bedrock, DeepSeek, Gemini, and SiliconFlow, plus any OpenAI-compatible endpoint — and selects among them with pluggable strategies: SimpleShuffle, LowestLatency, TagBased, TokenAware, RateLimitAware, Adaptive, OrderedFailover, and TagFiltered.
@@ -53,6 +59,7 @@ Each component addresses a different integration need and can be used independen
53| Find an appropriate service or collaborator | A2X Registry | Register service metadata, discover capabilities, and coordinate availability. |59| Find an appropriate service or collaborator | A2X Registry | Register service metadata, discover capabilities, and coordinate availability. |
54| Execute within user-approved boundaries | A4P Python SDK | Obtain verifiable authorization and validate its scope before a protected operation. |60| Execute within user-approved boundaries | A4P Python SDK | Obtain verifiable authorization and validate its scope before a protected operation. |
55| Authorize and execute payments within an approved intent | A4P Java SDK | Verify the signature chain and enforce payment constraints throughout the execution lifecycle. |61| Authorize and execute payments within an approved intent | A4P Java SDK | Verify the signature chain and enforce payment constraints throughout the execution lifecycle. |
62+| Run the payment-intent lifecycle on HarmonyOS | A4P ArkTS SDK | Build the signed intent chain and enforce payment constraints inside a HarmonyOS application. |
56| Route requests across multiple LLM deployments | IntelliRouter | Pool model endpoints, pick the best deployment per request, and fail over automatically. |63| Route requests across multiple LLM deployments | IntelliRouter | Pool model endpoints, pick the best deployment per request, and fail over automatically. |
57 64 
58## Repository Layout65## Repository Layout
@@ -64,6 +71,7 @@ agent-protocol/
64├── AgentRegistry/ # A2X registry, Python client, web UI, and documentation71├── AgentRegistry/ # A2X registry, Python client, web UI, and documentation
65├── A4P-python-sdk/ # A4P Python SDK, protocol documentation, and examples72├── A4P-python-sdk/ # A4P Python SDK, protocol documentation, and examples
66├── A4P-java-sdk/ # A4P Java payment-intent SDK, canonical JSON rules, and examples73├── A4P-java-sdk/ # A4P Java payment-intent SDK, canonical JSON rules, and examples
74+├── A4P-arkts-sdk/ # A4P ArkTS (HarmonyOS) payment-intent HAR library and on-device tests
67└── intelli_router/ # IntelliRouter LLM proxy SDK, tests, and examples75└── intelli_router/ # IntelliRouter LLM proxy SDK, tests, and examples
68```76```
69 77 
@@ -83,6 +91,7 @@ cd agent-protocol
83| [A2X Registry](./AgentRegistry/README.md) | Python ≥ 3.10; LLM configuration for A2X search | Install the registry, start the service, and register/query services through HTTP APIs or the UI. |91| [A2X Registry](./AgentRegistry/README.md) | Python ≥ 3.10; LLM configuration for A2X search | Install the registry, start the service, and register/query services through HTTP APIs or the UI. |
84| [A4P Python SDK](./A4P-python-sdk/README.md) | Python ≥ 3.10 and uv | Install dependencies and run the non-interactive Ed25519 authorization example. |92| [A4P Python SDK](./A4P-python-sdk/README.md) | Python ≥ 3.10 and uv | Install dependencies and run the non-interactive Ed25519 authorization example. |
85| [A4P Java SDK](./A4P-java-sdk/README.md) | JDK ≥ 17 and Maven ≥ 3.9 | Run `mvn test` and `mvn package` in `A4P-java-sdk`, then run `PaymentExample` following the SDK guide. |93| [A4P Java SDK](./A4P-java-sdk/README.md) | JDK ≥ 17 and Maven ≥ 3.9 | Run `mvn test` and `mvn package` in `A4P-java-sdk`, then run `PaymentExample` following the SDK guide. |
94+| [A4P ArkTS SDK](./A4P-arkts-sdk/README.md) | DevEco Studio 5.0+ with HarmonyOS SDK API 12; `ohpm`, `hvigorw`, and Bash for command-line builds | Run `scripts/build.sh` to build the HAR and the on-device test HAP, then run the hypium suites in DevEco Studio or on a device. |
86| [IntelliRouter](./intelli_router/README.md) | Python ≥ 3.9 | Install the SDK, run the unit tests, then try the end-to-end and observability examples. |95| [IntelliRouter](./intelli_router/README.md) | Python ≥ 3.9 | Install the SDK, run the unit tests, then try the end-to-end and observability examples. |
87 96 
88The components are built and installed separately. See each guide for complete dependency requirements and platform-specific instructions.97The components are built and installed separately. See each guide for complete dependency requirements and platform-specific instructions.
@@ -94,6 +103,7 @@ The components are built and installed separately. See each guide for complete d
94- **A2X:** [Registry guide](./AgentRegistry/README.md) · [Python client](./AgentRegistry/client/README.md) · [Agent Team deployment](./AgentRegistry/README_forAgentTeam.md)103- **A2X:** [Registry guide](./AgentRegistry/README.md) · [Python client](./AgentRegistry/client/README.md) · [Agent Team deployment](./AgentRegistry/README_forAgentTeam.md)
95- **A4P:** [Protocol](./A4P-python-sdk/A4P_PROTOCOL.md) · [SDK design](./A4P-python-sdk/A4P_SDK_DESIGN.md) · [MCP integration example](./A4P-python-sdk/examples/note_mcp_a4p/README.md)104- **A4P:** [Protocol](./A4P-python-sdk/A4P_PROTOCOL.md) · [SDK design](./A4P-python-sdk/A4P_SDK_DESIGN.md) · [MCP integration example](./A4P-python-sdk/examples/note_mcp_a4p/README.md)
96- **A4P Java:** [SDK guide](./A4P-java-sdk/README.md) · [Canonical JSON and signed bytes](./A4P-java-sdk/docs/canonical-json-spec.md) · [Payment example](./A4P-java-sdk/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java)105- **A4P Java:** [SDK guide](./A4P-java-sdk/README.md) · [Canonical JSON and signed bytes](./A4P-java-sdk/docs/canonical-json-spec.md) · [Payment example](./A4P-java-sdk/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java)
106+- **A4P ArkTS:** [SDK guide](./A4P-arkts-sdk/README.md) · [Canonical JSON and signed bytes](./A4P-java-sdk/docs/canonical-json-spec.md)
97- **IntelliRouter:** [SDK guide](./intelli_router/README.md) · [API reference](./intelli_router/API.md) · [Examples](./intelli_router/examples/)107- **IntelliRouter:** [SDK guide](./intelli_router/README.md) · [API reference](./intelli_router/API.md) · [Examples](./intelli_router/examples/)
98 108 
99## Contributing109## Contributing
@@ -6,7 +6,7 @@
6 6 
7**Agent Protocol** 是 [openJiuwen](https://github.com/openJiuwen-ai) 生态中面向智能体互操作的协议 SDK 与服务注册中心集合,帮助开发者连接智能体与工具、与远端智能体通信、发现可用服务,在多个 LLM 部署间智能路由请求,并在执行敏感操作前落实可验证的用户授权。7**Agent Protocol** 是 [openJiuwen](https://github.com/openJiuwen-ai) 生态中面向智能体互操作的协议 SDK 与服务注册中心集合,帮助开发者连接智能体与工具、与远端智能体通信、发现可用服务,在多个 LLM 部署间智能路由请求,并在执行敏感操作前落实可验证的用户授权。
8 8 
9-智能体应用除了模型和任务逻辑,还需要解决外部能力接入、协作对象发现、消息与任务结果交换,以及代理用户执行操作时的权限边界等问题。本仓库通过 **MCP C++ SDK**、**A2A C++ SDK**、**A2X Registry**、**A4P Python SDK**、**A4P Java SDK** 和 **IntelliRouter** 六个互补组件提供支持。开发者可以按需独立使用,也可以结合具体业务进行组合集成。9+智能体应用除了模型和任务逻辑,还需要解决外部能力接入、协作对象发现、消息与任务结果交换,以及代理用户执行操作时的权限边界等问题。本仓库通过 **MCP C++ SDK**、**A2A C++ SDK**、**A2X Registry**、**A4P Python SDK**、**A4P Java SDK**、**A4P ArkTS SDK** 和 **IntelliRouter** 七个互补组件提供支持。开发者可以按需独立使用,也可以结合具体业务进行组合集成。
10 10 
11## 核心能力11## 核心能力
12 12 
@@ -36,6 +36,12 @@ A4P Java SDK 当前的 SDK 构件版本为 `0.1.0`,实现的支付意图协议
36 36 
37SDK 提供不可变数据模型、规范化 JSON 序列化、执行上下文序列化与恢复、可插拔签名和验签接口,以及可选的 RSA-3072 适配器。执行账本保存在内存中,应用需自行实现持久化、数据库加锁、防重放和密钥与身份绑定。集成细节请参阅 [Java SDK 指南](./A4P-java-sdk/README_zh.md)。37SDK 提供不可变数据模型、规范化 JSON 序列化、执行上下文序列化与恢复、可插拔签名和验签接口,以及可选的 RSA-3072 适配器。执行账本保存在内存中,应用需自行实现持久化、数据库加锁、防重放和密钥与身份绑定。集成细节请参阅 [Java SDK 指南](./A4P-java-sdk/README_zh.md)。
38 38 
39+### 基于 A4P ArkTS 的支付意图授权
40+ 
41+A4P ArkTS SDK 将支付意图协议带入 **HarmonyOS**,以 HAR 库(模块名 `a4p`)形式交付,实现的协议报文版本为 `1.0`。它覆盖带签名的意图生命周期(创建 → 签发 → 授权 → 激活)、基于冻结授权快照的支付执行记账,以及用于签名与持久化的规范化 JSON 编解码,并与 Java SDK 共用智能体创建、意图中心签发和用户授权的 L1/L2/L3 签名链。
42+ 
43+密码学通过 `Signer` / `SignatureVerifier` 接口由使用方注入——SDK 不内置任何实现,基于 `@kit.CryptoArchitectureKit` 构建的适配器可与 Java SDK 的 `RSA3072` 套件互操作。执行账本保存在内存中,应用需自行实现持久化、数据库加锁、防重放和密钥与身份绑定。仓库中的 Java SDK 即移植自本 SDK,两者共享规范化 JSON 规则、错误码表和报文字段名。集成细节请参阅 [ArkTS SDK 指南](./A4P-arkts-sdk/README_zh.md)。
44+ 
39### 基于 IntelliRouter 的智能 LLM 路由45### 基于 IntelliRouter 的智能 LLM 路由
40 46 
41IntelliRouter 是一个轻量级 **LLM 代理 SDK**,将同一模型名映射到多个部署端点,并对每次请求进行智能路由。它支持池化管理多家 Provider 的部署——OpenAI、Anthropic、Bedrock、DeepSeek、Gemini、SiliconFlow,以及任意 OpenAI 兼容端点——并通过可插拔策略选择部署:SimpleShuffle、LowestLatency、TagBased、TokenAware、RateLimitAware、Adaptive、OrderedFailover 与 TagFiltered。47IntelliRouter 是一个轻量级 **LLM 代理 SDK**,将同一模型名映射到多个部署端点,并对每次请求进行智能路由。它支持池化管理多家 Provider 的部署——OpenAI、Anthropic、Bedrock、DeepSeek、Gemini、SiliconFlow,以及任意 OpenAI 兼容端点——并通过可插拔策略选择部署:SimpleShuffle、LowestLatency、TagBased、TokenAware、RateLimitAware、Adaptive、OrderedFailover 与 TagFiltered。
@@ -53,6 +59,7 @@ IntelliRouter 是一个轻量级 **LLM 代理 SDK**,将同一模型名映射
53| 寻找合适的服务或协作对象 | A2X Registry | 注册服务元数据、发现能力并协调服务可用状态。 |59| 寻找合适的服务或协作对象 | A2X Registry | 注册服务元数据、发现能力并协调服务可用状态。 |
54| 在用户批准的范围内执行操作 | A4P Python SDK | 获取可验证的授权,并在受保护操作执行前校验授权范围。 |60| 在用户批准的范围内执行操作 | A4P Python SDK | 获取可验证的授权,并在受保护操作执行前校验授权范围。 |
55| 在批准的意图范围内授权并执行支付 | A4P Java SDK | 验证签名链,在执行全生命周期内落实支付约束。 |61| 在批准的意图范围内授权并执行支付 | A4P Java SDK | 验证签名链,在执行全生命周期内落实支付约束。 |
62+| 在 HarmonyOS 上运行支付意图全流程 | A4P ArkTS SDK | 在鸿蒙应用内构建签名意图链,并在执行全生命周期内落实支付约束。 |
56| 在多个 LLM 部署间智能路由请求 | IntelliRouter | 池化模型端点,按请求选择最优部署,失败时自动切换。 |63| 在多个 LLM 部署间智能路由请求 | IntelliRouter | 池化模型端点,按请求选择最优部署,失败时自动切换。 |
57 64 
58## 仓库结构65## 仓库结构
@@ -64,6 +71,7 @@ agent-protocol/
64├── AgentRegistry/ # A2X 注册中心、Python 客户端、Web UI 与文档71├── AgentRegistry/ # A2X 注册中心、Python 客户端、Web UI 与文档
65├── A4P-python-sdk/ # A4P Python SDK、协议文档与示例72├── A4P-python-sdk/ # A4P Python SDK、协议文档与示例
66├── A4P-java-sdk/ # A4P Java 支付意图 SDK、规范化 JSON 规则与示例73├── A4P-java-sdk/ # A4P Java 支付意图 SDK、规范化 JSON 规则与示例
74+├── A4P-arkts-sdk/ # A4P ArkTS(HarmonyOS)支付意图 HAR 库与端侧测试
67└── intelli_router/ # IntelliRouter LLM 代理 SDK、测试与示例75└── intelli_router/ # IntelliRouter LLM 代理 SDK、测试与示例
68```76```
69 77 
@@ -83,6 +91,7 @@ cd agent-protocol
83| [A2X Registry](./AgentRegistry/README.md) | Python ≥ 3.10;A2X 搜索需要配置 LLM | 安装并启动注册中心,通过 HTTP API 或 UI 注册和查询服务。 |91| [A2X Registry](./AgentRegistry/README.md) | Python ≥ 3.10;A2X 搜索需要配置 LLM | 安装并启动注册中心,通过 HTTP API 或 UI 注册和查询服务。 |
84| [A4P Python SDK](./A4P-python-sdk/README.md) | Python ≥ 3.10 与 uv | 安装依赖,运行无需交互的 Ed25519 授权全链路示例。 |92| [A4P Python SDK](./A4P-python-sdk/README.md) | Python ≥ 3.10 与 uv | 安装依赖,运行无需交互的 Ed25519 授权全链路示例。 |
85| [A4P Java SDK](./A4P-java-sdk/README_zh.md) | JDK ≥ 17、Maven ≥ 3.9 | 在 `A4P-java-sdk` 中运行 `mvn test` 和 `mvn package`,再按 SDK 指南运行 `PaymentExample`。 |93| [A4P Java SDK](./A4P-java-sdk/README_zh.md) | JDK ≥ 17、Maven ≥ 3.9 | 在 `A4P-java-sdk` 中运行 `mvn test` 和 `mvn package`,再按 SDK 指南运行 `PaymentExample`。 |
94+| [A4P ArkTS SDK](./A4P-arkts-sdk/README_zh.md) | DevEco Studio 5.0 及 HarmonyOS SDK API 12;命令行构建另需 `ohpm`、`hvigorw` 与 Bash | 运行 `scripts/build.sh` 构建 HAR 与端侧测试 HAP,再在 DevEco Studio 中或设备上运行 hypium 测试套件。 |
86| [IntelliRouter](./intelli_router/README.md) | Python ≥ 3.9 | 安装 SDK,运行单元测试,体验端到端与可观测性示例。 |95| [IntelliRouter](./intelli_router/README.md) | Python ≥ 3.9 | 安装 SDK,运行单元测试,体验端到端与可观测性示例。 |
87 96 
88各组件分别构建和安装,完整依赖与各平台操作步骤请参阅对应指南。97各组件分别构建和安装,完整依赖与各平台操作步骤请参阅对应指南。
@@ -94,6 +103,7 @@ cd agent-protocol
94- **A2X:** [注册中心指南](./AgentRegistry/README.md) · [Python 客户端](./AgentRegistry/client/README.md) · [Agent Team 部署](./AgentRegistry/README_forAgentTeam.md)103- **A2X:** [注册中心指南](./AgentRegistry/README.md) · [Python 客户端](./AgentRegistry/client/README.md) · [Agent Team 部署](./AgentRegistry/README_forAgentTeam.md)
95- **A4P:** [协议说明](./A4P-python-sdk/A4P_PROTOCOL.md) · [SDK 设计](./A4P-python-sdk/A4P_SDK_DESIGN.md) · [MCP 集成示例](./A4P-python-sdk/examples/note_mcp_a4p/README.md)104- **A4P:** [协议说明](./A4P-python-sdk/A4P_PROTOCOL.md) · [SDK 设计](./A4P-python-sdk/A4P_SDK_DESIGN.md) · [MCP 集成示例](./A4P-python-sdk/examples/note_mcp_a4p/README.md)
96- **A4P Java:** [SDK 指南](./A4P-java-sdk/README_zh.md) · [规范化 JSON 与签名字节](./A4P-java-sdk/docs/canonical-json-spec.md) · [支付示例](./A4P-java-sdk/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java)105- **A4P Java:** [SDK 指南](./A4P-java-sdk/README_zh.md) · [规范化 JSON 与签名字节](./A4P-java-sdk/docs/canonical-json-spec.md) · [支付示例](./A4P-java-sdk/src/main/java/io/openjiuwen/a4p/examples/PaymentExample.java)
106+- **A4P ArkTS:** [SDK 指南](./A4P-arkts-sdk/README_zh.md) · [规范化 JSON 与签名字节](./A4P-java-sdk/docs/canonical-json-spec.md)
97- **IntelliRouter:** [SDK 指南](./intelli_router/README.md) · [API 参考](./intelli_router/API.md) · [示例](./intelli_router/examples/)107- **IntelliRouter:** [SDK 指南](./intelli_router/README.md) · [API 参考](./intelli_router/API.md) · [示例](./intelli_router/examples/)
98 108 
99## 参与贡献109## 参与贡献