ap2_mandate_verifier 0.4.0 → 0.5.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: 1e3f167538858b19e86097908f19d31235a3d6bf1f2478b13d0a3aa049ab527b
4
+ data.tar.gz: 818e4c88efa929adcc209710c6d8e042a601820589a80bf20e7115db2700f00e
5
5
  SHA512:
6
- metadata.gz: b90c9022582083189cfc9fe8edbe641c2f4a51618c60a6ad877c8ce479cd70d1fcf84bf2520d1e79565cbb4cef457dc804ce28ab972dcb9a1f05ffa9f03f8d9a
7
- data.tar.gz: 2aa4c0cbfbc879de935c15b93621fd3ac4f38990f9df414b0e322cceda844e5d226facfddb1678255908ff8cf2065b3640167fe6d619946bc729f3be8316c94b
6
+ metadata.gz: fe38d275af6ada51fbc70b2dbbf8d7d1c822d49304f839e0b9ca2b575b24ccd2e123c3b04c58862b30e90b375afe28c0c34a4376841f69f07e6c8438fc0abd1a
7
+ data.tar.gz: 9a0cf42696c264f27b62b674fe6ba1c10c5916434cc3b83b8582e15d78c103a9ea4dee976610f09bb3c84c8fe2a7b6b9c2152b17b637fd8359c0738d2f2b24b9
data/README.md CHANGED
@@ -1,6 +1,4 @@
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.4.0
4
2
 
5
3
  [日本語](README.ja.md)
6
4
 
@@ -10,24 +8,44 @@ Verify purchase-delegation data in Ruby using a deliberately fixed AP2 profile.
10
8
 
11
9
  ## Try the local demo
