ap2_mandate_verifier 0.3.0 → 0.4.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: 1367482ba612018a83790debee921f546003a7eabc0b43341602d9e3c1d4f9a6
4
- data.tar.gz: 92d43d757d99b941a8724a4e4f4a9bbe450ae1b5f297cb5b6ec86c0007c915ba
3
+ metadata.gz: d2630c74f49f2d59ee5895eb439c229c9269b202129e6574a3f2d627e302c565
4
+ data.tar.gz: 67055aafefb47cf5fe76cd3e5e78711de31496f715abe5e7fadf5e7f1fe293e2
5
5
  SHA512:
6
- metadata.gz: 444098518c421863e6a4ffaf41c33312f6634d88ddad3ad11402613bf068cbfbf0740351de43a4a5d1a8571c3d0b349d7e4697d3afa5c297fb1c08427683f8c8
7
- data.tar.gz: 5bd155bc56710aea9a84a70d0c0c7342fa26b0d0523694691b06e727a16977dd42d5257f08f8f2dc71d27a231409fa5bc11dd0d8770282d91797b16a56dc7987
6
+ metadata.gz: b90c9022582083189cfc9fe8edbe641c2f4a51618c60a6ad877c8ce479cd70d1fcf84bf2520d1e79565cbb4cef457dc804ce28ab972dcb9a1f05ffa9f03f8d9a
7
+ data.tar.gz: 2aa4c0cbfbc879de935c15b93621fd3ac4f38990f9df414b0e322cceda844e5d226facfddb1678255908ff8cf2065b3640167fe6d619946bc729f3be8316c94b
data/README.md CHANGED
@@ -1,225 +1,112 @@
1
- # AP2 Mandate Verifier — 0.3.0 candidate
1
+ # AP2 Mandate Verifier — 0.3.0
2
2
 
3
- The unpublished 0.3.0 candidate adds `InputBuilder`: map authenticated business records once, prepare and persist a challenge, then supply independent current state to the complete verifier. No hand-written trust/selection/Host JSON or hashes are needed. Start with the [runnable business-data example and Rails mapping](docs/INPUT_BUILDER.md). Existing seven-input APIs remain supported. Published installation below remains 0.2.1 until release approval.
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.
4
4
 
5
- [Japanese / 日本語](README.ja.md)
5
+ [日本語](README.ja.md)
6
6
 
7
- A Rails-independent Ruby Gem for a deliberately fixed AP2 verification profile. **A valid signature alone never authorizes a purchase.** Successful checks produce immutable Evidence; the Host makes the final business decision.
7
+ 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
8
 
9
- ## Start with the local demo
9
+ `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
10
 
11
- The [AP2 Mandate Verifier Demo](https://github.com/cuichangquan/ap2-mandate-verifier-demo) calls the real verifier on synthetic valid, tampered and expired examples, with Docker local-startup instructions; it is not a hosted demo site, production payments or Host authorization.
11
+ ## Try the local demo
12
12
 
13
- For a Japanese walkthrough of the three demo scenarios, see the [Zenn article](https://zenn.dev/ccq/articles/7f9643f96fe5c7).
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.
14
14
 
15
- ## Choose your starting point
15
+ ## Install
16
16
 
17
- | Route | Start here |
18
- | --- | --- |
19
- | Docker demo: compare three synthetic cases | Follow the [demo README](https://github.com/cuichangquan/ap2-mandate-verifier-demo#readme) for local startup and valid / tampered / expired examples. Docker commands are maintained there. |
20
- | Ruby without the demo: MRI 3.4.12 or 4.0.9 | Follow [installation](#distribution-and-installation), then the [saved synthetic example](#try-the-saved-synthetic-example) below. |
21
-
22
- Both routes use the fixed-profile verifier, not payment execution or Host authorization. See the [supported contract](#supported-contract) for the scope. The goal is to make the choices understandable in about five minutes, not to promise a five-minute installation or build.
23
-
24
- ## Distribution and installation
25
-
26
- [0.2.1 is published on RubyGems](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.2.1). This is the fixed-profile, verifier-only stable release; the research prerelease pre3 is a separate artifact.
27
-
28
- Use an MRI 3.4.12 or MRI 4.0.9 environment and your chosen Gem isolation. Normal installation may fetch dependencies and build JSON native extensions. Stop on conflicts or unknown providers rather than relaxing pins.
17
+ Formal support is **MRI 3.4.12 and MRI 4.0.9**. In your chosen Gem environment:
29
18
 
30
19
  ```sh
31
- ruby --version # MRI 3.4.12 or MRI 4.0.9
32
- gem install ap2_mandate_verifier --version 0.2.1
33
- ```
34
-
35
- Bundler Gemfile:
36
-
37
- ```ruby
38
- gem "ap2_mandate_verifier", "= 0.2.1"
20
+ gem install ap2_mandate_verifier --version 0.3.0
39
21
  ```
40
22
 
41
- Fixed runtime dependencies: JSON 2.19.9, JWT 3.3.0, base64 0.3.0, OpenSSL gem 4.0.2 and Digest 3.2.1.
42
- Bundler 4.0.20 is the observed resolver baseline, not a runtime dependency. Gem version constraints alone do not enforce the MRI engine, OS or native-provider provenance.
43
-
44
- ## Ruby 3.4.12 compatibility and published artifact
45
-
46
- 0.2.1 formally supports exactly MRI 3.4.12 and MRI 4.0.9 with the same five fixed dependencies. Its installation metadata permits Ruby `>= 3.4.12, < 4.1`; that interval does not declare every intermediate version or another engine supported.
47
-
48
- Both versions were measured on Debian 12/arm64 with official Ruby bookworm images: 885 source regressions, 190 additional checkout cases and 7 metadata cases passed per Ruby. The same final Gem passed ordinary installation, all 13 payload-file comparisons, 10 normally loaded product files and 118 installed cases on each version. Exact providers and evidence are in the [compatibility record](docs/RUBY_3_4_12_COMPATIBILITY.md). Historical macOS/Ubuntu observations are separate and do not establish 0.2.1 compatibility there.
49
-
50
- Published 2026-10-30 11:51:55.894 UTC; verified 11:53:55 UTC. Official RubyGems metadata, distribution bytes and the retained final Gem matched: **34,816 bytes**, SHA256 `a4ab7e0f6c9bd87355695369374f8e6e2dad104fb673700e9f616053afe6e114`, source `5a02bc3a192e16aa3628cf7899617623b0aed78c`. Owner `cuichangquan`, platform `ruby`, non-prerelease, not yanked at verification. The [v0.2.1 GitHub Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.2.1) uses that exact source tag.
51
-
52
- The Gem's packaged README/contract retain their preparation snapshot. These repository updates do not rebuild or replace the published bytes. GitHub source archives differ from the RubyGems Gem. Seven inputs, fixed profile, Fail Closed, Result/Evidence v2 and existing API meanings remain unchanged; publication does not establish Host production GO.
53
-
54
- ## Verification APIs: 0.2.1 and compatibility
55
-
56
- **The installation commands and saved example use published 0.2.1 and its recommended `verify_checkout` entry.** Existing 0.1.0 applications can continue using `verify_research`; it remains available in 0.2.1 without a deprecation warning. Installing 0.1.0 does not provide `verify_checkout`.
57
-
58
- | Entry | Availability and contract |
59
- | --- | --- |
60
- | `verify_checkout(**inputs)` | Recommended full-verification entry since 0.2.0, retained in 0.2.1. Delegates directly to `ResearchResult.verify` without changing inputs or the verification pipeline. |
61
- | `verify_research(**inputs)` | Full-verification entry in published 0.1.0; retained unchanged in v0.2.1, without a deprecation warning. |
62
- | `verify(presentation_json:)` | Existing JSON syntax check only. Valid JSON returns `:unverified` / `:verification_not_implemented`, never successful Evidence. It is not a substitute for full verification. |
63
-
64
- The recommended entry takes all seven inputs. In the saved example below, these values come from `full`; real integrations must supply the authenticated Host inputs described below:
23
+ Or add to your Gemfile:
65
24
 
66
25
  ```ruby
