ap2_mandate_verifier 1.4.0 → 1.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 +4 -4
- data/README.ja.md +20 -8
- data/README.md +20 -8
- data/SECURITY.md +4 -2
- data/docs/PAYMENT_ACCEPTANCE.md +88 -0
- data/docs/PAYMENT_POLICY.md +4 -2
- data/docs/PUBLIC_API.md +8 -2
- data/docs/RELEASE_140_CANDIDATE.md +2 -0
- data/docs/RELEASE_150_CANDIDATE.md +21 -0
- data/docs/SUPPORT_CONTRACT.md +5 -1
- data/examples/payment_acceptance.rb +77 -0
- data/lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb +316 -0
- data/lib/ap2_mandate_verifier/payment_acceptance.rb +263 -0
- data/lib/ap2_mandate_verifier.rb +2 -0
- metadata +10 -4
checksums.yaml
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
---
|
|
2
2
|
SHA256:
|
|
3
|
-
metadata.gz:
|
|
4
|
-
data.tar.gz:
|
|
3
|
+
metadata.gz: 20e9c745f34056d635afd6b61add96b7e231c8ddb42e7240ff740d8cba53f850
|
|
4
|
+
data.tar.gz: 859ca97589c71e283afc3cc9963f03d89e3518d58e93e6f74adabfa9b1804352
|
|
5
5
|
SHA512:
|
|
6
|
-
metadata.gz:
|
|
7
|
-
data.tar.gz:
|
|
6
|
+
metadata.gz: 118d2c83af40c04bba6d033880ab13676f401c9419a1f3c56f35a8c2822cd61b9622a0cf0eefffddbc4d097b3a0d2c4f6bec53bda910384167b1b5f1ebb23fa3
|
|
7
|
+
data.tar.gz: 856b624b16d3fdd369b43ac417308d4d0c6dac4cf8698b9a5359dd8c090677b88ddf303387adbea497d9cc3d4e35e06834ab5ed1d08c2e15ab50099ed33a3c5d
|
data/README.ja.md
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
# AP2 Mandate Verifier — Checkout・PaymentのRuby SDK
|
|
2
2
|
|
|
3
|
-
### 1.
|
|
3
|
+
### 1.5.0候補:Payment受理の原子性と冪等性支援
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
保護された業務上の支払い単位を原子的に予約し、開始前に全検証をやり直します。応答消失・結果不明では自動再実行せず、元のReceiptを照合して復旧できます。未公開候補です。[組込み・永続store・安全性契約](docs/PAYMENT_ACCEPTANCE.md)、[Ruby単体の復旧例](examples/payment_acceptance.rb)、[公開前の確認](docs/RELEASE_150_CANDIDATE.md)。
|
|
6
6
|
|
|
7
|
+
```ruby
|
|
8
|
+
accepted = service.accept(**trusted_scope, mode: :conditional, verification_inputs: raw_inputs)
|
|
9
|
+
dispatch = service.start(ticket: accepted.ticket, verification_inputs: fresh_inputs) if accepted.ticket
|
|
10
|
+
# 実際のprocessor呼出しはアプリ側。同じdispatch.processor_keyを使います。
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
検証成功・永続予約・決済完了は別の事象です。承認済みoccurrenceの保護、全worker共通の永続store、processorの冪等性・照会が必要です。旧1.xのverifierは変更せず、SQLite参照driverは任意の別依存です。
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
### 公開済み1.4.0:PISPと支払い実行日時の条件
|
|
17
|
+
|
|
18
|
+
承認したPISPと実行可能期間を指定し、アプリが独立して確認した決済サービス・実行予定時刻と照合できます。日時は解析した瞬間で比較し、旧1.xの既定動作を維持します。[仕様・API・公式との差](docs/PAYMENT_POLICY.md)、[3方式のRuby例](examples/payment_policy.rb)、[公開照合記録](docs/POST_RELEASE_140.md)。
|
|
7
19
|
|
|
8
20
|
### 公開済み1.3.0:CheckoutとPaymentの選択的開示
|
|
9
21
|
|
|
@@ -19,13 +31,13 @@
|
|
|
19
31
|
Direct/条件付きPayment Mandateと成功/エラーPayment Receiptを追加しました。[API・制約・信頼境界](docs/PAYMENT.md)、[Ruby単体サンプル](examples/payment.rb)、[公開照合記録](docs/POST_RELEASE_110.md)、[GitHub Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v1.1.0)。検証成功は実行許可ではなく、永続的・原子的な単発利用管理と実決済は利用アプリの責任です。
|
|
20
32
|
|
|
21
33
|
```sh
|
|
22
|
-
gem install ap2_mandate_verifier --version 1.
|
|
23
|
-
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.
|
|
34
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
35
|
+
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.4.0").full_gem_path')/examples/payment.rb"
|
|
24
36
|
```
|
|
25
37
|
|
|
26
38
|
[English](README.md)
|
|
27
39
|
|
|
28
|
-
**公開済み安定版は1.
|
|
40
|
+
**公開済み安定版は1.4.0です。**
|
|
29
41
|
|
|
30
42
|
1.0.0では、既存のDirectと条件付きCheckoutの公開API・保守契約を確立しました。
|
|
31
43
|
0.8.0の引数・既定値・profile・結果の意味・保存形式と製品実装を維持します。
|
|
@@ -45,8 +57,8 @@ Agent処理へProvider秘密鍵を渡しません。[API・信頼境界](docs/CO
|
|
|
45
57
|
正式対応MRI 3.4.12/4.0.9で動くRuby単体の導入例です。source checkoutやRailsは不要です:
|
|
46
58
|
|
|
47
59
|
```sh
|
|
48
|
-
gem install ap2_mandate_verifier --version 1.
|
|
49
|
-
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.
|
|
60
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
61
|
+
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.4.0").full_gem_path')/examples/conditional_checkout.rb"
|
|
50
62
|
```
|
|
51
63
|
|
|
52
64
|
[Ruby単体の実行例](examples/conditional_checkout.rb)はインストール済み公開APIだけを使い、
|
|
@@ -76,7 +88,7 @@ Rubyで購入委任データを検証する、AP2の固定profile向けGemです
|
|
|
76
88
|
正式対応は **MRI 3.4.12とMRI 4.0.9** です。利用者が選ぶGem環境で導入します。
|
|
77
89
|
|
|
78
90
|
```sh
|
|
79
|
-
gem install ap2_mandate_verifier --version 1.
|
|
91
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
80
92
|
```
|
|
81
93
|
|
|
82
94
|
BundlerのGemfile:
|
data/README.md
CHANGED
|
@@ -1,9 +1,21 @@
|
|
|
1
1
|
# AP2 Mandate Verifier — Ruby SDK for Checkout and Payment
|
|
2
2
|
|
|
3
|
-
### 1.
|
|
3
|
+
### 1.5.0 candidate: transactional Payment acceptance
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
Reserve a protected business occurrence atomically, reverify before one fenced start, and recover the original Receipt after response loss without reopening an uncertain attempt. This candidate is not published. [Integration/store/security contract](docs/PAYMENT_ACCEPTANCE.md), [plain Ruby recovery example](examples/payment_acceptance.rb), [release gates](docs/RELEASE_150_CANDIDATE.md).
|
|
6
6
|
|
|
7
|
+
```ruby
|
|
8
|
+
accepted = service.accept(**trusted_scope, mode: :conditional, verification_inputs: raw_inputs)
|
|
9
|
+
dispatch = service.start(ticket: accepted.ticket, verification_inputs: fresh_inputs) if accepted.ticket
|
|
10
|
+
# Application-owned processor call uses dispatch.processor_key; no SDK payment call.
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
Verification, durable reservation and settlement are separate. Use protected enrollment, one authoritative store and processor idempotency/lookup; no automatic timeout release. Existing1.x verifiers remain unchanged. The optional SQLite reference driver is installed separately.
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
### Published1.4.0: PISP and execution-date Payment conditions
|
|
17
|
+
|
|
18
|
+
Explicit Payment profiles now constrain approved PISPs and parsed inclusive execution windows, bound to independent application provider/time context. Existing1.x defaults remain unchanged. [Contract/API/official differences](docs/PAYMENT_POLICY.md), [plain Ruby three-mode example](examples/payment_policy.rb), [verified publication](docs/POST_RELEASE_140.md).
|
|
7
19
|
|
|
8
20
|
### Published 1.3.0: selective Checkout and Payment
|
|
9
21
|
|
|
@@ -19,13 +31,13 @@ Published1.2.0 adds explicit `SelectivePayment` candidate-array disclosure: reta
|
|
|
19
31
|
1.1.0 adds Direct and conditional Payment Mandates plus signed Success/Error Payment Receipts. [Payment APIs and constraints](docs/PAYMENT.md), [plain Ruby lifecycle sample](examples/payment.rb), [verified publication](docs/POST_RELEASE_110.md), [GitHub Release](https://github.com/cuichangquan/ap2-mandate-verifier/releases/tag/v1.1.0). Verification does not grant execution permission; durable atomic one-use state and actual payment remain application responsibilities.
|
|
20
32
|
|
|
21
33
|
```sh
|
|
22
|
-
gem install ap2_mandate_verifier --version 1.
|
|
23
|
-
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.
|
|
34
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
35
|
+
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.4.0").full_gem_path')/examples/payment.rb"
|
|
24
36
|
```
|
|
25
37
|
|
|
26
38
|
[日本語](README.ja.md)
|
|
27
39
|
|
|
28
|
-
**Published stable: 1.
|
|
40
|
+
**Published stable: 1.4.0.**
|
|
29
41
|
|
|
30
42
|
1.0.0 establishes the stable public contract for the existing
|
|
31
43
|
Direct and conditional Checkout APIs. It preserves 0.8.0 signatures, defaults,
|
|
@@ -49,8 +61,8 @@ multi-item profile. Provider private keys never enter Agent operations.
|
|
|
49
61
|
Ruby-only Quick Start on MRI 3.4.12 or 4.0.9; no source checkout or Rails required:
|
|
50
62
|
|
|
51
63
|
```sh
|
|
52
|
-
gem install ap2_mandate_verifier --version 1.
|
|
53
|
-
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.
|
|
64
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
65
|
+
ruby "$(ruby -e 'puts Gem::Specification.find_by_name("ap2_mandate_verifier", "1.4.0").full_gem_path')/examples/conditional_checkout.rb"
|
|
54
66
|
```
|
|
55
67
|
|
|
56
68
|
The [standalone Ruby example](examples/conditional_checkout.rb) uses only installed
|
|
@@ -84,7 +96,7 @@ The [Rails demo](https://github.com/cuichangquan/ap2-mandate-verifier-demo#readm
|
|
|
84
96
|
Formal support is **MRI 3.4.12 and MRI 4.0.9**. In your chosen Gem environment:
|
|
85
97
|
|
|
86
98
|
```sh
|
|
87
|
-
gem install ap2_mandate_verifier --version 1.
|
|
99
|
+
gem install ap2_mandate_verifier --version 1.4.0
|
|
88
100
|
```
|
|
89
101
|
|
|
90
102
|
Or add to your Gemfile:
|
data/SECURITY.md
CHANGED
|
@@ -2,9 +2,9 @@
|
|
|
2
2
|
|
|
3
3
|
## 現在の対象と限界 / Current scope
|
|
4
4
|
|
|
5
|
-
[Published 1.
|
|
5
|
+
[Published 1.4.0](https://rubygems.org/gems/ap2_mandate_verifier/versions/1.4.0) is a framework-independent Ruby SDK for the documented AP2 Checkout profiles, including Direct/conditional Checkout and Payment, selective disclosure, PISP/date conditions and Receipt confirmation. See [publication evidence](docs/POST_RELEASE_140.md), the stable [PUBLIC_API](docs/PUBLIC_API.md) and [SUPPORT_CONTRACT](docs/SUPPORT_CONTRACT.md) for its scope and limitations.
|
|
6
6
|
|
|
7
|
-
現在の配布版は、対応profileのDirect/条件付き購入委任の発行・提示・検証・Checkout Receipt確認を備えた、フレームワーク非依存のRuby SDK **1.
|
|
7
|
+
現在の配布版は、対応profileのDirect/条件付き購入委任の発行・提示・検証・Checkout Receipt確認を備えた、フレームワーク非依存のRuby SDK **1.4.0**です。1.xの保守対象は最新マイナー系列の最新修正版のみとし、旧マイナー・0.x・preへのbackportは約束しません。現行版の報告窓口は以下のままです。保守対象・互換性・セキュリティ修正の扱いは[公開後の整備](docs/POST_RELEASE_MAINTENANCE.md)を参照してください。
|
|
8
8
|
|
|
9
9
|
The 1.x policy covers only the latest patch of the latest 1.x minor series; older minors, 0.x and prereleases carry no backport promise. Existing reporting routes below remain available for the current release. See [maintenance and compatibility](docs/POST_RELEASE_MAINTENANCE.md). The pre.3, 0.1.0 candidate and R2 statements below are historical records of those stages, not the current release status.
|
|
10
10
|
|
|
@@ -12,6 +12,8 @@ Evidence is not Host ALLOW or payment permission. Real Issuer trust, specific Ho
|
|
|
12
12
|
|
|
13
13
|
EvidenceはHost ALLOW・決済許可ではありません。実Issuer信頼、特定Host本番GO、Phase 2-BはHOLDを維持し、一般AP2/全Schema・Phase2-A全面PASS・最悪資源/並行性能・native/runtime全面安全性は未証明です。SLA・固定保守年数・受付/修正期限は約束せず、既存のprovider/JSON勧告metadata・通信会計の限界を保持します。本記録は新たな実行・変更・公開を許可しません。
|
|
14
14
|
|
|
15
|
+
1.5.0 is an unpublished opt-in acceptance/idempotency candidate. Its store coordinates protected business occurrences and one start handle; it does not change existing verifier/Host authority contracts or prove external exactly-once/settlement. Store adapters, current authority/order/nonce CAS, filesystem/database recovery and processor lookup/idempotency require application guarantees. No memory fallback or timeout-based re-execution is safe. See [the candidate contract](docs/PAYMENT_ACCEPTANCE.md).
|
|
16
|
+
|
|
15
17
|
## 歴史記録:pre.3の対象と限界 / Historical pre.3 scope
|
|
16
18
|
|
|
17
19
|
`ap2_mandate_verifier 0.1.0.pre.3` is a fixed-profile research prerelease,
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
# Payment acceptance and idempotency support (1.5.0 candidate)
|
|
2
|
+
|
|
3
|
+
This opt-in application-side coordinator separates three events: cryptographic verification, durable reservation of an approved business occurrence, and an external payment processor’s outcome. Existing1.x verifiers and their result meanings remain unchanged. The SDK does not call a processor, transfer funds or promise distributed exactly-once execution.
|
|
4
|
+
|
|
5
|
+
## Stable identity and protected approval
|
|
6
|
+
|
|
7
|
+
A Checkout JWT hash (`transaction_id`), final Mandate hash or Receipt reference changes when an otherwise identical instruction is re-signed. None is sufficient as the business idempotency key. Use independently authenticated Host identifiers: `tenant_id`, `merchant_id` (the actual authority/account namespace), stable `operation_id`, `approval_id`, approved `occurrence_id` and `order_id`. Never allocate a fresh random operation/occurrence for each request or retry.
|
|
8
|
+
|
|
9
|
+
A protected Host approval backend must enroll the exact Checkout/payment semantics and pinned Receipt trust context before acceptance. `accept` cannot enroll or change authority from a received `approved: true` or arbitrary occurrence. The reference adapter enforces uniqueness of the business operation and of the approved occurrence. A secondary final-Closed-reference guard prevents dispatching the exact same final instruction under another occurrence. Wire hashes remain audit/Receipt bindings, not the sole replay key.
|
|
10
|
+
|
|
11
|
+
Canonical terms include the complete supported Checkout payload and payment fields. Only the technical Checkout-JWT hash is excluded from payment terms; parsed execution dates are normalized to exact instants. Changed amounts, products, provider/instrument or other terms conflict rather than create a new slot. JSON object key order is normalized; array order remains significant, so reordered business payload arrays can conservatively conflict. The original signed wires, Receipt reference and processor idempotency key stay pinned to the first reservation.
|
|
12
|
+
|
|
13
|
+
## Minimal integration
|
|
14
|
+
|
|
15
|
+
The optional SQLite reference adapter uses the separately installed `sqlite3 = 2.10.2` driver. It is not a new base-Gem runtime dependency. The ordinary verifier entry loads without SQLite. Missing driver/storage returns unavailable; there is no in-memory fallback.
|
|
16
|
+
|
|
17
|
+
```ruby
|
|
18
|
+
m = AP2MandateVerifier::PaymentAcceptance
|
|
19
|
+
# Protected one-time offline bootstrap only. Fails if the file already exists.
|
|
20
|
+
store = m::SQLiteStore.create(path: "/srv/app/payment_acceptance.sqlite3")
|
|
21
|
+
# Normal startup opens an EXISTING database; a lost file must never reset a ledger.
|
|
22
|
+
store = m::SQLiteStore.new(path: "/srv/app/payment_acceptance.sqlite3")
|
|
23
|
+
service = m::Service.new(store: store)
|
|
24
|
+
|
|
25
|
+
# All six IDs come from authenticated current application state.
|
|
26
|
+
scope = {tenant_id: "tenant-A", merchant_id: "shop", operation_id: "order-42/payment-1",
|
|
27
|
+
approval_id: "consent-99", occurrence_id: "payment-1", order_id: "order-42"}
|
|
28
|
+
# Call this only in the protected approval backend, never a request-driven flag.
|
|
29
|
+
store.authorize!(**scope, mode: :direct,
|
|
30
|
+
profile_ref: AP2MandateVerifier::Payment::PROFILE_REF,
|
|
31
|
+
checkout: approved_checkout, payment: approved_payment,
|
|
32
|
+
receipt_context: {trusted_public_key_pem: processor_public_key,
|
|
33
|
+
expected_issuer: "processor", expected_payment_id: "payment-42",
|
|
34
|
+
not_before: receipt_window_start, not_after: receipt_window_end})
|
|
35
|
+
|
|
36
|
+
accepted = service.accept(**scope, mode: :direct, verification_inputs: raw_payment_verify_inputs)
|
|
37
|
+
if accepted.ticket
|
|
38
|
+
# Fresh authenticated Host/trust/order/challenge/clock inputs; first wires unchanged.
|
|
39
|
+
dispatch = service.start(ticket: accepted.ticket, verification_inputs: fresh_verify_inputs)
|
|
40
|
+
if dispatch
|
|
41
|
+
# Application-owned processor call MUST reuse dispatch.processor_key.
|
|
42
|
+
# The SDK itself performs no network request or payment.
|
|
43
|
+
end
|
|
44
|
+
end
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
`mode` is `:direct`, `:conditional` or `:selective`. `verification_inputs` is the complete raw keyword hash of the corresponding existing `Payment.verify` or `SelectivePayment.verify`, including1.4 profile/context options where applicable. A caller-created verification result is not accepted as evidence. Current supported forms are fully verified; unsupported recurrence/budget formats remain rejected.
|
|
48
|
+
|
|
49
|
+
Enrollment, active authorization/occurrence checks, semantic comparison and reservation occur atomically in the reference DB. An immutable grant cannot be silently replaced; `revoke!` disables it without releasing an existing attempt. `start` reruns the full existing verification pipeline with fresh trusted inputs and requires every original signed Checkout/Payment wire to match. Payment expiry alone is insufficient: Checkout, trust and challenge can expire earlier. Grant/current-order/nonce checks in a production adapter must share its authoritative transaction with reservation/start CAS. A check in one DB followed by a CAS in another leaves a race; the reference grant is not a live connection to an external order or revocation service.
|
|
50
|
+
|
|
51
|
+
## States, retries and uncertain outcomes
|
|
52
|
+
|
|
53
|
+
| Observation | Meaning and permitted next step |
|
|
54
|
+
| --- | --- |
|
|
55
|
+
| `reserved` with opaque Ticket | First committed claim only; not purchase permission. Fresh `start` may yield one dispatch-coordination handle. |
|
|
56
|
+
| `pending` | Existing reservation/processing; no new Ticket or start rights. Read its stored original outcome/key. |
|
|
57
|
+
| `unknown` | Execution outcome uncertain; never automatically release, expire or take over. Query/reconcile using the original processor key. |
|
|
58
|
+
| `receipt_success` / `receipt_error` | Authentic reported Receipt outcome; no independent settlement or no-charge proof. No automatic re-execution. |
|
|
59
|
+
| `conflict` | Same operation/grant with different terms, scope or original instruction usage. No fresh slot. |
|
|
60
|
+
| `rejected` / `unavailable` | No capability. Unknown DB commit outcomes must not be treated as permission or retried as a new operation. |
|
|
61
|
+
|
|
62
|
+
Only the first successful fenced `reserved → processing` CAS returns an `Execution` handle. A crash after that commit but before a processor call can leave zero executions and a pending record. A crash after the call can leave one execution and the same pending record. The SDK cannot distinguish those cases by timeout. It intentionally provides no lease takeover, automatic release or re-execution API. Processor idempotency/lookup semantics and application reconciliation are necessary; database atomicity alone cannot cover an external side effect.
|
|
63
|
+
|
|
64
|
+
For an expired original presentation, use authenticated `lookup(**scope)` to retrieve existing state; it does not bypass fresh verification to create a new claim. Retrying with a re-signed equivalent presentation returns the first record without a Ticket. Never attach its old Receipt to a replacement Closed/Open wire. Returned first signed wires/reference describe the original attempt; no hidden candidate universe is reconstructed.
|
|
65
|
+
|
|
66
|
+
## Receipt and recovery
|
|
67
|
+
|
|
68
|
+
`finish(ticket:, receipt_jwt:, verified_at:)` authenticates a Receipt against the grant’s pinned issuer/key/payment ID/window and the first exact Closed bytes. Receipt time cannot predate successful start. `unknown(ticket:)` preserves an uncertain processing record. After a worker restart, `reconcile(**scope, receipt_jwt:, verified_at:)` may finalize processing/unknown with the same checks, but cannot return a Ticket or start again. `lookup(**scope)` is read-only.
|
|
69
|
+
|
|
70
|
+
A Receipt may arrive after the Mandate expires; its independently pinned Receipt window is distinct. Conflicting Receipt bytes/outcomes do not overwrite a completed record. Error Receipt, missing Receipt or response loss never frees the operation. Key rotation or changed Receipt trust after enrollment needs an explicit application recovery policy; the reference adapter does not silently replace trust.
|
|
71
|
+
|
|
72
|
+
## Reuse and new transactions
|
|
73
|
+
|
|
74
|
+
This API does not consume every Open Mandate globally. A reusable supported Open can lead to fresh Closed instructions for separately authorized new business occurrences. Those occurrences must be independently approved/enrolled and use their own stable operation identity. Arbitrary retry UUIDs are not new authority. The exact same final Closed cannot be dispatched twice under this local acceptance policy. Official recurrence/budget enforcement is not added by this release; applications must not infer reusable authority from an unsupported wire format.
|
|
75
|
+
|
|
76
|
+
## Persistence and adapter contract
|
|
77
|
+
|
|
78
|
+
SQLite is a local single-host reference using transactions, strict supported schema/index/FK checks, unique constraints, fencing and synchronous durable commits. Explicit initialization creates a private file; reopening requires the existing expected database. Missing/corrupt/unsupported schema is unavailable, with no repair/reset/migration or memory fallback. Use a protected local filesystem, one authoritative ledger for all workers and separate connections after fork. Do not create one ledger per worker or request.
|
|
79
|
+
|
|
80
|
+
Database deletion, rollback to an old backup, split-brain copies, broken filesystem locking/fsync, adversarial DB edits, NFS/multi-host replication or operator re-enrollment can invalidate protection. Restore must stop dispatch and reconcile against the processor. SQLite is not a distributed consensus service or a replacement for disaster recovery. Stored Checkout/payment terms and first wires may contain sensitive information; apply application access controls, retention and at-rest protection. Do not log Tickets/fences or raw payloads.
|
|
81
|
+
|
|
82
|
+
Custom adapters may integrate existing DB/Redis infrastructure but must implement atomic protected enrollment/uniqueness, read-and-claim, active-grant/order/occurrence CAS, no capability before durable commit, first-wire/processor-key retention, and monotonic fenced finalization. No check-then-insert, timeout reset or guessed success on I/O/commit error. They need their own independent concurrency/crash/durability tests; this SDK cannot attest an adapter’s persistence guarantees.
|
|
83
|
+
|
|
84
|
+
## Official evidence and guarantees
|
|
85
|
+
|
|
86
|
+
Adopted AP2 pin remains `b4587ac1d055888a73b4b21750973cffba961793`. Relevant docs/schema/SDK are byte-identical to observed official main `e1ea56db72a6385bce3e5c1112b3a56ce60acb43`; current changes there are outside those paths. [Issue346](https://github.com/google-agentic-commerce/AP2/issues/346), [Issue328](https://github.com/google-agentic-commerce/AP2/issues/328) and [Issue339](https://github.com/google-agentic-commerce/AP2/issues/339) remain discussions, not adopted requirements. [PR347](https://github.com/google-agentic-commerce/AP2/pull/347) adds sample reservations but does not establish stable business identity, terms binding and Receipt persistence as normative protocol behavior.
|
|
87
|
+
|
|
88
|
+
The [re-signing discussion](https://github.com/google-agentic-commerce/AP2/issues/346#issuecomment-6614173999) motivates stable merchant-scoped occurrences. AP2 still defines transaction_id from the Checkout JWT and Receipt reference from exact Closed bytes. Official SDK optional expected-Checkout bindings and hidden-constraint discussions do not relax this SDK’s existing strict verification. This local helper is application coordination around those cryptographic facts, not a new AP2 protocol or generic conformance/external exactly-once claim.
|
data/docs/PAYMENT_POLICY.md
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
# PISP and execution-date Payment constraints (
|
|
1
|
+
# PISP and execution-date Payment constraints (published1.4.0)
|
|
2
2
|
|
|
3
3
|
New explicit complete/selective Payment profiles add `payment.allowed_pisps` and `payment.execution_date` without changing the existing1.x defaults. Direct and conditional issuance, presentation, strict verification, selective Checkout/Payment and Payment Receipt references share the existing cryptographic and Host verification paths. This SDK remains framework independent and performs no payment scheduling or execution.
|
|
4
4
|
|
|
@@ -45,7 +45,7 @@ The new profiles require both explicit `pisp` and `execution_date` in Closed and
|
|
|
45
45
|
|
|
46
46
|
The official PISP Schema describes the domain as secured by an eIDAS QWAC certificate. This library does not fetch/validate QWACs, establish legal authorization or authenticate a network endpoint from text. Applications own certificate/channel validation, enrollment, revocation and the provenance/freshness of their trusted PISP input. A syntactically valid domain or valid Mandate signature does not establish those facts.
|
|
47
47
|
|
|
48
|
-
`execution_at` is an independently controlled application execution-plan/operational instant. It must represent the same instant as signed `execution_date`. It is distinct from `verified_at`, which checks signature/Mandate freshness. Future plan verification does not prove that execution occurred or will later occur under that context. At the actual execution gate, the application must recheck the actual provider/time/current approval and a valid Mandate, atomically consume one-use state and reconcile uncertain outcomes. The SDK does not schedule, call a PISP or settle a payment.
|
|
48
|
+
`execution_at` is an independently controlled application execution-plan/operational instant. It must represent the same instant as signed `execution_date`. It is distinct from `verified_at`, which checks signature/Mandate freshness. Future plan verification does not prove that execution occurred or will later occur under that context. The existing maximum600secondMandate lifetime is unchanged; a future execution date does not extend its expiry. At the actual execution gate, the application must recheck the actual provider/time/current approval and a valid Mandate, atomically consume one-use state and reconcile uncertain outcomes. The SDK does not schedule, call a PISP or settle a payment.
|
|
49
49
|
|
|
50
50
|
## Date semantics
|
|
51
51
|
|
|
@@ -68,3 +68,5 @@ Direct Payment uses exact protected `approved_payment`, including PISP and execu
|
|
|
68
68
|
Adopted source remains AP2v0.2.0 `b4587ac1d055888a73b4b21750973cffba961793`: [Payment specification](https://github.com/google-agentic-commerce/AP2/blob/b4587ac1d055888a73b4b21750973cffba961793/docs/ap2/payment_mandate.md), [Open Schema](https://github.com/google-agentic-commerce/AP2/blob/b4587ac1d055888a73b4b21750973cffba961793/code/sdk/schemas/ap2/open_payment_mandate.json), [PISP Schema](https://github.com/google-agentic-commerce/AP2/blob/b4587ac1d055888a73b4b21750973cffba961793/code/sdk/schemas/ap2/types/pisp.json).
|
|
69
69
|
|
|
70
70
|
The normative text requires inclusive execution bounds. Schema permits weakly typed strings; it does not itself enforce this strict timestamp subset. The pinned Python evaluator compares date strings lexically and permits absent dates even with a date constraint. Its PISP evaluator does compare all three identity fields. Ruby’s parsed/context-bound behavior is an explicit safer supported subset, not an unqualified claim that all official high-level helpers behave identically. Source interoperability observed three lifecycle cases in each direction (Direct/complete conditional/selective conditional), twelve Receipt checks and62 negatives, plus six explicitly recorded upstream date-check disagreements. Separate positive variants cover PISP-only/date-only/one-sided constraints. Exact signed-wire hashes and actual runtime provenance are recorded with the candidate; supported claims do not extend to QWAC provenance, execution or generic AP2 conformance.
|
|
71
|
+
|
|
72
|
+
[Verified public artifact, tag and Release](POST_RELEASE_140.md). The original candidate preparation is retained as [historical evidence](RELEASE_140_CANDIDATE.md).
|
data/docs/PUBLIC_API.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# Ruby SDK public API — 1.x
|
|
2
2
|
|
|
3
|
-
**Status: published 1.
|
|
3
|
+
**Status: published 1.4.0; the original 1.0.0 Checkout contract below is preserved.**
|
|
4
4
|
This document defines the 1.x contract for the existing Checkout APIs.
|
|
5
5
|
The 1.0.0 release preserves the 0.8.0 runtime behavior, API names and accepted
|
|
6
6
|
formats. Exact distribution identity and validation are in
|
|
@@ -212,6 +212,12 @@ The additive `SelectiveCheckout` profile is available in published 1.3.0. See th
|
|
|
212
212
|
|
|
213
213
|
For the explicit selective Checkout profile, Evidence `original_root_graph_closure` records that every signed commitment and supplied disclosure was inspected and accounted for, allowing unresolved candidate leaves only at registered positions. It does not certify hidden preimages, their schema or uniqueness, or consent provenance. The checked scope covers the visible candidate subset and all mandatory conditions.
|
|
214
214
|
|
|
215
|
-
##
|
|
215
|
+
## Published1.4.0: explicit Payment policy profiles
|
|
216
216
|
|
|
217
217
|
`PaymentPolicy::PROFILE_REF` and `SELECTIVE_PROFILE_REF` opt into PISP/execution constraints in existing `Payment`, `SelectivePayment` and `PaymentReceipt` APIs via `profile_ref:`. Verification additionally requires independently trusted `trusted_pisp:` and `execution_at:`; missing context is never filled from claims. New Open issuance requires `candidate_policy: :independent`. Both new fields are mandatory in Closed, even when only one new Open constraint is used. See [strict parsing, condition stages, API additions and official limitations](PAYMENT_POLICY.md). Old defaults, grammar and result meanings remain unchanged. No scheduler/payment execution is added.
|
|
218
|
+
|
|
219
|
+
## 1.5.0 candidate: application-side Payment acceptance
|
|
220
|
+
|
|
221
|
+
`PaymentAcceptance::Service` takes a transactional `store:` adapter. `accept` invokes existing raw verifiers then atomically checks an enrolled protected occurrence and reserves it; `start` requires fresh raw verification and exact first signed wires before fenced CAS. `finish`, `unknown`, `lookup` and `reconcile` retain first-wire/Receipt/processor-key bindings and never automatically release or reissue a Ticket. No existing verifier result is reinterpreted as Host ALLOW.
|
|
222
|
+
|
|
223
|
+
`SQLiteStore.create(path:)` explicitly initializes once; `new(path:)` opens an existing supported database and requires optional `sqlite3 = 2.10.2`. Base runtime dependencies remain unchanged. `authorize!` and `revoke!` are protected Host operations, never request-derived approval flags. See [all parameters, states, adapter guarantees, supported reuse and recovery limits](PAYMENT_ACCEPTANCE.md).
|
|
@@ -1,5 +1,7 @@
|
|
|
1
1
|
# 1.4.0 candidate preparation
|
|
2
2
|
|
|
3
|
+
**Historical prepublication record.1.4.0 is now public; see [verified publication](POST_RELEASE_140.md). Do not repeat its push or substitute a rebuilt artifact.**
|
|
4
|
+
|
|
3
5
|
Status: release candidate preparation. Final exact-source/package/CI evidence and GO/HOLD recommendation are recorded in the PR and external manifest after verification. RubyGems publication, formalv1.4.0 tag, GitHub Release, announcements, deployment and real payment remain HOLD for Owner decision.
|
|
4
6
|
|
|
5
7
|
## Proposed notes
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
# 1.5.0 release candidate preparation
|
|
2
|
+
|
|
3
|
+
Release candidate preparation; final exact-source/artifact/review/CI evidence is recorded in the PR and external manifest. RubyGems/public tag/GitHub Release/production connection/real payment remain HOLD pending Owner decision.
|
|
4
|
+
|
|
5
|
+
## Proposed notes and main use
|
|
6
|
+
|
|
7
|
+
1.5 adds opt-in transactional Payment acceptance: enroll a protected business occurrence, verify raw Mandates, reserve atomically, reverify before one fenced start and reconcile the original Receipt after uncertain outcomes. Re-signing does not create a new operation. Separately authorized new occurrences are supported without globally consuming every Open Mandate. Existing1.x verifier APIs/results and base runtime dependencies remain unchanged; SQLite reference persistence uses an optional pinned driver.
|
|
8
|
+
|
|
9
|
+
```ruby
|
|
10
|
+
accepted = service.accept(**trusted_scope, mode: :conditional, verification_inputs: raw_inputs)
|
|
11
|
+
dispatch = service.start(ticket: accepted.ticket, verification_inputs: fresh_inputs) if accepted.ticket
|
|
12
|
+
# Application-owned processor call reuses dispatch.processor_key; no SDK payment call.
|
|
13
|
+
```
|
|
14
|
+
|
|
15
|
+
State reservation, verification and settlement are distinct. No automatic release/takeover after timeout, Error Receipt, worker crash or response loss. Stable Host identity, protected enrollment, one authoritative durable store and processor lookup/idempotency remain application requirements. Receipt authenticity is not proof of settlement. Custom adapters need their own atomicity/durability tests.
|
|
16
|
+
|
|
17
|
+
## Final gates and publication procedure
|
|
18
|
+
|
|
19
|
+
Full supported MRI3.4.12/4.0.9 regressions; optional-driver absence isolation; source/installed acceptance tests; independent multi-process barrier/external counter/SIGKILL/restart and re-sign/new-occurrence controls; schema/commit/Receipt/expiry/privacy negatives; exact-HEAD independent review with zero unresolved P1/P2; Draft-first PRs, successful CI and verified merged-tree equality; candidate package metadata and every source/archive/installed file identical. Fixed builder/source-date epoch must reproduce the same archive; both MRIs install that one archive. Evidence/checksum remain outside their own package.
|
|
20
|
+
|
|
21
|
+
Only after Owner approves an exact candidate may publication begin. Recheck registry absence/source/bytes/review/CI; no blind retry of uncertain writes. Verify downloaded published bytes before formal tag/Release. No publication or deployment CI trigger may be added.
|
data/docs/SUPPORT_CONTRACT.md
CHANGED
|
@@ -1,6 +1,10 @@
|
|
|
1
1
|
# AP2 Checkout Ruby SDK — support contract and history
|
|
2
2
|
|
|
3
|
-
## Current
|
|
3
|
+
## Current published and candidate scope
|
|
4
|
+
|
|
5
|
+
Published stable is1.4.0: [verified publication](POST_RELEASE_140.md). The1.5.0 candidate adds opt-in [transactional Payment acceptance](PAYMENT_ACCEPTANCE.md) while preserving all existing1.x verifier APIs, defaults and stored formats. The SQLite reference adapter additionally requires optional pinned driver2.10.2 and a protected local persistent filesystem; other adapters require their own atomicity/durability validation. No new external exactly-once or production authorization guarantee is made. Final1.5 publication remains Owner-held.
|
|
6
|
+
|
|
7
|
+
## Historical1.0.0 baseline contract
|
|
4
8
|
|
|
5
9
|
**Published stable is 1.0.0.** It preserves the 0.8.0 product implementation and
|
|
6
10
|
acceptance contracts. The stable 1.x public surface is catalogued in
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
# Installed SDK; optional sqlite3=2.10.2. Synthetic temporary DB/mock processor.
|
|
3
|
+
# Production uses a protected persistent existing DB, never per-request temp storage.
|
|
4
|
+
require "ap2_mandate_verifier"
|
|
5
|
+
require "tmpdir"
|
|
6
|
+
require_relative "selective_checkout"
|
|
7
|
+
module PaymentAcceptanceExample
|
|
8
|
+
M = AP2MandateVerifier
|
|
9
|
+
A = M::PaymentAcceptance
|
|
10
|
+
NOW = SelectiveCheckoutExample::NOW
|
|
11
|
+
def self.run
|
|
12
|
+
state = SelectiveCheckoutExample.run
|
|
13
|
+
provider, agent, merchant = state.fetch(:keys)
|
|
14
|
+
signer = ->(key) { M::CheckoutJWT.es256_signer(private_key: key) }
|
|
15
|
+
checkout = state.fetch(:closed).checkout_jwt
|
|
16
|
+
details = M::Payment.details(checkout_jwt: checkout, trusted_merchant_public_key_pem: merchant.public_to_pem,
|
|
17
|
+
expected_merchant_id: "shop", payment_instrument: {"id" => "synthetic-card", "type" => "card"})
|
|
18
|
+
buyer = M::Buyer.issue_closed(checkout_jwt: checkout, approved_checkout_jwt: checkout,
|
|
19
|
+
trusted_merchant_public_key_pem: merchant.public_to_pem, expected_merchant_id: "shop", issued_at: NOW,
|
|
20
|
+
expires_at: NOW + 60, signer: signer.call(provider), public_key_pem: provider.public_to_pem)
|
|
21
|
+
payment_args = {payment: details, approved_payment: details, issued_at: NOW, expires_at: NOW + 60,
|
|
22
|
+
signer: signer.call(provider), public_key_pem: provider.public_to_pem}
|
|
23
|
+
payment = M::Payment.issue_direct(**payment_args)
|
|
24
|
+
raw = {closed_sd_jwt: payment.closed_sd_jwt, checkout_mode: :direct, checkout_inputs: {
|
|
25
|
+
closed_sd_jwt: buyer.closed_sd_jwt, trusted_provider_public_key_pem: provider.public_to_pem,
|
|
26
|
+
trusted_merchant_public_key_pem: merchant.public_to_pem, expected_checkout_jwt: checkout,
|
|
27
|
+
expected_merchant_id: "shop", verified_at: NOW}, expected_payment: details,
|
|
28
|
+
trusted_provider_public_key_pem: provider.public_to_pem, verified_at: NOW}
|
|
29
|
+
# These identifiers/terms are protected authenticated Host approval state,
|
|
30
|
+
# never request-generated retry UUIDs or values copied from received claims.
|
|
31
|
+
scope = {tenant_id: "tenant", merchant_id: "shop", operation_id: "office-1/payment-1",
|
|
32
|
+
approval_id: "synthetic-consent-1", occurrence_id: "payment-1", order_id: "office-1"}
|
|
33
|
+
Dir.mktmpdir("ap2-acceptance-example") do |directory|
|
|
34
|
+
path = File.join(directory, "acceptance.sqlite3")
|
|
35
|
+
store = A::SQLiteStore.create(path: path) # Explicit ONE-TIME bootstrap only.
|
|
36
|
+
store.authorize!(**scope, mode: :direct, profile_ref: M::Payment::PROFILE_REF,
|
|
37
|
+
checkout: state.fetch(:checkout), payment: details, receipt_context: {
|
|
38
|
+
trusted_public_key_pem: merchant.public_to_pem, expected_issuer: "processor-A",
|
|
39
|
+
expected_payment_id: "synthetic-payment-1", not_before: NOW, not_after: NOW + 1000})
|
|
40
|
+
service = A::Service.new(store: store)
|
|
41
|
+
first = service.accept(**scope, mode: :direct, verification_inputs: raw)
|
|
42
|
+
raise "first reservation failed" unless first.status == :reserved && first.ticket
|
|
43
|
+
# New salt/signature changes original bytes, but not the approved business operation.
|
|
44
|
+
resigned = M::Payment.issue_direct(**payment_args)
|
|
45
|
+
replay = service.accept(**scope, mode: :direct, verification_inputs: raw.merge(closed_sd_jwt: resigned.closed_sd_jwt))
|
|
46
|
+
raise "retry issued another ticket" unless replay.status == :pending && replay.ticket.nil? &&
|
|
47
|
+
replay.closed_sd_jwt == payment.closed_sd_jwt && replay.processor_key == first.processor_key
|
|
48
|
+
puts "First=reserved; re-signed retry=pending; no second Ticket; first wire retained"
|
|
49
|
+
# Production supplies FRESH authenticated Host/trust/order/clock inputs here.
|
|
50
|
+
execution = service.start(ticket: first.ticket, verification_inputs: raw)
|
|
51
|
+
raise "start failed" unless execution && !service.start(ticket: first.ticket, verification_inputs: raw)
|
|
52
|
+
mock_processor = {} # This counter is a demo side effect, not real money.
|
|
53
|
+
mock_processor[execution.processor_key] ||= "synthetic-processor-result"
|
|
54
|
+
service.unknown(ticket: first.ticket) # Simulated response loss after dispatch.
|
|
55
|
+
store.close
|
|
56
|
+
# New process/service opens the SAME existing ledger. No create/reset fallback.
|
|
57
|
+
reopened = A::SQLiteStore.new(path: path)
|
|
58
|
+
recovered = A::Service.new(store: reopened)
|
|
59
|
+
pending = recovered.lookup(**scope)
|
|
60
|
+
raise "unknown attempt reopened" unless pending.status == :unknown && pending.ticket.nil? &&
|
|
61
|
+
pending.processor_key == execution.processor_key
|
|
62
|
+
puts "After reopen=unknown; original processor key available for QUERY; mock dispatches=#{mock_processor.size}"
|
|
63
|
+
# Delayed authentic Receipt can resolve an unknown attempt after Mandate expiry.
|
|
64
|
+
receipt = M::PaymentReceipt.sign(closed_sd_jwt: execution.closed_sd_jwt, issuer: "processor-A",
|
|
65
|
+
payment_id: "synthetic-payment-1", outcome: "Success", issued_at: NOW + 120,
|
|
66
|
+
psp_confirmation_id: "synthetic-psp", network_confirmation_id: "synthetic-network",
|
|
67
|
+
signer: signer.call(merchant), public_key_pem: merchant.public_to_pem)
|
|
68
|
+
final = recovered.reconcile(**scope, receipt_jwt: receipt.jwt, verified_at: NOW + 120)
|
|
69
|
+
raise "Receipt recovery failed" unless final.status == :receipt_success && final.ticket.nil? &&
|
|
70
|
+
final.reference == first.reference
|
|
71
|
+
puts "Delayed original-wire Receipt=receipt_success; reconciliation grants no Ticket"
|
|
72
|
+
reopened.close
|
|
73
|
+
end
|
|
74
|
+
puts "Synthetic temporary demo only. Durable reservation is not settlement or external exactly-once; no payment performed."
|
|
75
|
+
end
|
|
76
|
+
end
|
|
77
|
+
PaymentAcceptanceExample.run if $PROGRAM_NAME == __FILE__
|
|
@@ -0,0 +1,316 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AP2MandateVerifier
|
|
4
|
+
module PaymentAcceptance
|
|
5
|
+
# Optional local durable reference. Production adapters must preserve the
|
|
6
|
+
# same protected-authorization + claim transaction and CAS guarantees.
|
|
7
|
+
class SQLiteStore
|
|
8
|
+
DRIVER_VERSION = "2.10.2".freeze
|
|
9
|
+
RECEIPT_FIELDS = %w[trusted_public_key_pem expected_issuer expected_payment_id not_before not_after].freeze
|
|
10
|
+
SCHEMA = {
|
|
11
|
+
"ap2_store" => "CREATE TABLE ap2_store (identity TEXT NOT NULL)",
|
|
12
|
+
"ap2_approvals" => "CREATE TABLE ap2_approvals (operation_key TEXT PRIMARY KEY, tenant TEXT NOT NULL, merchant TEXT NOT NULL, approval TEXT NOT NULL, occurrence TEXT NOT NULL, scope TEXT NOT NULL, instruction TEXT NOT NULL, receipt_context TEXT NOT NULL, active INTEGER NOT NULL DEFAULT 1 CHECK(active IN (0,1)), UNIQUE(tenant,merchant,approval,occurrence))",
|
|
13
|
+
"ap2_attempts" => "CREATE TABLE ap2_attempts (operation_key TEXT PRIMARY KEY REFERENCES ap2_approvals(operation_key), tenant TEXT NOT NULL, merchant TEXT NOT NULL, closed_reference TEXT NOT NULL, fence TEXT NOT NULL, state TEXT NOT NULL CHECK(state IN ('reserved','processing','unknown','receipt_success','receipt_error')), record TEXT NOT NULL, UNIQUE(tenant,merchant,closed_reference))"
|
|
14
|
+
}.transform_values(&:freeze).freeze
|
|
15
|
+
def self.create(**arguments)
|
|
16
|
+
raise Unavailable unless arguments.keys == [:path]
|
|
17
|
+
path = arguments.fetch(:path)
|
|
18
|
+
dependencies!
|
|
19
|
+
checked = path!(path)
|
|
20
|
+
File.open(checked, File::WRONLY | File::CREAT | File::EXCL, 0o600) { |f| f.fsync }
|
|
21
|
+
value = allocate
|
|
22
|
+
value.send(:setup!, checked, true)
|
|
23
|
+
value
|
|
24
|
+
rescue StandardError, LoadError
|
|
25
|
+
raise Unavailable.new, cause: nil
|
|
26
|
+
end
|
|
27
|
+
def self.dependencies!
|
|
28
|
+
gem "sqlite3", "= #{DRIVER_VERSION}"
|
|
29
|
+
require "sqlite3"
|
|
30
|
+
raise Unavailable unless Gem.loaded_specs.fetch("sqlite3").version.to_s == DRIVER_VERSION
|
|
31
|
+
end
|
|
32
|
+
def self.path!(path)
|
|
33
|
+
checked = InputValidator.snapshot!(path, max_bytes: 4096)
|
|
34
|
+
raise Invalid if checked.empty? || checked == ":memory:" || checked.include?("\0") || checked.start_with?("file:")
|
|
35
|
+
checked
|
|
36
|
+
end
|
|
37
|
+
private_class_method :dependencies!, :path!
|
|
38
|
+
def initialize(**arguments)
|
|
39
|
+
raise Unavailable unless arguments.keys == [:path]
|
|
40
|
+
setup!(self.class.send(:path!, arguments.fetch(:path)), false)
|
|
41
|
+
rescue StandardError, LoadError
|
|
42
|
+
raise Unavailable.new, cause: nil
|
|
43
|
+
end
|
|
44
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::SQLiteStore>"
|
|
45
|
+
def setup!(path, creating)
|
|
46
|
+
self.class.send(:dependencies!)
|
|
47
|
+
@path = path
|
|
48
|
+
@db = SQLite3::Database.new(@path, flags: SQLite3::Constants::Open::READWRITE)
|
|
49
|
+
@db.busy_timeout = 5000
|
|
50
|
+
unless creating
|
|
51
|
+
raise Unavailable unless @db.get_first_value("PRAGMA user_version") == 1 && @db.execute("PRAGMA quick_check") == [["ok"]]
|
|
52
|
+
expected = SCHEMA.map { |name,sql| ["table", name, name, sql] } +
|
|
53
|
+
[["index", "sqlite_autoindex_ap2_approvals_1", "ap2_approvals", nil],
|
|
54
|
+
["index", "sqlite_autoindex_ap2_approvals_2", "ap2_approvals", nil],
|
|
55
|
+
["index", "sqlite_autoindex_ap2_attempts_1", "ap2_attempts", nil],
|
|
56
|
+
["index", "sqlite_autoindex_ap2_attempts_2", "ap2_attempts", nil]]
|
|
57
|
+
actual = @db.execute("SELECT type,name,tbl_name,sql FROM sqlite_master ORDER BY type,name")
|
|
58
|
+
raise Unavailable unless actual == expected.sort_by { |row| row.first(2) }
|
|
59
|
+
identities = @db.execute("SELECT identity FROM ap2_store")
|
|
60
|
+
raise Unavailable unless identities.size == 1 && identities[0].size == 1
|
|
61
|
+
@store_id = identities[0][0]
|
|
62
|
+
raise Unavailable unless @store_id.instance_of?(String) && @store_id.match?(/\A[0-9a-f]{64}\z/)
|
|
63
|
+
end
|
|
64
|
+
@db.execute("PRAGMA journal_mode=DELETE")
|
|
65
|
+
@db.execute("PRAGMA synchronous=FULL")
|
|
66
|
+
@db.execute("PRAGMA foreign_keys=ON")
|
|
67
|
+
raise Unavailable unless @db.get_first_value("PRAGMA journal_mode") == "delete" &&
|
|
68
|
+
@db.get_first_value("PRAGMA synchronous") == 2 && @db.get_first_value("PRAGMA foreign_keys") == 1
|
|
69
|
+
if creating
|
|
70
|
+
require "securerandom"
|
|
71
|
+
@store_id = SecureRandom.hex(32)
|
|
72
|
+
@db.execute("BEGIN IMMEDIATE")
|
|
73
|
+
@db.execute(SCHEMA.fetch("ap2_store"))
|
|
74
|
+
@db.execute("INSERT INTO ap2_store(identity) VALUES (?)", [@store_id])
|
|
75
|
+
@db.execute(SCHEMA.fetch("ap2_approvals"))
|
|
76
|
+
@db.execute(SCHEMA.fetch("ap2_attempts"))
|
|
77
|
+
@db.execute("PRAGMA user_version=1")
|
|
78
|
+
@db.execute("COMMIT")
|
|
79
|
+
end
|
|
80
|
+
@mutex = Mutex.new
|
|
81
|
+
rescue StandardError, LoadError
|
|
82
|
+
@db&.close rescue nil
|
|
83
|
+
raise Unavailable.new, cause: nil
|
|
84
|
+
end
|
|
85
|
+
private :setup!
|
|
86
|
+
|
|
87
|
+
# Only a protected Host approval backend may enroll this immutable grant.
|
|
88
|
+
# A received ID/flag never enrolls or alters an approved occurrence.
|
|
89
|
+
def authorize!(tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:,
|
|
90
|
+
mode:, profile_ref:, checkout:, payment:, receipt_context:)
|
|
91
|
+
scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id,
|
|
92
|
+
"operation_id" => operation_id, "approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
|
|
93
|
+
profile = PaymentAcceptance.profile!(mode, profile_ref)
|
|
94
|
+
cart = InputBuilder.send(:copy!, checkout)
|
|
95
|
+
raise Invalid unless cart["id"] == scope["order_id"] && cart.dig("merchant", "id") == scope["merchant_id"]
|
|
96
|
+
instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
|
|
97
|
+
context = PaymentAcceptance.copy!(receipt_context).transform_keys(&:to_s)
|
|
98
|
+
raise Invalid unless context.keys.sort == RECEIPT_FIELDS.sort
|
|
99
|
+
RootSignature.public_jwk!(context["trusted_public_key_pem"])
|
|
100
|
+
%w[expected_issuer expected_payment_id].each { |f| CheckoutReceipt.send(:text!, context[f], 512) }
|
|
101
|
+
%w[not_before not_after].each { |f| CheckoutReceipt.send(:epoch!, context[f]) }
|
|
102
|
+
raise Invalid unless context["not_before"] <= context["not_after"]
|
|
103
|
+
row = [PaymentAcceptance.canonical(scope), instruction, PaymentAcceptance.canonical(context)]
|
|
104
|
+
transaction do
|
|
105
|
+
alias_key = @db.get_first_value("SELECT operation_key FROM ap2_approvals WHERE tenant=? AND merchant=? AND approval=? AND occurrence=?",
|
|
106
|
+
scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"))
|
|
107
|
+
raise Conflict if alias_key && alias_key != PaymentAcceptance.key(scope)
|
|
108
|
+
old = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END FROM ap2_approvals WHERE operation_key=?", [PaymentAcceptance.key(scope)])
|
|
109
|
+
check_grant!(old) if old
|
|
110
|
+
raise Conflict if old && old != row
|
|
111
|
+
unless old
|
|
112
|
+
begin
|
|
113
|
+
@db.execute("INSERT INTO ap2_approvals(operation_key,tenant,merchant,approval,occurrence,scope,instruction,receipt_context) VALUES (?,?,?,?,?,?,?,?)",
|
|
114
|
+
[PaymentAcceptance.key(scope), *scope.values_at("tenant_id", "merchant_id", "approval_id", "occurrence_id"), *row])
|
|
115
|
+
rescue SQLite3::ConstraintException
|
|
116
|
+
raise Conflict
|
|
117
|
+
end
|
|
118
|
+
end
|
|
119
|
+
true
|
|
120
|
+
end
|
|
121
|
+
end
|
|
122
|
+
|
|
123
|
+
def reserve!(scope:, instruction:, record:)
|
|
124
|
+
transaction do
|
|
125
|
+
key = PaymentAcceptance.key(scope)
|
|
126
|
+
grant = @db.get_first_row("SELECT CASE WHEN length(CAST(scope AS BLOB))<=131072 THEN scope END,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END,CASE WHEN length(CAST(receipt_context AS BLOB))<=8192 THEN receipt_context END,active FROM ap2_approvals WHERE operation_key=?", [key])
|
|
127
|
+
raise Invalid unless grant
|
|
128
|
+
check_grant!(grant)
|
|
129
|
+
raise Invalid unless grant[3] == 1
|
|
130
|
+
raise Conflict unless grant[0] == PaymentAcceptance.canonical(scope) && grant[1] == instruction
|
|
131
|
+
old = load_record(key)
|
|
132
|
+
if old
|
|
133
|
+
raise Conflict unless old["instruction"] == instruction
|
|
134
|
+
next PaymentAcceptance.result(old)
|
|
135
|
+
end
|
|
136
|
+
reused = @db.get_first_value("SELECT operation_key FROM ap2_attempts WHERE tenant=? AND merchant=? AND closed_reference=?",
|
|
137
|
+
[scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference")])
|
|
138
|
+
raise Conflict if reused
|
|
139
|
+
require "securerandom"
|
|
140
|
+
fence = SecureRandom.hex(32)
|
|
141
|
+
value = record.merge("state" => "reserved", "processor_key" => SecureRandom.hex(32),
|
|
142
|
+
"receipt_context" => decode!(grant[2], 8192))
|
|
143
|
+
raise Invalid if JSON.generate(value).bytesize > 1_048_576
|
|
144
|
+
begin
|
|
145
|
+
@db.execute("INSERT INTO ap2_attempts(operation_key,tenant,merchant,closed_reference,fence,state,record) VALUES (?,?,?,?,?,?,?)",
|
|
146
|
+
[key, scope.fetch("tenant_id"), scope.fetch("merchant_id"), record.fetch("reference"), fence, "reserved", JSON.generate(value)])
|
|
147
|
+
rescue SQLite3::ConstraintException
|
|
148
|
+
raise Conflict
|
|
149
|
+
end
|
|
150
|
+
# Returned only after COMMIT succeeds. A commit error is unavailable,
|
|
151
|
+
# even if SQLite may have persisted the row; no capability is returned.
|
|
152
|
+
Result.send(:new, :reserved, value, Ticket.send(:new, @store_id + key, fence))
|
|
153
|
+
end
|
|
154
|
+
end
|
|
155
|
+
|
|
156
|
+
def start!(ticket:, verified_at:, instruction:, signed_wires:)
|
|
157
|
+
key, fence = ticket_parts!(ticket)
|
|
158
|
+
transaction do
|
|
159
|
+
row = @db.get_first_row("SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
|
|
160
|
+
raise Invalid unless row
|
|
161
|
+
next nil unless row[0] == "reserved"
|
|
162
|
+
record = decode!(row[1], 1_048_576)
|
|
163
|
+
raise Unavailable unless record["state"] == row[0]
|
|
164
|
+
grant = @db.get_first_row("SELECT active,CASE WHEN length(CAST(instruction AS BLOB))<=131072 THEN instruction END FROM ap2_approvals WHERE operation_key=?", [key])
|
|
165
|
+
raise Invalid unless grant && grant[0] == 1 && grant[1] == instruction &&
|
|
166
|
+
record["instruction"] == instruction && record["signed_wires"] == signed_wires
|
|
167
|
+
next nil unless verified_at >= record["accepted_at"] && verified_at < record["valid_until"]
|
|
168
|
+
record["state"] = "processing"
|
|
169
|
+
record["started_at"] = verified_at
|
|
170
|
+
@db.execute("UPDATE ap2_attempts SET state='processing',record=? WHERE operation_key=? AND fence=? AND state='reserved'", [JSON.generate(record), key, fence])
|
|
171
|
+
raise Unavailable unless @db.changes == 1
|
|
172
|
+
record
|
|
173
|
+
end
|
|
174
|
+
end
|
|
175
|
+
|
|
176
|
+
def ticket_record!(ticket:)
|
|
177
|
+
key, fence = ticket_parts!(ticket)
|
|
178
|
+
transaction do
|
|
179
|
+
row = @db.get_first_row("SELECT CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=? AND fence=?", [key, fence])
|
|
180
|
+
raise Invalid unless row
|
|
181
|
+
decode!(row[0], 1_048_576)
|
|
182
|
+
end
|
|
183
|
+
end
|
|
184
|
+
|
|
185
|
+
def lookup_record!(scope:)
|
|
186
|
+
transaction do
|
|
187
|
+
record = load_record(PaymentAcceptance.key(scope))
|
|
188
|
+
raise Conflict if record && record["scope"] != scope
|
|
189
|
+
record
|
|
190
|
+
end
|
|
191
|
+
end
|
|
192
|
+
|
|
193
|
+
def unknown!(ticket:)
|
|
194
|
+
key, fence = ticket_parts!(ticket)
|
|
195
|
+
transaction do
|
|
196
|
+
record = load_record(key, fence)
|
|
197
|
+
raise Invalid unless record
|
|
198
|
+
if record["state"] == "processing"
|
|
199
|
+
record["state"] = "unknown"
|
|
200
|
+
save(key, record)
|
|
201
|
+
elsif record["state"] != "unknown"
|
|
202
|
+
raise Invalid
|
|
203
|
+
end
|
|
204
|
+
PaymentAcceptance.result(record)
|
|
205
|
+
end
|
|
206
|
+
end
|
|
207
|
+
|
|
208
|
+
def finish!(scope:, ticket:, receipt_jwt:, status:)
|
|
209
|
+
raise Invalid unless %w[receipt_success receipt_error].include?(status)
|
|
210
|
+
key = PaymentAcceptance.key(scope)
|
|
211
|
+
fence = ticket_parts!(ticket)[1] if ticket
|
|
212
|
+
raise Invalid if ticket && ticket_parts!(ticket)[0] != key
|
|
213
|
+
transaction do
|
|
214
|
+
record = load_record(key, fence)
|
|
215
|
+
raise Invalid unless record && record["scope"] == scope
|
|
216
|
+
if %w[receipt_success receipt_error].include?(record["state"])
|
|
217
|
+
raise Conflict unless record["receipt_jwt"] == receipt_jwt && record["state"] == status
|
|
218
|
+
else
|
|
219
|
+
raise Invalid unless %w[processing unknown].include?(record["state"])
|
|
220
|
+
record["state"], record["receipt_jwt"] = status, receipt_jwt
|
|
221
|
+
save(key, record)
|
|
222
|
+
end
|
|
223
|
+
PaymentAcceptance.result(record)
|
|
224
|
+
end
|
|
225
|
+
end
|
|
226
|
+
|
|
227
|
+
def close
|
|
228
|
+
@mutex.synchronize { @db.close }
|
|
229
|
+
rescue StandardError
|
|
230
|
+
raise Unavailable.new, cause: nil
|
|
231
|
+
end
|
|
232
|
+
|
|
233
|
+
def revoke!(**scope)
|
|
234
|
+
scope = PaymentAcceptance.scope_keywords!(scope)
|
|
235
|
+
transaction do
|
|
236
|
+
@db.execute("UPDATE ap2_approvals SET active=0 WHERE operation_key=? AND scope=?", [PaymentAcceptance.key(scope), PaymentAcceptance.canonical(scope)])
|
|
237
|
+
raise Invalid unless @db.changes == 1
|
|
238
|
+
true
|
|
239
|
+
end
|
|
240
|
+
end
|
|
241
|
+
|
|
242
|
+
private
|
|
243
|
+
def ticket_parts!(ticket)
|
|
244
|
+
raise Invalid unless ticket.instance_of?(Ticket)
|
|
245
|
+
key = ticket.send(:key)
|
|
246
|
+
raise Invalid unless key.start_with?(@store_id) && key.bytesize == 128
|
|
247
|
+
[key[64,64], ticket.send(:fence)]
|
|
248
|
+
end
|
|
249
|
+
def load_record(key, fence = nil)
|
|
250
|
+
sql = "SELECT state,CASE WHEN length(CAST(record AS BLOB))<=1048576 THEN record ELSE NULL END FROM ap2_attempts WHERE operation_key=?"
|
|
251
|
+
args = [key]
|
|
252
|
+
if fence
|
|
253
|
+
sql += " AND fence=?"; args << fence
|
|
254
|
+
end
|
|
255
|
+
row = @db.get_first_row(sql, args)
|
|
256
|
+
if row
|
|
257
|
+
record = decode!(row[1], 1_048_576)
|
|
258
|
+
raise Unavailable unless record["state"] == row[0]
|
|
259
|
+
record
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
def save(key, record)
|
|
263
|
+
raise Unavailable if JSON.generate(record).bytesize > 1_048_576
|
|
264
|
+
@db.execute("UPDATE ap2_attempts SET state=?,record=? WHERE operation_key=?", [record.fetch("state"), JSON.generate(record), key])
|
|
265
|
+
raise Unavailable unless @db.changes == 1
|
|
266
|
+
end
|
|
267
|
+
def check_grant!(row)
|
|
268
|
+
[131_072,131_072,8192].each_with_index { |limit,i| InputValidator.snapshot!(row[i], max_bytes: limit) }
|
|
269
|
+
end
|
|
270
|
+
def decode!(source, max)
|
|
271
|
+
wire = InputValidator.snapshot!(source, max_bytes: max)
|
|
272
|
+
InputValidator.send(:reject_extensions!, wire)
|
|
273
|
+
raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
|
|
274
|
+
JSON.parse(wire, create_additions: false, symbolize_names: false, max_nesting: 24,
|
|
275
|
+
allow_nan: false, allow_duplicate_key: false, allow_trailing_comma: false)
|
|
276
|
+
rescue StandardError
|
|
277
|
+
raise Unavailable.new, cause: nil
|
|
278
|
+
end
|
|
279
|
+
def transaction
|
|
280
|
+
@mutex.synchronize do
|
|
281
|
+
@db.execute("BEGIN IMMEDIATE")
|
|
282
|
+
begin
|
|
283
|
+
value = yield
|
|
284
|
+
@db.execute("COMMIT")
|
|
285
|
+
value
|
|
286
|
+
rescue StandardError
|
|
287
|
+
@db.execute("ROLLBACK") rescue nil
|
|
288
|
+
raise
|
|
289
|
+
end
|
|
290
|
+
end
|
|
291
|
+
rescue Invalid, Conflict
|
|
292
|
+
raise
|
|
293
|
+
rescue StandardError
|
|
294
|
+
raise Unavailable.new, cause: nil
|
|
295
|
+
end
|
|
296
|
+
|
|
297
|
+
%i[authorize! reserve! start! ticket_record! lookup_record! unknown! finish! close revoke!].each do |name|
|
|
298
|
+
implementation = instance_method(name)
|
|
299
|
+
required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
|
|
300
|
+
allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
|
|
301
|
+
rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
|
|
302
|
+
define_method(name) do |**arguments|
|
|
303
|
+
raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
|
|
304
|
+
implementation.bind_call(self, **arguments)
|
|
305
|
+
rescue Conflict
|
|
306
|
+
raise Conflict.new("payment acceptance conflict"), cause: nil
|
|
307
|
+
rescue Unavailable
|
|
308
|
+
raise Unavailable.new, cause: nil
|
|
309
|
+
rescue StandardError, LoadError
|
|
310
|
+
raise Invalid.new, cause: nil
|
|
311
|
+
end
|
|
312
|
+
public name
|
|
313
|
+
end
|
|
314
|
+
end
|
|
315
|
+
end
|
|
316
|
+
end
|
|
@@ -0,0 +1,263 @@
|
|
|
1
|
+
# frozen_string_literal: true
|
|
2
|
+
|
|
3
|
+
module AP2MandateVerifier
|
|
4
|
+
# Application-side single-attempt coordination, not a PSP execution engine.
|
|
5
|
+
module PaymentAcceptance
|
|
6
|
+
SCOPE = %w[tenant_id merchant_id operation_id approval_id occurrence_id order_id].freeze
|
|
7
|
+
class Invalid < ArgumentError
|
|
8
|
+
def initialize = super("invalid payment acceptance information")
|
|
9
|
+
end
|
|
10
|
+
class Unavailable < StandardError
|
|
11
|
+
def initialize = super("payment acceptance storage unavailable")
|
|
12
|
+
end
|
|
13
|
+
class Conflict < StandardError; end
|
|
14
|
+
|
|
15
|
+
class Ticket
|
|
16
|
+
def initialize(key, fence)
|
|
17
|
+
@key, @fence = key.freeze, fence.freeze
|
|
18
|
+
freeze
|
|
19
|
+
end
|
|
20
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Ticket>"
|
|
21
|
+
private
|
|
22
|
+
attr_reader :key, :fence
|
|
23
|
+
private_class_method :new
|
|
24
|
+
end
|
|
25
|
+
class Result
|
|
26
|
+
attr_reader :status, :ticket, :closed_sd_jwt, :reference, :receipt_jwt, :processor_key, :signed_wires
|
|
27
|
+
def initialize(status, record = nil, ticket = nil)
|
|
28
|
+
@status, @ticket = status, ticket
|
|
29
|
+
if record
|
|
30
|
+
@closed_sd_jwt, @reference, @receipt_jwt = record.values_at("closed_sd_jwt", "reference", "receipt_jwt").map { |v| v&.freeze }
|
|
31
|
+
@processor_key = record.fetch("processor_key").freeze
|
|
32
|
+
@signed_wires = ResearchEvidence.send(:copy_frozen, record.fetch("signed_wires"))
|
|
33
|
+
end
|
|
34
|
+
freeze
|
|
35
|
+
end
|
|
36
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Result status=#{status}>"
|
|
37
|
+
private_class_method :new
|
|
38
|
+
end
|
|
39
|
+
class Execution
|
|
40
|
+
attr_reader :processor_key, :closed_sd_jwt, :reference, :payment
|
|
41
|
+
def initialize(record)
|
|
42
|
+
@processor_key, @closed_sd_jwt, @reference = record.values_at("processor_key", "closed_sd_jwt", "reference").map(&:freeze)
|
|
43
|
+
@payment = ResearchEvidence.send(:copy_frozen, record.fetch("payment"))
|
|
44
|
+
freeze
|
|
45
|
+
end
|
|
46
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Execution>"
|
|
47
|
+
private_class_method :new
|
|
48
|
+
end
|
|
49
|
+
|
|
50
|
+
class Service
|
|
51
|
+
def initialize(**arguments)
|
|
52
|
+
raise Invalid.new, cause: nil unless arguments.keys == [:store]
|
|
53
|
+
@store = arguments.fetch(:store)
|
|
54
|
+
end
|
|
55
|
+
def inspect = "#<AP2MandateVerifier::PaymentAcceptance::Service>"
|
|
56
|
+
# Every call starts from raw verifier inputs, never a caller-made proof.
|
|
57
|
+
def accept(mode:, verification_inputs:, tenant_id:, merchant_id:, operation_id:, approval_id:, occurrence_id:, order_id:)
|
|
58
|
+
scope = PaymentAcceptance.scope!({"tenant_id" => tenant_id, "merchant_id" => merchant_id, "operation_id" => operation_id,
|
|
59
|
+
"approval_id" => approval_id, "occurrence_id" => occurrence_id, "order_id" => order_id})
|
|
60
|
+
record = verified_record(mode, verification_inputs, scope)
|
|
61
|
+
@store.reserve!(scope: scope, instruction: record.fetch("instruction"), record: record)
|
|
62
|
+
rescue Conflict
|
|
63
|
+
Result.send(:new, :conflict)
|
|
64
|
+
rescue Unavailable
|
|
65
|
+
Result.send(:new, :unavailable)
|
|
66
|
+
rescue StandardError, LoadError
|
|
67
|
+
Result.send(:new, :rejected)
|
|
68
|
+
end
|
|
69
|
+
|
|
70
|
+
def start(ticket:, verification_inputs:)
|
|
71
|
+
old = @store.ticket_record!(ticket: ticket)
|
|
72
|
+
fresh = verified_record(old.fetch("mode").to_sym, verification_inputs, old.fetch("scope"))
|
|
73
|
+
raise Invalid unless old.fetch("instruction") == fresh.fetch("instruction") && old.fetch("signed_wires") == fresh.fetch("signed_wires")
|
|
74
|
+
record = @store.start!(ticket: ticket, verified_at: fresh.fetch("accepted_at"),
|
|
75
|
+
instruction: fresh.fetch("instruction"), signed_wires: fresh.fetch("signed_wires"))
|
|
76
|
+
Execution.send(:new, record) if record
|
|
77
|
+
rescue StandardError, LoadError
|
|
78
|
+
nil # An uncertain commit NEVER produces an execution handle.
|
|
79
|
+
end
|
|
80
|
+
|
|
81
|
+
private
|
|
82
|
+
def verified_record(mode, verification_inputs, scope)
|
|
83
|
+
args = PaymentAcceptance.copy!(verification_inputs)
|
|
84
|
+
raise Invalid unless args.instance_of?(Hash)
|
|
85
|
+
profile = PaymentAcceptance.profile!(mode, args.fetch(:profile_ref, mode == :selective ? SelectivePayment::PROFILE_REF : Payment::PROFILE_REF))
|
|
86
|
+
result = case mode
|
|
87
|
+
when :direct, :conditional
|
|
88
|
+
raise Invalid unless args[:checkout_mode] == mode
|
|
89
|
+
Payment.verify(**args)
|
|
90
|
+
when :selective then SelectivePayment.verify(**args)
|
|
91
|
+
else raise Invalid
|
|
92
|
+
end
|
|
93
|
+
raise Invalid unless result.verified?
|
|
94
|
+
checkout_args = args.fetch(:checkout_inputs)
|
|
95
|
+
if mode == :direct
|
|
96
|
+
checkout = Buyer.verify(**checkout_args)
|
|
97
|
+
raise Invalid unless checkout.verified?
|
|
98
|
+
cart = checkout.checkout
|
|
99
|
+
valid_until = [checkout.expires_at, result.expires_at].min
|
|
100
|
+
else
|
|
101
|
+
checkout = AP2MandateVerifier.verify_checkout(**checkout_args)
|
|
102
|
+
raise Invalid unless checkout.success?
|
|
103
|
+
raise Invalid unless checkout.evidence["checkout_binding"].fetch("tenant_id") == scope["tenant_id"]
|
|
104
|
+
cart = Payment.send(:jwt_payload!, checkout_args.fetch(:host_checkout_jws), "JWT")
|
|
105
|
+
valid_until = [checkout.evidence["valid_until"], result.expires_at].min
|
|
106
|
+
end
|
|
107
|
+
raise Invalid unless cart.fetch("id") == scope["order_id"] && cart.fetch("merchant").fetch("id") == scope["merchant_id"]
|
|
108
|
+
payment = result.payment.slice(*PaymentPolicy.fields(profile))
|
|
109
|
+
instruction = PaymentAcceptance.instruction!(mode, profile, cart, payment)
|
|
110
|
+
closed = InputValidator.snapshot!(args.fetch(:closed_sd_jwt), max_bytes: 32_769)
|
|
111
|
+
checkout_wires = if mode == :direct
|
|
112
|
+
checkout_args.slice(:closed_sd_jwt, :expected_checkout_jwt)
|
|
113
|
+
else
|
|
114
|
+
checkout_args.slice(:root_presentation, :terminal_jws, :host_checkout_jws)
|
|
115
|
+
end
|
|
116
|
+
{"scope" => scope, "mode" => mode.to_s, "profile_ref" => profile, "instruction" => instruction,
|
|
117
|
+
"payment" => result.payment, "closed_sd_jwt" => closed, "reference" => result.reference,
|
|
118
|
+
"signed_wires" => {"payment" => args.slice(:open_sd_jwt, :open_presentation, :closed_sd_jwt).transform_keys(&:to_s),
|
|
119
|
+
"checkout" => checkout_wires.transform_keys(&:to_s)},
|
|
120
|
+
"accepted_at" => args.fetch(:verified_at), "valid_until" => valid_until}
|
|
121
|
+
end
|
|
122
|
+
public
|
|
123
|
+
|
|
124
|
+
def finish(ticket:, receipt_jwt:, verified_at:)
|
|
125
|
+
record = @store.ticket_record!(ticket: ticket)
|
|
126
|
+
finalize(record, receipt_jwt, verified_at, ticket)
|
|
127
|
+
rescue Conflict
|
|
128
|
+
Result.send(:new, :conflict)
|
|
129
|
+
rescue Unavailable
|
|
130
|
+
Result.send(:new, :unavailable)
|
|
131
|
+
rescue StandardError, LoadError
|
|
132
|
+
Result.send(:new, :rejected)
|
|
133
|
+
end
|
|
134
|
+
|
|
135
|
+
def unknown(ticket:)
|
|
136
|
+
@store.unknown!(ticket: ticket)
|
|
137
|
+
rescue Unavailable
|
|
138
|
+
Result.send(:new, :unavailable)
|
|
139
|
+
rescue StandardError
|
|
140
|
+
Result.send(:new, :rejected)
|
|
141
|
+
end
|
|
142
|
+
|
|
143
|
+
# Receipt reconciliation can finalize an uncertain attempt but cannot
|
|
144
|
+
# recover its fence, reserve it again, or grant another execution handle.
|
|
145
|
+
def reconcile(receipt_jwt:, verified_at:, **scope)
|
|
146
|
+
record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
|
|
147
|
+
raise Invalid unless record
|
|
148
|
+
finalize(record, receipt_jwt, verified_at, nil)
|
|
149
|
+
rescue Conflict
|
|
150
|
+
Result.send(:new, :conflict)
|
|
151
|
+
rescue Unavailable
|
|
152
|
+
Result.send(:new, :unavailable)
|
|
153
|
+
rescue StandardError, LoadError
|
|
154
|
+
Result.send(:new, :rejected)
|
|
155
|
+
end
|
|
156
|
+
|
|
157
|
+
def lookup(**scope)
|
|
158
|
+
record = @store.lookup_record!(scope: PaymentAcceptance.scope_keywords!(scope))
|
|
159
|
+
record ? PaymentAcceptance.result(record) : Result.send(:new, :rejected)
|
|
160
|
+
rescue Unavailable
|
|
161
|
+
Result.send(:new, :unavailable)
|
|
162
|
+
rescue StandardError
|
|
163
|
+
Result.send(:new, :rejected)
|
|
164
|
+
end
|
|
165
|
+
|
|
166
|
+
private
|
|
167
|
+
def finalize(record, receipt_jwt, verified_at, ticket)
|
|
168
|
+
jwt = InputValidator.snapshot!(receipt_jwt, max_bytes: 16_384)
|
|
169
|
+
context = record.fetch("receipt_context").transform_keys(&:to_sym)
|
|
170
|
+
raise Invalid unless record.key?("started_at")
|
|
171
|
+
context[:not_before] = [context.fetch(:not_before), record.fetch("started_at")].max
|
|
172
|
+
receipt = PaymentReceipt.verify(jwt: jwt, closed_sd_jwt: record.fetch("closed_sd_jwt"),
|
|
173
|
+
profile_ref: record.fetch("profile_ref") == SelectivePayment::PROFILE_REF ? Payment::PROFILE_REF : record.fetch("profile_ref"),
|
|
174
|
+
verified_at: verified_at, **context)
|
|
175
|
+
raise Invalid unless receipt.verified?
|
|
176
|
+
status = receipt.payment_succeeded? ? "receipt_success" : "receipt_error"
|
|
177
|
+
@store.finish!(scope: record.fetch("scope"), ticket: ticket, receipt_jwt: jwt, status: status)
|
|
178
|
+
end
|
|
179
|
+
|
|
180
|
+
%i[accept start finish unknown reconcile lookup].each do |name|
|
|
181
|
+
implementation = instance_method(name)
|
|
182
|
+
required = implementation.parameters.filter_map { |kind, key| key if kind == :keyreq }.freeze
|
|
183
|
+
allowed = implementation.parameters.filter_map { |kind, key| key if %i[keyreq key].include?(kind) }.freeze
|
|
184
|
+
rest = implementation.parameters.any? { |kind,_| kind == :keyrest }
|
|
185
|
+
define_method(name) do |**arguments|
|
|
186
|
+
raise Invalid unless (required - arguments.keys).empty? && (rest || (arguments.keys - allowed).empty?)
|
|
187
|
+
implementation.bind_call(self, **arguments)
|
|
188
|
+
rescue StandardError, LoadError
|
|
189
|
+
name == :start ? nil : Result.send(:new, :rejected)
|
|
190
|
+
end
|
|
191
|
+
public name
|
|
192
|
+
end
|
|
193
|
+
end
|
|
194
|
+
|
|
195
|
+
def self.scope!(value)
|
|
196
|
+
scope = copy!(value)
|
|
197
|
+
raise Invalid unless scope.instance_of?(Hash) && scope.keys.sort == SCOPE.sort
|
|
198
|
+
scope.each_value { |v| CheckoutReceipt.send(:text!, v, 256) }
|
|
199
|
+
ResearchEvidence.send(:copy_frozen, scope)
|
|
200
|
+
end
|
|
201
|
+
def self.scope_keywords!(value)
|
|
202
|
+
scope!(copy!(value).transform_keys { |key| key.instance_of?(Symbol) ? key.to_s : key })
|
|
203
|
+
end
|
|
204
|
+
def self.profile!(mode, value)
|
|
205
|
+
raise Invalid unless %i[direct conditional selective].include?(mode)
|
|
206
|
+
PaymentPolicy.profile!(value, selective: mode == :selective)
|
|
207
|
+
end
|
|
208
|
+
def self.instruction!(mode, profile, checkout, payment)
|
|
209
|
+
cart = InputBuilder.send(:copy!, checkout)
|
|
210
|
+
ScopedConstraints.multi_checkout!(cart)
|
|
211
|
+
details = Payment.send(:copy_details!, payment, profile_ref: profile)
|
|
212
|
+
terms = details.reject { |k,_| k == "transaction_id" }
|
|
213
|
+
if terms.key?("execution_date")
|
|
214
|
+
instant = PaymentPolicy.instant!(terms["execution_date"])
|
|
215
|
+
terms["execution_date"] = {"numerator" => instant.numerator, "denominator" => instant.denominator}
|
|
216
|
+
end
|
|
217
|
+
canonical({"mode" => mode.to_s, "profile_ref" => profile, "checkout" => cart, "payment" => terms})
|
|
218
|
+
end
|
|
219
|
+
def self.key(scope)
|
|
220
|
+
digest(canonical(scope.slice("tenant_id", "merchant_id", "operation_id")))
|
|
221
|
+
end
|
|
222
|
+
def self.canonical(value)
|
|
223
|
+
require "json"
|
|
224
|
+
raise Unavailable unless JSON::VERSION == InputValidator::JSON_VERSION
|
|
225
|
+
normalized = case value
|
|
226
|
+
when Hash then value.keys.sort.to_h { |k| [k, JSON.parse(canonical(value[k]))] }
|
|
227
|
+
when Array then value.map { |v| JSON.parse(canonical(v)) }
|
|
228
|
+
else value
|
|
229
|
+
end
|
|
230
|
+
JSON.generate(normalized)
|
|
231
|
+
end
|
|
232
|
+
def self.digest(value) = Digest::SHA256.hexdigest(value)
|
|
233
|
+
def self.result(record)
|
|
234
|
+
status = %w[reserved processing].include?(record.fetch("state")) ? :pending : record.fetch("state").to_sym
|
|
235
|
+
Result.send(:new, status, record)
|
|
236
|
+
end
|
|
237
|
+
# Raw verifier keyword graphs include Symbols. Bound/copy without invoking
|
|
238
|
+
# caller coercions or singleton callbacks, before any signature or storage.
|
|
239
|
+
def self.copy!(value, depth = 0, budget = [0, 0])
|
|
240
|
+
raise Invalid if depth > 20 || (budget[0] += 1) > 4096
|
|
241
|
+
raise Invalid unless Object.instance_method(:singleton_methods).bind_call(value, true).empty?
|
|
242
|
+
klass = Object.instance_method(:class).bind_call(value)
|
|
243
|
+
if klass == String
|
|
244
|
+
s = InputValidator.snapshot!(value)
|
|
245
|
+
raise Invalid if (budget[1] += s.bytesize) > 1_048_576
|
|
246
|
+
s
|
|
247
|
+
elsif klass == Hash
|
|
248
|
+
raise Invalid if value.size > 64
|
|
249
|
+
value.to_h do |k,v|
|
|
250
|
+
raise Invalid unless k.instance_of?(Symbol) || k.instance_of?(String)
|
|
251
|
+
[k.instance_of?(String) ? InputValidator.snapshot!(k, max_bytes: 256) : k, copy!(v, depth + 1, budget)]
|
|
252
|
+
end.freeze
|
|
253
|
+
elsif klass == Array
|
|
254
|
+
raise Invalid if value.size > 256
|
|
255
|
+
value.map { |v| copy!(v, depth + 1, budget) }.freeze
|
|
256
|
+
elsif [Integer, Symbol, NilClass, TrueClass, FalseClass].include?(klass)
|
|
257
|
+
value
|
|
258
|
+
else
|
|
259
|
+
raise Invalid
|
|
260
|
+
end
|
|
261
|
+
end
|
|
262
|
+
end
|
|
263
|
+
end
|
data/lib/ap2_mandate_verifier.rb
CHANGED
|
@@ -20,6 +20,8 @@ require_relative "ap2_mandate_verifier/payment_receipt"
|
|
|
20
20
|
require_relative "ap2_mandate_verifier/selective_payment"
|
|
21
21
|
require_relative "ap2_mandate_verifier/selective_checkout"
|
|
22
22
|
require_relative "ap2_mandate_verifier/payment_policy"
|
|
23
|
+
require_relative "ap2_mandate_verifier/payment_acceptance"
|
|
24
|
+
require_relative "ap2_mandate_verifier/payment_acceptance/sqlite_store"
|
|
23
25
|
|
|
24
26
|
module AP2MandateVerifier
|
|
25
27
|
# 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: 1.
|
|
4
|
+
version: 1.5.0
|
|
5
5
|
platform: ruby
|
|
6
6
|
authors:
|
|
7
7
|
- AP2 Mandate Verifier contributors
|
|
@@ -82,9 +82,10 @@ dependencies:
|
|
|
82
82
|
description: 'Framework-independent Ruby SDK for supported AP2 Checkout profiles:
|
|
83
83
|
Merchant JWT signing, Direct and conditional Mandate issuance and presentation,
|
|
84
84
|
full verification with immutable Evidence, Checkout Receipts, Direct and conditional
|
|
85
|
-
Payment Mandates, and Payment Receipts. Adds
|
|
86
|
-
|
|
87
|
-
trusted application inputs; verification does not grant purchase or
|
|
85
|
+
Payment Mandates, and Payment Receipts. Adds selective Checkout/Payment, PISP/date
|
|
86
|
+
constraints and opt-in transactional Payment acceptance/idempotency support. Requires
|
|
87
|
+
independently trusted application inputs; verification does not grant purchase or
|
|
88
|
+
payment permission.'
|
|
88
89
|
executables: []
|
|
89
90
|
extensions: []
|
|
90
91
|
extra_rdoc_files: []
|
|
@@ -101,6 +102,7 @@ files:
|
|
|
101
102
|
- docs/MERCHANT_SIGNING.md
|
|
102
103
|
- docs/MULTI_ITEM_CHECKOUT.md
|
|
103
104
|
- docs/PAYMENT.md
|
|
105
|
+
- docs/PAYMENT_ACCEPTANCE.md
|
|
104
106
|
- docs/PAYMENT_POLICY.md
|
|
105
107
|
- docs/POST_RELEASE_110.md
|
|
106
108
|
- docs/POST_RELEASE_MAINTENANCE.md
|
|
@@ -110,12 +112,14 @@ files:
|
|
|
110
112
|
- docs/RELEASE_120_CANDIDATE.md
|
|
111
113
|
- docs/RELEASE_130_CANDIDATE.md
|
|
112
114
|
- docs/RELEASE_140_CANDIDATE.md
|
|
115
|
+
- docs/RELEASE_150_CANDIDATE.md
|
|
113
116
|
- docs/SELECTIVE_CHECKOUT.md
|
|
114
117
|
- docs/SELECTIVE_PAYMENT.md
|
|
115
118
|
- docs/SUPPORT_CONTRACT.md
|
|
116
119
|
- docs/evidence/1.1.0_publication.json
|
|
117
120
|
- examples/conditional_checkout.rb
|
|
118
121
|
- examples/payment.rb
|
|
122
|
+
- examples/payment_acceptance.rb
|
|
119
123
|
- examples/payment_policy.rb
|
|
120
124
|
- examples/selective_checkout.rb
|
|
121
125
|
- examples/selective_checkout_payment.rb
|
|
@@ -131,6 +135,8 @@ files:
|
|
|
131
135
|
- lib/ap2_mandate_verifier/input_validator.rb
|
|
132
136
|
- lib/ap2_mandate_verifier/merchant_signature.rb
|
|
133
137
|
- lib/ap2_mandate_verifier/payment.rb
|
|
138
|
+
- lib/ap2_mandate_verifier/payment_acceptance.rb
|
|
139
|
+
- lib/ap2_mandate_verifier/payment_acceptance/sqlite_store.rb
|
|
134
140
|
- lib/ap2_mandate_verifier/payment_policy.rb
|
|
135
141
|
- lib/ap2_mandate_verifier/payment_receipt.rb
|
|
136
142
|
- lib/ap2_mandate_verifier/purchase_binding.rb
|