ap2_mandate_verifier 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA256:
3
- metadata.gz: d2630c74f49f2d59ee5895eb439c229c9269b202129e6574a3f2d627e302c565
4
- data.tar.gz: 67055aafefb47cf5fe76cd3e5e78711de31496f715abe5e7fadf5e7f1fe293e2
3
+ metadata.gz: dbeaa8817a128ad64b2307ae68a86cb2c36f40e710dc459f28354e24b3b251f9
4
+ data.tar.gz: 70d40f6293a88043e0f29f10b00e337418ae6819f91cffcb55db8f6c68f21785
5
5
  SHA512:
6
- metadata.gz: b90c9022582083189cfc9fe8edbe641c2f4a51618c60a6ad877c8ce479cd70d1fcf84bf2520d1e79565cbb4cef457dc804ce28ab972dcb9a1f05ffa9f03f8d9a
7
- data.tar.gz: 2aa4c0cbfbc879de935c15b93621fd3ac4f38990f9df414b0e322cceda844e5d226facfddb1678255908ff8cf2065b3640167fe6d619946bc729f3be8316c94b
6
+ metadata.gz: bd6ba8a1c4be5e8b81ff589624ab17d3e1d3861d49cb8aad457abf96708c2446b996381dc0c948f868538c6b80ae9d2ef45d1c693e2e1fa1cf6874df085faeb5
7
+ data.tar.gz: 7652d380a3ab2024016f0442672b384f6f8e8eecbec416318b1c9224cc8a954c3be1600e5eb1125f1f9eaa5b172609b41e6c0a3074564c0932bc897ae1f8d2ec
data/README.md CHANGED
@@ -1,33 +1,60 @@
1
- # AP2 Mandate Verifier — 0.3.0
2
-
3
- > **Unreleased 0.4.0 candidate:** adds `result.diagnostic` with stage, safe field, reason and English/Japanese guidance. See the [diagnostic guide](docs/DIAGNOSTICS.md). Ordinary installation below still selects published 0.3.0; use the guide’s local candidate path to try diagnostics.
1
+ # AP2 Mandate Verifier — 0.6.0 preparation
4
2
 
5
3
  [日本語](README.ja.md)
6
4
 
5
+ Published stable is **0.5.0**. This checkout prepares additive multi-item support for **0.6.0**, which is not published. Review, CI, final package validation and Owner publication approval are separate gates; see [current status](docs/PROJECT_STATUS.md).
6
+
7
+ ## Multiple items and quantities
8
+
9
+ Explicitly select `profile_ref: "ap2.checkout.single_merchant_multi_item"` when creating trust with `InputBuilder.trust`, signing a checkout with `CheckoutJWT.sign`, and using `CheckoutReceipt.reference/sign/verify`. The complete verifier follows the authenticated trust selection. The default `ap2.checkout.single_merchant_sku` v1 retains its exact definition, hash and one-line acceptance range.
10
+
11
+ The new v1 profile supports one merchant, one checkout, one currency and up to eight lines, with different quantities and repeated product IDs on distinct lines. It matches all disclosed product candidates using integer maximum flow: every requirement and every ordered unit must be consumed exactly once. Requirement IDs and checkout line IDs are distinct identifiers. See the [multi-item contract and migration](docs/MULTI_ITEM_CHECKOUT.md) and [synthetic runnable lifecycle](examples/multi_item_checkout.rb).
12
+
7
13
  Verify purchase-delegation data in Ruby using a deliberately fixed AP2 profile. The Gem checks signed data against independently supplied Host trust and order information, then returns immutable Evidence. **Verification success is not purchase or payment permission.**
8
14
 
9
15
  `InputBuilder` converts business records into verification inputs: it creates the Gem-specific trust/selection/Host JSON, fingerprints and original-wire digests for you. You still choose whom to trust and supply the expected order, challenge state and clock. The Gem is Rails-independent and performs no network, database or payment operations.
10
16
 
11
17
  ## Try the local demo
12
18
 