67
- result = AP2MandateVerifier.verify_checkout(
68
- trust_json: full.fetch("trust_json"),
69
- selection_json: full.fetch("selection_json"),
70
- host_json: full.fetch("host_json"),
71
- root_presentation: full.fetch("root_presentation"),
72
- terminal_jws: full.fetch("terminal_jws"),
73
- host_checkout_jws: full.fetch("host_checkout_jws"),
74
- verified_at: full.fetch("verified_at")
75
- )
26
+ gem "ap2_mandate_verifier", "= 0.3.0"
76
27
  ```
77
28
 
78
- Both full-verification entries require all seven inputs listed under [responsibility boundaries](#real-inputs-and-responsibility-boundaries): six original Strings and externally supplied integer Unix seconds. Seven inputs and seven supported shapes are different concepts. Neither entry broadens the fixed profile below or supplies missing trust, Host state or time. Missing or unknown keywords return `:unavailable` / `:research_verification_unavailable`, with `success? == false` and `evidence == nil`; positional arguments or invalid keyword expansion can raise before verification begins.
79
-
80
- The [result handling](#understanding-the-result) is unchanged: success remains `ResearchResult` with `:verified_research` / `:scoped_research_verified` and immutable Evidence v2; rejected and unavailable results have no Evidence. Evidence is checked facts, **not purchase authorization**. Exceptions or missing results must also stop the caller. See the [API migration plan](docs/V0_2_0_API_PLAN.md) for design history; its earlier implementation gates do not describe the published 0.1.0 artifact or replace this availability distinction.
81
-
82
- ## Supported contract
83
-
84
- - AP2 pinned source `b4587ac1d055888a73b4b21750973cffba961793`, registered profile `ap2.checkout.single_merchant_sku` v1: exact body/hash and seven supported shapes.
85
-
86
- - ES256/P256, Open1→Closed1, three fixed disclosure positions, one Merchant/SKU/line, USD/EUR/JPY and empty links; unknown/unsupported forms are rejected.
87
-
88
- - The Gem checks strict bounded inputs, supplied trust selection, signed Root wire and full supported closure, Agent/Merchant signatures, delegation, purchase/Host binding, types, constraints and time.
89
-
90
- - Both full-verification entries above preserve `verified_research` / `scoped_research_verified` result names and the Evidence v2 contract; a stable version does not imply generic AP2 support or Host authorization.
91
-
92
- See [SUPPORT_CONTRACT](docs/SUPPORT_CONTRACT.md) for exact required shapes, bounds and failure codes.
93
-
94
- ## Environment, compatibility and maintenance
95
-
96
- The supported MRI versions are 3.4.12 and 4.0.9 with fixed dependencies; current 0.2.1 measurements cover the exact Debian 12/arm64 configurations in the compatibility record above. Earlier MRI 4.0.9 MBA/macOS arm64 and Ubuntu 24.04/x86_64 observations retain their historical scope. Distinguish [historical release-package/provider evidence](research/stable010_release_linux_package/README.md) from the current artifact. Other OS versions, engines, architectures and arbitrary provider updates are not covered.
29
+ 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).
97
30
 
98
- Supported-input semantics and APIs do not change silently. Security-driven narrowing identifies reason, impact and migration; breaking API/required-field/profile changes are explicit. Dependency updates are not automatically compatible.
31
+ ## A small InputBuilder example
99
32
 
100
- Maintenance covers the latest patch in the initial stable series, with manual monthly/advisory/pre-release review. No old-series backport, fixed support term, response/fix deadline or 24/7 promise. See [SECURITY](SECURITY.md) and [maintenance](docs/POST_RELEASE_MAINTENANCE.md); never report private keys, real Mandates or personal data.
101
-
102
- ## Try the saved synthetic example
103
-
104
- This example reads the same public `FULL` input used by the successful installed-Gem checks. The input JSON is not packaged in the Gem. Fetch it from the pinned commit and verify its SHA256 first. It contains no private keys. Its trust/Host assertions are **synthetic test data**, not real Issuer enrollment, a current order or a live clock. `verified_at = 1800000000` is the saved scenario's fixed evaluation time.
105
-
106
- ```sh
107
- set -eu
108
- curl --fail --location --proto '=https' --proto-redir '=https' \
109
- --output AP2_RESEARCH_INPUTS.json \
110
- https://raw.githubusercontent.com/cuichangquan/ap2-mandate-verifier/f6d4f83d396b75505256dba5769a54a8f065eeea/research/stage15/results/R3/INPUTS.json
111
- printf '%s\n' '41ad845a7ea82a9c7316c9ef11fb8ee5281453afafe2b4932c7217c1936562c1 AP2_RESEARCH_INPUTS.json' | shasum -a 256 -c -
112
- # Save the Ruby example below as research_example.rb, then:
113
- ruby research_example.rb
114
- ```
33
+ 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.
115
34
 
116
35
  ```ruby
117
36
  require "ap2_mandate_verifier"
118
37
  require "json"
119
- require "digest"
120
-
121
- raw = File.binread("AP2_RESEARCH_INPUTS.json")
122
- expected = "41ad845a7ea82a9c7316c9ef11fb8ee5281453afafe2b4932c7217c1936562c1"
123
- raise "fixture checksum mismatch" unless Digest::SHA256.hexdigest(raw) == expected
124
-
125
- full = JSON.parse(raw).fetch("FULL")
126
- inputs = {
127
- trust_json: full.fetch("trust_json"),
128
- selection_json: full.fetch("selection_json"),
129
- host_json: full.fetch("host_json"),
130
- root_presentation: full.fetch("root_presentation"),
131
- terminal_jws: full.fetch("terminal_jws"),
132
- host_checkout_jws: full.fetch("host_checkout_jws"),
133
- verified_at: full.fetch("verified_at")
134
- }
135
-
136
- result = AP2MandateVerifier.verify_checkout(**inputs)
137
- puts "status=#{result.status} code=#{result.code}"
138
- if result.success?
139
- checked_facts = result.evidence.to_h # Detached, deeply frozen in-process facts.
140
- puts "Scoped verification succeeded; this is NOT purchase authorization."
141
- # No payment, order update or nonce consumption is performed here.
142
- else
143
- raise "Verification did not succeed; stop."
38
+ require "tmpdir"
39
+
40
+ builder = AP2MandateVerifier::InputBuilder
41
+ fixtures = File.join(__dir__, "examples/input_builder")
42
+ read = ->(name) { JSON.parse(File.binread(File.join(fixtures, "#{name}.json"))) }
43
+ trust_at = ->(now) do
44
+ builder.trust(snapshot: read.call("trust_snapshot"), tenant_id: "synthetic-tenant",
45
+ issuer: {"identity" => "issuer", "purpose" => "checkout", "key_ref" => "issuer-1"},
46
+ agent: {"identity" => "agent", "purpose" => "checkout", "key_ref" => "agent-1"},
47
+ merchant: {"identity" => "shop", "purpose" => "checkout", "key_ref" => "merchant-1"},
48
+ verified_at: now)
49
+ end
50
+ wires = read.call("signed_wires").transform_keys(&:to_sym) # Preserve String bytes.
51
+
52
+ # Before issuance: independent order/trust and Host-chosen challenge information.
53
+ prepared = builder.prepare(trust: trust_at.call(1_800_000_000),
54
+ order: read.call("order"), root_presentation: wires.fetch(:root_presentation),
55
+ host_checkout_jws: wires.fetch(:host_checkout_jws),
56
+ challenge_id: "synthetic-challenge", nonce: "n", issuer_id: "synthetic-host",
57
+ not_before: 1_799_998_000, not_after: 1_800_002_000)
58
+
59
+ Dir.mktmpdir do |directory|
60
+ record = File.join(directory, "challenge.json")
61
+ File.binwrite(record, prepared) # Demo persistence; the Host owns real storage.
62
+
63
+ # Later: load the saved bytes, and independently obtain current order/trust.
64
+ now = 1_800_000_000 # Supplied synthetic clock, not a production time source.
65
+ result = builder.verify(trust: trust_at.call(now),
66
+ saved_challenge: builder.restore(saved_challenge: File.binread(record)),
67
+ order: read.call("order"), **wires,
68
+ expected_challenge_issuer_id: "synthetic-host",
69
+ clock_source_id: "fixed-synthetic-clock", verified_at: now)
70
+ puts "#{result.status}/#{result.code}; evidence=#{!result.evidence.nil?}"
71
+ raise "Verification did not succeed; stop" unless result.success?
144
72
  end
