@provethebuy/verify 0.0.0-stage → 0.1.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.
Files changed (69) hide show
  1. package/LICENSE +202 -0
  2. package/README.md +43 -2
  3. package/dist/bodyObjects.d.ts +28 -0
  4. package/dist/bodyObjects.js +47 -0
  5. package/dist/bodyObjects.js.map +1 -0
  6. package/dist/cloud.d.ts +42 -0
  7. package/dist/cloud.js +102 -0
  8. package/dist/cloud.js.map +1 -0
  9. package/dist/confirmation.d.ts +17 -0
  10. package/dist/confirmation.js +31 -0
  11. package/dist/confirmation.js.map +1 -0
  12. package/dist/evidence.d.ts +39 -0
  13. package/dist/evidence.js +96 -0
  14. package/dist/evidence.js.map +1 -0
  15. package/dist/express.d.ts +43 -0
  16. package/dist/express.js +72 -0
  17. package/dist/express.js.map +1 -0
  18. package/dist/httpsig.d.ts +58 -0
  19. package/dist/httpsig.js +203 -0
  20. package/dist/httpsig.js.map +1 -0
  21. package/dist/index.d.ts +29 -0
  22. package/dist/index.js +16 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/jws.d.ts +28 -0
  25. package/dist/jws.js +93 -0
  26. package/dist/jws.js.map +1 -0
  27. package/dist/keys.d.ts +61 -0
  28. package/dist/keys.js +76 -0
  29. package/dist/keys.js.map +1 -0
  30. package/dist/ledger.d.ts +102 -0
  31. package/dist/ledger.js +131 -0
  32. package/dist/ledger.js.map +1 -0
  33. package/dist/mandates/ap2.d.ts +31 -0
  34. package/dist/mandates/ap2.js +91 -0
  35. package/dist/mandates/ap2.js.map +1 -0
  36. package/dist/mandates/index.d.ts +25 -0
  37. package/dist/mandates/index.js +26 -0
  38. package/dist/mandates/index.js.map +1 -0
  39. package/dist/mandates/verifiableIntent.d.ts +20 -0
  40. package/dist/mandates/verifiableIntent.js +128 -0
  41. package/dist/mandates/verifiableIntent.js.map +1 -0
  42. package/dist/order.d.ts +9 -0
  43. package/dist/order.js +32 -0
  44. package/dist/order.js.map +1 -0
  45. package/dist/payment.d.ts +22 -0
  46. package/dist/payment.js +19 -0
  47. package/dist/payment.js.map +1 -0
  48. package/dist/policy.d.ts +39 -0
  49. package/dist/policy.js +29 -0
  50. package/dist/policy.js.map +1 -0
  51. package/dist/replay.d.ts +46 -0
  52. package/dist/replay.js +61 -0
  53. package/dist/replay.js.map +1 -0
  54. package/dist/reputation.d.ts +16 -0
  55. package/dist/reputation.js +46 -0
  56. package/dist/reputation.js.map +1 -0
  57. package/dist/testing.d.ts +53 -0
  58. package/dist/testing.js +100 -0
  59. package/dist/testing.js.map +1 -0
  60. package/dist/types.d.ts +72 -0
  61. package/dist/types.js +2 -0
  62. package/dist/types.js.map +1 -0
  63. package/dist/util.d.ts +15 -0
  64. package/dist/util.js +59 -0
  65. package/dist/util.js.map +1 -0
  66. package/dist/verify.d.ts +50 -0
  67. package/dist/verify.js +309 -0
  68. package/dist/verify.js.map +1 -0
  69. package/package.json +63 -4
