@armory-sh/middleware-express 0.3.11 → 0.4.1

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.
package/package.json CHANGED
@@ -1,20 +1,19 @@
1
1
  {
2
2
  "name": "@armory-sh/middleware-express",
3
- "version": "0.3.11",
3
+ "version": "0.4.1",
4
4
  "license": "MIT",
5
5
  "author": "Sawyer Cutler <sawyer@dirtroad.dev>",
6
6
  "type": "module",
7
- "main": "./dist/index.js",
8
- "types": "./dist/index.d.ts",
7
+ "main": "./src/index.ts",
8
+ "types": "./src/index.ts",
9
9
  "exports": {
10
10
  ".": {
11
- "types": "./dist/index.d.ts",
12
- "bun": "./src/index.ts",
13
- "default": "./dist/index.js"
11
+ "types": "./src/index.ts",
12
+ "default": "./src/index.ts"
14
13
  }
15
14
  },
16
15
  "files": [
17
- "dist"
16
+ "src"
18
17
  ],
19
18
  "publishConfig": {
20
19
  "access": "public"
@@ -25,20 +24,19 @@
25
24
  "directory": "packages/middleware-express"
26
25
  },
27
26
  "peerDependencies": {
28
- "express": "^4"
27
+ "express": "^5"
29
28
  },
30
29
  "dependencies": {
31
- "@armory-sh/base": "0.2.12",
32
- "@armory-sh/facilitator": "0.2.12"
30
+ "@armory-sh/base": "workspace:*"
33
31
  },
34
32
  "devDependencies": {
35
33
  "bun-types": "latest",
36
34
  "typescript": "5.9.3",
37
- "express": "^4",
38
- "@types/express": "^4"
35
+ "express": "^5",
36
+ "@types/express": "^5"
39
37
  },
40
38
  "scripts": {
41
- "build": "tsup",
39
+ "build": "rm -rf dist && tsup",
42
40
  "test": "bun test"
43
41
  }
44
42
  }