12
10
 
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.
11
+ The [Rails demo](https://github.com/cuichangquan/ap2-mandate-verifier-demo#readme) uses published 0.4.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. It is local-only; it does not issue real challenges, consume nonces or execute purchases.
14
12
 
15
13
  ## Install
16
14
 
17
15
  Formal support is **MRI 3.4.12 and MRI 4.0.9**. In your chosen Gem environment:
18
16
 
19
17
  ```sh
20
- gem install ap2_mandate_verifier --version 0.3.0
18
+ gem install ap2_mandate_verifier --version 0.4.0
21
19
  ```
22
20
 
23
21
  Or add to your Gemfile:
24
22
 
25
23
  ```ruby
26
- gem "ap2_mandate_verifier", "= 0.3.0"
24
+ gem "ap2_mandate_verifier", "= 0.4.0"
27
25
  ```
28
26
 
29
27
  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
28
 
29
+ ## Merchant signing and Receipt (unpublished 0.5.0 candidate)
30
+
31
+ Create a signed checkout, then sign the application's explicit outcome. These
32
+ additive APIs are available from the candidate source, not published 0.4.0:
33
+
34
+ ```ruby
35
+ signing = AP2MandateVerifier::CheckoutJWT
36
+ signed = signing.sign(checkout: checkout, signer: signing.es256_signer(private_key: key),
37
+ public_key_pem: key.public_to_pem)
38
+ # Retain signed.jwt unchanged; use it as InputBuilder's host_checkout_jws.
39
+ receipt = AP2MandateVerifier::CheckoutReceipt.sign(closed_sd_jwt: received_closed_sd_jwt,
40
+ issuer: "shop", outcome: "Error", error: "declined", error_description: "Application declined",
41
+ issued_at: now, signer: signing.es256_signer(private_key: key), public_key_pem: key.public_to_pem)
42
+ ```
43
+
44
+ Receipt verification separately checks a trusted public key, expected issuer,
45
+ explicit time window and original closed-Mandate reference. An authentic Error
46
+ Receipt has `verified? == true` and `purchase_succeeded? == false`.
47
+ See the [complete API example, supported wire shape and SDK differences](docs/MERCHANT_SIGNING.md).
48
+
31
49
  ## A small InputBuilder example
32
50
 
33
51
  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,6 +102,16 @@ Do not call `prepare` again during verification or update saved hashes/reference
84
102
  | `:rejected`, `rejected? == true` | No Evidence. Stop and inspect `result.code`. |
85
103
  | `:unavailable`, `unavailable? == true` | No Evidence. Stop; a dependency or processing failure is not proof of invalid business data. |
86
104
 
105
+ On failure, inspect supplemental check candidates. Successful results have no failure diagnostic.
106
+
107
+ ```ruby
108
+ if (diagnostic = result.diagnostic)
109
+ puts diagnostic.to_h(locale: :en) # :ja for Japanese
110
+ end
111
+ ```
112
+
113
+ `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).
114
+
87
115
  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
116
 
89
117
  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.
@@ -94,7 +122,7 @@ Supported scope is the fixed `ap2.checkout.single_merchant_sku` profile v1: ES25
94
122
 
95
123
  | Entry | Role |
96
124
  | --- | --- |
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. |
125
+ | `InputBuilder.verify(**business_information)` | Recommended business-data path in 0.4.0. Assembles inputs and runs complete verification; preparation and restoration are separate steps shown above. |
98
126
  | `verify_checkout(**inputs)` | Direct complete verification with the existing seven inputs, including caller-supplied trust/selection/Host JSON. |
99
127
  | `verify_research(**inputs)` | Retained name for the same seven-input verification pipeline; no deprecation warning. |
100
128
  | `verify(presentation_json:)` | Legacy JSON syntax check only. Never returns successful Evidence. |
@@ -105,7 +133,7 @@ Malformed assembly arguments, including missing keywords, to `InputBuilder.verif
105
133
 
106
134
  - [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
135
  - [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.
136
+ - [Published 0.4.0 release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.4.0), [publication/withdrawal records](docs/PROJECT_STATUS.md) and [changelog](CHANGELOG.md). Repository README changes do not rebuild or replace published Gem bytes.
109
137
  - [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
138
  - [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
139
 
@@ -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,149 @@
1
+ # Merchant Checkout signing (unpublished candidate)
2
+
3
+ ## Scope and responsibility
4
+
5
+ This additive API starts from the existing single Merchant / single SKU Checkout
6
+ profile, ES256 with a P-256 key. It leaves `Verifier`, `Result`, `Evidence`,
7
+ `InputBuilder` and diagnostics unchanged. A merchant signature attests to the
8
+ merchant-authored order bytes; it does not create user authorization, establish
9
+ merchant enrollment, persist an order, consume a nonce or make a payment.
10
+
11
+ The adopted AP2 source remains
12
+ [`b4587ac1d055888a73b4b21750973cffba961793`](https://github.com/google-agentic-commerce/AP2/tree/b4587ac1d055888a73b4b21750973cffba961793).
13
+ Checkout-specific ordering is defined by the existing local fixed profile, not
14
+ all UCP shapes. Unsupported fields, multiple items, nonempty links and unsupported
15
+ currencies are rejected. Amounts are integer minor units; totals must agree.
16
+
17
+ ## Minimal executable example
18
+
19
+ Run from this repository with the documented runtime and dependencies:
20
+
21
+ ```ruby
22
+ require "ap2_mandate_verifier"
23
+ require "openssl"
24
+
25
+ key = OpenSSL::PKey::EC.generate("prime256v1") # Test only; app owns real keys.
26
+ totals = [{"type" => "subtotal", "amount" => 100}, {"type" => "total", "amount" => 100}]
27
+ checkout = {
28
+ "id" => "order-1", "merchant" => {"id" => "shop", "name" => "Demo shop"},
29
+ "status" => "ready_for_complete", "currency" => "USD", "links" => [],
30
+ "line_items" => [{"id" => "line-1", "item" => {"id" => "sku", "title" => "Sample", "price" => 100},
31
+ "quantity" => 1, "totals" => totals}], "totals" => totals
32
+ }
33
+ signing = AP2MandateVerifier::CheckoutJWT
34
+ signed = signing.sign(checkout: checkout, signer: signing.es256_signer(private_key: key),
35
+ public_key_pem: key.public_to_pem)
36
+ puts signed.jwt.split(".").length # 3
37
+ puts signed.checkout_hash.length # 43
38
+ ```
39
+
40
+ `signed.jwt` is the frozen original compact JWT to transmit and retain. Supply
41
+ that exact String as `host_checkout_jws` to InputBuilder and Verifier; supply
42
+ `signed.checkout_hash` when a test or external Agent binds a Closed Mandate.
43
+ The Gem does not issue a product Mandate API. Re-encoding claims or signing again
44
+ creates different original wire, even when the order is the same.
45
+
46
+ `signer.call(signing_input)` receives the frozen ASCII `header.payload` and returns
47
+ 64 binary bytes containing the JOSE ES256 `r || s` signature. An HSM/remote
48
+ adapter must implement this interface and handle its own authorization, timeouts
49
+ and availability. The Gem itself performs no network operation. The selected
50
+ independent canonical public SPKI PEM verifies the final signature before a
51
+ `Signed` object is returned. The token cannot choose its own verification key.
52
+ `es256_signer` is a convenience closure over an application-owned OpenSSL P-256
53
+ private key; it never serializes the private key.
54
+
55
+ Invalid orders, wrong keys, unsupported keys, failed signer calls and invalid
56
+ signer output raise `CheckoutJWT::Invalid` with a fixed message and no original
57
+ cause. They never return a signed result. All application key lifecycle and trust
58
+ registration remain outside the Gem.
59
+
60
+ ## Checkout Receipt contract and specification discrepancy
61
+
62
+ Checkout-specific Schema uses `status: Success/Error`, `iss`, `iat`, `reference`;
63
+ Success requires `order_id`; Error requires `error` and `error_description`.
64
+ The generic authorization prose instead describes `result: success/error`.
65
+ Checkout schema and generated model do not strictly forbid fields from the other
66
+ branch; a stricter local profile must be documented as such.
67
+
68
+ Normative authorization/dispute text requires the final closed SD-JWT hash in
69
+ the same manner as `sd_hash`. Fixed SDK `sdjwt/common.py` includes the terminal
70
+ `~` even without disclosures. `MandateClient.get_closed_mandate_jwt` instead
71
+ extracts only compact JWT, discarding disclosures and `~`, and recommends hashing
72
+ that. These are distinct hashes even in the existing inline terminal profile.
73
+ The adopted contract prioritizes normative `sd_hash`: explicit original
74
+ closed SD-JWT input `<terminal_jws>~`, default SHA256/base64url without padding.
75
+ This is the existing inline terminal profile serialized as its final SD-JWT.
76
+ The caller must supply this exact representation; compact-only input is rejected.
77
+ The Gem never adds a missing `~`, extracts a leaf from a chain, or guesses a
78
+ reference from unparseable input. Disclosures, extra hops, `_sd_alg` extensions
79
+ and unsupported terminal claims are rejected. Bounded `kid` is accepted exactly
80
+ as in the existing verifier but never selects a trusted key. The entire input,
81
+ including `kid` bytes and terminal `~`, contributes to the hash.
82
+
83
+ The generic `result` spelling is not accepted. Success permits only `order_id`,
84
+ and Error permits only `error` and `error_description` alongside common fields.
85
+ This branch exclusivity, nonempty bounded strings and rejection of unknown
86
+ fields are explicit local-profile constraints, stronger than the base Schema.
87
+ `iat` is an integer epoch. `not_before <= iat <= verified_at <= not_after` is an
88
+ explicit application verification window, not an upstream freshness guarantee.
89
+ The application owns trusted key enrollment, expected issuer and time policy.
90
+
91
+ ```ruby
92
+ receipt = AP2MandateVerifier::CheckoutReceipt
93
+ # closed_sd_jwt is the exact received final `<terminal_jws>~` String.
94
+ rejection = receipt.sign(closed_sd_jwt: closed_sd_jwt, issuer: "shop",
95
+ outcome: "Error", error: "declined", error_description: "Application declined",
96
+ issued_at: now, signer: signing.es256_signer(private_key: key),
97
+ public_key_pem: key.public_to_pem)
98
+ checked = receipt.verify(jwt: rejection.jwt, closed_sd_jwt: closed_sd_jwt,
99
+ trusted_public_key_pem: independently_registered_public_pem, expected_issuer: "shop",
100
+ not_before: now - 60, not_after: now + 60, verified_at: now)
101
+ p [checked.verified?, checked.purchase_succeeded?, checked.purchase_rejected?]
102
+ # => [true, false, true]
103
+ ```
104
+
105
+ A Success call replaces Error fields with `outcome: "Success", order_id: "order-1"`.
106
+ `Signed#jwt` is the immutable transmitted receipt wire and `Signed#reference` its
107
+ Mandate reference. Invalid creation raises `CheckoutReceipt::Invalid` without
108
+ input values or original cause. Verification returns an immutable
109
+ `CheckoutReceipt::Verification`: `verified?`, `outcome` (`Success` or `Error`),
110
+ `purchase_succeeded?`, `purchase_rejected?`, `order_id`, `error`,
111
+ `error_description`, and a `code`. Failure exposes no untrusted claim values and
112
+ returns false for all three predicates. It never returns existing Verifier
113
+ `Result`/`Evidence` or modifies their status/code meanings.
114
+
115
+ Reference calculation validates supported syntax and preserves byte identity;
116
+ it does not verify the Mandate's authority. Receipt authenticity does not verify
117
+ Mandate authorization or evidence of payment/order execution. Obtain authorization
118
+ through the existing complete verifier plus Host responsibilities separately.
119
+ The application must explicitly provide its final business outcome; no Verifier
120
+ success is automatically converted into a Success Receipt.
121
+
122
+ ## Current verification
123
+
124
+ Dedicated offline Docker checks exercise original-wire hashing, signer failures,
125
+ wrong keys, unsupported input and complete existing Verifier/InputBuilder
126
+ integration. `test/merchant_interop.py` uses the fixed official Python SDK's
127
+ `create_jwt` and `verify_jwt`, compares decoded checkout claims and independently
128
+ computes the original JWT SHA256; reverse-direction wrong-key verification must
129
+ reject. Synthetic private keys stay in process memory. The scripts do not imply
130
+ real issuer provenance or universal AP2 conformance.
131
+
132
+ The fixed SDK `ReceiptClient.verify_receipt` checks signature/model/callback but
133
+ not expected issuer or application time policy. Our interoperability test compares
134
+ these separately on the Ruby side and verifies every callback argument against
135
+ the independently computed expected reference; a JWT-only hash must fail.
136
+ The SDK annotation says cryptography public key, but `jwt_helper.verify_jwt` uses
137
+ jwcrypto; the test supplies a public `JWK` adapter without skipping verification.
138
+ Success creation uses SDK ReceiptClient with a deterministic test clock; Error
139
+ uses the generated CheckoutReceipt model and official signing helper. SDK model
140
+ validation is also checked against original JSON Schema. No unconditional
141
+ success callback or reference-validation bypass is used.
142
+
143
+ The pinned Receipt Schema references `types/receipt_status.json`, while the
144
+ referenced file declares `$id` `.../schemas/receipt-status.json`. The local
145
+ Schema registry explicitly registers the reference URI as an alias for the
146
+ unaltered pinned file, plus declared IDs; it performs no network fallback.
147
+ This reference-resolution adjustment is recorded by the test output and does
148
+ not rewrite Schema conditions or skip validation. Checkout and Closed Mandate
149
+ payloads are also validated with the unaltered original JSON Schemas.
@@ -1,6 +1,11 @@
1
- # Fixed-profile AP2 verification — published 0.3.0 / historical releases
1
+ # Fixed-profile AP2 verification — published 0.4.0 / historical releases
2
+
3
+ Unpublished **0.5.0 candidate** 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.
4
+
5
+ Published 0.4.0 adds supplemental safe diagnostics; see [API and troubleshooting](DIAGNOSTICS.md). Existing verdict/Evidence contracts remain unchanged.
6
+
7
+ [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
8
 
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
9
 
5
10
  ## Published 0.3.0 input assistance
6
11
 
@@ -0,0 +1,81 @@
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:)
24
+ RootSignature.send(:dependencies!)
25
+ value = InputBuilder.send(:copy!, checkout)
26
+ validate!(value)
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)
48
+ c = ScopedConstraints
49
+ c.send(:exact!, checkout, %w[currency id line_items links merchant status totals])
50
+ c.send(:text!, checkout["id"])
51
+ raise Invalid unless checkout["status"] == "ready_for_complete" &&
52
+ c::CURRENCIES.include?(checkout["currency"]) && checkout["links"] == []
53
+ c.send(:exact!, checkout["merchant"], %w[id name])
54
+ c.send(:text!, checkout["merchant"]["id"])
55
+ c.send(:text!, checkout["merchant"]["name"], 512)
56
+ line = c.send(:one!, checkout["line_items"])
57
+ c.send(:exact!, line, %w[id item quantity totals])
58
+ c.send(:text!, line["id"])
59
+ c.send(:quantity!, line["quantity"])
60
+ item = line["item"]
61
+ c.send(:exact!, item, %w[id price title])
62
+ c.send(:text!, item["id"])
63
+ c.send(:text!, item["title"], 512)
64
+ c.send(:amount!, item["price"])
65
+ total = item["price"] * line["quantity"]
66
+ c.send(:amount!, total)
67
+ c.send(:totals!, line["totals"], total)
68
+ c.send(:totals!, checkout["totals"], total)
69
+ nil
70
+ end
71
+ %i[sign es256_signer].each do |name|
72
+ implementation = method(name)
73
+ fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
74
+ define_singleton_method(name) do |**arguments|
75
+ raise Invalid.new, cause: nil unless (fields - arguments.keys).empty? && (arguments.keys - fields).empty?
76
+ implementation.call(**arguments)
77
+ end
78
+ end
79
+ private_class_method :validate!
80
+ end
81
+ end
@@ -0,0 +1,143 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Checkout-specific pinned Schema; independent of Verifier Result/Evidence.
5
+ module CheckoutReceipt
6
+ class Invalid < ArgumentError
7
+ def initialize = super("invalid checkout receipt information")
8
+ end
9
+ class Signed
10
+ attr_reader :jwt, :reference
11
+ def initialize(jwt, reference)
12
+ @jwt, @reference = jwt.freeze, reference.freeze
13
+ freeze
14
+ end
15
+ private_class_method :new
16
+ end
17
+ class Verification
18
+ attr_reader :code, :outcome, :order_id, :error, :error_description
19
+ def initialize(code, claims = nil)
20
+ @code = code
21
+ if claims
22
+ @outcome = claims.fetch("status").freeze
23
+ @order_id, @error, @error_description = claims.values_at("order_id", "error", "error_description").map { |v| v&.freeze }
24
+ end
25
+ freeze
26
+ end
27
+ def verified? = code == :receipt_verified
28
+ def purchase_succeeded? = verified? && outcome == "Success"
29
+ def purchase_rejected? = verified? && outcome == "Error"
30
+ private_class_method :new
31
+ end
32
+
33
+ # Exact received final closed SD-JWT, no disclosures or additional hop.
34
+ # A terminal compact JWS alone is intentionally not accepted or repaired.
35
+ def self.reference(closed_sd_jwt:)
36
+ wire = InputValidator.snapshot!(closed_sd_jwt, max_bytes: 32_769)
37
+ raise Invalid unless wire.ascii_only? && wire.end_with?("~") && wire.count("~") == 1
38
+ compact = wire.byteslice(0, wire.bytesize - 1)
39
+ parts = compact.split(".", -1)
40
+ raise Invalid unless parts.size == 3
41
+ RootSignature.send(:dependencies!)
42
+ header = InputValidator.parse!(RootSignature.send(:decode!, parts[0], 2_048))
43
+ claims = InputValidator.parse!(RootSignature.send(:decode!, parts[1], 24_576))
44
+ signature = RootSignature.send(:decode!, parts[2], 64)
45
+ header!(header, "kb+sd-jwt")
46
+ raise Invalid unless signature.bytesize == 64
47
+ # Existing inline terminal grammar only, never general SD resolution.
48
+ PurchaseBinding.send(:exact!, claims, %w[aud delegate_payload iat nonce sd_hash])
49
+ %w[aud nonce sd_hash].each { |field| text!(claims[field], 512) }
50
+ epoch!(claims["iat"])
51
+ raise Invalid unless claims["sd_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
52
+ closed = ScopedConstraints.send(:one!, claims["delegate_payload"])
53
+ PurchaseBinding.send(:exact!, closed, %w[checkout_hash checkout_jwt exp iat vct])
54
+ raise Invalid unless closed["vct"] == "mandate.checkout.1"
55
+ epoch!(closed["iat"]); epoch!(closed["exp"])
56
+ raise Invalid unless closed["exp"] > closed["iat"] && closed["checkout_hash"].instance_of?(String) &&
57
+ closed["checkout_hash"].match?(/\A[A-Za-z0-9_-]{43}\z/)
58
+ checkout = InputValidator.snapshot!(closed["checkout_jwt"], max_bytes: 16_384)
59
+ raise Invalid unless checkout.ascii_only? && checkout.split(".", -1).size == 3 &&
60
+ checkout.split(".", -1).all? { |part| part.match?(/\A[A-Za-z0-9_-]+\z/) }
61
+ checkout_parts = checkout.split(".", -1)
62
+ checkout_header = InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[0], 2_048))
63
+ header!(checkout_header, "JWT")
64
+ raise Invalid unless RootSignature.send(:decode!, checkout_parts[2], 64).bytesize == 64
65
+ CheckoutJWT.send(:validate!, InputValidator.parse!(RootSignature.send(:decode!, checkout_parts[1], 12_000)))
66
+ raise Invalid unless closed["checkout_hash"] == hash(checkout)
67
+ hash(wire).freeze
68
+ rescue StandardError, LoadError
69
+ raise Invalid.new, cause: nil
70
+ end
71
+
72
+ def self.sign(closed_sd_jwt:, issuer:, outcome:, issued_at:, signer:, public_key_pem:, order_id: nil, error: nil, error_description: nil)
73
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
74
+ claims = {"iss" => issuer, "status" => outcome, "iat" => issued_at, "reference" => ref}
75
+ claims["order_id"] = order_id unless order_id.nil?
76
+ claims["error"] = error unless error.nil?
77
+ claims["error_description"] = error_description unless error_description.nil?
78
+ claims = InputBuilder.send(:copy!, claims)
79
+ validate!(claims)
80
+ jwt = MerchantSignature.sign!(claims, signer, public_key_pem)
81
+ Signed.send(:new, jwt, ref)
82
+ rescue StandardError, LoadError
83
+ raise Invalid.new, cause: nil
84
+ end
85
+
86
+ # The Host supplies trusted enrollment key, expected signer and explicit time
87
+ # window independently. JWT iss/kid are never used to choose trust.
88
+ # Reference authenticates byte identity, not Mandate authorization/validity.
89
+ def self.verify(jwt:, closed_sd_jwt:, trusted_public_key_pem:, expected_issuer:, not_before:, not_after:, verified_at:)
90
+ expected = InputValidator.snapshot!(expected_issuer, max_bytes: 512)
91
+ text!(expected, 512)
92
+ [not_before, not_after, verified_at].each { |t| epoch!(t) }
93
+ raise Invalid unless not_before <= verified_at && verified_at <= not_after
94
+ ref = reference(closed_sd_jwt: closed_sd_jwt)
95
+ claims = RootSignature.verified_payload!(jwt, trusted_public_key_pem, expected_typ: "JWT", max_bytes: 16_384)
96
+ validate!(claims)
97
+ return Verification.send(:new, :receipt_issuer_mismatch) unless claims["iss"] == expected
98
+ return Verification.send(:new, :receipt_reference_mismatch) unless claims["reference"] == ref
99
+ return Verification.send(:new, :receipt_time_mismatch) unless claims["iat"].between?(not_before, verified_at)
100
+ Verification.send(:new, :receipt_verified, claims)
101
+ rescue StandardError, LoadError
102
+ Verification.send(:new, :receipt_verification_failed)
103
+ end
104
+
105
+ def self.validate!(claims)
106
+ raise Invalid unless claims.instance_of?(Hash)
107
+ fields = case claims["status"]
108
+ when "Success" then %w[iss status iat reference order_id]
109
+ when "Error" then %w[iss status iat reference error error_description]
110
+ else raise Invalid
111
+ end
112
+ raise Invalid unless claims.keys.sort == fields.sort
113
+ epoch!(claims["iat"])
114
+ (fields - %w[iat]).each { |field| text!(claims[field], field == "error_description" ? 2_048 : 512) }
115
+ raise Invalid unless claims["reference"].match?(/\A[A-Za-z0-9_-]{43}\z/)
116
+ end
117
+ def self.text!(value, max)
118
+ raise Invalid unless value.instance_of?(String) && value.bytesize.between?(1, max)
119
+ end
120
+ def self.epoch!(value)
121
+ raise Invalid unless Object.instance_method(:instance_of?).bind_call(value, Integer) && value.between?(0, PurchaseBinding::MAX_EPOCH)
122
+ end
123
+ def self.header!(header, typ)
124
+ raise Invalid unless header.instance_of?(Hash) && (header.keys - %w[alg typ kid]).empty? &&
125
+ header["alg"] == "ES256" && header["typ"] == typ
126
+ text!(header["kid"], 128) if header.key?("kid")
127
+ end
128
+ def self.hash(wire) = Base64.urlsafe_encode64(Digest::SHA256.digest(wire), padding: false)
129
+ %i[reference sign verify].each do |name|
130
+ implementation = method(name)
131
+ required = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
132
+ fields = implementation.parameters.filter_map { |kind, field| field if %i[key keyreq].include?(kind) }.freeze
133
+ define_singleton_method(name) do |**arguments|
134
+ unless (required - arguments.keys).empty? && (arguments.keys - fields).empty?
135
+ next Verification.send(:new, :receipt_verification_failed) if name == :verify
136
+ raise Invalid.new, cause: nil
137
+ end
138
+ implementation.call(**arguments)
139
+ end
140
+ end
141
+ private_class_method :validate!, :text!, :epoch!, :header!, :hash
142
+ end
143
+ end
@@ -0,0 +1,22 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Internal ES256 primitive. Callers must validate the payload's own profile.
5
+ module MerchantSignature
6
+ def self.sign!(claims, signer, public_key_pem)
7
+ RootSignature.send(:dependencies!)
8
+ payload = InputBuilder.send(:json!, claims, 12_000)
9
+ pem = InputValidator.snapshot!(public_key_pem, max_bytes: 1_024)
10
+ RootSignature.public_jwk!(pem)
11
+ header = Base64.urlsafe_encode64('{"alg":"ES256","typ":"JWT"}', padding: false)
12
+ input = "#{header}.#{Base64.urlsafe_encode64(payload, padding: false)}".freeze
13
+ raw = signer.call(input)
14
+ raise ArgumentError unless Object.instance_method(:instance_of?).bind_call(raw, String) &&
15
+ String.instance_method(:bytesize).bind_call(raw) == 64
16
+ signature = String.instance_method(:byteslice).bind_call(raw, 0, 64)
17
+ jwt = "#{input}.#{Base64.urlsafe_encode64(signature, padding: false)}"
18
+ raise ArgumentError unless RootSignature.verified_payload!(jwt, pem, expected_typ: "JWT", max_bytes: 16_384) == claims
19
+ jwt.freeze
20
+ end
21
+ end
22
+ end
@@ -10,6 +10,9 @@ require_relative "ap2_mandate_verifier/trust_context"
10
10
  require_relative "ap2_mandate_verifier/host_binding"
11
11
  require_relative "ap2_mandate_verifier/research_result"
12
12
  require_relative "ap2_mandate_verifier/input_builder"
13
+ require_relative "ap2_mandate_verifier/merchant_signature"
14
+ require_relative "ap2_mandate_verifier/checkout_jwt"
15
+ require_relative "ap2_mandate_verifier/checkout_receipt"
13
16
 
14
17
  module AP2MandateVerifier
15
18
  # Accepts original JSON bytes only. Syntax validity is not AP2 validity,
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: ap2_mandate_verifier
3
3
  version: !ruby/object:Gem::Version
4
- version: 0.4.0
4
+ version: 0.5.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
@@ -91,12 +91,16 @@ files:
91
91
  - README.md
92
92
  - docs/DIAGNOSTICS.ja.md
93
93
  - docs/DIAGNOSTICS.md
94
+ - docs/MERCHANT_SIGNING.md
94
95
  - docs/SUPPORT_CONTRACT.md
95
96
  - lib/ap2_mandate_verifier.rb
97
+ - lib/ap2_mandate_verifier/checkout_jwt.rb
98
+ - lib/ap2_mandate_verifier/checkout_receipt.rb
96
99
  - lib/ap2_mandate_verifier/diagnostic.rb
97
100
  - lib/ap2_mandate_verifier/host_binding.rb
98
101
  - lib/ap2_mandate_verifier/input_builder.rb
99
102
  - lib/ap2_mandate_verifier/input_validator.rb
103
+ - lib/ap2_mandate_verifier/merchant_signature.rb
100
104
  - lib/ap2_mandate_verifier/purchase_binding.rb
101
105
  - lib/ap2_mandate_verifier/research_result.rb
102
106
  - lib/ap2_mandate_verifier/result.rb
@@ -125,7 +129,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
125
129
  - !ruby/object:Gem::Version
126
130
  version: '0'
127
131
  requirements: []
128
- rubygems_version: 4.0.20
132
+ rubygems_version: 3.6.9
129
133
  specification_version: 4
130
134
  summary: Fixed-profile AP2 verification for Ruby
131
135
  test_files: []