@@ -0,0 +1,26 @@
1
+ import { verifyVerifiableIntent } from "./verifiableIntent.js";
2
+ import { verifyAp2Cart, verifyAp2Intent } from "./ap2.js";
3
+ export async function verifyMandate(m, ctx) {
4
+ if (!m)
5
+ return null;
6
+ if (!ctx.accept.includes(m.type)) {
7
+ return {
8
+ info: { type: m.type, valid: false, summary: `Mandate type ${m.type} is not accepted by policy` },
9
+ checks: [{ name: "mandate_valid", status: "fail", detail: `This merchant's policy does not accept ${m.type} mandates.` }],
10
+ };
11
+ }
12
+ switch (m.type) {
13
+ case "verifiable-intent":
14
+ return verifyVerifiableIntent(m, ctx);
15
+ case "ap2-cart":
16
+ return verifyAp2Cart(m, ctx);
17
+ case "ap2-intent":
18
+ return verifyAp2Intent(m, ctx);
19
+ default:
20
+ return {
21
+ info: { type: String(m.type), valid: false },
22
+ checks: [{ name: "mandate_valid", status: "fail", detail: "Unknown mandate type." }],
23
+ };
24
+ }
25
+ }
26
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":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 @@
1
+ import type { MandateContext, MandateOutcome } from "./index.js";
2
+ export interface VerifiableIntentMandate {
3
+ type: "verifiable-intent";
4
+ l1: string;
5
+ l2: string;
6
+ l3: string;
7
+ }
8
+ export interface ViConstraints {
9
+ allowed_merchants?: string[];
10
+ max_amount?: {
11
+ amount: number;
12
+ currency: string;
13
+ };
14
+ line_items?: {
15
+ sku: string;
16
+ max_qty?: number;
17
+ }[];
18
+ }
19
+ export declare function verifyVerifiableIntent(m: VerifiableIntentMandate, ctx: MandateContext): Promise<MandateOutcome>;
20
+ export declare function describeConstraints(c: ViConstraints): string;
@@ -0,0 +1,128 @@
1
+ /**
2
+ * Layered intent credentials, modelled on Mastercard Verifiable Intent.
3
+ *
4
+ * L1 issuer -> user SD-JWT, signed by the card issuer, binds the user's key (cnf.jwk)
5
+ * L2 user -> agent SD-JWT, signed by the user's key, carries constraints; in autonomous
6
+ * mode it binds the agent's key (cnf.jwk)
7
+ * L3 agent -> merchant JWT, signed by the agent key (autonomous) or user key (immediate),
8
+ * names the exact checkout; transaction_id must equal our order hash
9
+ *
10
+ * Each layer carries `prev`: the SHA-256 (base64url) of the previous layer as received.
11
+ *
12
+ * STATUS: preview. Field names follow the public description of the specification; they will be
13
+ * aligned with the reference implementation's test vectors (github.com/agent-intent/verifiable-intent)
14
+ * in a later release. See docs/protocols.md.
15
+ */
16
+ import { sha256B64url } from "../util.js";
17
+ import { formatMoney } from "../order.js";
18
+ import { decodeJws, verifyJws, verifySdJwt, splitSdJwt } from "../jws.js";
19
+ export async function verifyVerifiableIntent(m, ctx) {
20
+ const checks = [];
21
+ const fail = (detail, data) => {
22
+ checks.push({ name: "mandate_valid", status: "fail", detail, data });
23
+ return { info: { type: m.type, valid: false, summary: detail }, checks };
24
+ };
25
+ // ---- L1: issuer credential
26
+ if (!ctx.issuers)
27
+ return fail("No issuer key directory is configured, so layer 1 cannot be checked.");
28
+ let l1Claims;
29
+ let issuerJwk;
30
+ try {
31
+ const kid = String(decodeJws(splitSdJwt(m.l1).jwt).header.kid ?? "");
32
+ const issuerKey = await ctx.issuers.resolve(kid);
33
+ if (!issuerKey)
34
+ return fail(`Issuer key "${kid}" was not found in any issuer directory.`);
35
+ issuerJwk = { ...issuerKey.jwk, kid };
36
+ l1Claims = verifySdJwt(m.l1, issuerKey.key).claims;
37
+ }
38
+ catch (e) {
39
+ return fail(`Layer 1 (issuer credential) failed: ${e.message}`);
40
+ }
41
+ if (typeof l1Claims.exp === "number" && l1Claims.exp < ctx.now)
42
+ return fail("Layer 1 (issuer credential) has expired.");
43
+ const userJwk = l1Claims.cnf?.jwk;
44
+ if (!userJwk)
45
+ return fail("Layer 1 does not bind a user key (cnf.jwk).");
46
+ // ---- L2: user mandate
47
+ let l2Claims;
48
+ try {
49
+ l2Claims = verifySdJwt(m.l2, userJwk).claims;
50
+ }
51
+ catch (e) {
52
+ return fail(`Layer 2 (user mandate) failed: ${e.message}`);
53
+ }
54
+ if (l2Claims.prev !== sha256B64url(m.l1))
55
+ return fail("Layer 2 is not linked to layer 1 (prev hash mismatch).");
56
+ if (typeof l2Claims.exp === "number" && l2Claims.exp < ctx.now)
57
+ return fail("Layer 2 (user mandate) has expired.");
58
+ const mode = String(l2Claims.mode ?? "immediate");
59
+ const constraints = (l2Claims.constraints ?? {});
60
+ // ---- L3: agent presentation to the merchant
61
+ const l3Key = mode === "autonomous" ? l2Claims.cnf?.jwk : userJwk;
62
+ if (!l3Key)
63
+ return fail("Autonomous mandate does not bind an agent key (cnf.jwk) in layer 2.");
64
+ let l3;
65
+ try {
66
+ l3 = verifyJws(m.l3, l3Key).payload;
67
+ }
68
+ catch (e) {
69
+ return fail(`Layer 3 (agent presentation) failed: ${e.message}`);
70
+ }
71
+ if (l3.prev !== sha256B64url(m.l2))
72
+ return fail("Layer 3 is not linked to layer 2 (prev hash mismatch).");
73
+ if (typeof l3.exp === "number" && l3.exp < ctx.now)
74
+ return fail("Layer 3 (agent presentation) has expired.");
75
+ checks.push({
76
+ name: "mandate_valid",
77
+ status: "pass",
78
+ detail: `Credential chain verified: issuer, user mandate (${mode}) and agent presentation.`,
79
+ data: { mode, l2_expires: l2Claims.exp, l3_expires: l3.exp },
80
+ });
81
+ // ---- bind to the order
82
+ const problems = [];
83
+ if (l3.transaction_id !== ctx.orderHash)
84
+ problems.push("the presented checkout does not match this order (transaction_id differs from the order hash)");
85
+ if (constraints.allowed_merchants && !constraints.allowed_merchants.includes(ctx.merchantId))
86
+ problems.push(`merchant ${ctx.merchantId} is not in the allowed merchants`);
87
+ if (constraints.max_amount) {
88
+ if (constraints.max_amount.currency.toLowerCase() !== ctx.order.currency.toLowerCase())
89
+ problems.push(`currency ${ctx.order.currency} differs from the mandate's ${constraints.max_amount.currency}`);
90
+ else if (ctx.order.total > constraints.max_amount.amount)
91
+ problems.push(`order total ${ctx.order.total} exceeds the mandate cap ${constraints.max_amount.amount}`);
92
+ }
93
+ if (constraints.line_items) {
94
+ for (const item of ctx.order.items) {
95
+ const rule = constraints.line_items.find((r) => r.sku === item.sku);
96
+ if (!rule)
97
+ problems.push(`item ${item.sku} is not allowed by the mandate`);
98
+ else if (rule.max_qty !== undefined && item.qty > rule.max_qty)
99
+ problems.push(`item ${item.sku} quantity ${item.qty} exceeds ${rule.max_qty}`);
100
+ }
101
+ }
102
+ checks.push(problems.length
103
+ ? { name: "order_within_mandate", status: "fail", detail: "Order is outside the mandate: " + problems.join("; ") + ".", data: { problems } }
104
+ : { name: "order_within_mandate", status: "pass", detail: "Order matches the presented checkout and every mandate constraint." });
105
+ return {
106
+ issuerKeyJwk: issuerJwk,
107
+ info: {
108
+ type: m.type,
109
+ mode,
110
+ valid: true,
111
+ constraintsOk: problems.length === 0,
112
+ expiresAt: typeof l2Claims.exp === "number" ? new Date(l2Claims.exp * 1000).toISOString() : undefined,
113
+ summary: describeConstraints(constraints),
114
+ },
115
+ checks,
116
+ };
117
+ }
118
+ export function describeConstraints(c) {
119
+ const parts = [];
120
+ if (c.max_amount)
121
+ parts.push(`up to ${formatMoney(c.max_amount.amount, c.max_amount.currency)}`);
122
+ if (c.allowed_merchants)
123
+ parts.push(`at ${c.allowed_merchants.join(", ")}`);
124
+ if (c.line_items)
125
+ parts.push(`items ${c.line_items.map((i) => i.sku + (i.max_qty ? " x" + i.max_qty : "")).join(", ")}`);
126
+ return parts.join(", ") || "no constraints";
127
+ }
128
+ //# sourceMappingURL=verifiableIntent.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"verifiableIntent.js","sourceRoot":"","sources":["../../src/mandates/verifiableIntent.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;GAcG;AACH,OAAO,EAAE,YAAY,EAAE,MAAM,YAAY,CAAC;AAC1C,OAAO,EAAE,WAAW,EAAE,MAAM,aAAa,CAAC;AAC1C,OAAO,EAAE,SAAS,EAAE,SAAS,EAAE,WAAW,EAAE,UAAU,EAAE,MAAM,WAAW,CAAC;AAkB1E,MAAM,CAAC,KAAK,UAAU,sBAAsB,CAAC,CAA0B,EAAE,GAAmB;IAC1F,MAAM,MAAM,GAAY,EAAE,CAAC;IAC3B,MAAM,IAAI,GAAG,CAAC,MAAc,EAAE,IAA8B,EAAkB,EAAE;QAC9E,MAAM,CAAC,IAAI,CAAC,EAAE,IAAI,EAAE,eAAe,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,IAAI,EAAE,CAAC,CAAC;QACrE,OAAO,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,KAAK,EAAE,KAAK,EAAE,OAAO,EAAE,MAAM,EAAE,EAAE,MAAM,EAAE,CAAC;IAC3E,CAAC,CAAC;IAEF,6BAA6B;IAC7B,IAAI,CAAC,GAAG,CAAC,OAAO;QAAE,OAAO,IAAI,CAAC,sEAAsE,CAAC,CAAC;IACtG,IAAI,QAAiC,CAAC;IACtC,IAAI,SAA0B,CAAC;IAC/B,IAAI,CAAC;QACH,MAAM,GAAG,GAAG,MAAM,CAAC,SAAS,CAAC,UAAU,CAAC,CAAC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AAE,CAAC,CAAC;IACjG,IAAI,CAAC,CAAC,iBAAiB;QAAE,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IAC5E,IAAI,CAAC,CAAC,UAAU;QAAE,KAAK,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,IAAI,GAAG,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC;IACzH,OAAO,KAAK,CAAC,IAAI,CAAC,IAAI,CAAC,IAAI,gBAAgB,CAAC;AAC9C,CAAC"}
@@ -0,0 +1,9 @@
1
+ import type { Order } from "./types.js";
2
+ /**
3
+ * One stable hash per order: canonical JSON (RFC 8785) of the fields that define what was bought.
4
+ * The same order always gives the same hash, whatever key order or whitespace it arrived in.
5
+ */
6
+ export declare function orderHash(order: Order): string;
7
+ /** Sum of line items, for catching orders whose total does not match their items. */
8
+ export declare function itemsTotal(order: Order): number;
9
+ export declare function formatMoney(amount: number, currency: string): string;
package/dist/order.js ADDED
@@ -0,0 +1,32 @@
1
+ import { canonicalize, sha256B64url } from "./util.js";
2
+ /**
3
+ * One stable hash per order: canonical JSON (RFC 8785) of the fields that define what was bought.
4
+ * The same order always gives the same hash, whatever key order or whitespace it arrived in.
5
+ */
6
+ export function orderHash(order) {
7
+ const core = {
8
+ merchant_id: order.merchant_id,
9
+ currency: order.currency.toLowerCase(),
10
+ total: order.total,
11
+ items: order.items
12
+ .map((i) => ({ sku: i.sku, qty: i.qty, unit_amount: i.unit_amount }))
13
+ .sort((a, b) => (a.sku < b.sku ? -1 : a.sku > b.sku ? 1 : 0)),
14
+ };
15
+ return sha256B64url(canonicalize(core));
16
+ }
17
+ /** Sum of line items, for catching orders whose total does not match their items. */
18
+ export function itemsTotal(order) {
19
+ return order.items.reduce((s, i) => s + i.qty * i.unit_amount, 0);
20
+ }
21
+ export function formatMoney(amount, currency) {
22
+ const cur = currency.toUpperCase();
23
+ const zeroDecimal = ["JPY", "KRW", "VND"].includes(cur);
24
+ const v = zeroDecimal ? amount : amount / 100;
25
+ try {
26
+ return new Intl.NumberFormat("en-US", { style: "currency", currency: cur }).format(v);
27
+ }
28
+ catch {
29
+ return `${v.toFixed(zeroDecimal ? 0 : 2)} ${cur}`;
30
+ }
31
+ }
32
+ //# sourceMappingURL=order.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"order.js","sourceRoot":"","sources":["../src/order.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAGvD;;;GAGG;AACH,MAAM,UAAU,SAAS,CAAC,KAAY;IACpC,MAAM,IAAI,GAAG;QACX,WAAW,EAAE,KAAK,CAAC,WAAW;QAC9B,QAAQ,EAAE,KAAK,CAAC,QAAQ,CAAC,WAAW,EAAE;QACtC,KAAK,EAAE,KAAK,CAAC,KAAK;QAClB,KAAK,EAAE,KAAK,CAAC,KAAK;aACf,GAAG,CAAC,CAAC,CAAC,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,GAAG,EAAE,CAAC,CAAC,GAAG,EAAE,WAAW,EAAE,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC;aACpE,IAAI,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;KAChE,CAAC;IACF,OAAO,YAAY,CAAC,YAAY,CAAC,IAAI,CAAC,CAAC,CAAC;AAC1C,CAAC;AAED,qFAAqF;AACrF,MAAM,UAAU,UAAU,CAAC,KAAY;IACrC,OAAO,KAAK,CAAC,KAAK,CAAC,MAAM,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,GAAG,CAAC,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;AACpE,CAAC;AAED,MAAM,UAAU,WAAW,CAAC,MAAc,EAAE,QAAgB;IAC1D,MAAM,GAAG,GAAG,QAAQ,CAAC,WAAW,EAAE,CAAC;IACnC,MAAM,WAAW,GAAG,CAAC,KAAK,EAAE,KAAK,EAAE,KAAK,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;IACxD,MAAM,CAAC,GAAG,WAAW,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,GAAG,GAAG,CAAC;IAC9C,IAAI,CAAC;QACH,OAAO,IAAI,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,EAAE,KAAK,EAAE,UAAU,EAAE,QAAQ,EAAE,GAAG,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACxF,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,GAAG,CAAC,CAAC,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,GAAG,EAAE,CAAC;IACpD,CAAC;AACH,CAAC"}
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Scoped payment credentials: Stripe shared payment tokens and ACP delegated-payment allowances.
3
+ * Both carry limits (max amount, currency, merchant, expiry). The merchant must never charge outside them.
4
+ */
5
+ import type { Check, Order } from "./types.js";
6
+ export interface PaymentAllowance {
7
+ max_amount: number;
8
+ currency: string;
9
+ merchant_id?: string;
10
+ /** RFC 3339 or unix seconds. */
11
+ expires_at: string | number;
12
+ checkout_session_id?: string;
13
+ reason?: "one_time" | string;
14
+ }
15
+ export interface PaymentCredential {
16
+ type: "stripe-spt" | "acp-allowance";
17
+ /** e.g. spt_... or vt_... — never a card number. */
18
+ token: string;
19
+ /** Limits as returned by the PSP (e.g. retrieved from Stripe). */
20
+ allowance: PaymentAllowance;
21
+ }
22
+ export declare function checkPaymentLimits(p: PaymentCredential | undefined, order: Order, merchantId: string, now: number): Check;
@@ -0,0 +1,19 @@
1
+ export function checkPaymentLimits(p, order, merchantId, now) {
2
+ if (!p)
3
+ return { name: "token_limits", status: "skip", detail: "No scoped payment credential in the request." };
4
+ const a = p.allowance;
5
+ const exp = typeof a.expires_at === "number" ? a.expires_at : Math.floor(Date.parse(a.expires_at) / 1000);
6
+ const problems = [];
7
+ if (a.currency.toLowerCase() !== order.currency.toLowerCase())
8
+ problems.push(`token currency ${a.currency} differs from order currency ${order.currency}`);
9
+ if (order.total > a.max_amount)
10
+ problems.push(`order total ${order.total} exceeds the token cap ${a.max_amount}`);
11
+ if (a.merchant_id && a.merchant_id !== merchantId)
12
+ problems.push(`token is scoped to merchant ${a.merchant_id}`);
13
+ if (Number.isFinite(exp) && exp < now)
14
+ problems.push("token has expired");
15
+ return problems.length
16
+ ? { name: "token_limits", status: "fail", detail: "Charging would break the token's limits: " + problems.join("; ") + ".", data: { type: p.type } }
17
+ : { name: "token_limits", status: "pass", detail: `Order fits the ${p.type === "stripe-spt" ? "shared payment token" : "ACP allowance"} limits.`, data: { type: p.type, max_amount: a.max_amount } };
18
+ }
19
+ //# sourceMappingURL=payment.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"payment.js","sourceRoot":"","sources":["../src/payment.ts"],"names":[],"mappings":"AAwBA,MAAM,UAAU,kBAAkB,CAAC,CAAgC,EAAE,KAAY,EAAE,UAAkB,EAAE,GAAW;IAChH,IAAI,CAAC,CAAC;QAAE,OAAO,EAAE,IAAI,EAAE,cAAc,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,8CAA8C,EAA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AE,MAAM,EAAE,MAAM,EAAE,kBAAkB,CAAC,CAAC,IAAI,KAAK,YAAY,CAAC,CAAC,CAAC,sBAAsB,CAAC,CAAC,CAAC,eAAe,UAAU,EAAE,IAAI,EAAE,EAAE,IAAI,EAAE,CAAC,CAAC,IAAI,EAAE,UAAU,EAAE,CAAC,CAAC,UAAU,EAAE,EAAE,CAAC;AACzM,CAAC"}
@@ -0,0 +1,39 @@
1
+ export interface Policy {
2
+ version?: string;
3
+ /** shadow: record decisions but never block. enforce: apply them. */
4
+ mode: "shadow" | "enforce";
5
+ /** What to do if verification code throws. open = treat as normal traffic. */
6
+ fail: "open" | "closed";
7
+ agents: {
8
+ /** Tags that must carry a valid signature. */
9
+ require_signature_for: string[];
10
+ /** Directory names to trust. Empty = all configured directories. */
11
+ directories: string[];
12
+ /** Largest allowed expires - created, in seconds. Visa TAP uses 8 minutes. */
13
+ max_window_seconds: number;
14
+ /** Allowed clock skew, in seconds. */
15
+ clock_skew_seconds: number;
16
+ };
17
+ mandate: {
18
+ accept: string[];
19
+ /** What happens to a paying agent request with no valid mandate. */
20
+ on_missing: "allow" | "step_up" | "block";
21
+ on_outside: "step_up" | "block";
22
+ };
23
+ limits: {
24
+ require_merchant_match: boolean;
25
+ /** Above this total (minor units), an intent-only mandate triggers a step-up. 0 = off. */
26
+ intent_mandate_max_order: number;
27
+ };
28
+ reputation: {
29
+ step_up_if_agent_dispute_rate_over: number;
30
+ min_orders_for_reputation: number;
31
+ };
32
+ }
33
+ export declare const DEFAULT_POLICY: Policy;
34
+ type DeepPartial<T> = {
35
+ [K in keyof T]?: T[K] extends object ? (T[K] extends unknown[] ? T[K] : DeepPartial<T[K]>) : T[K];
36
+ };
37
+ export type PolicyInput = DeepPartial<Policy>;
38
+ export declare function resolvePolicy(input?: PolicyInput): Policy;
39
+ export {};
package/dist/policy.js ADDED
@@ -0,0 +1,29 @@
1
+ /** Merchant policy: turns check results into allow / step-up / block. */
2
+ import { canonicalize, sha256Hex } from "./util.js";
3
+ export const DEFAULT_POLICY = {
4
+ mode: "shadow",
5
+ fail: "open",
6
+ agents: { require_signature_for: ["agent-payer-auth"], directories: [], max_window_seconds: 480, clock_skew_seconds: 60 },
7
+ mandate: { accept: ["verifiable-intent", "ap2-cart", "ap2-intent"], on_missing: "step_up", on_outside: "step_up" },
8
+ limits: { require_merchant_match: true, intent_mandate_max_order: 50000 },
9
+ reputation: { step_up_if_agent_dispute_rate_over: 0.02, min_orders_for_reputation: 20 },
10
+ };
11
+ export function resolvePolicy(input = {}) {
12
+ const p = {
13
+ ...DEFAULT_POLICY,
14
+ ...input,
15
+ agents: { ...DEFAULT_POLICY.agents, ...(input.agents ?? {}) },
16
+ mandate: { ...DEFAULT_POLICY.mandate, ...(input.mandate ?? {}) },
17
+ limits: { ...DEFAULT_POLICY.limits, ...(input.limits ?? {}) },
18
+ reputation: { ...DEFAULT_POLICY.reputation, ...(input.reputation ?? {}) },
19
+ };
20
+ if (!["shadow", "enforce"].includes(p.mode))
21
+ throw new Error(`policy.mode must be "shadow" or "enforce"`);
22
+ if (!["open", "closed"].includes(p.fail))
23
+ throw new Error(`policy.fail must be "open" or "closed"`);
24
+ if (p.agents.max_window_seconds <= 0 || p.agents.max_window_seconds > 3600)
25
+ throw new Error("agents.max_window_seconds must be between 1 and 3600");
26
+ p.version = input.version ?? "p_" + sha256Hex(canonicalize({ ...p, version: undefined })).slice(0, 8);
27
+ return p;
28
+ }
29
+ //# sourceMappingURL=policy.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"policy.js","sourceRoot":"","sources":["../src/policy.ts"],"names":[],"mappings":"AAAA,yEAAyE;AACzE,OAAO,EAAE,YAAY,EAAE,SAAS,EAAE,MAAM,WAAW,CAAC;AAmCpD,MAAM,CAAC,MAAM,cAAc,GAAW;IACpC,IAAI,EAAE,QAAQ;IACd,IAAI,EAAE,MAAM;IACZ,MAAM,EAAE,EAAE,qBAAqB,EAAE,CAAC,kBAAkB,CAAC,EAAE,WAAW,EAAE,E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CAAC,kBAAkB,IAAI,CAAC,IAAI,CAAC,CAAC,MAAM,CAAC,kBAAkB,GAAG,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,sDAAsD,CAAC,CAAC;IACpJ,CAAC,CAAC,OAAO,GAAG,KAAK,CAAC,OAAO,IAAI,IAAI,GAAG,SAAS,CAAC,YAAY,CAAC,EAAE,GAAG,CAAC,EAAE,OAAO,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;IACtG,OAAO,CAAC,CAAC;AACX,CAAC"}
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Replay protection: every (keyid, nonce) pair may be seen once inside its validity window.
3
+ * Use one shared store across all servers, otherwise a replayed request can hit a second server.
4
+ */
5
+ export interface ReplayStore {
6
+ /** Returns true if the nonce was unused and is now recorded; false if it was seen before. */
7
+ checkAndRemember(key: string, ttlSeconds: number): Promise<boolean>;
8
+ }
9
+ /** In-process store. Fine for a single server, tests and shadow mode. */
10
+ export declare class MemoryReplayStore implements ReplayStore {
11
+ private readonly seen;
12
+ checkAndRemember(key: string, ttlSeconds: number): Promise<boolean>;
13
+ }
14
+ /** Minimal interface satisfied by node-redis v4+ and ioredis clients. */
15
+ export interface RedisLike {
16
+ set(key: string, value: string, ...args: unknown[]): Promise<unknown>;
17
+ }
18
+ export interface RedisReplayStoreOptions {
19
+ /** "node-redis" (default) passes { NX, EX }; "ioredis" passes "EX", ttl, "NX". */
20
+ client?: "node-redis" | "ioredis";
21
+ prefix?: string;
22
+ }
23
+ /** Shared store backed by Redis using SET key value NX EX ttl. */
24
+ export declare class RedisReplayStore implements ReplayStore {
25
+ private readonly redis;
26
+ private readonly flavour;
27
+ private readonly prefix;
28
+ constructor(redis: RedisLike, opts?: RedisReplayStoreOptions);
29
+ checkAndRemember(key: string, ttlSeconds: number): Promise<boolean>;
30
+ }
31
+ export interface UpstashReplayStoreOptions {
32
+ /** UPSTASH_REDIS_REST_URL */
33
+ url: string;
34
+ /** UPSTASH_REDIS_REST_TOKEN */
35
+ token: string;
36
+ prefix?: string;
37
+ fetch?: typeof fetch;
38
+ }
39
+ /** Shared store for serverless deployments, using Upstash's Redis REST API (no TCP connection needed). */
40
+ export declare class UpstashReplayStore implements ReplayStore {
41
+ private readonly opts;
42
+ private readonly prefix;
43
+ private readonly doFetch;
44
+ constructor(opts: UpstashReplayStoreOptions);
45
+ checkAndRemember(key: string, ttlSeconds: number): Promise<boolean>;
46
+ }
package/dist/replay.js ADDED
@@ -0,0 +1,61 @@
1
+ /** In-process store. Fine for a single server, tests and shadow mode. */
2
+ export class MemoryReplayStore {
3
+ seen = new Map();
4
+ async checkAndRemember(key, ttlSeconds) {
5
+ const now = Date.now();
6
+ if (this.seen.size > 10_000) {
7
+ for (const [k, exp] of this.seen)
8
+ if (exp <= now)
9
+ this.seen.delete(k);
10
+ }
11
+ const exp = this.seen.get(key);
12
+ if (exp && exp > now)
13
+ return false;
14
+ this.seen.set(key, now + Math.max(1, ttlSeconds) * 1000);
15
+ return true;
16
+ }
17
+ }
18
+ /** Shared store backed by Redis using SET key value NX EX ttl. */
19
+ export class RedisReplayStore {
20
+ redis;
21
+ flavour;
22
+ prefix;
23
+ constructor(redis, opts = {}) {
24
+ this.redis = redis;
25
+ this.flavour = opts.client ?? "node-redis";
26
+ this.prefix = opts.prefix ?? "ptb:nonce:";
27
+ }
28
+ async checkAndRemember(key, ttlSeconds) {
29
+ const ttl = Math.max(1, Math.ceil(ttlSeconds));
30
+ const res = this.flavour === "ioredis"
31
+ ? await this.redis.set(this.prefix + key, "1", "EX", ttl, "NX")
32
+ : await this.redis.set(this.prefix + key, "1", { NX: true, EX: ttl });
33
+ return res === "OK";
34
+ }
35
+ }
36
+ /** Shared store for serverless deployments, using Upstash's Redis REST API (no TCP connection needed). */
37
+ export class UpstashReplayStore {
38
+ opts;
39
+ prefix;
40
+ doFetch;
41
+ constructor(opts) {
42
+ this.opts = opts;
43
+ this.prefix = opts.prefix ?? "ptb:nonce:";
44
+ this.doFetch = opts.fetch ?? fetch;
45
+ }
46
+ async checkAndRemember(key, ttlSeconds) {
47
+ const ttl = Math.max(1, Math.ceil(ttlSeconds));
48
+ const res = await this.doFetch(this.opts.url.replace(/\/$/, ""), {
49
+ method: "POST",
50
+ headers: { authorization: `Bearer ${this.opts.token}`, "content-type": "application/json" },
51
+ body: JSON.stringify(["SET", this.prefix + key, "1", "NX", "EX", String(ttl)]),
52
+ });
53
+ if (!res.ok)
54
+ throw new Error(`Upstash replay store returned HTTP ${res.status}`);
55
+ const data = (await res.json());
56
+ if (data.error)
57
+ throw new Error(`Upstash replay store: ${data.error}`);
58
+ return data.result === "OK";
59
+ }
60
+ }
61
+ //# sourceMappingURL=replay.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"replay.js","sourceRoot":"","sources":["../src/replay.ts"],"names":[],"mappings":"AASA,yEAAyE;AACzE,MAAM,OAAO,iBAAiB;IACX,IAAI,GAAG,IAAI,GAAG,EAAkB,CAAC;IAElD,KAAK,CAAC,gBAAgB,CAAC,GAAW,EAAE,UAAkB;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,EAAE,CAAC;QACvB,IAAI,IAAI,CAAC,IAAI,CAAC,IAAI,GAAG,MAAM,EAAE,CAAC;YAC5B,KAAK,MAAM,CAAC,CAAC,EAAE,GAAG,CAAC,IAAI,IAAI,CAAC,IAAI;gBAAE,IAAI,GAAG,IAAI,GAAG;oBAAE,IAAI,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;QACxE,CAAC;QACD,MAAM,GAAG,GAAG,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,CAAC,CAAC;QAC/B,IAAI,GAAG,IAAI,GAAG,GAAG,GAAG;YAAE,OAAO,KAAK,CAAC;QACnC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,GAAG,EAAE,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,UAAU,CAAC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ACrC,CAAC;IAED,KAAK,CAAC,gBAAgB,CAAC,GAAW,EAAE,UAAkB;QACpD,MAAM,GAAG,GAAG,IAAI,CAAC,GAAG,CAAC,CAAC,EAAE,IAAI,CAAC,IAAI,CAAC,UAAU,CAAC,CAAC,CAAC;QAC/C,MAAM,GAAG,GAAG,MAAM,IAAI,CAAC,OAAO,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,CAAC,OAAO,CAAC,KAAK,EAAE,EAAE,CAAC,EAAE;YAC/D,MAAM,EAAE,MAAM;YACd,OAAO,EAAE,EAAE,aAAa,EAAE,UAAU,IAAI,CAAC,IAAI,CAAC,KAAK,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;YAC3F,IAAI,EAAE,IAAI,CAAC,SAAS,CAAC,CAAC,KAAK,EAAE,IAAI,CAAC,MAAM,GAAG,GAAG,EAAE,GAAG,EAAE,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC;SAC/E,CAAC,CAAC;QACH,IAAI,CAAC,GAAG,CAAC,EAAE;YAAE,MAAM,IAAI,KAAK,CAAC,sCAAsC,GAAG,CAAC,MAAM,EAAE,CAAC,CAAC;QACjF,MAAM,IAAI,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,EAAE,CAAyC,CAAC;QACxE,IAAI,IAAI,CAAC,KAAK;YAAE,MAAM,IAAI,KAAK,CAAC,yBAAyB,IAAI,CAAC,KAAK,EAAE,CAAC,CAAC;QACvE,OAAO,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC;IAC9B,CAAC;CACF"}
@@ -0,0 +1,16 @@
1
+ /** Per-agent statistics computed from your own ledger. */
2
+ import type { EvidenceLedger } from "./ledger.js";
3
+ import type { AgentStats, ReputationProvider } from "./verify.js";
4
+ export interface AgentSummary extends AgentStats {
5
+ keyid: string;
6
+ protocol?: string;
7
+ directory?: string;
8
+ requests: number;
9
+ blocked: number;
10
+ stepUps: number;
11
+ disputesWon: number;
12
+ disputesLost: number;
13
+ lastSeen?: string;
14
+ }
15
+ export declare function agentSummaries(ledger: EvidenceLedger): AgentSummary[];
16
+ export declare function ledgerReputation(ledger: EvidenceLedger): ReputationProvider;
@@ -0,0 +1,46 @@
1
+ export function agentSummaries(ledger) {
2
+ const map = new Map();
3
+ for (const r of ledger.verifications()) {
4
+ if (!r.agent?.keyid)
5
+ continue;
6
+ const s = map.get(r.agent.keyid) ??
7
+ { keyid: r.agent.keyid, protocol: r.agent.protocol, directory: r.agent.directory, requests: 0, orders: 0, blocked: 0, stepUps: 0, disputes: 0, mismatches: 0, disputesWon: 0, disputesLost: 0 };
8
+ s.requests++;
9
+ if (r.decision === "allow" && r.order)
10
+ s.orders++;
11
+ if (r.decision === "block")
12
+ s.blocked++;
13
+ if (r.decision === "step_up")
14
+ s.stepUps++;
15
+ if (r.checks.some((c) => c.name === "order_within_mandate" && c.status === "fail"))
16
+ s.mismatches++;
17
+ if (r.agent.directory)
18
+ s.directory = r.agent.directory;
19
+ s.lastSeen = r.received_at;
20
+ map.set(r.agent.keyid, s);
21
+ }
22
+ const seenDispute = new Set();
23
+ for (const d of ledger.disputes()) {
24
+ if (!d.agent_keyid)
25
+ continue;
26
+ const s = map.get(d.agent_keyid);
27
+ if (!s)
28
+ continue;
29
+ if (d.status === "opened" && !seenDispute.has(d.dispute_id)) {
30
+ s.disputes++;
31
+ seenDispute.add(d.dispute_id);
32
+ }
33
+ if (d.status === "won")
34
+ s.disputesWon++;
35
+ if (d.status === "lost")
36
+ s.disputesLost++;
37
+ }
38
+ return [...map.values()].sort((a, b) => b.requests - a.requests);
39
+ }
40
+ export function ledgerReputation(ledger) {
41
+ return (keyid) => {
42
+ const s = agentSummaries(ledger).find((a) => a.keyid === keyid);
43
+ return s ? { orders: s.orders, disputes: s.disputes, mismatches: s.mismatches } : undefined;
44
+ };
45
+ }
46
+ //# sourceMappingURL=reputation.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"reputation.js","sourceRoot":"","sources":["../src/reput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C,KAAK,KAAK,KAAK,CAAC,CAAC;QAChE,OAAO,CAAC,CAAC,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,CAAC,CAAC,QAAQ,EAAE,UAAU,EAAE,CAAC,CAAC,UAAU,EAAE,CAAC,CAAC,CAAC,SAAS,CAAC;IAC9F,CAAC,CAAC;AACJ,CAAC"}
@@ -0,0 +1,53 @@
1
+ import { type AgentTag, type HttpRequestLike } from "./httpsig.js";
2
+ import { type Jwk } from "./keys.js";
3
+ import { signBodyObject } from "./bodyObjects.js";
4
+ import type { Order } from "./types.js";
5
+ import type { ViConstraints, VerifiableIntentMandate } from "./mandates/verifiableIntent.js";
6
+ import type { Ap2CartMandate, Ap2IntentMandate } from "./mandates/ap2.js";
7
+ export interface KeyPair {
8
+ kid: string;
9
+ privateJwk: Jwk;
10
+ publicJwk: Jwk;
11
+ }
12
+ /** Ed25519 key pair. Pass a seed string for deterministic keys (test vectors). */
13
+ export declare function generateKey(kid: string, seed?: string): KeyPair;
14
+ export interface TestAgent extends KeyPair {
15
+ name: string;
16
+ sign(req: HttpRequestLike, o?: {
17
+ tag?: AgentTag;
18
+ nonce?: string;
19
+ created?: number;
20
+ expires?: number;
21
+ components?: string[];
22
+ }): HttpRequestLike;
23
+ }
24
+ export declare function createAgent(name: string, seed?: string): TestAgent;
25
+ /** Build a JSON checkout request body carrying the order, mandate and payment token. */
26
+ export declare function checkoutRequest(origin: string, body: Record<string, unknown>, path?: string): HttpRequestLike;
27
+ /** Verifiable Intent style three-layer chain for an order. */
28
+ export declare function buildVerifiableIntent(o: {
29
+ issuer: KeyPair;
30
+ user: KeyPair;
31
+ agent: KeyPair;
32
+ order: Order;
33
+ constraints: ViConstraints;
34
+ mode?: "immediate" | "autonomous";
35
+ now?: number;
36
+ seed?: string;
37
+ /** Override what the agent presents (for negative tests). */
38
+ presentedTransactionId?: string;
39
+ }): VerifiableIntentMandate;
40
+ export declare function buildAp2Cart(o: {
41
+ merchant: KeyPair;
42
+ user: KeyPair;
43
+ order: Order;
44
+ expiresInSeconds?: number;
45
+ }): Ap2CartMandate;
46
+ export declare function buildAp2Intent(o: {
47
+ user: KeyPair;
48
+ merchants?: string[];
49
+ maxAmount: number;
50
+ currency: string;
51
+ expiresInSeconds?: number;
52
+ }): Ap2IntentMandate;
53
+ export { signBodyObject };