ap2_mandate_verifier 0.6.0 → 0.8.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.
@@ -0,0 +1,168 @@
1
+ # Conditional Checkout delegation — 0.8.0 candidate
2
+
3
+ Adopted AP2 v0.2.0 source remains `b4587ac1d055888a73b4b21750973cffba961793`.
4
+ This is an additive Ruby issuance API for the existing explicit
5
+ `ap2.checkout.single_merchant_multi_item` v1 profile. It does not relax old
6
+ profiles, add a general Schema engine, or establish real Issuer trust.
7
+
8
+ ## Security proposition and responsibilities
9
+
10
+ An authenticated approval service issues an Open for one registered Agent key,
11
+ one merchant and 1–8 requirements, each with 1–8 candidate products and an exact
12
+ integer quantity. The Agent can close it only against an authentic merchant
13
+ Checkout that completely satisfies those requirements. All signed original
14
+ bytes are retained. The existing full verifier independently checks the result
15
+ against registered trust, the current order and Host challenge.
16
+
17
+ The application authenticates the person, obtains informed consent and purchasing
18
+ authority, protects the approved conditions and controls the Provider signer.
19
+ No boolean approval establishes consent. Provider key material is never passed
20
+ to the Agent. Agent and Merchant keys are independently registered, not trusted
21
+ because they appear in received tokens. Host owns challenge issuance, trusted
22
+ clock, current order, revocation, durable atomic consumption and execution.
23
+ SDK verification is evidence, never Host ALLOW or payment completion.
24
+
25
+ ## Public API design
26
+
27
+ `ConditionalCheckout.issue_open(merchant:, requirements:, agent_public_key_pem:,
28
+ issued_at:, expires_at:, signer:, public_key_pem:)` returns immutable
29
+ `Open#root_presentation`. Merchant is `{id, name}`; requirements contain
30
+ `{id, quantity, acceptable_items: [{id, title}]}` with string keys. Input is a
31
+ protected application approval record, not untrusted Agent parameters.
32
+
33
+ `ConditionalCheckout.issue_closed(root_presentation:, checkout_jwt:,
34
+ trusted_issuer_public_key_pem:, agent_public_key_pem:,
35
+ trusted_merchant_public_key_pem:, expected_merchant_id:, audience:, nonce:,
36
+ verified_at:, signer:)` returns immutable `Closed` with original
37
+ `root_presentation`, `terminal_jws`, `closed_sd_jwt` and `checkout_jwt`.
38
+ It verifies Open signature, complete disclosure graph, schema subset, Agent
39
+ cnf, validity, Merchant signature and all quantity constraints before signing.
40
+ The signer receives frozen ASCII ES256 signing input and returns 64 JOSE bytes;
41
+ the supplied public key verifies the exact returned signature before success.
42
+ Signer network access, timeout and access control belong to the application.
43
+
44
+ `ConditionalCheckout.present(root_presentation:, terminal_jws:, checkout_jwt:)`
45
+ restores detached immutable original strings for transport/storage. It checks
46
+ bounded supported syntax and original-byte bindings, not authentication;
47
+ Merchant must use `InputBuilder.verify` / `verify_checkout` with independent
48
+ trust and Host inputs. The issuance object can be persisted as these three
49
+ strings; no claims or disclosures are reserialized during presentation.
50
+ Issuance/restoration failures raise a fixed redacted `ConditionalCheckout::Invalid`
51
+ without a cause. No partial claims, keys, nonce or raw tokens appear in errors.
52
+
53
+ ## Wire contract, limits and completeness
54
+
55
+ Open uses ES256 root `example+sd-jwt`, one SD array commitment to Open content,
56
+ one to the merchant, and one per candidate. All candidates and constraints are
57
+ always disclosed; subset selection is not supported. Salts are random 128-bit
58
+ values. No omitted, extra, duplicate, unknown or decoy commitments are accepted.
59
+ The profile's original-byte, depth, graph, 8-line/requirement/candidate and amount
60
+ limits apply jointly. Quantity matching uses exact integral max flow by product
61
+ ID, including same-product separate rows. Unknown constraints fail closed.
62
+
63
+ Open carries `cnf.jwk`, `iat`, `exp`, two ordered constraints and
64
+ `vct: mandate.checkout.open.1`. Lifetime is positive and at most 7200 seconds;
65
+ all checks use explicit integer epochs and `iat <= now < exp`. Agent Closed
66
+ inherits Open `iat/exp` exactly, as required by this existing profile. Terminal
67
+ KB-SD-JWT has `typ: kb+sd-jwt`, `aud`, `nonce`, fresh `iat`, `sd_hash` of the
68
+ entire original Open SD-JWT including disclosures and trailing `~`, and one
69
+ inline Closed containing the exact merchant JWT and its SHA256 base64url hash.
70
+ There are no selective disclosures in this final Closed; its SD-JWT is exactly
71
+ `terminal_jws + "~"`. Audience and nonce come from the Host challenge and must
72
+ also be independently checked by the Merchant. Proof age is at most 300 seconds.
73
+ Agent signing uses the existing terminal limits (24,576 decoded claim bytes and
74
+ 32,768 compact bytes), accommodating the embedded original Merchant JWT.
75
+ Merchant/Direct signing retain 12,000 decoded claim bytes and 16,384 wire bytes;
76
+ Checkout text/count limits and all joint effective bounds still apply.
77
+
78
+ Receipt `reference` is base64url without padding of SHA256 of **only the final
79
+ Closed SD-JWT**, including its trailing `~`. It excludes the preceding Open
80
+ chain, includes any disclosure bytes in profiles that have them, and never hashes
81
+ compact JWT alone or reconstructed JSON. This profile has zero final disclosures;
82
+ reordering Open disclosures changes the Agent's root binding but not that rule.
83
+ Existing `CheckoutReceipt.sign/verify` use the explicit multi-item profile.
84
+
85
+ ## Application outcomes and compatibility
86
+
87
+ After evidence verification, the application reserves/consumes the approval,
88
+ challenge and order transactionally and signs its explicit Success/Error outcome.
89
+ Authentic Success confirms the merchant's recorded result; authentic Error is
90
+ not automatic permission to replay. Retry requires current order/approval/nonce
91
+ policy. Missing Receipt, transport errors or uncertain commits remain pending;
92
+ reconcile saved operation IDs rather than repeat a purchase blindly.
93
+
94
+ Direct, old single-product defaults, InputBuilder saved formats, diagnostics,
95
+ Result/Evidence and Receipt contracts remain unchanged. No migration is required.
96
+ This new API explicitly selects the existing multi-item profile; no token can
97
+ select policy. Payment Mandates, budgets, repeated/split/multi-merchant purchases,
98
+ User Credentials, Rails and tax/shipping/discount calculation are out of scope.
99
+
100
+ ## Acceptance and independent evidence
101
+
102
+ Required checks: public-only installed example from conditions through both
103
+ Receipt outcomes; 1/8 rows, candidates, varying quantities, repeated product rows;
104
+ shortage/excess, wrong merchant/Agent/Open/Checkout, authentic invalid orders;
105
+ signature/hash/disclosure tampering, unknown/missing/duplicate fields, bounds,
106
+ expiry/future/proof-age boundaries, audience/nonce mismatch, exact receipt hash
107
+ scope and wrong key/issuer/time/reference; existing complete regression.
108
+ Official Python SDK primitives and unmodified pinned Schemas must independently
109
+ verify Ruby output and produce Ruby-accepted signed input. Normative specification,
110
+ SDK behavior and stricter local rules are recorded separately; SDK shortage and
111
+ empty-candidate differences remain in MULTI_ITEM_INTEROP.md. Latest-HEAD Codex
112
+ review and the same candidate Gem installed on both supported Rubies are required.
113
+
114
+ Status: implemented and locally tested; release gates and final package/review
115
+ evidence are tracked in RELEASE_080_CANDIDATE.md and the external manifest.
116
+ No RubyGems push, public tag/Release,
117
+ production connection or actual payment is authorized by this task.
118
+
119
+ ## Official-source comparison and independent results
120
+
121
+ On 2026-11-01 official main is `e1ea56db72a6385bce3e5c1112b3a56ce60acb43`.
122
+ GitHub compare from the adopted commit changes only CHANGELOG, CONTRIBUTING,
123
+ README and uv.lock; normative docs, Schemas and SDK code are unchanged. Current
124
+ [Checkout](https://ap2-protocol.org/ap2/checkout_mandate/) and
125
+ [Agent Authorization](https://ap2-protocol.org/ap2/agent_authorization/) pages
126
+ were also read. Adoption stays pinned, with no dependency/source upgrade.
127
+
128
+ `test/conditional_interop.py` uses the pinned official `sd_jwt.create/verify`,
129
+ `kb_sd_jwt.verify`, JWT sign/verify helpers, unmodified Open/Closed/Checkout/Receipt
130
+ Schemas, independent commitment traversal and SHA256. Ruby Open/Closed is
131
+ verified by Python. Official Python Open issuance plus official JWT helper inline
132
+ Closed signing is accepted by Ruby; both Receipt outcomes work in both directions.
133
+ Keys remain in memory and no runtime network or remote Schema fallback is used.
134
+
135
+ The official high-level `kb_sd_jwt.create` always discloses `delegate_payload`
136
+ through a commitment and emits `_sd_alg`, even with empty metadata. Its output is
137
+ tested unchanged as an unsupported-form rejection. We do not strip signed claims
138
+ or weaken the existing inline-terminal profile to accept it. The supported inline
139
+ form uses official JWT signing and the same normative claim/hash rules, validated
140
+ independently. Choosing a new selective-disclosure terminal profile is future work.
141
+ This is bounded interoperability, not all SDK helpers or general AP2 compatibility.
142
+
143
+ The initial Codex P2 on restoration completeness was fixed by sharing the exact
144
+ Root closure walker for structural restoration. Restoration still authenticates
145
+ neither Root nor Agent signatures; full merchant verification remains mandatory.
146
+ Negative tests sign terminals bound to malformed/missing/duplicate Root disclosures
147
+ and require restoration rejection. Package/source results and final review status
148
+ are in [release preparation](RELEASE_080_CANDIDATE.md).
149
+
150
+ ## Handling non-success without replay
151
+
152
+ ```ruby
153
+ case result.status # from InputBuilder.verify / verify_checkout
154
+ when :verified_research
155
+ # Recheck current application authorization/order/trust; atomically reserve.
156
+ when :rejected
157
+ # Decline this presentation; do not execute or issue a Success Receipt.
158
+ when :unavailable
159
+ # Verification could not establish evidence; hold, diagnose and retry only
160
+ # verification under application policy, without executing the order.
161
+ end
162
+ # Missing/unverified Receipt after submission: retain operation_id => :pending,
163
+ # reconcile the merchant's saved result; do not resubmit a purchase blindly.
164
+ ```
165
+
166
+ Issuance `Invalid` similarly never means that an order was executed; a remote
167
+ signer error may have an uncertain signing outcome, so reconcile the application's
168
+ issuance record before reissuing. SDK operations here perform no payment side effect.
@@ -1,8 +1,8 @@
1
1
  # Merchant Checkout signing and Receipt
2
2
 
3
- ## Explicit multi-item selection — 0.6.0 preparation
3
+ ## Explicit multi-item selection — published 0.6.0
4
4
 
5
- Published 0.5.0 APIs below retain their default single-SKU behavior. This checkout
5
+ The APIs introduced in 0.5.0 retain their default single-SKU behavior. Published 0.6.0
6
6
  adds optional `profile_ref: "ap2.checkout.single_merchant_multi_item"` to
7
7
  `CheckoutJWT.sign` and `CheckoutReceipt.reference/sign/verify`. Pass it consistently
8
8
  when working with a multi-item Checkout. The new profile validates every line,
@@ -15,9 +15,10 @@ Receipt still references the complete original `<terminal_jws>~`, without
15
15
  per-line hashes or a compact-only alternate. Profile selection validates the
16
16
  supported embedded Checkout shape; reference computation alone does not verify
17
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.
18
+ unchanged. The [0.6.0 publication record](PROJECT_STATUS.md#060-publication) identifies
19
+ the reviewed source, distribution and validation separately.
19
20
 
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
+ The original single-SKU signing/Receipt APIs were introduced in [0.5.0](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.5.0); the explicit multi-item selection above is available in 0.6.0. [Complete runnable single-SKU example](../examples/merchant_signing.rb). The example is repository content, not part of the installed Gem.
21
22
 
22
23
  ## Scope and responsibility
23
24
 
@@ -61,7 +62,9 @@ puts signed.checkout_hash.length # 43
61
62
  `signed.jwt` is the frozen original compact JWT to transmit and retain. Supply
62
63
  that exact String as `host_checkout_jws` to InputBuilder and Verifier; supply
63
64
  `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
+ These 0.5/0.6 APIs do not issue a product Mandate. The published 0.7.0
66
+ [Direct buyer module](BUYER_DIRECT_CHECKOUT.md) adds a separate issuance flow.
67
+ Re-encoding claims or signing again
65
68
  creates different original wire, even when the order is the same.
66
69
 
67
70
  `signer.call(signing_input)` receives the frozen ASCII `header.payload` and returns
@@ -1,10 +1,11 @@
1
- # Multiple-item Checkout profile — 0.6.0 preparation
1
+ # Multiple-item Checkout profile — published 0.6.0
2
2
 
3
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.
4
+ `ap2.checkout.single_merchant_multi_item` version `1`, available in published
5
+ 0.6.0. The `ap2.checkout.single_merchant_sku` v1 default remains unchanged.
6
+ Tests, review, distribution identity and publication are recorded separately in
7
+ [project status](PROJECT_STATUS.md#060-publication); publication does not authorize
8
+ a Host purchase or payment.
8
9
 
9
10
  ## Selection and lifecycle
10
11
 
@@ -0,0 +1,109 @@
1
+ # 0.8.0 candidate — conditional Checkout delegation, unpublished
2
+
3
+ Compatible feature release preparation for approved conditional purchasing:
4
+ `ConditionalCheckout.issue_open` → Agent `.issue_closed` → `.present` → existing
5
+ full `InputBuilder.verify` → `CheckoutReceipt.sign/verify`. The installed
6
+ [standalone example](../examples/conditional_checkout.rb) uses A/B×1 and C×2,
7
+ three rows and repeated C products. [API/specification](CONDITIONAL_CHECKOUT.md).
8
+
9
+ Published stable remains 0.7.0, verified from the official RubyGems versions API
10
+ on 2026-11-01; 0.8.0 is absent, so no version-plan collision is currently observed.
11
+ 0.7.0 source/tag is `9b4b78a7ed9aa95e7d35e01a64efc1281ba95be3`; its published
12
+ 64,000-byte SHA256 is `baab8c68355b5e6c9351e7d86a836fab50652cdad662bbc99d1676c5e6134447`.
13
+ Current base main is `50f9639a4fe316556189088ab6b737a642f5f6e2`, initially no open PRs.
14
+ No verified prior artifact or previous task checkout was modified.
15
+
16
+ ## Validation and compatibility
17
+
18
+ All 17 source-suite entry points pass offline on MRI 3.4.12 and 4.0.9. Existing
19
+ regression includes Direct, both old profiles, signed missing/unknown/duplicate
20
+ disclosures, original-wire binding, InputBuilder save/restore, Result/Evidence,
21
+ diagnostics and Receipt outcomes. New tests add 8 cases (123 assertions on MRI
22
+ 3.4.12 / 126 on MRI 4.0.9, including installed-Gem execution) for
23
+ issuance, sign-before-check prevention, bounds, 8×8 candidate/requirement cases,
24
+ same-product separate rows, wrong keys/time/audience/nonce, restoration closure,
25
+ and exact final Closed Receipt reference. A long-ID/title eight-row Checkout
26
+ also completes through the larger existing Agent-terminal bounds while Merchant
27
+ JWT and Direct signing bounds remain unchanged. Suite counts include shared legacy
28
+ dependencies; no misleading aggregate of repeated assertion counters is claimed.
29
+
30
+ Official pinned Python comparison passes for signatures in both directions,
31
+ Open/Closed/Checkout/Receipt Schemas, complete Open commitments and normative
32
+ sd_hash including final `~`, both receipt outcomes and negative controls. SDK
33
+ high-level Closed helper emits an unsupported SD form; it is a rejection control,
34
+ not claimed accepted interoperability. Existing max-flow shortage/empty-candidate
35
+ differences and compact-only Receipt helper remain documented and fail closed.
36
+
37
+ Candidate Gem identity, corresponding final source SHA, payload hashes, byte size,
38
+ ordinary installation on both Rubies and exact example output are recorded in the
39
+ external candidate manifest beside the Gem. The Gem includes both READMEs, this
40
+ decision document, the API contract and the standalone example. Dependencies and
41
+ supported MRI versions are unchanged; old callers require no migration.
42
+
43
+ ## Review and external-operation status
44
+
45
+ Initial independent Codex review found one substantive P2 (restoration Root
46
+ closure); fixed through shared structural parsing and signed negative regression.
47
+ GitHub review additionally found that the Merchant signing helper's 12,000-byte
48
+ claims / 16,384-byte JWS limits prevented valid larger Agent terminals. KB terminal
49
+ signing now uses its existing verifier's 24,576-byte payload / 32,768-byte wire
50
+ bounds only; JWT and Direct retain the old limits. Long-ID/title eight-row Ruby
51
+ and official Python signature/Schema/hash regressions exercise this fix.
52
+ Latest-HEAD independent review must be completed and identified in the external
53
+ verification report. Review no-findings alone is not a security proof.
54
+
55
+ Initial Draft PR branch push was denied by automatic approval review before
56
+ execution. Owner subsequently explicitly authorized the specified commit/branch
57
+ push, Draft PR, existing-budget CI, latest-HEAD Codex review/fixes and conditional
58
+ Squash Merge at 2026-11-01 14:41 JST. The branch was pushed and
59
+ [Draft PR #231](https://github.com/cuichangquan/ap2-mandate-verifier/pull/231)
60
+ created. No alternate route bypassed the denial; authorization resolved it first.
61
+ No owner approval review is submitted. Current exact-HEAD review, CI and merge
62
+ results are recorded in that PR and the external final verification report.
63
+ Only existing `merchant-source-package.yml` is expected to trigger for this diff:
64
+ two MRI jobs in one workflow run, existing Ubuntu runner/15-minute job timeout,
65
+ public dependencies, no secrets, extra cost zero. No workflow edits. Issue #101's
66
+ maximum 3 runs/PR is a ceiling, no blind reruns; the PR records every consumed run.
67
+
68
+ ## Build and final candidate evidence
69
+
70
+ Use the final committed tree, existing pinned Docker images and no network:
71
+
72
+ ```sh
73
+ gem build ap2_mandate_verifier.gemspec --output /out/ap2_mandate_verifier-0.8.0.gem
74
+ sh scripts/check_candidate_package.sh /out/package /out/ap2_mandate_verifier-0.8.0.gem
75
+ ```
76
+
77
+ Run source regression with `sh scripts/check_ruby_compatibility.sh /out/source`.
78
+ The packaging script installs the **same** built Gem with normal RubyGems
79
+ resolution (`gem install --local`), audits every source/archive/installed payload,
80
+ then executes detached old APIs and the example physically inside the installed
81
+ Gem. Reuse one artifact across both MRI runtimes. Do not substitute an earlier
82
+ working-tree package or rebuild a lookalike after approval. Exact source SHA and
83
+ Gem SHA cannot be embedded recursively in their own bytes; use external manifest.
84
+
85
+ ## Publication decision and recovery plan
86
+
87
+ 1. Review final source SHA, strict latest-HEAD review, all tests/independent
88
+ comparison, exact candidate manifest and remaining GitHub PR/CI gates.
89
+ 2. Obtain separate Owner authorization for that exact Gem publication; **no push,
90
+ public tag or GitHub Release is authorized by this request**.
91
+ 3. After explicit authorization only, RubyGems push the approved exact artifact,
92
+ fetch the official distribution and compare bytes/SHA/size and every payload.
93
+ 4. Only under publication/tag/Release authorization, bind `v0.8.0` to its verified
94
+ source, publish release notes and update stable install guides/demo after the
95
+ registry version is actually available. A candidate README is not publication.
96
+ 5. On mismatch, invalid dependency/content, signature or material regression,
97
+ stop rollout and retain evidence. Do not overwrite a published version; assess
98
+ scoped yank/patch publication with separate Owner decision. Keep 0.7.0 install
99
+ guidance until the successor is independently verified. Preserve original
100
+ saved mandates/challenges; do not reinterpret them under a changed profile.
101
+
102
+ Limits: one merchant/Checkout, all candidates disclosed, ES256/P-256, exact finite
103
+ profile, no real Issuer trust/production Host proof. Authentication/consent,
104
+ revocation/key lifecycle, persistence/CAS/nonce consumption, execution and payment
105
+ remain app responsibilities. Payment Mandates, budgets, repeating/split orders,
106
+ User Credentials and tax/shipping/discount engines remain out of scope.
107
+ Production/real wallet/payment/deployment, RubyGems push and public tag/Release
108
+ are NOT_RUN. Release readiness requires the final exact-HEAD PR/review/CI and
109
+ package gates; the external report records their actual completion state.
@@ -1,8 +1,29 @@
1
- # Fixed-profile AP2 verification — 0.6.0 preparation / published history
1
+ # Fixed-profile AP2 verification — published 0.7.0 / history
2
+
3
+ ## Unpublished 0.8.0 additive candidate
4
+
5
+ `ConditionalCheckout.issue_open/issue_closed/present` add conditional delegation
6
+ issuance and original-wire presentation under the unchanged explicit multi-item
7
+ profile v1. [Contract, errors, limits and application responsibilities](CONDITIONAL_CHECKOUT.md).
8
+ The packaged standalone example uses only public installed APIs. No old default,
9
+ profile definition/hash, Result/Evidence/diagnostic, saved record or Receipt
10
+ acceptance condition is changed. All candidates remain required; no new selective
11
+ disclosure profile is introduced. Published stable remains 0.7.0.
12
+
13
+ Published 0.7.0 adds the separate [Direct buyer module](BUYER_DIRECT_CHECKOUT.md):
14
+ merchant Checkout verification before human approval, Provider-signed issuance,
15
+ Agent presentation, Direct merchant verification and whole-wire Receipt confirmation.
16
+ It supports one merchant, 1–8 lines and multiple products; existing Open→Closed
17
+ Result/Evidence/profile/save contracts are unchanged. Publication was verified at
18
+ 2026-11-01 03:14:04 UTC: 64,000 bytes, SHA256
19
+ `baab8c68355b5e6c9351e7d86a836fab50652cdad662bbc99d1676c5e6134447`, all 24 payloads
20
+ match source `9b4b78a7ed9aa95e7d35e01a64efc1281ba95be3`.
21
+ [Publication record](PROJECT_STATUS.md#070-publication). Older version statements below
22
+ retain their historical scope; they do not exclude the new Direct APIs.
2
23
 
3
24
  ## Current source: explicit multi-item profile
4
25
 
5
- This checkout prepares **0.6.0**, not yet published. It adds the explicitly
26
+ Published **0.6.0** adds the explicitly
6
27
  selected `ap2.checkout.single_merchant_multi_item` v1 across input preparation,
7
28
  restoration/current-state verification, Checkout signing and Checkout Receipts.
8
29
  The [multi-item contract](MULTI_ITEM_CHECKOUT.md) defines the accepted shapes,
@@ -14,9 +35,20 @@ their original releases; they do not exclude this separately selected addition.
14
35
 
15
36
  Formal MRI 3.4.12 and 4.0.9, all five dependency pins, Result/status/code,
16
37
  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.
38
+ CI and archive identities are recorded separately in the
39
+ [0.6.0 publication record](PROJECT_STATUS.md#060-publication) and
40
+ [validation record](MULTI_ITEM_VALIDATION.md); pending work is not a PASS.
41
+
42
+ Registered 2026-10-31 **11:50:18.664 UTC**, official metadata/distribution
43
+ comparison completed **11:51:54 UTC**: 56,832 bytes, SHA256
44
+ `ff669a62717f91b2295b3cea1b68c6c4143c490d98df071fd322ad4b0007195d`,
45
+ source `baee59a603d08123adc0af50e57c8710ea62f4f9`. All 22 payloads match
46
+ the approved source and candidate, with unchanged five runtime pins and Ruby
47
+ requirement. Platform `ruby`, non-prerelease, not yanked at comparison.
48
+ Source association is established by candidate/distribution bytes, not RubyGems
49
+ source attestation. [Publication receipt](evidence/0.6.0_publication.json).
50
+ Packaged documents retain their preparation snapshot; these repository-only
51
+ updates do not rebuild, repush or replace the published Gem.
20
52
 
21
53
  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
54
 
@@ -382,3 +414,12 @@ The summary must explicitly identify the completed observation; a missing,
382
414
  failed or mismatched report is not success. No local path is a public evidence
383
415
  URL. Raw local environment logs are not published by this package.
384
416
 
417
+
418
+ ## Direct buyer module — published 0.7.0
419
+
420
+ Additive `CheckoutJWT.verify` and `Buyer.issue_closed/present_closed/verify`
421
+ implement Trusted Agent Provider / Human Present exact-order approval. Direct
422
+ Receipt requires explicit `Buyer::PROFILE_REF`; existing defaults and 2profile
423
+ contracts are unchanged. Supports the existing 1–8-line multi-item Checkout subset
424
+ end to end. [Full input, failure, trust and replay contract](BUYER_DIRECT_CHECKOUT.md).
425
+ No general AP2, production authorization, payment or real-Issuer claim is added.
@@ -0,0 +1,84 @@
1
+ # frozen_string_literal: true
2
+ # Ordinary installed Gem only. No test fixtures, source-path loading or network.
3
+ require "ap2_mandate_verifier"
4
+ require "openssl"
5
+
6
+ module ConditionalCheckoutExample
7
+ M = AP2MandateVerifier
8
+ PROFILE = M::ConditionalCheckout::PROFILE_REF
9
+ NOW = 1_800_000_000
10
+ def self.totals(n) = %w[subtotal total].map { |type| {"type" => type, "amount" => n} }
11
+ def self.run
12
+ provider, agent, merchant = Array.new(3) { OpenSSL::PKey::EC.generate("prime256v1") }
13
+ seller = {"id" => "shop", "name" => "Office supplies"}
14
+ # This protected record is created AFTER application authentication, display
15
+ # of these conditions and authority/consent checks. No approved flag is proof.
16
+ requirements = [{"id" => "choice", "quantity" => 1,
17
+ "acceptable_items" => %w[A B].map { |id| {"id" => id, "title" => "Product #{id}"} }},
18
+ {"id" => "required", "quantity" => 2, "acceptable_items" => [{"id" => "C", "title" => "Product C"}]}]
19
+ opening = M::ConditionalCheckout.issue_open(merchant: seller, requirements: requirements,
20
+ agent_public_key_pem: agent.public_to_pem, issued_at: NOW, expires_at: NOW + 600,
21
+ signer: M::CheckoutJWT.es256_signer(private_key: provider), public_key_pem: provider.public_to_pem)
22
+ # Merchant Checkout has three rows, including C in two distinct rows.
23
+ lines = %w[B C C].each_with_index.map do |id, i|
24
+ {"id" => "row-#{i}", "item" => {"id" => id, "title" => "Product #{id}", "price" => 100},
25
+ "quantity" => 1, "totals" => totals(100)}
26
+ end
27
+ order = {"id" => "office-1", "merchant" => seller, "status" => "ready_for_complete",
28
+ "currency" => "USD", "line_items" => lines, "totals" => totals(300), "links" => []}
29
+ checkout = M::CheckoutJWT.sign(checkout: order, profile_ref: PROFILE,
30
+ signer: M::CheckoutJWT.es256_signer(private_key: merchant), public_key_pem: merchant.public_to_pem)
31
+
32
+ # Host enrollment and challenge are synthetic authenticated application data.
33
+ roles = %w[Issuer Agent Merchant]
34
+ records = roles.zip([provider, agent, merchant]).map do |role, key|
35
+ {"role" => role, "identity" => role == "Merchant" ? "shop" : role.downcase,
36
+ "tenant_id" => "tenant", "purpose" => "checkout", "key_ref" => role.downcase,
37
+ "public_key_pem" => key.public_to_pem, "active" => true, "not_before" => NOW - 1, "not_after" => NOW + 1000}
38
+ end
39
+ selectors = records.to_h { |record| [record["role"].downcase.to_sym, record.slice("identity", "purpose", "key_ref")] }
40
+ trust = M::InputBuilder.trust(snapshot: {"id" => "registry", "policy_version" => "1", "active" => true,
41
+ "not_before" => NOW - 1, "not_after" => NOW + 1000, "records" => records},
42
+ tenant_id: "tenant", verified_at: NOW, profile_ref: PROFILE, **selectors)
43
+ host_order = {"tenant_id" => "tenant", "buyer_account_id" => "buyer", "order_id" => "office-1",
44
+ "merchant_id" => "shop", "audience" => "merchant-host", "order_version" => "1", "currency" => "USD", "expected_total" => 300}
45
+ host_inputs = {trust: trust, order: host_order, root_presentation: opening.root_presentation, host_checkout_jws: checkout.jwt}
46
+ saved = M::InputBuilder.prepare(**host_inputs, challenge_id: "challenge-1", nonce: "synthetic-one-use-nonce",
47
+ issuer_id: "host", not_before: NOW, not_after: NOW + 60)
48
+ # Agent receives public trust, Open, Checkout, challenge and its own signer.
49
+ # Provider signer/private key is not an input to this operation.
50
+ closed = M::ConditionalCheckout.issue_closed(root_presentation: opening.root_presentation, checkout_jwt: checkout.jwt,
51
+ trusted_issuer_public_key_pem: provider.public_to_pem, agent_public_key_pem: agent.public_to_pem,
52
+ trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop",
53
+ audience: "merchant-host", nonce: "synthetic-one-use-nonce", verified_at: NOW,
54
+ signer: M::CheckoutJWT.es256_signer(private_key: agent))
55
+ wire = M::ConditionalCheckout.present(root_presentation: closed.root_presentation,
56
+ terminal_jws: closed.terminal_jws, checkout_jwt: closed.checkout_jwt)
57
+ checked = M::InputBuilder.verify(**host_inputs, terminal_jws: wire.terminal_jws,
58
+ saved_challenge: M::InputBuilder.restore(saved_challenge: saved), expected_challenge_issuer_id: "host",
59
+ clock_source_id: "synthetic-clock", verified_at: NOW)
60
+ raise "verification failed" unless checked.success?
61
+ puts "Open -> Agent Closed -> merchant evidence: verified=true; rows=3; requirements=2"
62
+ # These are ALTERNATIVE synthetic application outcomes, never two executions.
63
+ %w[Success Error].each do |outcome|
64
+ fields = outcome == "Success" ? {order_id: "office-1"} : {error: "policy_rejected", error_description: "Application declined"}
65
+ receipt = M::CheckoutReceipt.sign(closed_sd_jwt: wire.closed_sd_jwt, profile_ref: PROFILE,
66
+ issuer: "shop", outcome: outcome, issued_at: NOW, **fields,
67
+ signer: M::CheckoutJWT.es256_signer(private_key: merchant), public_key_pem: merchant.public_to_pem)
68
+ result = M::CheckoutReceipt.verify(jwt: receipt.jwt, closed_sd_jwt: wire.closed_sd_jwt,
69
+ profile_ref: PROFILE, trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "shop",
70
+ not_before: NOW, not_after: NOW + 60, verified_at: NOW)
71
+ raise "receipt failed" unless result.verified? && result.outcome == outcome
72
+ puts "Receipt #{outcome}: authentic=true; purchase_succeeded=#{result.purchase_succeeded?}"
73
+ end
74
+ # Application state, not an SDK purchase permit: durable transaction/CAS in
75
+ # real code must consume approval/challenge/order once and save its receipt.
76
+ states = {"success" => :consumed, "error" => :requires_new_policy_decision, "missing_receipt" => :pending}
77
+ raise "unknown replay" unless states["missing_receipt"] == :pending
78
+ puts "Success=consumed; Error=policy decision; missing Receipt/uncertain commit=pending"
79
+ puts "Synthetic only; evidence and Receipt authenticity are not payment completion."
80
+ {opening: opening, closed: closed, result: checked, host_inputs: host_inputs, saved: saved,
81
+ keys: [provider, agent, merchant], requirements: requirements, checkout: order}
82
+ end
83
+ end
84
+ ConditionalCheckoutExample.run if $PROGRAM_NAME == __FILE__
@@ -0,0 +1,153 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Optional Direct/Human Present profile; never an Open -> Closed chain.
5
+ module Buyer
6
+ PROFILE_REF = "ap2.checkout.direct.single_merchant".freeze
7
+ CHECKOUT_PROFILE = ScopedConstraints::MULTI_PROFILE_REF
8
+ MAX_LIFETIME = 600
9
+ class Invalid < ArgumentError
10
+ def initialize = super("invalid direct checkout information")
11
+ end
12
+ class Issued
13
+ attr_reader :closed_sd_jwt
14
+ def initialize(wire)
15
+ @closed_sd_jwt = wire.freeze
16
+ freeze
17
+ end
18
+ private_class_method :new
19
+ end
20
+ class Verification
21
+ attr_reader :code, :checkout, :checkout_hash, :reference, :expires_at
22
+ def initialize(code, parsed = nil)
23
+ @code = code
24
+ if parsed
25
+ @checkout = parsed.fetch(:checkout)
26
+ @checkout_hash = parsed.fetch(:closed).fetch("checkout_hash").freeze
27
+ @expires_at = parsed.fetch(:closed).fetch("exp")
28
+ @reference = Buyer.send(:hash, parsed.fetch(:wire)).freeze
29
+ end
30
+ freeze
31
+ end
32
+ def verified? = code == :direct_checkout_verified
33
+ private_class_method :new
34
+ end
35
+
36
+ # Only the authenticated approval backend calls this method. The approved
37
+ # wire comes from its protected approval record, never an Agent boolean.
38
+ # This is an equality contract, not authentication of the approver.
39
+ def self.issue_closed(checkout_jwt:, approved_checkout_jwt:, trusted_merchant_public_key_pem:,
40
+ expected_merchant_id:, issued_at:, expires_at:, signer:, public_key_pem:)
41
+ wire = InputValidator.snapshot!(checkout_jwt, max_bytes: 16_384)
42
+ approved = InputValidator.snapshot!(approved_checkout_jwt, max_bytes: 16_384)
43
+ raise Invalid unless wire == approved
44
+ epoch!(issued_at); epoch!(expires_at)
45
+ raise Invalid unless expires_at > issued_at && expires_at - issued_at <= MAX_LIFETIME
46
+ checked = CheckoutJWT.verify(jwt: wire, trusted_public_key_pem: trusted_merchant_public_key_pem,
47
+ expected_merchant_id: expected_merchant_id, profile_ref: CHECKOUT_PROFILE)
48
+ require "securerandom"
49
+ disclosure = encode([encode(SecureRandom.random_bytes(16)), "checkout_jwt", checked.jwt])
50
+ closed = {"vct" => "mandate.checkout.1", "checkout_hash" => checked.checkout_hash,
51
+ "iat" => issued_at, "exp" => expires_at, "_sd" => [hash(disclosure)]}
52
+ content = encode([encode(SecureRandom.random_bytes(16)), closed])
53
+ payload = {"delegate_payload" => [{"..." => hash(content)}], "_sd_alg" => "sha-256"}
54
+ jwt = MerchantSignature.sign!(payload, signer, public_key_pem, typ: "example+sd-jwt")
55
+ result = "#{jwt}~#{content}~#{disclosure}~"
56
+ parse!(result)
57
+ Issued.send(:new, result)
58
+ rescue StandardError, LoadError
59
+ raise Invalid.new, cause: nil
60
+ end
61
+
62
+ # All two disclosures are required for this profile. No Agent signature,
63
+ # aud, nonce, or KB-JWT is added. Restoration preserves the exact bytes.
64
+ def self.present_closed(closed_sd_jwt:)
65
+ parse!(closed_sd_jwt).fetch(:wire)
66
+ rescue StandardError, LoadError
67
+ raise Invalid.new, cause: nil
68
+ end
69
+
70
+ # Merchant supplies independently registered Provider/Merchant keys and
71
+ # the exact current order from its own database. Success is not Host ALLOW.
72
+ def self.verify(closed_sd_jwt:, trusted_provider_public_key_pem:, trusted_merchant_public_key_pem:,
73
+ expected_checkout_jwt:, expected_merchant_id:, verified_at:)
74
+ epoch!(verified_at)
75
+ parsed = parse!(closed_sd_jwt)
76
+ RootSignature.verified_payload!(parsed.fetch(:jwt), trusted_provider_public_key_pem)
77
+ closed = parsed.fetch(:closed)
78
+ raise Invalid unless closed.fetch("iat") <= verified_at && verified_at < closed.fetch("exp")
79
+ expected = InputValidator.snapshot!(expected_checkout_jwt, max_bytes: 16_384)
80
+ raise Invalid unless closed.fetch("checkout_jwt") == expected
81
+ checked = CheckoutJWT.verify(jwt: expected, trusted_public_key_pem: trusted_merchant_public_key_pem,
82
+ expected_merchant_id: expected_merchant_id, profile_ref: CHECKOUT_PROFILE)
83
+ Verification.send(:new, :direct_checkout_verified, parsed.merge(checkout: checked.checkout))
84
+ rescue StandardError, LoadError
85
+ Verification.send(:new, :direct_checkout_verification_failed)
86
+ end
87
+
88
+ # Exact bounded grammar, not a general selective-disclosure resolver.
89
+ # Every commitment is consumed exactly once, without decoys/hidden fields.
90
+ def self.parse!(source)
91
+ RootSignature.send(:dependencies!)
92
+ wire = InputValidator.snapshot!(source, max_bytes: 32_768)
93
+ raise Invalid unless wire.ascii_only?
94
+ jwt, content, disclosure, tail, *extra = wire.split("~", -1)
95
+ raise Invalid unless tail == "" && extra.empty?
96
+ parts = jwt.split(".", -1)
97
+ raise Invalid unless parts.size == 3
98
+ header = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
99
+ CheckoutReceipt.send(:header!, header, "example+sd-jwt")
100
+ raise Invalid unless RootSignature.send(:decode!, parts[2], 64).bytesize == 64
101
+ payload = InputValidator.parse!(RootSignature.send(:decode!, parts[1], 2_048))
102
+ exact!(payload, %w[_sd_alg delegate_payload])
103
+ raise Invalid unless payload["_sd_alg"] == "sha-256"
104
+ pointer = ScopedConstraints.send(:one!, payload["delegate_payload"])
105
+ exact!(pointer, ["..."])
106
+ raise Invalid unless pointer["..."] == hash(content)
107
+ revealed = decode_disclosure!(content, 2)
108
+ closed = revealed[1]
109
+ exact!(closed, %w[_sd checkout_hash exp iat vct])
110
+ raise Invalid unless closed["vct"] == "mandate.checkout.1" && closed["_sd"] == [hash(disclosure)]
111
+ epoch!(closed["iat"]); epoch!(closed["exp"])
112
+ raise Invalid unless closed["exp"] > closed["iat"] && closed["exp"] - closed["iat"] <= MAX_LIFETIME
113
+ leaf = decode_disclosure!(disclosure, 3)
114
+ raise Invalid unless leaf[1] == "checkout_jwt"
115
+ checkout = InputValidator.snapshot!(leaf[2], max_bytes: 16_384)
116
+ raise Invalid unless closed["checkout_hash"] == hash(checkout)
117
+ # Parse supported merchant syntax too, without claiming its authenticity.
118
+ checkout_parts = checkout.split(".", -1)
119
+ raise Invalid unless checkout_parts.size == 3
120
+ checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
121
+ CheckoutReceipt.send(:header!, checkout_header, "JWT")
122
+ raise Invalid unless RootSignature.send(:decode!, checkout_parts[2], 64).bytesize == 64
123
+ claims = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000))
124
+ CheckoutJWT.send(:validate!, claims, profile_ref: CHECKOUT_PROFILE)
125
+ {wire: wire, jwt: jwt, closed: closed.merge("checkout_jwt" => checkout)}
126
+ end
127
+ def self.decode_disclosure!(wire, size)
128
+ value = InputValidator.parse!(RootSignature.send(:decode!, wire, 24_576))
129
+ raise Invalid unless value.instance_of?(Array) && value.size == size &&
130
+ value[0].instance_of?(String) && value[0].match?(/\A[A-Za-z0-9_-]{22,128}\z/)
131
+ value
132
+ end
133
+ def self.epoch!(value) = CheckoutReceipt.send(:epoch!, value)
134
+ def self.exact!(value, fields) = PurchaseBinding.send(:exact!, value, fields)
135
+ def self.hash(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
136
+ def self.encode(value)
137
+ require "json"
138
+ Base64.urlsafe_encode64(value.instance_of?(String) ? value : JSON.generate(value), padding: false)
139
+ end
140
+ %i[issue_closed present_closed verify].each do |name|
141
+ implementation = method(name)
142
+ fields = implementation.parameters.map(&:last).freeze
143
+ define_singleton_method(name) do |**arguments|
144
+ unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
145
+ next Verification.send(:new, :direct_checkout_verification_failed) if name == :verify
146
+ raise Invalid.new, cause: nil
147
+ end
148
+ implementation.call(**arguments)
149
+ end
150
+ end
151
+ private_class_method :parse!, :decode_disclosure!, :epoch!, :exact!, :hash, :encode
152
+ end
153
+ end