@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,100 @@
1
+ /**
2
+ * Test helpers: create agents, issuers and users, and sign requests and mandates the way real
3
+ * agents do. Used by the test suite, the conformance vectors and the local playground.
4
+ * Never use generated keys in production.
5
+ */
6
+ import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes } from "node:crypto";
7
+ import { signRequest } from "./httpsig.js";
8
+ import { issueSdJwt, signJws } from "./jws.js";
9
+ import { publicJwk } from "./keys.js";
10
+ import { signBodyObject } from "./bodyObjects.js";
11
+ import { orderHash } from "./order.js";
12
+ import { sha256B64url } from "./util.js";
13
+ const ED25519_PKCS8_PREFIX = Buffer.from("302e020100300506032b657004220420", "hex");
14
+ /** Ed25519 key pair. Pass a seed string for deterministic keys (test vectors). */
15
+ export function generateKey(kid, seed) {
16
+ let priv;
17
+ if (seed) {
18
+ const s = createHash("sha256").update(seed).digest();
19
+ priv = createPrivateKey({ key: Buffer.concat([ED25519_PKCS8_PREFIX, s]), format: "der", type: "pkcs8" });
20
+ }
21
+ else {
22
+ priv = generateKeyPairSync("ed25519").privateKey;
23
+ }
24
+ const privateJwk = { ...priv.export({ format: "jwk" }), kid, alg: "EdDSA" };
25
+ const pub = { ...createPublicKey(priv).export({ format: "jwk" }), kid, alg: "EdDSA", use: "sig" };
26
+ return { kid, privateJwk, publicJwk: publicJwk(pub) };
27
+ }
28
+ export function createAgent(name, seed) {
29
+ const kp = generateKey(`${name.toLowerCase().replace(/[^a-z0-9]+/g, "-")}-${seed ? "k1" : randomBytes(3).toString("hex")}`, seed);
30
+ return {
31
+ ...kp,
32
+ name,
33
+ sign(req, o = {}) {
34
+ return signRequest(req, {
35
+ privateJwk: kp.privateJwk,
36
+ keyid: kp.kid,
37
+ tag: o.tag ?? "agent-payer-auth",
38
+ nonce: o.nonce ?? randomBytes(16).toString("base64url"),
39
+ created: o.created,
40
+ expires: o.expires,
41
+ components: o.components,
42
+ });
43
+ },
44
+ };
45
+ }
46
+ /** Build a JSON checkout request body carrying the order, mandate and payment token. */
47
+ export function checkoutRequest(origin, body, path = "/checkout") {
48
+ const json = JSON.stringify(body);
49
+ const url = new URL(path, origin);
50
+ return { method: "POST", url: url.toString(), headers: { host: url.host, "content-type": "application/json" }, body: json };
51
+ }
52
+ let saltCounter = 0;
53
+ const salt = (seed) => (n) => (seed ? sha256B64url(seed + n).slice(0, 16) : randomBytes(12).toString("base64url") + ++saltCounter);
54
+ /** Verifiable Intent style three-layer chain for an order. */
55
+ export function buildVerifiableIntent(o) {
56
+ const now = o.now ?? Math.floor(Date.now() / 1000);
57
+ const mode = o.mode ?? "autonomous";
58
+ const l1 = issueSdJwt({ iss: "https://issuer.example", sub: "cardholder-123", iat: now, exp: now + 365 * 86400, cnf: { jwk: o.user.publicJwk }, card_last4: "4242" }, ["sub", "card_last4"], o.issuer.privateJwk, salt(o.seed && o.seed + "l1"));
59
+ const l2 = issueSdJwt({
60
+ iat: now,
61
+ exp: now + (mode === "autonomous" ? 7 * 86400 : 900),
62
+ mode,
63
+ prev: sha256B64url(l1),
64
+ constraints: o.constraints,
65
+ ...(mode === "autonomous" ? { cnf: { jwk: o.agent.publicJwk } } : {}),
66
+ prompt_playback: "Buy the items in my saved list when they are in stock",
67
+ }, ["prompt_playback"], o.user.privateJwk, salt(o.seed && o.seed + "l2"));
68
+ const l3 = signJws({
69
+ iat: now,
70
+ exp: now + 300,
71
+ prev: sha256B64url(l2),
72
+ merchant: o.order.merchant_id,
73
+ transaction_id: o.presentedTransactionId ?? orderHash(o.order),
74
+ total: { amount: o.order.total, currency: o.order.currency },
75
+ line_items: o.order.items.map((i) => ({ sku: i.sku, qty: i.qty })),
76
+ }, mode === "autonomous" ? o.agent.privateJwk : o.user.privateJwk);
77
+ return { type: "verifiable-intent", l1, l2, l3 };
78
+ }
79
+ export function buildAp2Cart(o) {
80
+ const cart = {
81
+ cart_id: o.order.id ?? "cart_1",
82
+ merchant_id: o.order.merchant_id,
83
+ currency: o.order.currency,
84
+ total: o.order.total,
85
+ items: o.order.items.map((i) => ({ sku: i.sku, qty: i.qty, unit_amount: i.unit_amount })),
86
+ expires_at: new Date(Date.now() + (o.expiresInSeconds ?? 900) * 1000).toISOString(),
87
+ };
88
+ return { type: "ap2-cart", merchant_signature: signJws(cart, o.merchant.privateJwk), user_signature: signJws(cart, o.user.privateJwk), user_jwk: o.user.publicJwk };
89
+ }
90
+ export function buildAp2Intent(o) {
91
+ const intent = {
92
+ merchants: o.merchants,
93
+ max_amount: { amount: o.maxAmount, currency: o.currency },
94
+ expires_at: new Date(Date.now() + (o.expiresInSeconds ?? 86400) * 1000).toISOString(),
95
+ prompt_playback: "Reorder coffee beans when I run low, up to the limit",
96
+ };
97
+ return { type: "ap2-intent", jws: signJws(intent, o.user.privateJwk), user_jwk: o.user.publicJwk };
98
+ }
99
+ export { signBodyObject };
100
+ //# sourceMappingURL=testing.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"testing.js","sourceRoot":"","sources":["../src/testing.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AACH,OAAO,EAAE,UAAU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AAQ,EAAE,CAAC,CAAC,QAAQ,EAAE;QACzD,UAAU,EAAE,IAAI,IAAI,CAAC,IAAI,CAAC,GAAG,EAAE,GAAG,CAAC,CAAC,CAAC,gBAAgB,IAAI,KAAK,CAAC,GAAG,IAAI,CAAC,CAAC,WAAW,EAAE;QACrF,eAAe,EAAE,sDAAsD;KACxE,CAAC;IACF,OAAO,EAAE,IAAI,EAAE,YAAY,EAAE,GAAG,EAAE,OAAO,CAAC,MAAM,EAAE,CAAC,CAAC,IAAI,CAAC,UAAU,CAAC,EAAE,QAAQ,EAAE,CAAC,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;AACrG,CAAC;AAED,OAAO,EAAE,cAAc,EAAE,CAAC"}
@@ -0,0 +1,72 @@
1
+ import type { AgentTag } from "./httpsig.js";
2
+ import type { Jwk } from "./keys.js";
3
+ export type CheckStatus = "pass" | "fail" | "skip" | "warn";
4
+ export interface Check {
5
+ /** Stable machine name, e.g. "signature_valid". */
6
+ name: string;
7
+ status: CheckStatus;
8
+ /** One plain-language sentence a developer can act on. */
9
+ detail: string;
10
+ /** Optional structured data for the inspector. */
11
+ data?: Record<string, unknown>;
12
+ }
13
+ export type Decision = "allow" | "step_up" | "block" | "not_agent";
14
+ export interface Money {
15
+ /** Amount in minor units (cents, paise). */
16
+ amount: number;
17
+ currency: string;
18
+ }
19
+ export interface OrderItem {
20
+ sku: string;
21
+ name?: string;
22
+ qty: number;
23
+ unit_amount: number;
24
+ }
25
+ export interface Order {
26
+ id?: string;
27
+ merchant_id: string;
28
+ currency: string;
29
+ total: number;
30
+ items: OrderItem[];
31
+ }
32
+ export interface AgentInfo {
33
+ protocol: "visa-tap" | "mastercard-agent-pay" | "web-bot-auth";
34
+ keyid: string;
35
+ tag?: AgentTag | string;
36
+ directory?: string;
37
+ alg?: string;
38
+ keySnapshotSha256?: string;
39
+ nonce?: string;
40
+ created?: number;
41
+ expires?: number;
42
+ }
43
+ export interface MandateInfo {
44
+ type: string;
45
+ mode?: string;
46
+ valid: boolean;
47
+ constraintsOk?: boolean;
48
+ expiresAt?: string;
49
+ summary?: string;
50
+ }
51
+ export interface VerificationResult {
52
+ decision: Decision;
53
+ /** False in shadow mode: the decision is recorded but never applied. */
54
+ enforced: boolean;
55
+ reasons: string[];
56
+ checks: Check[];
57
+ agent?: AgentInfo;
58
+ mandate?: MandateInfo;
59
+ orderHash?: string;
60
+ rawSha256?: string;
61
+ policyVersion: string;
62
+ receivedAt: string;
63
+ /** Public key the agent signed with, kept for the evidence record. */
64
+ agentKeyJwk?: Jwk;
65
+ /** Mandate issuer key used (Verifiable Intent layer 1), kept for re-verification. */
66
+ issuerKeyJwk?: Jwk;
67
+ /** Present when decision is step_up: what to ask the person to confirm. */
68
+ stepUp?: {
69
+ reason: string;
70
+ suggested: "ap2-cart-mandate" | "3ds" | "confirm-in-session";
71
+ };
72
+ }
package/dist/types.js ADDED
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":""}
package/dist/util.d.ts ADDED
@@ -0,0 +1,15 @@
1
+ /** base64url without padding */
2
+ export declare function b64url(input: Buffer | Uint8Array | string): string;
3
+ export declare function fromB64url(input: string): Buffer;
4
+ export declare function sha256(input: Buffer | string): Buffer;
5
+ export declare function sha256Hex(input: Buffer | string): string;
6
+ export declare function sha256B64url(input: Buffer | string): string;
7
+ /**
8
+ * JSON Canonicalization Scheme (RFC 8785).
9
+ * Object keys are sorted by UTF-16 code units; numbers use ECMAScript serialisation,
10
+ * which is what JSON.stringify produces for finite numbers.
11
+ */
12
+ export declare function canonicalize(value: unknown): string;
13
+ export declare function nowSeconds(): number;
14
+ export declare function lowerKeys(headers: Record<string, string | string[] | undefined>): Record<string, string>;
15
+ export declare function randomId(prefix: string): string;
package/dist/util.js ADDED
@@ -0,0 +1,59 @@
1
+ import { createHash } from "node:crypto";
2
+ /** base64url without padding */
3
+ export function b64url(input) {
4
+ const buf = typeof input === "string" ? Buffer.from(input, "utf8") : Buffer.from(input);
5
+ return buf.toString("base64url");
6
+ }
7
+ export function fromB64url(input) {
8
+ return Buffer.from(input, "base64url");
9
+ }
10
+ export function sha256(input) {
11
+ return createHash("sha256").update(input).digest();
12
+ }
13
+ export function sha256Hex(input) {
14
+ return createHash("sha256").update(input).digest("hex");
15
+ }
16
+ export function sha256B64url(input) {
17
+ return sha256(input).toString("base64url");
18
+ }
19
+ /**
20
+ * JSON Canonicalization Scheme (RFC 8785).
21
+ * Object keys are sorted by UTF-16 code units; numbers use ECMAScript serialisation,
22
+ * which is what JSON.stringify produces for finite numbers.
23
+ */
24
+ export function canonicalize(value) {
25
+ if (value === null || typeof value === "boolean")
26
+ return JSON.stringify(value);
27
+ if (typeof value === "number") {
28
+ if (!Number.isFinite(value))
29
+ throw new TypeError("JCS: non-finite numbers are not allowed");
30
+ return JSON.stringify(value);
31
+ }
32
+ if (typeof value === "string")
33
+ return JSON.stringify(value);
34
+ if (Array.isArray(value))
35
+ return "[" + value.map((v) => canonicalize(v === undefined ? null : v)).join(",") + "]";
36
+ if (typeof value === "object") {
37
+ const obj = value;
38
+ const keys = Object.keys(obj).filter((k) => obj[k] !== undefined).sort();
39
+ return "{" + keys.map((k) => JSON.stringify(k) + ":" + canonicalize(obj[k])).join(",") + "}";
40
+ }
41
+ throw new TypeError(`JCS: unsupported type ${typeof value}`);
42
+ }
43
+ export function nowSeconds() {
44
+ return Math.floor(Date.now() / 1000);
45
+ }
46
+ export function lowerKeys(headers) {
47
+ const out = {};
48
+ for (const [k, v] of Object.entries(headers)) {
49
+ if (v === undefined)
50
+ continue;
51
+ out[k.toLowerCase()] = Array.isArray(v) ? v.join(", ") : String(v);
52
+ }
53
+ return out;
54
+ }
55
+ export function randomId(prefix) {
56
+ const rnd = createHash("sha256").update(String(Math.random()) + Date.now() + process.hrtime.bigint()).digest("base64url");
57
+ return `${prefix}_${rnd.slice(0, 22)}`;
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,OAAsD;IAC9E,MAAM,GAAG,GAA2B,EAAE,CAAC;IACvC,KAAK,MAAM,CAAC,CAAC,EAAE,CAAC,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,OAAO,CAAC,EAAE,CAAC;QAC7C,IAAI,CAAC,KAAK,SAAS;YAAE,SAAS;QAC9B,GAAG,CAAC,CAAC,CAAC,WAAW,EAAE,CAAC,GAAG,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,CAAC;IACrE,CAAC;IACD,OAAO,GAAG,CAAC;AACb,CAAC;AAED,MAAM,UAAU,QAAQ,CAAC,MAAc;IACrC,MAAM,GAAG,GAAG,UAAU,CAAC,QAAQ,CAAC,CAAC,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC,GAAG,IAAI,CAAC,GAAG,EAAE,GAAG,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,CAAC,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC;IAC1H,OAAO,GAAG,MAAM,IAAI,GAAG,CAAC,KAAK,CAAC,CAAC,EAAE,EAAE,CAAC,EAAE,CAAC;AACzC,CAAC"}
@@ -0,0 +1,50 @@
1
+ import { KeyDirectory, type Jwk } from "./keys.js";
2
+ import { type ReplayStore } from "./replay.js";
3
+ import { type HttpRequestLike } from "./httpsig.js";
4
+ import { type SignedBodyObject } from "./bodyObjects.js";
5
+ import { type Mandate } from "./mandates/index.js";
6
+ import { type PaymentCredential } from "./payment.js";
7
+ import { type Policy, type PolicyInput } from "./policy.js";
8
+ import type { Order, VerificationResult } from "./types.js";
9
+ export interface CheckoutContext {
10
+ order?: Order;
11
+ mandate?: Mandate;
12
+ payment?: PaymentCredential;
13
+ consumerRecognition?: SignedBodyObject;
14
+ paymentContainer?: SignedBodyObject;
15
+ }
16
+ export interface AgentStats {
17
+ orders: number;
18
+ disputes: number;
19
+ mismatches: number;
20
+ }
21
+ export type ReputationProvider = (keyid: string) => AgentStats | undefined | Promise<AgentStats | undefined>;
22
+ export interface ProveTheBuyOptions {
23
+ /** Your merchant id, as it appears in mandates and payment tokens. */
24
+ merchantId: string;
25
+ /** Where agent keys come from. */
26
+ keys: KeyDirectory;
27
+ /** Issuer keys for Verifiable Intent layer 1. */
28
+ issuers?: KeyDirectory;
29
+ /** Shared nonce store. Defaults to in-memory (single server only). */
30
+ replay?: ReplayStore;
31
+ policy?: PolicyInput;
32
+ /** Your own public key, to check your signature on AP2 cart mandates. */
33
+ merchantJwk?: Jwk;
34
+ reputation?: ReputationProvider;
35
+ /** Clock override for tests. */
36
+ now?: () => number;
37
+ }
38
+ /** Pull checkout context out of a JSON body: { order, mandate, payment, consumer_recognition, payment_container }. */
39
+ export declare function contextFromBody(body: string | undefined): CheckoutContext;
40
+ export declare class ProveTheBuy {
41
+ private readonly opts;
42
+ readonly policy: Policy;
43
+ private readonly replay;
44
+ private readonly now;
45
+ constructor(opts: ProveTheBuyOptions);
46
+ /** Return a copy of this verifier with a different policy (used for dry runs). */
47
+ withPolicy(policy: PolicyInput): ProveTheBuy;
48
+ verify(req: HttpRequestLike, ctxIn?: CheckoutContext): Promise<VerificationResult>;
49
+ private run;
50
+ }
package/dist/verify.js ADDED
@@ -0,0 +1,309 @@
1
+ /**
2
+ * The verifier: one call per incoming request.
3
+ *
4
+ * 1. Is this an agent? Signature-Input / Signature headers present
5
+ * 2. Is the agent who it says? window, nonce, tag, key directory, RFC 9421 signature, body objects
6
+ * 3. Was it allowed to buy? mandate chain (Verifiable Intent, AP2) and scoped token limits
7
+ * 4. Is this the order it was allowed to buy? order hash and constraints
8
+ * 5. Decide allow / step_up / block, applied only in enforce mode
9
+ */
10
+ import { sha256Hex, nowSeconds } from "./util.js";
11
+ import { MemoryReplayStore } from "./replay.js";
12
+ import { AGENT_TAGS, inferAlg, parseSignatureHeader, parseSignatureInput, signatureBase, verifyBytes, } from "./httpsig.js";
13
+ import { verifyBodyObject } from "./bodyObjects.js";
14
+ import { verifyMandate } from "./mandates/index.js";
15
+ import { checkPaymentLimits } from "./payment.js";
16
+ import { itemsTotal, orderHash } from "./order.js";
17
+ import { resolvePolicy } from "./policy.js";
18
+ /** Pull checkout context out of a JSON body: { order, mandate, payment, consumer_recognition, payment_container }. */
19
+ export function contextFromBody(body) {
20
+ if (!body)
21
+ return {};
22
+ try {
23
+ const j = JSON.parse(body);
24
+ return {
25
+ order: j.order,
26
+ mandate: j.mandate,
27
+ payment: j.payment,
28
+ consumerRecognition: (j.consumer_recognition ?? j.agenticConsumer),
29
+ paymentContainer: (j.payment_container ?? j.agenticPaymentContainer),
30
+ };
31
+ }
32
+ catch {
33
+ return {};
34
+ }
35
+ }
36
+ function protocolFor(directory) {
37
+ if (directory === "visa")
38
+ return "visa-tap";
39
+ if (directory === "mastercard")
40
+ return "mastercard-agent-pay";
41
+ return "web-bot-auth";
42
+ }
43
+ export class ProveTheBuy {
44
+ opts;
45
+ policy;
46
+ replay;
47
+ now;
48
+ constructor(opts) {
49
+ this.opts = opts;
50
+ this.policy = resolvePolicy(opts.policy);
51
+ this.replay = opts.replay ?? new MemoryReplayStore();
52
+ this.now = opts.now ?? nowSeconds;
53
+ }
54
+ /** Return a copy of this verifier with a different policy (used for dry runs). */
55
+ withPolicy(policy) {
56
+ return new ProveTheBuy({ ...this.opts, policy, replay: new MemoryReplayStore() });
57
+ }
58
+ async verify(req, ctxIn) {
59
+ const receivedAt = new Date(this.now() * 1000).toISOString();
60
+ try {
61
+ return await this.run(req, ctxIn ?? contextFromBody(req.body), receivedAt);
62
+ }
63
+ catch (e) {
64
+ const open = this.policy.fail === "open";
65
+ return {
66
+ decision: open ? "not_agent" : "block",
67
+ enforced: this.policy.mode === "enforce",
68
+ reasons: [`Verification error (${open ? "failing open" : "failing closed"}): ${e.message}`],
69
+ checks: [{ name: "internal_error", status: "warn", detail: e.message }],
70
+ policyVersion: this.policy.version,
71
+ receivedAt,
72
+ };
73
+ }
74
+ }
75
+ async run(req, ctx, receivedAt) {
76
+ const p = this.policy;
77
+ const now = this.now();
78
+ const checks = [];
79
+ const reasons = [];
80
+ const headers = req.headers;
81
+ const rawSha256 = sha256Hex(`${req.method.toUpperCase()} ${req.url}\n` + Object.keys(headers).sort().map((k) => `${k}: ${headers[k]}`).join("\n") + "\n\n" + (req.body ?? ""));
82
+ const base = { enforced: p.mode === "enforce", policyVersion: p.version, receivedAt, rawSha256 };
83
+ let keyForRecord;
84
+ let issuerForRecord;
85
+ const done = (decision, extra = {}) => ({ decision, reasons, checks, ...base, agentKeyJwk: keyForRecord, issuerKeyJwk: issuerForRecord, ...extra });
86
+ // ---------------------------------------------------------------- 1. agent?
87
+ const sigInput = headers["signature-input"];
88
+ const sigHeader = headers["signature"];
89
+ if (!sigInput || !sigHeader) {
90
+ checks.push({ name: "signature_present", status: "skip", detail: "No agent signature headers. Left to your existing fraud tools." });
91
+ reasons.push("Not a signed agent request.");
92
+ return done("not_agent");
93
+ }
94
+ checks.push({ name: "signature_present", status: "pass", detail: "Signature-Input and Signature headers are present." });
95
+ let parsed;
96
+ let sigBytes;
97
+ try {
98
+ const inputs = parseSignatureInput(sigInput);
99
+ const sigs = parseSignatureHeader(sigHeader);
100
+ const chosen = inputs.find((i) => AGENT_TAGS.includes(String(i.params.tag))) ?? inputs[0];
101
+ if (!chosen || !sigs[chosen.label])
102
+ throw new Error("no Signature value matches the Signature-Input label");
103
+ parsed = chosen;
104
+ sigBytes = sigs[chosen.label];
105
+ }
106
+ catch (e) {
107
+ checks.push({ name: "signature_parse", status: "fail", detail: `Signature headers could not be parsed: ${e.message}.` });
108
+ reasons.push("Malformed agent signature.");
109
+ return done("block");
110
+ }
111
+ const sp = parsed.params;
112
+ const agent = {
113
+ protocol: "web-bot-auth",
114
+ keyid: String(sp.keyid ?? ""),
115
+ tag: sp.tag,
116
+ alg: sp.alg,
117
+ nonce: sp.nonce,
118
+ created: sp.created,
119
+ expires: sp.expires,
120
+ };
121
+ // params complete
122
+ const missing = ["created", "expires", "keyid", "nonce", "tag"].filter((k) => sp[k] === undefined);
123
+ if (missing.length) {
124
+ checks.push({ name: "params_complete", status: "fail", detail: `Signature is missing required parameters: ${missing.join(", ")}.` });
125
+ reasons.push("Incomplete agent signature.");
126
+ return done("block", { agent });
127
+ }
128
+ checks.push({ name: "params_complete", status: "pass", detail: "created, expires, keyid, nonce and tag are all present." });
129
+ // tag
130
+ const tag = String(sp.tag);
131
+ if (!AGENT_TAGS.includes(tag)) {
132
+ checks.push({ name: "tag_valid", status: "fail", detail: `Tag "${tag}" is not agent-browser-auth or agent-payer-auth.` });
133
+ reasons.push("Unknown agent tag.");
134
+ return done("block", { agent });
135
+ }
136
+ checks.push({ name: "tag_valid", status: "pass", detail: tag === "agent-payer-auth" ? "Agent declares it is paying (agent-payer-auth)." : "Agent declares it is browsing (agent-browser-auth)." });
137
+ // window
138
+ const created = Number(sp.created);
139
+ const expires = Number(sp.expires);
140
+ const skew = p.agents.clock_skew_seconds;
141
+ const windowProblems = [];
142
+ if (expires <= created)
143
+ windowProblems.push("expires is not after created");
144
+ if (expires - created > p.agents.max_window_seconds)
145
+ windowProblems.push(`window of ${expires - created}s exceeds ${p.agents.max_window_seconds}s`);
146
+ if (created > now + skew)
147
+ windowProblems.push("created is in the future");
148
+ if (expires < now - skew)
149
+ windowProblems.push(`signature expired ${now - expires}s ago`);
150
+ if (windowProblems.length) {
151
+ checks.push({ name: "window", status: "fail", detail: "Signature time window is invalid: " + windowProblems.join("; ") + ".", data: { created, expires, now } });
152
+ reasons.push("Expired or invalid signature window.");
153
+ return done("block", { agent });
154
+ }
155
+ checks.push({ name: "window", status: "pass", detail: `Signed ${Math.max(0, now - created)}s ago, valid for ${expires - created}s.`, data: { created, expires } });
156
+ // key
157
+ const key = await this.opts.keys.resolve(agent.keyid, p.agents.directories.length ? p.agents.directories : undefined);
158
+ if (!key) {
159
+ checks.push({ name: "key_found", status: "fail", detail: `Key "${agent.keyid}" is not in any trusted directory (${this.opts.keys.sourceNames.join(", ") || "none configured"}).` });
160
+ reasons.push("Unknown agent key.");
161
+ return done("block", { agent });
162
+ }
163
+ agent.directory = key.source;
164
+ agent.protocol = protocolFor(key.source);
165
+ agent.keySnapshotSha256 = key.snapshotSha256;
166
+ keyForRecord = key.jwk;
167
+ checks.push({ name: "key_found", status: "pass", detail: `Key found in the ${key.source} directory.`, data: { snapshot: key.snapshotSha256 } });
168
+ // signature
169
+ const alg = inferAlg(key.jwk, sp.alg);
170
+ if (!alg) {
171
+ checks.push({ name: "signature_valid", status: "fail", detail: `Unsupported signature algorithm "${String(sp.alg)}".` });
172
+ reasons.push("Unsupported algorithm.");
173
+ return done("block", { agent });
174
+ }
175
+ let sigOk = false;
176
+ let baseStr = "";
177
+ try {
178
+ baseStr = signatureBase(req, parsed);
179
+ sigOk = verifyBytes(alg, key.key, Buffer.from(baseStr, "utf8"), sigBytes);
180
+ }
181
+ catch (e) {
182
+ checks.push({ name: "signature_valid", status: "fail", detail: `Signature base could not be built: ${e.message}.` });
183
+ reasons.push("Signature could not be checked.");
184
+ return done("block", { agent });
185
+ }
186
+ if (!sigOk) {
187
+ checks.push({ name: "signature_valid", status: "fail", detail: "Signature does not match. The request was altered, or signed with a different key.", data: { signature_base: baseStr } });
188
+ reasons.push("Invalid agent signature.");
189
+ return done("block", { agent });
190
+ }
191
+ checks.push({ name: "signature_valid", status: "pass", detail: `${alg} signature verified over ${parsed.components.join(", ")}.`, data: { signature_base: baseStr } });
192
+ // nonce: only after the signature is valid, so forged requests cannot burn nonces
193
+ const fresh = await this.replay.checkAndRemember(`${agent.keyid}:${agent.nonce}`, expires - now + skew);
194
+ if (!fresh) {
195
+ checks.push({ name: "nonce_unused", status: "fail", detail: "This nonce was already used. The request is a replay." });
196
+ reasons.push("Replayed request.");
197
+ return done("block", { agent });
198
+ }
199
+ checks.push({ name: "nonce_unused", status: "pass", detail: "Nonce has not been seen before." });
200
+ // body objects
201
+ for (const [name, obj] of [["consumer_recognition", ctx.consumerRecognition], ["payment_container", ctx.paymentContainer]]) {
202
+ const c = verifyBodyObject(name, obj, { nonce: agent.nonce, keyid: agent.keyid, alg, key: key.key });
203
+ if (c) {
204
+ checks.push(c);
205
+ if (c.status === "fail") {
206
+ reasons.push("Signed body object is not bound to this request.");
207
+ return done("block", { agent });
208
+ }
209
+ }
210
+ }
211
+ // browsing agents stop here
212
+ if (tag === "agent-browser-auth" && !ctx.order) {
213
+ reasons.push("Verified browsing agent.");
214
+ return done("allow", { agent });
215
+ }
216
+ // ---------------------------------------------------------------- 3-4. mandate and order
217
+ const order = ctx.order;
218
+ const state = { decision: "allow" };
219
+ let mandateInfo;
220
+ let oh;
221
+ const escalate = (to, why) => {
222
+ reasons.push(why);
223
+ const rank = { not_agent: 0, allow: 1, step_up: 2, block: 3 };
224
+ if (rank[to] > rank[state.decision])
225
+ state.decision = to;
226
+ };
227
+ if (!order) {
228
+ checks.push({ name: "order_present", status: "warn", detail: "Paying agent request has no order in the body, so it cannot be bound to a mandate." });
229
+ escalate(p.mandate.on_missing === "allow" ? "allow" : p.mandate.on_missing, "No order to bind.");
230
+ }
231
+ else {
232
+ oh = orderHash(order);
233
+ const sumOk = itemsTotal(order) === order.total;
234
+ checks.push(sumOk
235
+ ? { name: "order_consistent", status: "pass", detail: "Order total equals the sum of its items.", data: { order_hash: oh } }
236
+ : { name: "order_consistent", status: "fail", detail: `Order total ${order.total} does not equal the items sum ${itemsTotal(order)}.`, data: { order_hash: oh } });
237
+ if (!sumOk)
238
+ escalate("block", "Inconsistent order.");
239
+ if (p.limits.require_merchant_match && order.merchant_id !== this.opts.merchantId) {
240
+ checks.push({ name: "merchant_match", status: "fail", detail: `Order is for merchant ${order.merchant_id}, not ${this.opts.merchantId}.` });
241
+ escalate("block", "Order for a different merchant.");
242
+ }
243
+ const m = await verifyMandate(ctx.mandate, {
244
+ order,
245
+ orderHash: oh,
246
+ now,
247
+ merchantId: this.opts.merchantId,
248
+ issuers: this.opts.issuers,
249
+ merchantJwk: this.opts.merchantJwk,
250
+ accept: p.mandate.accept,
251
+ });
252
+ if (!m) {
253
+ checks.push({ name: "mandate_present", status: "fail", detail: "No mandate: nothing shows what the person allowed the agent to buy." });
254
+ if (p.mandate.on_missing !== "allow")
255
+ escalate(p.mandate.on_missing, "No mandate from the person.");
256
+ }
257
+ else {
258
+ checks.push({ name: "mandate_present", status: "pass", detail: `Mandate type ${m.info.type}.` });
259
+ checks.push(...m.checks);
260
+ mandateInfo = m.info;
261
+ issuerForRecord = m.issuerKeyJwk;
262
+ if (!m.info.valid)
263
+ escalate("block", "Mandate does not verify.");
264
+ else if (m.info.constraintsOk === false)
265
+ escalate(p.mandate.on_outside, "Order is outside the mandate.");
266
+ const intentOnly = m.info.type === "ap2-intent" || m.info.mode === "autonomous";
267
+ if (m.info.valid && intentOnly && p.limits.intent_mandate_max_order > 0 && order.total > p.limits.intent_mandate_max_order) {
268
+ checks.push({ name: "intent_threshold", status: "warn", detail: `Unattended purchase of ${order.total} is above the ${p.limits.intent_mandate_max_order} confirmation threshold.` });
269
+ escalate("step_up", "Large unattended purchase.");
270
+ }
271
+ }
272
+ const t = checkPaymentLimits(ctx.payment, order, this.opts.merchantId, now);
273
+ checks.push(t);
274
+ if (t.status === "fail")
275
+ escalate("block", "Payment token limits would be exceeded.");
276
+ }
277
+ // ---------------------------------------------------------------- reputation
278
+ if (this.opts.reputation) {
279
+ const s = await this.opts.reputation(agent.keyid);
280
+ if (s && s.orders >= p.reputation.min_orders_for_reputation) {
281
+ const rate = s.disputes / s.orders;
282
+ const bad = rate > p.reputation.step_up_if_agent_dispute_rate_over;
283
+ checks.push({
284
+ name: "reputation",
285
+ status: bad ? "warn" : "pass",
286
+ detail: `This agent key: ${s.orders} orders, ${(rate * 100).toFixed(1)}% disputed.`,
287
+ data: { ...s, rate },
288
+ });
289
+ if (bad)
290
+ escalate("step_up", "Agent has a high dispute rate.");
291
+ }
292
+ else {
293
+ checks.push({ name: "reputation", status: "skip", detail: "Not enough history for this agent key yet." });
294
+ }
295
+ }
296
+ const final = state.decision;
297
+ if (final === "allow" && !reasons.length)
298
+ reasons.push("Verified agent, valid mandate, order inside its limits.");
299
+ return done(final, {
300
+ agent,
301
+ mandate: mandateInfo,
302
+ orderHash: oh,
303
+ stepUp: final === "step_up"
304
+ ? { reason: reasons[reasons.length - 1], suggested: ctx.mandate?.type === "ap2-intent" || !ctx.mandate ? "ap2-cart-mandate" : "confirm-in-session" }
305
+ : undefined,
306
+ });
307
+ }
308
+ }
309
+ //# sourceMappingURL=verify.js.map