13
- The [Rails demo](https://github.com/cuichangquan/ap2-mandate-verifier-demo#readme) uses published 0.3.0 and InputBuilder by default. Its Docker instructions require no host Ruby installation. Compare synthetic normal, tampered and expired cases, including actual status/code and Evidence presence. It is local-only; it does not issue real challenges, consume nonces or execute purchases.
19
+ The [Rails demo](https://github.com/cuichangquan/ap2-mandate-verifier-demo#readme) uses published 0.5.0 and InputBuilder by default. Its Docker instructions require no host Ruby installation. Compare synthetic normal, tampered and expired cases, including actual status/code, diagnostics and Evidence presence. Merchant signing and authentic Success/Error Receipts are also available. It is local-only; it does not issue real challenges, consume nonces or execute purchases.
14
20
 
15
21
  ## Install
16
22
 
17
23
  Formal support is **MRI 3.4.12 and MRI 4.0.9**. In your chosen Gem environment:
18
24
 
19
25
  ```sh
20
- gem install ap2_mandate_verifier --version 0.3.0
26
+ gem install ap2_mandate_verifier --version 0.5.0
21
27
  ```
22
28
 
23
29
  Or add to your Gemfile:
24
30
 
25
31
  ```ruby
26
- gem "ap2_mandate_verifier", "= 0.3.0"
32
+ gem "ap2_mandate_verifier", "= 0.5.0"
27
33
  ```
28
34
 
29
35
  Runtime dependencies are pinned to JSON 2.19.9, JWT 3.3.0, base64 0.3.0, OpenSSL gem 4.0.2 and Digest 3.2.1. Normal installation may download/build dependencies; do not relax the pins to work around a conflict. The Ruby resolution interval is not certification of every Ruby version, OS or native provider. See the [support contract](docs/SUPPORT_CONTRACT.md).
30
36
 
37
+ ## Merchant signing and Receipt
38
+
39
+ Create a signed checkout, then sign the application's explicit outcome. These additive APIs are included in published 0.5.0.
40
+ Here `checkout` is the application order Hash, `key` its P-256 signing key,
41
+ `received_closed_sd_jwt` the original final inline SD-JWT and `now` the application clock:
42
+
43
+ ```ruby
44
+ signing = AP2MandateVerifier::CheckoutJWT
45
+ signed = signing.sign(checkout: checkout, signer: signing.es256_signer(private_key: key),
46
+ public_key_pem: key.public_to_pem)
47
+ # Retain signed.jwt unchanged; use it as InputBuilder's host_checkout_jws.
48
+ receipt = AP2MandateVerifier::CheckoutReceipt.sign(closed_sd_jwt: received_closed_sd_jwt,
49
+ issuer: "shop", outcome: "Error", error: "declined", error_description: "Application declined",
50
+ issued_at: now, signer: signing.es256_signer(private_key: key), public_key_pem: key.public_to_pem)
51
+ ```
52
+
53
+ Receipt verification separately checks a trusted public key, expected issuer,
54
+ explicit time window and original closed-Mandate reference. An authentic Error
55
+ Receipt has `verified? == true` and `purchase_succeeded? == false`.
56
+ See the [complete runnable example](examples/merchant_signing.rb) and [API contract / SDK differences](docs/MERCHANT_SIGNING.md).
57
+
31
58
  ## A small InputBuilder example
32
59
 
33
60
  After installation, use a checkout of this repository. Save the following as `quick_start.rb` in its root and run `ruby quick_start.rb`. The JSON files under [`examples/input_builder/`](examples/input_builder/) contain explicit synthetic order/registration records and original signed Strings; they are not part of the installed Gem. Their fixed clock is intentional because the saved signatures expire. These are test inputs, not real enrollment or current production data.
@@ -84,17 +111,27 @@ Do not call `prepare` again during verification or update saved hashes/reference
84
111
  | `:rejected`, `rejected? == true` | No Evidence. Stop and inspect `result.code`. |
85
112
  | `:unavailable`, `unavailable? == true` | No Evidence. Stop; a dependency or processing failure is not proof of invalid business data. |
86
113
 
114
+ On failure, inspect supplemental check candidates. Successful results have no failure diagnostic.
115
+
116
+ ```ruby
117
+ if (diagnostic = result.diagnostic)
118
+ puts diagnostic.to_h(locale: :en) # :ja for Japanese
119
+ end
120
+ ```
121
+
122
+ `stage / field / reason / hint` are guidance; they do not change status/code or the verdict. Unknown fields/causes are not asserted. See the [diagnostic guide](docs/DIAGNOSTICS.md).
123
+
87
124
  Exceptions, process failure and missing results also never authorize an operation. Do not log raw inputs/nonces or treat serialized Evidence as an authenticated credential.
88
125
 
89
126
  The Gem checks signatures, supported disclosure closure, delegation, purchase/Host bindings, constraints and validity. The Host supplies authenticated, independent and current trust/keys/revocation, order/challenge state and clock. Before acting, it rechecks current state and validity, atomically consumes the nonce with order CAS, handles uncertain outcomes, and makes the final authorization/payment decision. `prepare`/`restore` do not authenticate storage or prove an unused nonce.
90
127
 
91
- Supported scope is the fixed `ap2.checkout.single_merchant_sku` profile v1: ES256/P256, one Merchant/SKU/cart line, USD/EUR/JPY and the documented disclosure shapes. Unknown/unsupported forms fail closed. General AP2/all-Schema support, real Issuer interoperability, signing/Receipt generation, Rails adapters, DB/payment execution and numeric performance guarantees are outside this release. Real Issuer/Host production GO and Phase 2-B remain separate HOLDs.
128
+ Published 0.5.0 uses `ap2.checkout.single_merchant_sku` v1: ES256/P256, one Merchant/SKU/cart line, USD/EUR/JPY and the documented disclosure shapes. This checkout adds the explicitly selected [multi-item profile](docs/MULTI_ITEM_CHECKOUT.md). Unknown/unsupported forms fail closed. General AP2/all-Schema support, real Issuer interoperability, product Mandate issuance/presentation, Rails adapters, DB/payment execution and numeric performance guarantees remain outside scope. Real Issuer/Host production GO and Phase 2-B remain separate HOLDs.
92
129
 
93
130
  ### Which API should I use?
94
131
 
95
132
  | Entry | Role |
96
133
  | --- | --- |
97
- | `InputBuilder.verify(**business_information)` | Recommended business-data path in 0.3.0. Assembles inputs and runs complete verification; preparation and restoration are separate steps shown above. |
134
+ | `InputBuilder.verify(**business_information)` | Recommended business-data path in 0.5.0. Assembles inputs and runs complete verification; preparation and restoration are separate steps shown above. |
98
135
  | `verify_checkout(**inputs)` | Direct complete verification with the existing seven inputs, including caller-supplied trust/selection/Host JSON. |
99
136
  | `verify_research(**inputs)` | Retained name for the same seven-input verification pipeline; no deprecation warning. |
100
137
  | `verify(presentation_json:)` | Legacy JSON syntax check only. Never returns successful Evidence. |
@@ -105,7 +142,7 @@ Malformed assembly arguments, including missing keywords, to `InputBuilder.verif
105
142
 
106
143
  - [Business-data lifecycle and Rails mapping](docs/INPUT_BUILDER.md), [complete Ruby example](examples/input_builder.rb) and [before/after example](examples/input_builder_before.rb).
107
144
  - [Supported inputs, limits and Result/Evidence contract](docs/SUPPORT_CONTRACT.md); [Issuer/Host responsibilities](docs/ISSUER_HOST_MINIMUM_CONTRACT.md).
108
- - [Published 0.3.0 release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.3.0), [publication/withdrawal records](docs/PROJECT_STATUS.md) and [changelog](CHANGELOG.md). Repository README changes do not rebuild or replace published Gem bytes.
145
+ - [Published 0.5.0 release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.5.0), [publication/withdrawal records](docs/PROJECT_STATUS.md) and [changelog](CHANGELOG.md). Repository README changes do not rebuild or replace published Gem bytes.
109
146
  - [Pinned historical seven-input / saved FULL example](https://github.com/cuichangquan/ap2-mandate-verifier/blob/e0ab9fb21045e89fc58fb06145eeda4855b2dc54/README.md#try-the-saved-synthetic-example), [older artifact/provider evidence](research/stable010_release_linux_package/README.md) and [historical conceptual diagrams](https://github.com/cuichangquan/ap2-mandate-verifier/blob/e0ab9fb21045e89fc58fb06145eeda4855b2dc54/README.md#illustrated-concepts-japanese-diagrams). These records are preserved, not current integration instructions or broader support claims.
110
147
  - [Security reporting](SECURITY.md), [maintenance policy](docs/POST_RELEASE_MAINTENANCE.md) and [product direction](docs/PRODUCT_VISION.md). Do not include secrets, real Mandates or personal data in reports.
111
148
 
@@ -1,4 +1,4 @@
1
- # 失敗時の診断(未公開 0.4.0候補)
1
+ # 失敗時の診断(公開済み 0.4.0)
2
2
 
3
3
  Gem内部を追わず、失敗した検査と次の確認候補を取得できます。診断は補助情報です。
4
4
  既存呼び出し、status/code、固定profile、Fail Closed、非成功時のEvidenceなし契約は不変です。
@@ -53,14 +53,13 @@ trust選択、Host・challengeの確認候補を提供します。旧unverified
53
53
  署名原文、鍵、nonce、個人情報、stack traceは保持・表示しません。診断はEvidenceではなく、
54
54
  元入力の再構築もできません。
55
55
 
56
- ## ローカルで試す
56
+ ## 公開版をローカルで試す
57
57
 
58
- 公開済み0.3.0は変更しません。対応MRI 3.4.12または4.0.9と固定依存を備えた隔離環境で、
59
- チェックアウトから候補を通常インストールしてください。
58
+ 対応MRI 3.4.12または4.0.9と固定依存を備えた環境で、公開済み0.4.0を通常導入し、
59
+ リポジトリのチェックアウトから例を実行してください。
60
60
 
61
61
  ```sh
62
- gem build ap2_mandate_verifier.gemspec
63
- gem install --local --no-document ./ap2_mandate_verifier-0.4.0.gem
62
+ gem install ap2_mandate_verifier --version 0.4.0
64
63
  ruby examples/input_builder.rb valid
65
64
  ruby examples/input_builder.rb tampered
66
65
  ruby examples/input_builder.rb expired
@@ -74,4 +73,4 @@ ruby examples/input_builder.rb unsupported_saved_format
74
73
  後半4例はrejected / invalid_host_contextのまま、理由が順にmissing_required_field、invalid_type、
75
74
  unknown_field、unsupported_saved_formatになります。合成fixtureの固定時刻を使います。
76
75
  業務データの対応・保存責務は[InputBuilderガイド](INPUT_BUILDER.ja.md)を参照してください。
77
- 公開、実Issuer接続、本番購入許可、Phase 2-B移行を意味しません。
76
+ Gemの公開は、実Issuer接続、本番購入許可、Phase 2-B移行を意味しません。
data/docs/DIAGNOSTICS.md CHANGED
@@ -1,4 +1,4 @@
1
- # Failure diagnostics (unreleased 0.4.0)
1
+ # Failure diagnostics (published 0.4.0)
2
2
 
3
3
  Diagnostics help you inspect a failed check without reading gem internals. They
4
4
  are supplemental: existing calls, status/code, fixed profile, Fail Closed and
@@ -62,15 +62,13 @@ hints come from a closed catalog. No values, arbitrary field names, signed
62
62
  wires, public/private keys, nonce, PII or stack traces are retained or emitted.
63
63
  The diagnostic is not Evidence and cannot reconstruct original inputs.
64
64
 
65
- ## Try the candidate locally
65
+ ## Try the published release locally
66
66
 
67
- Published 0.3.0 remains unchanged. Build and normally install the unpublished
68
- candidate from this checkout in an isolated environment with the supported
69
- MRI (3.4.12 or 4.0.9) and pinned dependencies:
67
+ Normally install published 0.4.0 in an environment with supported MRI
68
+ (3.4.12 or 4.0.9) and pinned dependencies. Run the examples from a repository checkout:
70
69
 
71
70
  ```sh
72
- gem build ap2_mandate_verifier.gemspec
73
- gem install --local --no-document ./ap2_mandate_verifier-0.4.0.gem
71
+ gem install ap2_mandate_verifier --version 0.4.0
74
72
  ruby examples/input_builder.rb valid
75
73
  ruby examples/input_builder.rb tampered
76
74
  ruby examples/input_builder.rb expired
@@ -86,5 +84,5 @@ assembly examples return `rejected / invalid_host_context` with diagnostic
86
84
  reasons `missing_required_field`, `invalid_type`, `unknown_field` and
87
85
  `unsupported_saved_format`. Synthetic fixture clocks are intentional. See
88
86
  [InputBuilder](INPUT_BUILDER.md) for data mapping and storage responsibilities.
89
- No publication, real Issuer connection, production authorization or Phase 2-B
90
- GO is implied.
87
+ Gem availability does not imply real Issuer interoperability, production
88
+ authorization or Phase 2-B GO.
@@ -0,0 +1,170 @@
1
+ # Merchant Checkout signing and Receipt
2
+
3
+ ## Explicit multi-item selection — 0.6.0 preparation
4
+
5
+ Published 0.5.0 APIs below retain their default single-SKU behavior. This checkout
6
+ adds optional `profile_ref: "ap2.checkout.single_merchant_multi_item"` to
7
+ `CheckoutJWT.sign` and `CheckoutReceipt.reference/sign/verify`. Pass it consistently
8
+ when working with a multi-item Checkout. The new profile validates every line,
9
+ integer product/sum limits and unique line IDs before signing. Its
10
+ [full contract](MULTI_ITEM_CHECKOUT.md) covers quantities, candidate matching,
11
+ limits and migration; the [synthetic example](../examples/multi_item_checkout.rb)
12
+ connects signing with InputBuilder verification and both Receipt outcomes.
13
+
14
+ Receipt still references the complete original `<terminal_jws>~`, without
15
+ per-line hashes or a compact-only alternate. Profile selection validates the
16
+ supported embedded Checkout shape; reference computation alone does not verify
17
+ Mandate authorization. Result/Evidence and business-outcome separation remain
18
+ unchanged. 0.6.0 is not yet published; its final validation is recorded separately.
19
+
20
+ Published [0.5.0](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.5.0) includes these APIs. [Complete runnable synthetic example](../examples/merchant_signing.rb). The example is repository content, not part of the installed Gem.
21
+
22
+ ## Scope and responsibility
23
+
24
+ This additive API starts from the existing single Merchant / single SKU Checkout
25
+ profile, ES256 with a P-256 key. It leaves `Verifier`, `Result`, `Evidence`,
26
+ `InputBuilder` and diagnostics unchanged. A merchant signature attests to the
27
+ merchant-authored order bytes; it does not create user authorization, establish
28
+ merchant enrollment, persist an order, consume a nonce or make a payment.
29
+
30
+ The adopted AP2 source remains
31
+ [`b4587ac1d055888a73b4b21750973cffba961793`](https://github.com/google-agentic-commerce/AP2/tree/b4587ac1d055888a73b4b21750973cffba961793).
32
+ Checkout-specific ordering is defined by the existing local fixed profile, not
33
+ all UCP shapes. Under the default profile, multiple items are rejected. The
34
+ explicit multi-item profile supports the documented bounded subset. Unsupported
35
+ fields, nonempty links and unsupported currencies are rejected in both profiles.
36
+ Amounts are integer minor units; totals must agree.
37
+
38
+ ## Minimal executable example
39
+
40
+ Run from this repository with the documented runtime and dependencies:
41
+
42
+ ```ruby
43
+ require "ap2_mandate_verifier"
44
+ require "openssl"
45
+
46
+ key = OpenSSL::PKey::EC.generate("prime256v1") # Test only; app owns real keys.
47
+ totals = [{"type" => "subtotal", "amount" => 100}, {"type" => "total", "amount" => 100}]
48
+ checkout = {
49
+ "id" => "order-1", "merchant" => {"id" => "shop", "name" => "Demo shop"},
50
+ "status" => "ready_for_complete", "currency" => "USD", "links" => [],
51
+ "line_items" => [{"id" => "line-1", "item" => {"id" => "sku", "title" => "Sample", "price" => 100},
52
+ "quantity" => 1, "totals" => totals}], "totals" => totals
53
+ }
54
+ signing = AP2MandateVerifier::CheckoutJWT
55
+ signed = signing.sign(checkout: checkout, signer: signing.es256_signer(private_key: key),
56
+ public_key_pem: key.public_to_pem)
57
+ puts signed.jwt.split(".").length # 3
58
+ puts signed.checkout_hash.length # 43
59
+ ```
60
+
61
+ `signed.jwt` is the frozen original compact JWT to transmit and retain. Supply
62
+ that exact String as `host_checkout_jws` to InputBuilder and Verifier; supply
63
+ `signed.checkout_hash` when a test or external Agent binds a Closed Mandate.
64
+ The Gem does not issue a product Mandate API. Re-encoding claims or signing again
65
+ creates different original wire, even when the order is the same.
66
+
67
+ `signer.call(signing_input)` receives the frozen ASCII `header.payload` and returns
68
+ 64 binary bytes containing the JOSE ES256 `r || s` signature. An HSM/remote
69
+ adapter must implement this interface and handle its own authorization, timeouts
70
+ and availability. The Gem itself performs no network operation. The selected
71
+ independent canonical public SPKI PEM verifies the final signature before a
72
+ `Signed` object is returned. The token cannot choose its own verification key.
73
+ `es256_signer` is a convenience closure over an application-owned OpenSSL P-256
74
+ private key; it never serializes the private key.
75
+
76
+ Invalid orders, wrong keys, unsupported keys, failed signer calls and invalid
77
+ signer output raise `CheckoutJWT::Invalid` with a fixed message and no original
78
+ cause. They never return a signed result. All application key lifecycle and trust
79
+ registration remain outside the Gem.
80
+
81
+ ## Checkout Receipt contract and specification discrepancy
82
+
83
+ Checkout-specific Schema uses `status: Success/Error`, `iss`, `iat`, `reference`;
84
+ Success requires `order_id`; Error requires `error` and `error_description`.
85
+ The generic authorization prose instead describes `result: success/error`.
86
+ Checkout schema and generated model do not strictly forbid fields from the other
87
+ branch; a stricter local profile must be documented as such.
88
+
89
+ Normative authorization/dispute text requires the final closed SD-JWT hash in
90
+ the same manner as `sd_hash`. Fixed SDK `sdjwt/common.py` includes the terminal
91
+ `~` even without disclosures. `MandateClient.get_closed_mandate_jwt` instead
92
+ extracts only compact JWT, discarding disclosures and `~`, and recommends hashing
93
+ that. These are distinct hashes even in the existing inline terminal profile.
94
+ The adopted contract prioritizes normative `sd_hash`: explicit original
95
+ closed SD-JWT input `<terminal_jws>~`, default SHA256/base64url without padding.
96
+ This is the existing inline terminal profile serialized as its final SD-JWT.
97
+ The caller must supply this exact representation; compact-only input is rejected.
98
+ The Gem never adds a missing `~`, extracts a leaf from a chain, or guesses a
99
+ reference from unparseable input. Disclosures, extra hops, `_sd_alg` extensions
100
+ and unsupported terminal claims are rejected. Bounded `kid` is accepted exactly
101
+ as in the existing verifier but never selects a trusted key. The entire input,
102
+ including `kid` bytes and terminal `~`, contributes to the hash.
103
+
104
+ The generic `result` spelling is not accepted. Success permits only `order_id`,
105
+ and Error permits only `error` and `error_description` alongside common fields.
106
+ This branch exclusivity, nonempty bounded strings and rejection of unknown
107
+ fields are explicit local-profile constraints, stronger than the base Schema.
108
+ `iat` is an integer epoch. `not_before <= iat <= verified_at <= not_after` is an
109
+ explicit application verification window, not an upstream freshness guarantee.
110
+ The application owns trusted key enrollment, expected issuer and time policy.
111
+
112
+ ```ruby
113
+ receipt = AP2MandateVerifier::CheckoutReceipt
114
+ # closed_sd_jwt is the exact received final `<terminal_jws>~` String.
115
+ rejection = receipt.sign(closed_sd_jwt: closed_sd_jwt, issuer: "shop",
116
+ outcome: "Error", error: "declined", error_description: "Application declined",
117
+ issued_at: now, signer: signing.es256_signer(private_key: key),
118
+ public_key_pem: key.public_to_pem)
119
+ checked = receipt.verify(jwt: rejection.jwt, closed_sd_jwt: closed_sd_jwt,
120
+ trusted_public_key_pem: independently_registered_public_pem, expected_issuer: "shop",
121
+ not_before: now - 60, not_after: now + 60, verified_at: now)
122
+ p [checked.verified?, checked.purchase_succeeded?, checked.purchase_rejected?]
123
+ # => [true, false, true]
124
+ ```
125
+
126
+ A Success call replaces Error fields with `outcome: "Success", order_id: "order-1"`.
127
+ `Signed#jwt` is the immutable transmitted receipt wire and `Signed#reference` its
128
+ Mandate reference. Invalid creation raises `CheckoutReceipt::Invalid` without
129
+ input values or original cause. Verification returns an immutable
130
+ `CheckoutReceipt::Verification`: `verified?`, `outcome` (`Success` or `Error`),
131
+ `purchase_succeeded?`, `purchase_rejected?`, `order_id`, `error`,
132
+ `error_description`, and a `code`. Failure exposes no untrusted claim values and
133
+ returns false for all three predicates. It never returns existing Verifier
134
+ `Result`/`Evidence` or modifies their status/code meanings.
135
+
136
+ Reference calculation validates supported syntax and preserves byte identity;
137
+ it does not verify the Mandate's authority. Receipt authenticity does not verify
138
+ Mandate authorization or evidence of payment/order execution. Obtain authorization
139
+ through the existing complete verifier plus Host responsibilities separately.
140
+ The application must explicitly provide its final business outcome; no Verifier
141
+ success is automatically converted into a Success Receipt.
142
+
143
+ ## Current verification
144
+
145
+ Dedicated offline Docker checks exercise original-wire hashing, signer failures,
146
+ wrong keys, unsupported input and complete existing Verifier/InputBuilder
147
+ integration. `test/merchant_interop.py` uses the fixed official Python SDK's
148
+ `create_jwt` and `verify_jwt`, compares decoded checkout claims and independently
149
+ computes the original JWT SHA256; reverse-direction wrong-key verification must
150
+ reject. Synthetic private keys stay in process memory. The scripts do not imply
151
+ real issuer provenance or universal AP2 conformance.
152
+
153
+ The fixed SDK `ReceiptClient.verify_receipt` checks signature/model/callback but
154
+ not expected issuer or application time policy. Our interoperability test compares
155
+ these separately on the Ruby side and verifies every callback argument against
156
+ the independently computed expected reference; a JWT-only hash must fail.
157
+ The SDK annotation says cryptography public key, but `jwt_helper.verify_jwt` uses
158
+ jwcrypto; the test supplies a public `JWK` adapter without skipping verification.
159
+ Success creation uses SDK ReceiptClient with a deterministic test clock; Error
160
+ uses the generated CheckoutReceipt model and official signing helper. SDK model
161
+ validation is also checked against original JSON Schema. No unconditional
162
+ success callback or reference-validation bypass is used.
163
+
164
+ The pinned Receipt Schema references `types/receipt_status.json`, while the
165
+ referenced file declares `$id` `.../schemas/receipt-status.json`. The local
166
+ Schema registry explicitly registers the reference URI as an alias for the
167
+ unaltered pinned file, plus declared IDs; it performs no network fallback.
168
+ This reference-resolution adjustment is recorded by the test output and does
169
+ not rewrite Schema conditions or skip validation. Checkout and Closed Mandate
170
+ payloads are also validated with the unaltered original JSON Schemas.
@@ -0,0 +1,118 @@
1
+ # Multiple-item Checkout profile — 0.6.0 preparation
2
+
3
+ This is the contract for the additive, explicitly selected
4
+ `ap2.checkout.single_merchant_multi_item` version `1`. Published 0.5.0 remains
5
+ available with the unchanged `ap2.checkout.single_merchant_sku` v1 default.
6
+ Candidate test/CI/review/package completion is recorded separately in
7
+ [project status](PROJECT_STATUS.md); this document does not authorize publication.
8
+
9
+ ## Selection and lifecycle
10
+
11
+ Pass `profile_ref: "ap2.checkout.single_merchant_multi_item"` to:
12
+
13
+ - `InputBuilder.trust(snapshot:, tenant_id:, issuer:, agent:, merchant:, verified_at:, profile_ref:)`;
14
+ - `CheckoutJWT.sign(checkout:, signer:, public_key_pem:, profile_ref:)`;
15
+ - `CheckoutReceipt.reference`, `.sign` and `.verify`, alongside their existing arguments.
16
+
17
+ The complete `InputBuilder.verify` / seven-input `verify_checkout` pipeline
18
+ selects the profile from authenticated Host trust, never a token's self-claim.
19
+ Other arguments, Result status/code, supplemental diagnostic meaning, immutable
20
+ Evidence v2 and responsibility boundaries retain their existing meanings.
21
+ Lower-level purchase/constraint APIs accept an explicit `profile_ref:`; omitted
22
+ selection retains their old default.
23
+
24
+ For a complete synthetic preparation → saved challenge → restore → current-state
25
+ verification → Success/Error Receipt example, see
26
+ [`examples/multi_item_checkout.rb`](../examples/multi_item_checkout.rb).
27
+ Its test-only issuer/Agent construction is not a product Mandate issuance API.
28
+ The expected successful verifier result remains
29
+ `verified_research/scoped_research_verified`; an authentic Error Receipt has
30
+ `verified? == true`, `purchase_succeeded? == false`.
31
+
32
+ Persist the original challenge String and all signed Strings. Restore trust and
33
+ challenge bytes without reserializing them. Migration creates a new authenticated
34
+ profile selection and a new challenge before presentation; it never relabels or
35
+ repairs an old challenge. An old saved envelope remains an old-profile envelope.
36
+ Current profile, order, trust and signed-byte differences must remain detectable.
37
+
38
+ ## Product, requirement and line identity
39
+
40
+ There are three independent identities: requirement `id`, checkout line `id`,
41
+ and product `item.id` / candidate `id`. Requirement IDs must be unique within
42
+ requirements; line IDs must be unique within checkout lines. They need not match
43
+ each other. Candidate product IDs must be unique within each requirement.
44
+ Different requirements may contain overlapping candidate IDs.
45
+
46
+ Repeated product IDs on different checkout lines are supported. Quantity
47
+ allocation connects lines to requirements by product ID only for evaluation; it never deletes,
48
+ deduplicates, sorts or replaces signed lines. Titles remain bounded strings,
49
+ but product matching uses IDs. Price and totals are checked for every line.
50
+
51
+ An integer maximum-flow allocation must consume both all required quantities
52
+ and all ordered quantities. A unit cannot satisfy two requirements. For example,
53
+ requirements `{A or B: 1}` and `{A: 1}` accept `A: 1, B: 1`; a greedy allocation
54
+ which consumes A for the first requirement is insufficient. Missing units,
55
+ extra units and extra products reject. One requirement's quantity may be
56
+ distributed across its revealed candidate IDs.
57
+
58
+ Ordering does not change quantity satisfiability. A separately and correctly
59
+ signed checkout in another order has different original bytes and must be bound
60
+ by its own Mandate and Host challenge. Reordering an existing signed JWT or
61
+ reusing the previous reference is a signature/binding failure.
62
+
63
+ ## Closed subset and limits
64
+
65
+ These are Gem profile restrictions, not general AP2 requirements.
66
+
67
+ | Input | New v1 limit / supported form |
68
+ | --- | --- |
69
+ | Merchant / Checkout / currency | One each; USD, EUR or JPY |
70
+ | Checkout lines | 1–8; distinct line IDs |
71
+ | Requirements | 1–8; distinct requirement IDs |
72
+ | Candidates per requirement | 1–8; distinct product IDs within the requirement |
73
+ | Quantity per line / requirement | Integer 1–1,000,000 |
74
+ | Unit price / multiplication / summed total | Integer minor units, 0–9,007,199,254,740,991 |
75
+ | Line and Checkout totals | Exactly subtotal and total, each equal to its checked amount |
76
+ | Constraints | Ordered `checkout.line_items`, then `checkout.allowed_merchants`; no unknown constraints |
77
+ | Links / taxes / shipping / discount | Empty links; no tax, shipping or discount engine or extra total types |
78
+ | Root disclosures | Every candidate, the Open payload and allowed merchant; at most 66 |
79
+ | Disclosure segment / Root input | 8,192 / 131,072 bytes |
80
+ | Commitment walk | At most 2,048 visits; container depth 24; array length 16 |
81
+ | Checkout JWT / terminal JWS | Existing 16,384 / 32,768 byte limits |
82
+
83
+ All candidate positions must be array commitments under
84
+ `delegate_payload[0].disclosed.constraints[0].items[i].acceptable_items[j]`.
85
+ The Open payload and sole allowed merchant retain their existing commitment
86
+ positions. Missing, reused or unused disclosures and unsupported positions fail
87
+ closed. Bounds apply together: an input below one count cap can still exceed
88
+ the segment, wire or traversal cap. Oversized values are rejected, never truncated.
89
+ No unmeasured worst-case CPU, memory, concurrency or numeric SLA is promised.
90
+
91
+ ## Normative source and SDK differences
92
+
93
+ The AP2 source stays pinned to
94
+ `b4587ac1d055888a73b4b21750973cffba961793`. The Line Items normative text defines
95
+ maximum flow and requires both sides to be fully satisfied. Schema descriptions
96
+ and Python helper behavior must be compared independently; see
97
+ [the interoperability record](MULTI_ITEM_INTEROP.md) for measured cases and scope.
98
+ No generic AP2/full-Schema or real-Issuer conformance claim follows from synthetic
99
+ tests. Unrelated latest-spec changes are not adopted by this profile.
100
+
101
+ Receipt still uses Checkout-specific `status: Success/Error`. Its reference is
102
+ the original final closed SD-JWT `<terminal_jws>~`; no per-line receipt or
103
+ compact-only alternate hash is introduced. The existing
104
+ [Receipt specification/SDK differences](MERCHANT_SIGNING.md) remain applicable.
105
+
106
+ ## Host responsibilities
107
+
108
+ The Host independently supplies authenticated, current trust/keys/revocation,
109
+ clock, expected order/currency/total and saved challenge state. A total extracted
110
+ from the received checkout is not an independent expected order. It rechecks
111
+ state before acting, atomically consumes the nonce with order CAS, handles
112
+ uncertain outcomes and makes the final purchase/payment decision.
113
+
114
+ Verification success is checked Evidence, not Host ALLOW or payment success.
115
+ Receipt authenticity is separate from its explicit business outcome. Multiple
116
+ merchants, splitting one Open Mandate across Checkouts, Payment Mandates/Receipts,
117
+ product issuance/presentation, real payments and production operation are outside
118
+ this task. Formal MRI 3.4.12 / 4.0.9 and all five runtime dependency pins are unchanged.
@@ -1,6 +1,31 @@
1
- # Fixed-profile AP2 verification — published 0.3.0 / historical releases
1
+ # Fixed-profile AP2 verification — 0.6.0 preparation / published history
2
+
3
+ ## Current source: explicit multi-item profile
4
+
5
+ This checkout prepares **0.6.0**, not yet published. It adds the explicitly
6
+ selected `ap2.checkout.single_merchant_multi_item` v1 across input preparation,
7
+ restoration/current-state verification, Checkout signing and Checkout Receipts.
8
+ The [multi-item contract](MULTI_ITEM_CHECKOUT.md) defines the accepted shapes,
9
+ eight-line/eight-requirement/eight-candidate bounds, integer maximum-flow matching,
10
+ complete disclosures, exact original-byte binding and migration. Existing
11
+ `ap2.checkout.single_merchant_sku` v1 identifier/body/hash/acceptance range and all
12
+ default APIs remain unchanged. Historical single-profile statements below describe
13
+ their original releases; they do not exclude this separately selected addition.
14
+
15
+ Formal MRI 3.4.12 and 4.0.9, all five dependency pins, Result/status/code,
16
+ diagnostic and Evidence meanings remain unchanged. Tests, independent review,
17
+ CI and final archive identities must be read from the task's final validation
18
+ record; pending work is not a PASS. Publication/tag/Release operations require
19
+ Owner judgment and have not been performed for 0.6.0.
20
+
21
+ Published **0.5.0** adds separate [Merchant signing and Checkout Receipt APIs](MERCHANT_SIGNING.md). They do not broaden the existing Verifier profile or change Result/Evidence/status/code. Checkout Receipt uses the dedicated Schema and normative final SD-JWT reference; unsupported forms fail closed. No product Mandate issuance, payment, persistence or real key/trust management is included.
22
+
23
+ [0.5.0 publication record](PROJECT_STATUS.md#050-publication): 50,688 bytes, SHA256 `00b0ce0981070864c67a056906c5af204bbc5aaa80d029cb4a64294634367dd8`, approved source `bf796a53600c189b0cfe66c9cfcd1de8a353c03d`. Current repository examples/docs do not replace the published preparation snapshot.
24
+
25
+ Historical published 0.4.0 adds supplemental safe diagnostics; see [API and troubleshooting](DIAGNOSTICS.md). Existing verdict/Evidence contracts remain unchanged.
26
+
27
+ [0.4.0 on RubyGems](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.4.0) was registered 2026-10-31 04:25:06.427 UTC and compared at 04:26:15 UTC: owner `cuichangquan`, platform `ruby`, prerelease false, not yanked at comparison; 44,032 bytes, SHA256 `b212db01e7deb18dcef1199414f9d93ef43cb1f74b62baa55306de3955dfe177`. The download matches the saved reviewed artifact and all 17 payload files match source `fc42852f53c615f96d7c165a8de494b24b252519`. RubyGems does not independently attest the source SHA. Formal MRI support and all five runtime pins below are unchanged. [Publication record](PROJECT_STATUS.md#040-publication) and [validation scope](DIAGNOSTICS_VALIDATION.md). Packaged documentation retains its preparation snapshot; repository updates do not replace published bytes.
2
28
 
3
- Unreleased 0.4.0 adds supplemental safe diagnostics; see [API and troubleshooting](DIAGNOSTICS.md). Published 0.3.0 and existing verdict/Evidence contracts remain unchanged.
4
29
 
5
30
  ## Published 0.3.0 input assistance
6
31
 
@@ -61,7 +86,7 @@ Gem-owned signature/original-wire/closure, delegation, binding, supplied-trust s
61
86
  Host inputs must be authenticated, independent of the token and current: trust/keys/profile/revocation/rollback protection, clock and order/challenge state. Recheck before use; atomically consume nonce with order CAS, reconcile unknown results as PENDING, and decide final ALLOW/payment separately.
62
87
  Evidence is immutable checked facts in the same trusted Ruby process, not ALLOW or a transport credential. JSON/Hash reconstruction does not authenticate it. Rejection, unavailability, exceptions and no result never authorize an operation. Trusted Ruby is a precondition, not a malicious-Ruby sandbox.
63
88
 
64
- No worst-case CPU/RSS/concurrency or numeric SLA is promised. Host process/time/memory/concurrency limits supplement, not replace, Gem finite input bounds. Issuance, presentation generation, Receipt, Rails adapter, real payments and Host DB operations are outside this verifier.
89
+ No worst-case CPU/RSS/concurrency or numeric SLA is promised. Host process/time/memory/concurrency limits supplement, not replace, Gem finite input bounds. Product Mandate issuance/presentation, Rails adapters, real payments and Host DB operations remain outside the Gem. Separate merchant signing/Checkout Receipt APIs are documented in [MERCHANT_SIGNING](MERCHANT_SIGNING.md).
65
90
  Supported-input semantics and existing API/status/code/Evidence contracts must not change silently. Security-driven acceptance narrowing requires impact/reason/migration disclosure; breaking required-field/profile/API changes must be explicit. Dependency updates are not automatically compatible.
66
91
 
67
92
  The published 0.2.0 and historical baseline below is MRI4.0.9 plus JSON2.19.9/JWT3.3.0/base640.3.0/OpenSSL gem4.0.2/Digest3.2.1, with the exact observed MBA arm64-darwin25 and Ubuntu24.04/x86_64 configurations. RubyGems version constraints do not enforce MRI/OS/provider identity. All OS versions, other engines/architectures and arbitrary provider updates are not supported by past observations.
@@ -76,7 +101,7 @@ The API/limit specification below preserves the existing contract. All pre2/pre3
76
101
 
77
102
  ## Supported proposition and environment
78
103
 
79
- The sole registered profile is `ap2.checkout.single_merchant_sku` version1,
104
+ The historical sole registered profile is `ap2.checkout.single_merchant_sku` version1,
80
105
  with the exact `TrustContext::PROFILE_BODY`/hash. Official AP2 source is fixed at
81
106
  b4587ac1d055888a73b4b21750973cffba961793; its subset-source reference027ed4734...
82
107
  is historical profile provenance, not runtime code attestation. Root typ is
@@ -0,0 +1,88 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Merchant-authored checkout, not a Mandate or authorization decision.
5
+ module CheckoutJWT
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid checkout signing information")
8
+ end
9
+
10
+ class Signed
11
+ attr_reader :jwt, :checkout_hash
12
+ def initialize(jwt)
13
+ @jwt = jwt.freeze
14
+ @checkout_hash = Base64.urlsafe_encode64(Digest::SHA256.digest(jwt), padding: false).freeze
15
+ freeze
16
+ end
17
+ private_class_method :new
18
+ end
19
+
20
+ # signer.call receives the exact ASCII JWS signing input and must return a
21
+ # 64-byte JOSE ES256 signature. The supplied independent public key verifies
22
+ # the result before any signed object is returned (including remote signers).
23
+ def self.sign(checkout:, signer:, public_key_pem:, profile_ref: TrustContext::PROFILE_REF)
24
+ RootSignature.send(:dependencies!)
25
+ value = InputBuilder.send(:copy!, checkout)
26
+ validate!(value, profile_ref: profile_ref)
27
+ jwt = MerchantSignature.sign!(value, signer, public_key_pem)
28
+ Signed.send(:new, jwt)
29
+ rescue StandardError, LoadError
30
+ raise Invalid.new, cause: nil
31
+ end
32
+
33
+ # No key serialization, storage, lookup or logging. The application owns the
34
+ # lifetime of this key/closure. Remote signers can implement the same call.
35
+ def self.es256_signer(private_key:)
36
+ RootSignature.send(:dependencies!)
37
+ raise Invalid unless private_key.instance_of?(OpenSSL::PKey::EC) &&
38
+ private_key.private? && private_key.group.curve_name == "prime256v1"
39
+ lambda do |input|
40
+ der = private_key.dsa_sign_asn1(Digest::SHA256.digest(input))
41
+ OpenSSL::ASN1.decode(der).value.map { |n| n.value.to_s(2).rjust(32, "\0") }.join
42
+ end
43
+ rescue StandardError, LoadError
44
+ raise Invalid.new, cause: nil
45
+ end
46
+
47
+ def self.validate!(checkout, profile_ref: TrustContext::PROFILE_REF)
48
+ profile_ref = InputValidator.snapshot!(profile_ref, max_bytes: 256)
49
+ if profile_ref == ScopedConstraints::MULTI_PROFILE_REF
50
+ ScopedConstraints.multi_checkout!(checkout)
51
+ return nil
52
+ end
53
+ raise Invalid unless profile_ref == TrustContext::PROFILE_REF
54
+ c = ScopedConstraints
55
+ c.send(:exact!, checkout, %w[currency id line_items links merchant status totals])
56
+ c.send(:text!, checkout["id"])
57
+ raise Invalid unless checkout["status"] == "ready_for_complete" &&
58
+ c::CURRENCIES.include?(checkout["currency"]) && checkout["links"] == []
59
+ c.send(:exact!, checkout["merchant"], %w[id name])
60
+ c.send(:text!, checkout["merchant"]["id"])
61
+ c.send(:text!, checkout["merchant"]["name"], 512)
62
+ line = c.send(:one!, checkout["line_items"])
63
+ c.send(:exact!, line, %w[id item quantity totals])
64
+ c.send(:text!, line["id"])
65
+ c.send(:quantity!, line["quantity"])
66
+ item = line["item"]
67
+ c.send(:exact!, item, %w[id price title])
68
+ c.send(:text!, item["id"])
69
+ c.send(:text!, item["title"], 512)
70
+ c.send(:amount!, item["price"])
71
+ total = item["price"] * line["quantity"]
72
+ c.send(:amount!, total)
73
+ c.send(:totals!, line["totals"], total)
74
+ c.send(:totals!, checkout["totals"], total)
75
+ nil
76
+ end
77
+ %i[sign es256_signer].each do |name|
78
+ implementation = method(name)
79
+ fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
80
+ optional = implementation.parameters.filter_map { |kind, field| field if kind == :key }.freeze
81
+ define_singleton_method(name) do |**arguments|
82
+ raise Invalid.new, cause: nil unless (fields - arguments.keys).empty? && (arguments.keys - fields - optional).empty?
83
+ implementation.call(**arguments)
84
+ end
85
+ end
86
+ private_class_method :validate!
87
+ end
88
+ end