package/src/index.ts ADDED
@@ -0,0 +1,88 @@
1
+ import type { Request, Response, NextFunction } from "express";
2
+ import type {
3
+ PaymentPayload,
4
+ PaymentRequirements,
5
+ } from "./payment-utils";
6
+ import {
7
+ getRequirementsVersion,
8
+ getHeadersForVersion,
9
+ encodeRequirements,
10
+ decodePayload,
11
+ verifyPaymentWithRetry,
12
+ extractPayerAddress,
13
+ } from "./payment-utils";
14
+
15
+ export interface PaymentMiddlewareConfig {
16
+ requirements: PaymentRequirements;
17
+ facilitatorUrl?: string;
18
+ skipVerification?: boolean;
19
+ }
20
+
21
+ export interface AugmentedRequest extends Request {
22
+ payment?: {
23
+ payload: PaymentPayload;
24
+ payerAddress: string;
25
+ version: 1 | 2;
26
+ verified: boolean;
27
+ };
28
+ }
29
+
30
+ const sendError = (
31
+ res: Response,
32
+ status: number,
33
+ headers: Record<string, string>,
34
+ body: unknown
35
+ ): void => {
36
+ // Express v5: use res.statusCode instead of res.status()
37
+ res.statusCode = status;
38
+ Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v));
39
+ res.json(body);
40
+ };
41
+
42
+ export const paymentMiddleware = (config: PaymentMiddlewareConfig) => {
43
+ const { requirements, facilitatorUrl, skipVerification = false } = config;
44
+ const version = getRequirementsVersion(requirements);
45
+ const headers = getHeadersForVersion(version);
46
+
47
+ return async (req: AugmentedRequest, res: Response, next: NextFunction): Promise<void> => {
48
+ try {
49
+ const paymentHeader = req.headers[headers.payment.toLowerCase()] as string | undefined;
50
+
51
+ if (!paymentHeader) {
52
+ sendError(res, 402, { [headers.required]: encodeRequirements(requirements, req.url || req.originalUrl), "Content-Type": "application/json" }, { error: "Payment required", accepts: [requirements] });
53
+ return;
54
+ }
55
+
56
+ let payload: PaymentPayload;
57
+ let payloadVersion: 1 | 2;
58
+ try {
59
+ ({ payload, version: payloadVersion } = decodePayload(paymentHeader));
60
+ } catch (error) {
61
+ sendError(res, 400, {}, { error: "Invalid payment payload", message: error instanceof Error ? error.message : "Unknown error" });
62
+ return;
63
+ }
64
+
65
+ if (payloadVersion !== version) {
66
+ sendError(res, 400, {}, { error: "Payment version mismatch", expected: version, received: payloadVersion });
67
+ return;
68
+ }
69
+
70
+ const payerAddress = skipVerification
71
+ ? extractPayerAddress(payload)
72
+ : await (async () => {
73
+ const result = await verifyPaymentWithRetry(payload, requirements, facilitatorUrl);
74
+ if (!result.success) {
75
+ sendError(res, 402, { [headers.required]: encodeRequirements(requirements) }, { error: result.error });
76
+ throw new Error("Verification failed");
77
+ }
78
+ return result.payerAddress!;
79
+ })();
80
+
81
+ req.payment = { payload, payerAddress, version, verified: !skipVerification };
82
+ res.setHeader(headers.response, JSON.stringify({ status: "verified", payerAddress, version }));
83
+ next();
84
+ } catch (error) {
85
+ sendError(res, 500, {}, { error: "Payment middleware error", message: error instanceof Error ? error.message : "Unknown error" });
86
+ }
87
+ };
88
+ };
@@ -0,0 +1,193 @@
1
+ import type {
2
+ X402PaymentPayload,
3
+ X402PaymentRequirements,
4
+ } from "@armory-sh/base";
5
+ import { extractPaymentFromHeaders, X402_HEADERS } from "@armory-sh/base";
6
+
7
+ // Legacy V1 payload type for backward compatibility
8
+ export interface LegacyPaymentPayloadV1 {
9
+ amount: string;
10
+ network: string;
11
+ contractAddress: string;
12
+ payTo: string;
13
+ from: string;
14
+ expiry: number;
15
+ signature: string;
16
+ }
17
+
18
+ // Legacy V2 payload type for backward compatibility
19
+ export interface LegacyPaymentPayloadV2 {
20
+ to: string;
21
+ from: string;
22
+ amount: string;
23
+ chainId: string;
24
+ assetId: string;
25
+ nonce: string;
26
+ expiry: number;
27
+ signature: string;
28
+ }
29
+
30
+ // Union type for all payload formats
31
+ export type AnyPaymentPayload = X402PaymentPayload | LegacyPaymentPayloadV1 | LegacyPaymentPayloadV2;
32
+
33
+ // Re-export types for use in index.ts
34
+ export type PaymentPayload = AnyPaymentPayload;
35
+ export type { X402PaymentRequirements as PaymentRequirements } from "@armory-sh/base";
36
+
37
+ export type PaymentVersion = 1 | 2;
38
+
39
+ export interface PaymentVerificationResult {
40
+ success: boolean;
41
+ payload?: AnyPaymentPayload;
42
+ version?: PaymentVersion;
43
+ payerAddress?: string;
44
+ error?: string;
45
+ }
46
+
47
+ export interface PaymentHeaders {
48
+ payment: string;
49
+ required: string;
50
+ response: string;
51
+ }
52
+
53
+ export const getHeadersForVersion = (version: PaymentVersion): PaymentHeaders =>
54
+ version === 1
55
+ ? { payment: "X-PAYMENT", required: "X-PAYMENT-REQUIRED", response: "X-PAYMENT-RESPONSE" }
56
+ : { payment: "PAYMENT-SIGNATURE", required: "PAYMENT-REQUIRED", response: "PAYMENT-RESPONSE" };
57
+
58
+ export const getRequirementsVersion = (requirements: X402PaymentRequirements): PaymentVersion =>
59
+ "contractAddress" in requirements && "network" in requirements ? 1 : 2;
60
+
61
+ export const encodeRequirements = (requirements: X402PaymentRequirements, _resourceUrl?: string): string =>
62
+ JSON.stringify(requirements);
63
+
64
+ function isLegacyV1(payload: unknown): payload is LegacyPaymentPayloadV1 {
65
+ return (
66
+ typeof payload === "object" &&
67
+ payload !== null &&
68
+ "contractAddress" in payload &&
69
+ "network" in payload &&
70
+ "signature" in payload &&
71
+ typeof (payload as LegacyPaymentPayloadV1).signature === "string"
72
+ );
73
+ }
74
+
75
+ function isLegacyV2(payload: unknown): payload is LegacyPaymentPayloadV2 {
76
+ return (
77
+ typeof payload === "object" &&
78
+ payload !== null &&
79
+ "chainId" in payload &&
80
+ "assetId" in payload &&
81
+ "signature" in payload &&
82
+ typeof (payload as LegacyPaymentPayloadV2).signature === "string"
83
+ );
84
+ }
85
+
86
+ export const decodePayload = (
87
+ headerValue: string
88
+ ): { payload: AnyPaymentPayload; version: PaymentVersion } => {
89
+ let parsed: unknown;
90
+ let isJsonString = false;
91
+ try {
92
+ if (headerValue.startsWith("{")) {
93
+ parsed = JSON.parse(headerValue);
94
+ isJsonString = true;
95
+ } else {
96
+ parsed = JSON.parse(atob(headerValue));
97
+ }
98
+ } catch {
99
+ throw new Error("Invalid payment payload");
100
+ }
101
+
102
+ const base64Value = isJsonString
103
+ ? Buffer.from(headerValue).toString("base64")
104
+ : headerValue;
105
+ const headers = new Headers();
106
+ headers.set(X402_HEADERS.PAYMENT, base64Value);
107
+ const x402Payload = extractPaymentFromHeaders(headers);
108
+ if (x402Payload) {
109
+ return { payload: x402Payload, version: 2 };
110
+ }
111
+
112
+ if (isLegacyV1(parsed)) {
113
+ return { payload: parsed, version: 1 };
114
+ }
115
+
116
+ if (isLegacyV2(parsed)) {
117
+ return { payload: parsed, version: 2 };
118
+ }
119
+
120
+ throw new Error("Unrecognized payment payload format");
121
+ };
122
+
123
+ export const verifyWithFacilitator = async (
124
+ facilitatorUrl: string,
125
+ payload: AnyPaymentPayload,
126
+ requirements: X402PaymentRequirements
127
+ ): Promise<PaymentVerificationResult> => {
128
+ try {
129
+ const response = await fetch(`${facilitatorUrl}/verify`, {
130
+ method: "POST",
131
+ headers: { "Content-Type": "application/json" },
132
+ body: JSON.stringify({ payload, requirements }),
133
+ });
134
+
135
+ if (!response.ok) {
136
+ const error = await response.json();
137
+ return { success: false, error: JSON.stringify(error) };
138
+ }
139
+
140
+ const result = await response.json() as { success: boolean; error?: string; payerAddress?: string };
141
+ if (!result.success) {
142
+ return { success: false, error: result.error ?? "Verification failed" };
143
+ }
144
+
145
+ return { success: true, payerAddress: result.payerAddress ?? "" };
146
+ } catch (error) {
147
+ return {
148
+ success: false,
149
+ error: error instanceof Error ? error.message : "Unknown facilitator error",
150
+ };
151
+ }
152
+ };
153
+
154
+ export const verifyLocally = async (
155
+ payload: AnyPaymentPayload,
156
+ requirements: X402PaymentRequirements
157
+ ): Promise<PaymentVerificationResult> => {
158
+ if (isLegacyV1(payload) || isLegacyV2(payload)) {
159
+ return {
160
+ success: false,
161
+ error: "Local verification not supported for legacy payload formats. Use a facilitator.",
162
+ };
163
+ }
164
+
165
+ return {
166
+ success: true,
167
+ payerAddress: (payload as X402PaymentPayload).payload.authorization.from,
168
+ };
169
+ };
170
+
171
+ export const verifyPaymentWithRetry = async (
172
+ payload: AnyPaymentPayload,
173
+ requirements: X402PaymentRequirements,
174
+ facilitatorUrl?: string
175
+ ): Promise<PaymentVerificationResult> =>
176
+ facilitatorUrl
177
+ ? verifyWithFacilitator(facilitatorUrl, payload, requirements)
178
+ : verifyLocally(payload, requirements);
179
+
180
+ export const extractPayerAddress = (payload: AnyPaymentPayload): string => {
181
+ if ("payload" in payload) {
182
+ const x402Payload = payload as X402PaymentPayload;
183
+ if ("authorization" in x402Payload.payload) {
184
+ return x402Payload.payload.authorization.from;
185
+ }
186
+ }
187
+
188
+ if ("from" in payload && typeof payload.from === "string") {
189
+ return payload.from;
190
+ }
191
+
192
+ throw new Error("Unable to extract payer address from payload");
193
+ };
package/src/types.ts ADDED
@@ -0,0 +1,44 @@
1
+ import type { Address, CAIP2ChainId, CAIPAssetId } from "@armory-sh/base";
2
+
3
+ export interface FacilitatorConfig {
4
+ url: string;
5
+ createHeaders?: () => Record<string, string>;
6
+ }
7
+
8
+ export type SettlementMode = "verify" | "settle" | "async";
9
+ export type PayToAddress = Address | CAIP2ChainId | CAIPAssetId;
10
+
11
+ export interface MiddlewareConfig {
12
+ payTo: PayToAddress;
13
+ network: string | number;
14
+ amount: string;
15
+ facilitator?: FacilitatorConfig;
16
+ settlementMode?: SettlementMode;
17
+ }
18
+
19
+ export interface HttpRequest {
20
+ headers: Record<string, string | string[] | undefined>;
21
+ body?: unknown;
22
+ method?: string;
23
+ url?: string;
24
+ }
25
+
26
+ export interface HttpResponse {
27
+ status: number;
28
+ headers: Record<string, string>;
29
+ body?: unknown;
30
+ }
31
+
32
+ export interface FacilitatorVerifyResult {
33
+ success: boolean;
34
+ payerAddress?: string;
35
+ balance?: string;
36
+ requiredAmount?: string;
37
+ error?: string;
38
+ }
39
+
40
+ export interface FacilitatorSettleResult {
41
+ success: boolean;
42
+ txHash?: string;
43
+ error?: string;
44
+ }
package/dist/index.d.ts DELETED
@@ -1,43 +0,0 @@
1
- import { Request, Response, NextFunction } from 'express';
2
- import { X402PaymentPayload, X402PaymentRequirements } from '@armory-sh/base';
3
- import { VerifyPaymentOptions } from '@armory-sh/facilitator';
4
-
5
- interface LegacyPaymentPayloadV1 {
6
- amount: string;
7
- network: string;
8
- contractAddress: string;
9
- payTo: string;
10
- from: string;
11
- expiry: number;
12
- signature: string;
13
- }
14
- interface LegacyPaymentPayloadV2 {
15
- to: string;
16
- from: string;
17
- amount: string;
18
- chainId: string;
19
- assetId: string;
20
- nonce: string;
21
- expiry: number;
22
- signature: string;
23
- }
24
- type AnyPaymentPayload = X402PaymentPayload | LegacyPaymentPayloadV1 | LegacyPaymentPayloadV2;
25
- type PaymentPayload = AnyPaymentPayload;
26
-
27
- interface PaymentMiddlewareConfig {
28
- requirements: X402PaymentRequirements;
29
- facilitatorUrl?: string;
30
- verifyOptions?: VerifyPaymentOptions;
31
- skipVerification?: boolean;
32
- }
33
- interface AugmentedRequest extends Request {
34
- payment?: {
35
- payload: PaymentPayload;
36
- payerAddress: string;
37
- version: 1 | 2;
38
- verified: boolean;
39
- };
40
- }
41
- declare const paymentMiddleware: (config: PaymentMiddlewareConfig) => (req: AugmentedRequest, res: Response, next: NextFunction) => Promise<void>;
42
-
43
- export { type AugmentedRequest, type PaymentMiddlewareConfig, paymentMiddleware };
package/dist/index.js DELETED
@@ -1,142 +0,0 @@
1
- // src/payment-utils.ts
2
- import { extractPaymentFromHeaders, X402_HEADERS } from "@armory-sh/base";
3
- import { verifyX402Payment as verifyPayment } from "@armory-sh/facilitator";
4
- var getHeadersForVersion = (version) => version === 1 ? { payment: "X-PAYMENT", required: "X-PAYMENT-REQUIRED", response: "X-PAYMENT-RESPONSE" } : { payment: "PAYMENT-SIGNATURE", required: "PAYMENT-REQUIRED", response: "PAYMENT-RESPONSE" };
5
- var getRequirementsVersion = (requirements) => "contractAddress" in requirements && "network" in requirements ? 1 : 2;
6
- var encodeRequirements = (requirements) => JSON.stringify(requirements);
7
- function isLegacyV1(payload) {
8
- return typeof payload === "object" && payload !== null && "contractAddress" in payload && "network" in payload && "signature" in payload && typeof payload.signature === "string";
9
- }
10
- function isLegacyV2(payload) {
11
- return typeof payload === "object" && payload !== null && "chainId" in payload && "assetId" in payload && "signature" in payload && typeof payload.signature === "string";
12
- }
13
- var decodePayload = (headerValue) => {
14
- let parsed;
15
- try {
16
- if (headerValue.startsWith("{")) {
17
- parsed = JSON.parse(headerValue);
18
- } else {
19
- parsed = JSON.parse(atob(headerValue));
20
- }
21
- } catch {
22
- throw new Error("Invalid payment payload");
23
- }
24
- const headers = new Headers();
25
- headers.set(X402_HEADERS.PAYMENT, headerValue);
26
- const x402Payload = extractPaymentFromHeaders(headers);
27
- if (x402Payload) {
28
- return { payload: x402Payload, version: 2 };
29
- }
30
- if (isLegacyV1(parsed)) {
31
- return { payload: parsed, version: 1 };
32
- }
33
- if (isLegacyV2(parsed)) {
34
- return { payload: parsed, version: 2 };
35
- }
36
- throw new Error("Unrecognized payment payload format");
37
- };
38
- var verifyWithFacilitator = async (facilitatorUrl, payload, requirements, verifyOptions) => {
39
- try {
40
- const response = await fetch(`${facilitatorUrl}/verify`, {
41
- method: "POST",
42
- headers: { "Content-Type": "application/json" },
43
- body: JSON.stringify({ payload, requirements, options: verifyOptions })
44
- });
45
- if (!response.ok) {
46
- const error = await response.json();
47
- return { success: false, error: JSON.stringify(error) };
48
- }
49
- const result = await response.json();
50
- if (!result.success) {
51
- return { success: false, error: result.error ?? "Verification failed" };
52
- }
53
- return { success: true, payerAddress: result.payerAddress ?? "" };
54
- } catch (error) {
55
- return {
56
- success: false,
57
- error: error instanceof Error ? error.message : "Unknown facilitator error"
58
- };
59
- }
60
- };
61
- var verifyLocally = async (payload, requirements, verifyOptions) => {
62
- if (isLegacyV1(payload) || isLegacyV2(payload)) {
63
- return {
64
- success: false,
65
- error: "Local verification not supported for legacy payload formats. Use a facilitator."
66
- };
67
- }
68
- const result = await verifyPayment(payload, requirements, verifyOptions);
69
- if (!result.success) {
70
- return {
71
- success: false,
72
- error: JSON.stringify({
73
- error: "Payment verification failed",
74
- reason: result.error.name,
75
- message: result.error.message
76
- })
77
- };
78
- }
79
- return { success: true, payerAddress: result.payerAddress };
80
- };
81
- var verifyPaymentWithRetry = async (payload, requirements, facilitatorUrl, verifyOptions) => facilitatorUrl ? verifyWithFacilitator(facilitatorUrl, payload, requirements, verifyOptions) : verifyLocally(payload, requirements, verifyOptions);
82
- var extractPayerAddress = (payload) => {
83
- if ("payload" in payload) {
84
- const x402Payload = payload;
85
- if ("authorization" in x402Payload.payload) {
86
- return x402Payload.payload.authorization.from;
87
- }
88
- }
89
- if ("from" in payload && typeof payload.from === "string") {
90
- return payload.from;
91
- }
92
- throw new Error("Unable to extract payer address from payload");
93
- };
94
-
95
- // src/index.ts
96
- var sendError = (res, status, headers, body) => {
97
- res.status(status);
98
- Object.entries(headers).forEach(([k, v]) => res.setHeader(k, v));
99
- res.json(body);
100
- };
101
- var paymentMiddleware = (config) => {
102
- const { requirements, facilitatorUrl, verifyOptions, skipVerification = false } = config;
103
- const version = getRequirementsVersion(requirements);
104
- const headers = getHeadersForVersion(version);
105
- return async (req, res, next) => {
106
- try {
107
- const paymentHeader = req.headers[headers.payment.toLowerCase()];
108
- if (!paymentHeader) {
109
- sendError(res, 402, { [headers.required]: encodeRequirements(requirements), "Content-Type": "application/json" }, { error: "Payment required", requirements });
110
- return;
111
- }
112
- let payload;
113
- let payloadVersion;
114
- try {
115
- ({ payload, version: payloadVersion } = decodePayload(paymentHeader));
116
- } catch (error) {
117
- sendError(res, 400, {}, { error: "Invalid payment payload", message: error instanceof Error ? error.message : "Unknown error" });
118
- return;
119
- }
120
- if (payloadVersion !== version) {
121
- sendError(res, 400, {}, { error: "Payment version mismatch", expected: version, received: payloadVersion });
122
- return;
123
- }
124
- const payerAddress = skipVerification ? extractPayerAddress(payload) : await (async () => {
125
- const result = await verifyPaymentWithRetry(payload, requirements, facilitatorUrl, verifyOptions);
126
- if (!result.success) {
127
- sendError(res, 402, { [headers.required]: encodeRequirements(requirements) }, { error: result.error });
128
- throw new Error("Verification failed");
129
- }
130
- return result.payerAddress;
131
- })();
132
- req.payment = { payload, payerAddress, version, verified: !skipVerification };
133
- res.setHeader(headers.response, JSON.stringify({ status: "verified", payerAddress, version }));
134
- next();
135
- } catch (error) {
136
- sendError(res, 500, {}, { error: "Payment middleware error", message: error instanceof Error ? error.message : "Unknown error" });
137
- }
138
- };
139
- };
140
- export {
141
- paymentMiddleware
142
- };