145
73
  ```
146
74
 
147
- For this saved `FULL` case, the expected result is `status=:verified_research`, `code=:scoped_research_verified`, `success?=true`. This is not the expected outcome for arbitrary real inputs, unsupported forms or dependency failures. Non-success results have nil Evidence. Exceptions or process termination without a result must also stop the caller. Avoid logging complete Evidence or raw inputs.
148
-
149
- ## Understanding the result
75
+ Expected for these unchanged synthetic inputs: `verified_research/scoped_research_verified; evidence=true`. This example models preparation, persistence and later verification in one process; it does not implement real issuance or atomic consumption. In an application, map authenticated registry/order records explicitly and preserve the original signed bytes. Structured business inputs use plain Ruby values with String keys, not ActiveRecord objects.
150
76
 
151
- | Outcome | `status` and predicate | Evidence and handling |
152
- | --- | --- | --- |
153
- | Successful scoped verification | `:verified_research`; `success? == true`; `code == :scoped_research_verified` | Present: checked facts, **not purchase authorization**. Host responsibilities still apply. |
154
- | Rejected | `:rejected`; `rejected? == true` | Absent (`nil`). Stop; inspect `result.code` for the rejection reason. |
155
- | Verification unavailable | `:unavailable`; `unavailable? == true` | Absent (`nil`). Stop; a dependency or verification failure does not by itself establish that the input is invalid. |
77
+ Do not call `prepare` again during verification or update saved hashes/references to match current values. Changed orders, trust or signed bytes must remain detectable. Persisted trust JSON can be loaded with `restore_trust` without reserializing it. The [complete example](examples/input_builder.rb) includes normal/tampered/expired cases; the [input guide](docs/INPUT_BUILDER.md) explains the business fields, exact restoration and Rails model mapping.
156
78
 
157
- An exception, process termination or missing result must also stop the caller without authorizing a purchase. The example above deliberately stops on every non-success result. See [Result and Evidence](docs/SUPPORT_CONTRACT.md#result-and-evidence) for details.
79
+ ## Results and responsibility boundaries
158
80
 
159
- ## Real inputs and responsibility boundaries
160
-
161
- | Keyword | Input contract |
81
+ | Result | Meaning and next step |
162
82
  | --- | --- |
163
- | `trust_json` | Original JSON String for authenticated Host trust snapshot, profile and public-key registration. |
164
- | `selection_json` | Independently selected tenant, profile version and role/identity/purpose/key references. |
165
- | `host_json` | Authenticated current order binding, issued challenge, expected issuer and clock identity. |
166
- | `root_presentation` | Original signed Root presentation String, preserving disclosure order and trailing `~`. |
167
- | `terminal_jws` | Original Agent terminal compact JWS String. |
168
- | `host_checkout_jws` | Original Merchant Checkout compact JWT String frozen by the Host. |
169
- | `verified_at` | Integer Unix seconds supplied by an external trusted clock. |
170
-
171
- See [SUPPORT_CONTRACT](docs/SUPPORT_CONTRACT.md#full-entry-and-required-inputs) for exact required shapes, types and limits. Do not register trust from the presented token or parse/re-encode/reorder signed wire input. Matching Host-only Buyer/account fields does not establish Issuer-signed identity authentication.
172
-
173
- A successful result from either full-verification entry establishes scoped verification facts. The Host still must recheck latest trust/revocation/order version/challenge/time and atomically consume the nonce with order CAS. The Gem does not perform those operations. Serializing Evidence to JSON does not preserve or reconstruct authenticity through this API. Legacy `verify(presentation_json:)` checks only the JSON syntax boundary and never returns successful Evidence.
174
-
175
- Before integration, consult the [Issuer onboarding checklist](docs/ISSUER_ONBOARDING_CHECKLIST.md) and [Issuer/Host minimum contract](docs/ISSUER_HOST_MINIMUM_CONTRACT.md). Real-Issuer trust and a specific Host's production GO are not established by this Gem version or verification success. The contract and Host/DB code under `research/` describe synthetic research designs and limited observations, not a production adapter.
176
-
177
- Raw nonce values are input-only; Evidence projects their SHA256. Other low-level verification entries also keep `success?=false` and `evidence=nil`; do not apply the successful example to those entries.
178
-
179
- ## Exclusions and safe stopping
180
-
181
- General AP2/full Schema, arbitrary real-Issuer interoperability, issuance/presentation/Receipt generation, Rails adapters, real payments/Host/DB/revocation operations, worst CPU/RSS/concurrency and numerical SLAs are outside scope. No defect-free/all-path safety proof is claimed; exclusions do not excuse known major defects or missing Gem checks.
83
+ | `:verified_research` / `:scoped_research_verified`, `success? == true` | Immutable Evidence contains checked facts for the fixed profile. The Host must still decide whether to authorize the purchase. |
84
+ | `:rejected`, `rejected? == true` | No Evidence. Stop and inspect `result.code`. |
85
+ | `:unavailable`, `unavailable? == true` | No Evidence. Stop; a dependency or processing failure is not proof of invalid business data. |
182
86
 
183
- The Host supplies authenticated token-independent trust/keys/profile and current revocation/clock/order/challenge state, rechecks before use, atomically consumes nonce with order CAS, reconciles PENDING and decides ALLOW. Existing Gem checks remain Gem responsibilities. Evidence is in-process checked facts in trusted Ruby, not a transport credential. Unknown/rejected/unavailable/exception/missing results never authorize; the Host provides outer time/memory/concurrency limits.
87
+ 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.
184
88
 
185
- ## Evidence and history
89
+ 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.
186
90
 
187
- The published 0.2.0 Gem is **33,280 bytes**, SHA256 `9a52e802de5a0564c34d198f4c4ad2c2b60791a8f1eb6e31db14c49e28e91f16`, from source commit `9b2e28d91fc4886722de7b9c39a5422e966953a9`. Publication on 2026-10-30 was verified against official RubyGems metadata, distribution bytes and the retained Gem. Its final Debian 12/arm64 / MRI 4.0.9 packaging observation matched all 13 payload files across source/archive/installation, loaded 10 product Ruby files normally and passed 118 installed cases using saved inputs/expected values. This is a limited observation, not a supported-platform expansion; source190/885 were not rerun in that packaging step. See [historical 0.2.0 publication record](docs/PROJECT_STATUS.md#020公開済み--現在の配布状態).
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.
188
92
 
189
- The packaged README and contract are snapshots from before publication. These repository documentation updates do not change the published Gem, require no rebuild, and do not transfer its validation to a rebuilt artifact. GitHub source archives contain repository source, not the RubyGems binary.
93
+ ### Which API should I use?
190
94
 
191
- The published 0.1.0 archive is **34,304 bytes**, SHA256 `37b2a235b6fab2d9d9765ae985dd9db27afd3b2c5407fe263a6b65314550db32`. Official metadata, owner `cuichangquan`, downloaded distribution bytes and all 13 payload hashes were checked on 2026-10-26. See the [publication record](research/stable010_release_linux_package/README.md#rubygems-publication-verified). This repository README was reorganized after publication and differs from the packaged README; the published archive was not rebuilt.
192
-
193
- See the [versioned validation record](research/stable010_release_linux_package/README.md) for this archive's external SHA, per-environment observations and limits. The archive hash is kept outside its payload to avoid self-reference. A hash identifies bytes, not Host trust or global safety.
194
-
195
- [Earlier 0.1.0 candidate R1](research/stable010_candidate/README.md), [published pre3](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.1.0.pre.3) and [pre2 Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.1.0.pre.2) are different archives. Historical NOT_RUN/stops/passes remain tied to their original bytes and time. Reusing 885 regressions (including 147) and Ruby4.0.1 independent comparisons is not a fresh 885 run or Linux independent Oracle.
196
-
197
- [Historical research documentation](https://github.com/cuichangquan/ap2-mandate-verifier/blob/2546d112b4bd4eaaf0a55b502f1c40b1fd61be65/README.md#research-documentation) does not override the current contract or release status. Future SDK plans are described in [PRODUCT_VISION](docs/PRODUCT_VISION.md).
198
-
199
- ## Illustrated concepts (Japanese diagrams)
200
-
201
- These existing diagrams contain Japanese text and illustrate broader AP2 concepts, not the exact fixed-profile implementation contract. The fixed-profile contract above takes precedence. Issuer trust and current revocation are supplied and maintained by the Host; the Gem does not independently establish live external trust or revocation. Arbitrary chains, issuance, Payment Mandates and payment execution shown conceptually are not supported features of this release.
202
-
203
- ### AP2 overview (Japanese)
204
-
205
- ![AP2 overview (Japanese)](docs/assets/ap2-overview.png)
206
-
207
- ### Delegation and Host responsibility boundaries (Japanese)
208
-
209
- ![Delegation and Host responsibility boundaries (Japanese)](docs/assets/ap2-delegation-trust-flow.png)
210
-
211
- ### Mandate anatomy (Japanese)
212
-
213
- ![Mandate anatomy (Japanese)](docs/assets/mandate-anatomy.png)
214
-
215
- ### SD-JWT and delegation concepts (Japanese)
216
-
217
- ![SD-JWT and delegation concepts (Japanese)](docs/assets/sd-jwt-delegation-chain.png)
95
+ | Entry | Role |
96
+ | --- | --- |
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. |
98
+ | `verify_checkout(**inputs)` | Direct complete verification with the existing seven inputs, including caller-supplied trust/selection/Host JSON. |
99
+ | `verify_research(**inputs)` | Retained name for the same seven-input verification pipeline; no deprecation warning. |
100
+ | `verify(presentation_json:)` | Legacy JSON syntax check only. Never returns successful Evidence. |
218
101
 
219
- ### Fail-closed attack patterns and Host replay prevention (Japanese)
102
+ Malformed assembly arguments, including missing keywords, to `InputBuilder.verify` return `:rejected / :invalid_host_context`. Assembly dependency/unexpected failures return `:unavailable / :research_verification_unavailable`; results from the complete core retain their codes. In contrast, missing/unknown keywords to the direct `verify_checkout` / `verify_research` entries return `:unavailable / :research_verification_unavailable`. Every such failure has `success? == false` and `evidence == nil`. See [the exact contract](docs/SUPPORT_CONTRACT.md#full-entry-and-required-inputs) for shapes, bounds and Ruby argument-binding caveats.
220
103
 
221
- ![Fail-closed attack patterns and Host replay prevention (Japanese)](docs/assets/attack-patterns-fail-closed.png)
104
+ ## More detail
222
105
 
223
- ## License
106
+ - [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
+ - [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.
109
+ - [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
+ - [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.
224
111
 
225
112
  MIT. See [LICENSE](LICENSE).
@@ -0,0 +1,77 @@
1
+ # 失敗時の診断(未公開 0.4.0候補)
2
+
3
+ Gem内部を追わず、失敗した検査と次の確認候補を取得できます。診断は補助情報です。
4
+ 既存呼び出し、status/code、固定profile、Fail Closed、非成功時のEvidenceなし契約は不変です。
5
+ 成功時のdiagnosticはnilです。診断処理が失敗してもnilとなり、検証結果は変わりません。
6
+ ヒントから購入・決済の許可を判断しないでください。
7
+
8
+ ## Before / After
9
+
10
+ ```ruby
11
+ result = AP2MandateVerifier::InputBuilder.verify(**host_arguments)
12
+ # 従来の利用方法も引き続き有効
13
+ puts "#{result.status}/#{result.code}"
14
+ # 追加の診断
15
+ if (diagnostic = result.diagnostic)
16
+ puts diagnostic.to_h(locale: :ja) # 英語は :en(既定)
17
+ # stage: :input_assembly, field: "order.currency",
18
+ # reason: :missing_required_field, hint: "文書記載の必須項目を…"
19
+ end
20
+ ```
21
+
22
+ 診断は変更不能なDiagnosticオブジェクトです。stage、field、reason、hint(locale:)と
23
+ 変更不能なHashを返すto_h(locale:)を利用できます。diagnostic[:stage]等も利用可能です
24
+ (hintは英語)。未対応localeは英語になります。機械判読識別子は翻訳せず、アプリ独自の
25
+ 翻訳も可能です。ヒントの文面は固定契約ではないので文字列一致で判定しないでください。
26
+ 今後、診断の詳細が追加される場合があります。検証結果には従来のstatus/codeを使います。
27
+
28
+ 純粋なBuilder補助メソッドtrust・restore_trust・prepare・restore・inputsは、従来どおり
29
+ 不備時にInputBuilder::Invalid(ArgumentErrorの子クラス)を送出します。
30
+ rescueしてerror.diagnosticを確認できます。依存障害の例外型は維持します。
31
+ 例外を成功扱いせず、入力原文・任意の依存例外メッセージ・例外チェーンをログに出さないでください。
32
+
33
+ | stage / field / reason | 意味と次の確認 |
34
+ | --- | --- |
35
+ | input_assembly / order.currency / missing_required_field | 独立した現在の注文情報から通貨を取得してください。 |
36
+ | input_assembly / order.expected_total / invalid_type | 価格の表示文字列ではなく最小単位のIntegerを渡してください。 |
37
+ | input_assembly / order / unknown_field | 文書の注文項目一覧と照合してください。未知項目名は表示しません。 |
38
+ | input_assembly / saved_challenge / unsupported_saved_format | 保存形式とprofileの版の対応を確認してください。受理させるために保存済みの版を書き換えないでください。 |
39
+ | host_binding / nil / host_binding_mismatch | 保存記録と独立した現在の注文・trust・期待issuer・原文digestを比較してください。具体的な不一致項目は特定していません。 |
40
+ | purchase_binding / nil / invalid_purchase_time | 独立した時計、署名済みOpen・Closedの有効期間、terminal proofの時刻窓を確認してください。どの時刻が誤りかは断定しません。 |
41
+ | verification_unavailable / nil / 既存code | 検証を完了できません。対応依存・実行環境を確認し、業務データ不正と決めつけないでください。 |
42
+ | verification / nil / undetermined | 安全に詳しく診断できません。API契約とstatus/codeを確認してください。 |
43
+
44
+ stageは失敗検査の分類であり、実行経路の証明ではありません。既存invalid_root_signatureは
45
+ Root以外にAgent・Merchant署名でも使われるため、signature_verificationと表示します。
46
+ 犯人や根本原因を断定しません。必須不足を未知項目より先に表示します。グラフ上限、parse、
47
+ 下位検査等ではfieldがnil・理由が汎用になる場合があります。診断は一件だけで、後続検査は
48
+ 未実行の場合があります。
49
+
50
+ 既存Resultの全コードに対し、JSON・バイト、署名、Root開示、購入・委任、制約・schema、
51
+ trust選択、Host・challengeの確認候補を提供します。旧unverifiedには保証範囲の案内を返し、
52
+ 完全検証成功にはしません。工程・項目・理由・ヒントは既知候補のみです。値、未知の項目名、
53
+ 署名原文、鍵、nonce、個人情報、stack traceは保持・表示しません。診断はEvidenceではなく、
54
+ 元入力の再構築もできません。
55
+
56
+ ## ローカルで試す
57
+
58
+ 公開済み0.3.0は変更しません。対応MRI 3.4.12または4.0.9と固定依存を備えた隔離環境で、
59
+ チェックアウトから候補を通常インストールしてください。
60
+
61
+ ```sh
62
+ gem build ap2_mandate_verifier.gemspec
63
+ gem install --local --no-document ./ap2_mandate_verifier-0.4.0.gem
64
+ ruby examples/input_builder.rb valid
65
+ ruby examples/input_builder.rb tampered
66
+ ruby examples/input_builder.rb expired
67
+ ruby examples/input_builder.rb missing_currency
68
+ ruby examples/input_builder.rb wrong_total_type
69
+ ruby examples/input_builder.rb unknown_order_field
70
+ ruby examples/input_builder.rb unsupported_saved_format
71
+ ```
72
+
73
+ 正常はEvidenceあり、改ざんはhost_binding_mismatch、期限切れはinvalid_purchase_timeです。
74
+ 後半4例はrejected / invalid_host_contextのまま、理由が順にmissing_required_field、invalid_type、
75
+ unknown_field、unsupported_saved_formatになります。合成fixtureの固定時刻を使います。
76
+ 業務データの対応・保存責務は[InputBuilderガイド](INPUT_BUILDER.ja.md)を参照してください。
77
+ 公開、実Issuer接続、本番購入許可、Phase 2-B移行を意味しません。
@@ -0,0 +1,90 @@
1
+ # Failure diagnostics (unreleased 0.4.0)
2
+
3
+ Diagnostics help you inspect a failed check without reading gem internals. They
4
+ are supplemental: existing calls, status/code, fixed profile, Fail Closed and
5
+ non-success `evidence == nil` are unchanged. A successful result has
6
+ `diagnostic == nil`. A diagnostic failure also returns nil and cannot change a
7
+ verification result. Never make a payment/authorization decision from a hint.
8
+
9
+ ## Before / after
10
+
11
+ ```ruby
12
+ result = AP2MandateVerifier::InputBuilder.verify(**host_arguments)
13
+ # Before (still supported):
14
+ puts "#{result.status}/#{result.code}"
15
+ # After:
16
+ if (diagnostic = result.diagnostic)
17
+ puts diagnostic.to_h(locale: :en) # :ja for Japanese
18
+ # stage: :input_assembly, field: "order.currency",
19
+ # reason: :missing_required_field, hint: "Supply ..."
20
+ end
21
+ ```
22
+
23
+ `Diagnostic` is immutable, with `stage`, `field`, `reason`, `hint(locale: :en)`
24
+ and `to_h(locale: :en)` readers. `diagnostic[:stage]` etc. also work (English
25
+ hint). Unsupported locales fall back to English. Machine identifiers are not
26
+ translated; applications may translate them themselves. Hints are guidance,
27
+ not stable text for matching. New diagnostic detail may be added in later
28
+ versions. Continue to use status/code for the verifier outcome.
29
+
30
+ Pure Builder helpers (`trust`, `restore_trust`, `prepare`, `restore`, `inputs`)
31
+ still raise `InputBuilder::Invalid < ArgumentError` for malformed input. Rescue
32
+ it and inspect `error.diagnostic`; do not treat an exception as success.
33
+ Unavailable dependency errors retain their existing exception types. Do not log
34
+ raw inputs, arbitrary provider exception messages, or full exception chains.
35
+
36
+ ## What to check
37
+
38
+ | Diagnostic | Meaning and next check |
39
+ | --- | --- |
40
+ | `input_assembly / order.currency / missing_required_field` | Obtain currency from independent current order data. |
41
+ | `input_assembly / order.expected_total / invalid_type` | Pass an Integer in minor units, not a formatted price String. |
42
+ | `input_assembly / order / unknown_field` | Compare with documented order fields; the unknown name is deliberately withheld. |
43
+ | `input_assembly / saved_challenge / unsupported_saved_format` | Check saved format/profile version compatibility. Never edit the saved version to force acceptance. |
44
+ | `host_binding / nil / host_binding_mismatch` | Compare saved challenge with independent current order, trust, issuer and original wire digests. The exact mismatching member is not identified. |
45
+ | `purchase_binding / nil / invalid_purchase_time` | Check independent clock, signed Open/Closed validity and terminal proof window. The code does not establish which time source is wrong. |
46
+ | `verification_unavailable / nil / <existing code>` | Verification could not finish. Check supported dependencies/runtime; do not label business data invalid. |
47
+ | `verification / nil / undetermined` | No safe precise diagnosis is available. Inspect the API contract and status/code. |
48
+
49
+ A stage names a failed check category, not an attested execution trace. In
50
+ particular, the legacy `invalid_root_signature` code can arise when checking
51
+ Root, Agent or Merchant signatures: `signature_verification` deliberately does
52
+ not name a specific signer. No hint identifies a malicious actor or proves a
53
+ root cause. Missing fields take precedence over unknown fields. Bounded graph,
54
+ parse or lower-level validation failures may have `field == nil` and a generic
55
+ reason. Only one diagnostic is returned; later checks may not have run.
56
+
57
+ The catalog covers every existing Result code: JSON/byte checks, signatures,
58
+ Root disclosures, purchase/delegation binding, scoped schema/constraints,
59
+ trust selection and Host/challenge checks. Legacy `unverified` results receive
60
+ scope guidance, not full-verification success. Diagnostic fields, reasons and
61
+ hints come from a closed catalog. No values, arbitrary field names, signed
62
+ wires, public/private keys, nonce, PII or stack traces are retained or emitted.
63
+ The diagnostic is not Evidence and cannot reconstruct original inputs.
64
+
65
+ ## Try the candidate locally
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:
70
+
71
+ ```sh
72
+ gem build ap2_mandate_verifier.gemspec
73
+ gem install --local --no-document ./ap2_mandate_verifier-0.4.0.gem
74
+ ruby examples/input_builder.rb valid
75
+ ruby examples/input_builder.rb tampered
76
+ ruby examples/input_builder.rb expired
77
+ ruby examples/input_builder.rb missing_currency
78
+ ruby examples/input_builder.rb wrong_total_type
79
+ ruby examples/input_builder.rb unknown_order_field
80
+ ruby examples/input_builder.rb unsupported_saved_format
81
+ ```
82
+
83
+ The successful example returns Evidence, tampered returns
84
+ `host_binding_mismatch`, expired returns `invalid_purchase_time`, and the four
85
+ assembly examples return `rejected / invalid_host_context` with diagnostic
86
+ reasons `missing_required_field`, `invalid_type`, `unknown_field` and
87
+ `unsupported_saved_format`. Synthetic fixture clocks are intentional. See
88
+ [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.
@@ -1,10 +1,18 @@
1
- # Fixed-profile AP2 verification — published 0.2.1 / historical 0.2.0
1
+ # Fixed-profile AP2 verification — published 0.3.0 / historical releases
2
2
 
3
- ## Unpublished 0.3.0 input-assistance candidate
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
+
5
+ ## Published 0.3.0 input assistance
4
6
 
5
7
  `InputBuilder` is an additive, Rails-independent conversion layer for explicit authenticated Host business records, versioned challenge preparation/restoration, and independently obtained current state. `verify` enters the unchanged complete `verify_checkout` core; assembly/restore alone never returns Evidence. Existing seven inputs, fixed profile/AP2 source, Result/Evidence v2, MRI 3.4.12/4.0.9 and all five pinned runtime dependencies remain unchanged.
6
8
 
7
- New business Hash/Array graphs are bounded before serialization and require plain built-ins with String keys; unknown fields, formats/profiles, conflicting keys and unsupported shapes fail closed. Persist the original returned challenge String and original signed wires. `restore_trust` validates and preserves exact stored trust/selection Strings. Rebuilding trust from business records creates a new snapshot whose exact bytes may differ; it must not repair old challenge references. Stored B/digests/references are never regenerated from current values. Host authentication, freshness/revocation, storage, issuance/atomic consumption and final authorization remain Host duties. See [input assistance](INPUT_BUILDER.md). These candidate statements do not authorize publication or production operation.
9
+ New business Hash/Array graphs are bounded before serialization and require plain built-ins with String keys; unknown fields, formats/profiles, conflicting keys and unsupported shapes fail closed. Persist the original returned challenge String and original signed wires. `restore_trust` validates and preserves exact stored trust/selection Strings. Rebuilding trust from business records creates a new snapshot whose exact bytes may differ; it must not repair old challenge references. Stored B/digests/references are never regenerated from current values. Host authentication, freshness/revocation, storage, issuance/atomic consumption and final authorization remain Host duties. See [input assistance](INPUT_BUILDER.md). Publication does not establish Host production authorization.
10
+
11
+ [0.3.0 is published on RubyGems](https://rubygems.org/gems/ap2_mandate_verifier/versions/0.3.0): registered 2026-10-31 01:31:40.743 UTC; official metadata fetched at 01:32:40 UTC and final comparison completed at 01:33:27 UTC. Owner `cuichangquan`, platform `ruby`, non-prerelease, not yanked at verification. Metadata, distributed Gem and saved final candidate matched: **37,376 bytes**, SHA256 `b3a31d5a8b0718f1085745dd4d97d85f210ff9a1628798110da9ff382ae546bd`, source `877f59195632f74714a60551b6afb22ac81d93e3`. RubyGems does not independently attest a source commit; the source association is from the retained reviewed candidate, whose bytes match the download. [v0.3.0 tag/Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v0.3.0) points to that exact source and was published at 01:35:52 UTC.
12
+
13
+ On Debian 12/arm64, MRI 3.4.12 and 4.0.9 each passed the merged-source existing885 + checkout190 + metadata7 + builder109 suites. The same final Gem passed ordinary installation, 14 source/archive/installed payload matches, 11 normally loaded product files and 134 installed cases per Ruby. Five runtime pins remain JSON2.19.9/JWT3.3.0/base640.3.0/OpenSSL gem4.0.2/Digest3.2.1. Scope and withdrawn-candidate history are in the [publication record](PROJECT_STATUS.md#030公開済み--現在の配布状態); these observations do not validate real Issuers, actual Hosts, performance or production GO.
14
+
15
+ The earlier archive SHA256 `5de6907cfcf0565ddaba1385b1d38ae113cc5e26d52259d769030237378a48a8` is withdrawn and was not published. [PR219](https://github.com/cuichangquan/ap2-mandate-verifier/pull/219) fixed its unregistered failure Result codes, unavailable classification and selector shape checks. Published failure handling reuses existing registered Result codes and preserves dependency-unavailable typing. The published Gem's README/contract remain the preparation snapshot; this repository update does not rebuild, repush or replace those bytes. GitHub source archives are separate from the RubyGems Gem.
8
16
 
9
17
  **Fixed-profile verification contract; Evidence is not Host ALLOW or payment permission.**
10
18
  Distribution availability is determined by the official RubyGems version listing, not by this document. Specific Host production GO remains separate.
@@ -0,0 +1,85 @@
1
+ # frozen_string_literal: true
2
+
3
+ module AP2MandateVerifier
4
+ # Supplemental guidance, never a verification decision or an input echo.
5
+ # Only the closed catalog below can construct diagnostics. No input retained.
6
+ class Diagnostic
7
+ GROUPS = {
8
+ input_validation: [%i[invalid_input_type input_too_large invalid_encoding invalid_json duplicate_key input_too_deep],
9
+ "Check original String bytes, JSON syntax, duplicate keys and documented input limits.",
10
+ "原文のString型、JSON構文、重複キー、文書記載の入力上限を確認してください。"],
11
+ signature_verification: [%i[invalid_root_jws unsupported_root_header unsupported_root_algorithm unsupported_root_type invalid_root_payload invalid_root_signature],
12
+ "Check original signed Root/Agent/Merchant bytes, the fixed header profile and independently selected public keys. A signature failure alone does not identify which input is wrong.",
13
+ "署名原文、固定ヘッダー仕様、独立に選択した公開鍵を確認してください。署名失敗だけでは誤った入力を特定できません。"],
14
+ root_disclosures: [%i[invalid_root_presentation unsupported_disclosure_profile invalid_disclosure missing_disclosure duplicate_disclosure duplicate_commitment extra_disclosure disclosure_limit_exceeded],
15
+ "Check the complete original Root presentation and disclosures against the supported profile; do not repair received signed data.",
16
+ "原Root提示全体と開示を対応profileと照合してください。受信した署名データを補修しないでください。"],
17
+ purchase_binding: [%i[unsupported_purchase_profile agent_key_mismatch root_binding_mismatch audience_mismatch nonce_mismatch invalid_purchase_time delegation_claim_mismatch checkout_binding_mismatch checkout_identity_mismatch],
18
+ "Compare original Root, Agent and Merchant wires with independent Host audience, nonce, identity and clock inputs. The code identifies a failed check, not its underlying cause.",
19
+ "Root・Agent・Merchant原文と、Hostが独立に取得したaudience、nonce、主体、時刻を照合してください。コードは失敗した検査を示し、根本原因を断定しません。"],
20
+ constraints: [%i[invalid_scoped_schema unsupported_scoped_profile unsupported_constraint constraint_mismatch amount_mismatch currency_mismatch constraint_limit_exceeded],
21
+ "Compare signed constraints, checkout items, currency and minor-unit totals with independent current order data and the fixed profile.",
22
+ "署名済み制約、購入項目、通貨、最小単位の合計額を、独立した現在の注文情報および固定profileと照合してください。"],
23
+ trust_context: [%i[invalid_trust_context trust_context_mismatch unsupported_trust_profile inactive_trust_snapshot trust_snapshot_time_mismatch invalid_trust_key trust_key_not_found ambiguous_trust_key inactive_trust_key trust_key_time_mismatch],
24
+ "Check authenticated current trust snapshot, explicit role/key selection, active state and validity at the independent verification time. Never select trust from received claims.",
25
+ "認証された現在のtrust snapshot、明示的な役割・鍵選択、active状態、独立した検証時刻での有効期間を確認してください。受信claimから信頼先を選ばないでください。"],
26
+ host_binding: [%i[invalid_host_context host_binding_mismatch challenge_state_mismatch challenge_reference_mismatch challenge_time_mismatch invalid_host_validity],
27
+ "Compare the authenticated saved challenge with independent current order, trust references, expected issuer and time. Preserve the saved record; do not rebuild it from current values.",
28
+ "認証された保存済みchallengeと、独立した現在の注文、trust参照、期待issuer、時刻を照合してください。保存記録を現在値で作り直さないでください。"]
29
+ }.freeze
30
+ GROUPS.each_value { |entry| entry[0].freeze; entry.freeze }
31
+ SPECIAL = {
32
+ invalid_purchase_time: ["Check the independent clock and the signed Open/Closed validity and terminal proof time window. This does not establish whether the clock or signed times are wrong.",
33
+ "独立した時計、署名済みOpen・Closedの有効期間、terminal proofの時刻窓を確認してください。時計と署名時刻のどちらが誤っているかは断定できません。"]
34
+ }.freeze
35
+ BUILDER_HINTS = {
36
+ missing_required_field: ["Supply the documented required field from independent Host data.", "文書記載の必須項目を、独立したHost情報から渡してください。"],
37
+ invalid_type: ["Check the documented exact Ruby/JSON type; coercion and subclasses are not supported.", "文書記載のRuby・JSONの厳密な型を確認してください。暗黙変換やサブクラスは対応外です。"],
38
+ unknown_field: ["Remove unsupported fields using the documented schema. Unknown field names are intentionally omitted.", "文書記載の構造と照合し、未対応項目を除いてください。未知の項目名は意図的に表示しません。"],
39
+ unsupported_saved_format: ["Check the saved format/profile version against this gem. Restore original authenticated bytes; do not rewrite the version.", "保存形式・profileの版がGemの対応版か確認してください。認証された原文を復元し、版を書き換えないでください。"],
40
+ invalid_value: ["Check documented bounds and supported values for this field.", "この項目の文書記載の範囲と対応値を確認してください。"],
41
+ invalid_builder_input: ["Check the InputBuilder contract and bounded, plain Ruby input shapes. The exact cause could not be safely identified.", "InputBuilder契約と上限内の通常Ruby入力構造を確認してください。正確な原因は安全に特定できませんでした。"]
42
+ }.freeze
43
+ SPECIAL.each_value(&:freeze)
44
+ BUILDER_HINTS.each_value(&:freeze)
45
+ FIELDS = (%w[order trust verified_at saved_challenge snapshot snapshot.records issuer agent merchant arguments root_presentation terminal_jws host_checkout_jws trust_json selection_json expected_challenge_issuer_id clock_source_id challenge_id nonce issuer_id not_before not_after] +
46
+ %w[tenant_id buyer_account_id order_id merchant_id audience order_version currency expected_total].map { |f| "order.#{f}" } +
47
+ %w[id policy_version active not_before not_after records].map { |f| "snapshot.#{f}" } +
48
+ %w[format_version profile_ref profile_version challenge].map { |f| "saved_challenge.#{f}" } +
49
+ %w[issuer agent merchant].flat_map { |r| %w[identity purpose key_ref].map { |f| "#{r}.#{f}" } }).each(&:freeze).freeze
50
+
51
+ attr_reader :stage, :field, :reason
52
+ def initialize(stage, field, reason, hints)
53
+ @stage, @field, @reason = stage, field, reason
54
+ @hints = hints.map { |s| s.dup.freeze }.freeze
55
+ freeze
56
+ end
57
+ private_class_method :new, :allocate
58
+ def hint(locale: :en) = @hints[locale == :ja ? 1 : 0]
59
+ def to_h(locale: :en) = {stage: stage, field: field, reason: reason, hint: hint(locale: locale)}.freeze
60
+ def [](key) = to_h[key]
61
+ def dup = self
62
+ def clone(freeze: true) = self
63
+ def self.for_result(status, code)
64
+ return nil if status == :verified_research
65
+ known = Result::CODES.fetch(status, []).include?(code)
66
+ if status == :unavailable && known
67
+ return new(:verification_unavailable, nil, code,
68
+ ["Verification could not be completed. Check supported dependency versions and service/runtime health; this is not proof of invalid business data.",
69
+ "検証を完了できませんでした。対応依存バージョンと実行環境の状態を確認してください。業務データ不正の証拠ではありません。"])
70
+ end
71
+ GROUPS.each do |stage, (codes, en, ja)|
72
+ return new(stage, nil, code, SPECIAL.fetch(code, [en, ja])) if known && codes.include?(code)
73
+ end
74
+ new(:verification, nil, :undetermined,
75
+ ["No precise diagnostic is available. Check status/code and the documented API scope; do not infer checkout permission.",
76
+ "詳細診断はありません。status・codeとAPIの保証範囲を確認してください。購入許可とは解釈しないでください。"])
77
+ end
78
+ def self.builder(field, reason)
79
+ # Look up canonical strings; never retain a caller string or arbitrary key.
80
+ safe_field = FIELDS.find { |known| known == field }
81
+ safe_reason = BUILDER_HINTS.key?(reason) ? reason : :invalid_builder_input
82
+ new(:input_assembly, safe_field, safe_reason, BUILDER_HINTS.fetch(safe_reason))
83
+ end
84
+ end
85
+ end
@@ -4,10 +4,22 @@ module AP2MandateVerifier
4
4
  # Pure, fixed-profile conversion of authenticated Host business information.
5
5
  # Preparation is not issuance, verification, nonce consumption or Host ALLOW.
6
6
  module InputBuilder
7
+ VERIFY_FIELDS = %i[trust saved_challenge order root_presentation terminal_jws host_checkout_jws
8
+ expected_challenge_issuer_id clock_source_id verified_at].freeze
7
9
  FORMAT_VERSION = "1"
8
10
  ORDER_FIELDS = %w[tenant_id buyer_account_id order_id merchant_id audience order_version currency expected_total].freeze
9
11
  RECORD_FIELDS = (TrustContext::RECORD_FIELDS - %w[profile_ref profile_version algorithm key_fingerprint]).freeze
10
- class Invalid < ArgumentError; end
12
+ class Invalid < ArgumentError
13
+ def initialize(field = nil, reason = :invalid_builder_input)
14
+ @field, @reason = field, reason
15
+ super("invalid input-builder information")
16
+ end
17
+ def diagnostic
18
+ Diagnostic.builder(@field, @reason)
19
+ rescue StandardError, LoadError
20
+ nil
21
+ end
22
+ end
11
23
 
12
24
  class Trust
13
25
  attr_reader :trust_json, :selection_json
@@ -24,8 +36,9 @@ module AP2MandateVerifier
24
36
  def self.trust(snapshot:, tenant_id:, issuer:, agent:, merchant:, verified_at:)
25
37
  verified_at = copy!(verified_at)
26
38
  source = copy!(snapshot)
27
- shape!(source, %w[id policy_version active not_before not_after records])
28
- invalid! unless source["records"].instance_of?(Array) && source["records"].length.between?(1, 16)
39
+ shape!(source, %w[id policy_version active not_before not_after records], "snapshot")
40
+ invalid!("snapshot.records", :invalid_type) unless source["records"].instance_of?(Array)
41
+ invalid!("snapshot.records", :invalid_value) unless source["records"].length.between?(1, 16)
29
42
  source["records"].each do |record|
30
43
  shape!(record, RECORD_FIELDS)
31
44
  record.merge!("profile_ref" => TrustContext::PROFILE_REF, "profile_version" => TrustContext::PROFILE_VERSION,
@@ -37,7 +50,7 @@ module AP2MandateVerifier
37
50
  "profile_ref" => TrustContext::PROFILE_REF, "profile_version" => TrustContext::PROFILE_VERSION,
38
51
  "profile_definition_hash" => TrustContext::PROFILE_HASH,
39
52
  "Issuer" => copy!(issuer), "Agent" => copy!(agent), "Merchant" => copy!(merchant)}
40
- TrustContext::ROLES.each_key { |role| shape!(selection[role], %w[identity purpose key_ref]) }
53
+ TrustContext::ROLES.each_key { |role| shape!(selection[role], %w[identity purpose key_ref], role.downcase) }
41
54
  wire = json!({"snapshot" => {"id" => source["id"], "policy_version" => source["policy_version"],
42
55
  "content_hash" => selection["trust_content_hash"], "body" => body},
43
56
  "profile" => {"profile_ref" => TrustContext::PROFILE_REF, "version" => TrustContext::PROFILE_VERSION,
@@ -46,6 +59,8 @@ module AP2MandateVerifier
46
59
  context = TrustContext.verified_context!(trust_json: wire, selection_json: selected, verified_at: verified_at,
47
60
  expected_merchant_id: selection.fetch("Merchant").fetch("identity"))
48
61
  Trust.send(:new, wire, selected, context)
62
+ rescue Invalid
63
+ raise
49
64
  rescue RootSignature::Unavailable
50
65
  raise
51
66
  rescue InputValidator::Invalid, RootSignature::Rejected, KeyError, TypeError
@@ -61,6 +76,8 @@ module AP2MandateVerifier
61
76
  context = TrustContext.verified_context!(trust_json: wire, selection_json: selected,
62
77
  verified_at: copy!(verified_at), expected_merchant_id: selection.fetch("Merchant").fetch("identity"))
63
78
  Trust.send(:new, wire, selected, context)
79
+ rescue Invalid
80
+ raise
64
81
  rescue RootSignature::Unavailable
65
82
  raise
66
83
  rescue InputValidator::Invalid, RootSignature::Rejected, KeyError, TypeError, NoMethodError
@@ -80,6 +97,8 @@ module AP2MandateVerifier
80
97
  saved = json!({"format_version" => FORMAT_VERSION, "profile_ref" => TrustContext::PROFILE_REF,
81
98
  "profile_version" => TrustContext::PROFILE_VERSION, "challenge" => challenge}, 32_768)
82
99
  restore(saved_challenge: saved)
100
+ rescue Invalid
101
+ raise
83
102
  rescue RootSignature::Unavailable
84
103
  raise
85
104
  rescue InputValidator::Invalid, RootSignature::Rejected, KeyError, TypeError
@@ -91,8 +110,8 @@ module AP2MandateVerifier
91
110
  def self.restore(saved_challenge:)
92
111
  wire = InputValidator.snapshot!(saved_challenge, max_bytes: 32_768)
93
112
  value = InputValidator.parse!(wire)
94
- shape!(value, %w[format_version profile_ref profile_version challenge])
95
- invalid! unless value.values_at("format_version", "profile_ref", "profile_version") ==
113
+ shape!(value, %w[format_version profile_ref profile_version challenge], "saved_challenge")
114
+ invalid!("saved_challenge", :unsupported_saved_format) unless value.values_at("format_version", "profile_ref", "profile_version") ==
96
115
  [FORMAT_VERSION, TrustContext::PROFILE_REF, TrustContext::PROFILE_VERSION]
97
116
  challenge = value["challenge"]
98
117
  shape!(challenge, HostBinding::CHALLENGE_FIELDS)
@@ -104,6 +123,8 @@ module AP2MandateVerifier
104
123
  %w[not_before not_after].each { |field| HostBinding.send(:time!, challenge[field]) }
105
124
  invalid! unless challenge["not_before"] < challenge["not_after"]
106
125
  wire
126
+ rescue Invalid
127
+ raise
107
128
  rescue RootSignature::Unavailable
108
129
  raise
109
130
  rescue InputValidator::Invalid, RootSignature::Rejected, KeyError, TypeError
@@ -121,6 +142,8 @@ module AP2MandateVerifier
121
142
  "expected_challenge_issuer_id" => copy!(expected_challenge_issuer_id), "clock_source_id" => copy!(clock_source_id)}
122
143
  {trust_json: trust.trust_json, selection_json: trust.selection_json, host_json: json!(host, 32_768),
123
144
  root_presentation: root, terminal_jws: terminal, host_checkout_jws: checkout, verified_at: verified_at}.freeze
145
+ rescue Invalid
146
+ raise
124
147
  rescue RootSignature::Unavailable
125
148
  raise
126
149
  rescue InputValidator::Invalid, RootSignature::Rejected, KeyError, TypeError
@@ -129,9 +152,14 @@ module AP2MandateVerifier
129
152
 
130
153
  # Building alone never produces Evidence; always enter the full old core.
131
154
  def self.verify(**arguments)
155
+ invalid!("arguments", :missing_required_field) unless VERIFY_FIELDS.all? { |field| arguments.key?(field) }
156
+ invalid!("arguments", :unknown_field) unless arguments.length == VERIFY_FIELDS.length
132
157
  AP2MandateVerifier.verify_checkout(**inputs(**arguments))
133
- rescue Invalid, ArgumentError
134
- Result.new(status: :rejected, code: :invalid_host_context)
158
+ rescue Invalid => error
159
+ Result.new(status: :rejected, code: :invalid_host_context, diagnostic: error.diagnostic)
160
+ rescue ArgumentError
161
+ Result.new(status: :rejected, code: :invalid_host_context,
162
+ diagnostic: Invalid.new.diagnostic)
135
163
  rescue InputValidator::Unavailable, RootSignature::Unavailable, LoadError
136
164
  Result.new(status: :unavailable, code: :research_verification_unavailable)
137
165
  rescue StandardError
@@ -139,13 +167,22 @@ module AP2MandateVerifier
139
167
  end
140
168
 
141
169
  def self.context!(trust, now)
142
- invalid! unless Object.instance_method(:instance_of?).bind_call(trust, Trust)
170
+ invalid!("trust", :invalid_type) unless Object.instance_method(:instance_of?).bind_call(trust, Trust)
143
171
  HostBinding.send(:time!, copy!(now))
144
172
  trust.instance_variable_get(:@context)
145
173
  end
146
174
  def self.binding!(context, order, root, checkout)
147
175
  value = copy!(order)
148
- shape!(value, ORDER_FIELDS)
176
+ shape!(value, ORDER_FIELDS, "order")
177
+ ORDER_FIELDS.each do |field|
178
+ expected = field == "expected_total" ? Integer : String
179
+ invalid!("order.#{field}", :invalid_type) unless value[field].instance_of?(expected)
180
+ end
181
+ HostBinding::B_IDS.grep_v(/profile/).each do |field|
182
+ invalid!("order.#{field}", :invalid_value) unless value[field].bytesize.between?(1, 256)
183
+ end
184
+ invalid!("order.currency", :invalid_value) unless ScopedConstraints::CURRENCIES.include?(value["currency"])
185
+ invalid!("order.expected_total", :invalid_value) unless value["expected_total"].between?(0, ScopedConstraints::MAX_AMOUNT)
149
186
  references = context.fetch(:references)
150
187
  value.merge!("profile_ref" => references.fetch("profile_ref"), "profile_version" => references.fetch("profile_version"),
151
188
  "approved_agent_key_fingerprint" => context.fetch(:agent_fingerprint),
@@ -154,10 +191,15 @@ module AP2MandateVerifier
154
191
  HostBinding.send(:binding!, value)
155
192
  value
156
193
  end
157
- def self.shape!(value, fields)
158
- invalid! unless value.instance_of?(Hash) && value.keys.sort == fields.sort
194
+ def self.shape!(value, fields, path = nil)
195
+ invalid!(path, :invalid_type) unless value.instance_of?(Hash)
196
+ missing = fields.find { |field| !value.key?(field) }
197
+ invalid!(path && "#{path}.#{missing}", :missing_required_field) if missing
198
+ invalid!(path, :unknown_field) unless value.keys.sort == fields.sort
199
+ end
200
+ def self.invalid!(field = nil, reason = :invalid_builder_input)
201
+ raise Invalid.new(field, reason), cause: nil
159
202
  end
160
- def self.invalid! = raise(Invalid, "invalid input-builder information")
161
203
  def self.json!(value, limit = InputValidator::MAX_BYTES)
162
204
  require "json"
163
205
  raise InputValidator::Unavailable, :json_dependency_unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
@@ -206,6 +248,18 @@ module AP2MandateVerifier
206
248
  invalid!
207
249
  end
208
250
  end
251
+ # Validate keyword shape before Ruby's keyword errors can echo arbitrary
252
+ # caller-supplied names. Each captured implementation keeps its typed API.
253
+ %i[trust restore_trust prepare restore inputs].each do |name|
254
+ implementation = method(name)
255
+ fields = implementation.parameters.filter_map { |kind, field| field if kind == :keyreq }.freeze
256
+ define_singleton_method(name) do |**arguments|
257
+ missing = fields.find { |field| !arguments.key?(field) }
258
+ invalid!(missing&.to_s, :missing_required_field) if missing
259
+ invalid!("arguments", :unknown_field) unless arguments.length == fields.length
260
+ implementation.call(**arguments)
261
+ end
262
+ end
209
263
  private_class_method :context!, :binding!, :shape!, :invalid!, :json!, :copy!, :walk!
210
264
  end
211
265
  end
@@ -67,6 +67,7 @@ module AP2MandateVerifier
67
67
  freeze
68
68
  end
69
69
  private_class_method :new, :allocate
70
+ def diagnostic = nil
70
71
  def status = :verified_research
71
72
  def code = :scoped_research_verified
72
73
  def success? = true
@@ -1,5 +1,7 @@
1
1
  # frozen_string_literal: true
2
2
 
3
+ require_relative "diagnostic"
4
+
3
5
  module AP2MandateVerifier
4
6
  # Legacy non-success type. The opt-in research entry uses a separate type.
5
7
  class Result
@@ -32,15 +34,23 @@ module AP2MandateVerifier
32
34
 
33
35
  attr_reader :status, :code
34
36
 
35
- def initialize(status:, code:)
37
+ def initialize(status:, code:, diagnostic: nil)
36
38
  unless CODES.fetch(status, []).include?(code)
37
39
  raise ArgumentError, "unsupported non-success result"
38
40
  end
39
41
  @status = status
40
42
  @code = code
43
+ @diagnostic = diagnostic if Object.instance_method(:instance_of?).bind_call(diagnostic, Diagnostic) && diagnostic.frozen?
41
44
  freeze
42
45
  end
43
46
 
47
+ # A diagnostic failure cannot affect the already determined verdict.
48
+ def diagnostic
49
+ @diagnostic || Diagnostic.for_result(status, code)
50
+ rescue StandardError, LoadError
51
+ nil
52
+ end
53
+
44
54
  def success? = false
45
55
  def evidence = nil
46
56
  def rejected? = status == :rejected
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.3.0
4
+ version: 0.4.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - AP2 Mandate Verifier contributors
@@ -89,8 +89,11 @@ extra_rdoc_files: []
89
89
  files:
90
90
  - LICENSE
91
91
  - README.md
92
+ - docs/DIAGNOSTICS.ja.md
93
+ - docs/DIAGNOSTICS.md
92
94
  - docs/SUPPORT_CONTRACT.md
93
95
  - lib/ap2_mandate_verifier.rb
96
+ - lib/ap2_mandate_verifier/diagnostic.rb
94
97
  - lib/ap2_mandate_verifier/host_binding.rb
95
98
  - lib/ap2_mandate_verifier/input_builder.rb
96
99
  - lib/ap2_mandate_verifier/input_validator.rb
@@ -122,7 +125,7 @@ required_rubygems_version: !ruby/object:Gem::Requirement
122
125
  - !ruby/object:Gem::Version
123
126
  version: '0'
124
127
  requirements: []
125
- rubygems_version: 3.6.9
128
+ rubygems_version: 4.0.20
126
129
  specification_version: 4
127
130
  summary: Fixed-profile AP2 verification for Ruby
128
131
  test_files: []