s402 0.1.1 → 0.1.2

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/CHANGELOG.md CHANGED
@@ -5,6 +5,21 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [0.1.1] - 2026-02-16
9
+
10
+ ### Fixed
11
+
12
+ - Facilitator `verify()` and `settle()` now have the same defense-in-depth guards as `process()`:
13
+ - Reject non-number `expiresAt` values (prevents silent bypass with string types)
14
+ - Reject payload schemes not in `requirements.accepts` (scheme-mismatch guard)
15
+ - `protocolFeeBps` validation now requires an integer (rejects `50.5`)
16
+ - Sub-object fields (stream, escrow, unlock, prepaid, mandate) are now stripped of unknown keys at the trust boundary, matching the top-level field stripping behavior
17
+ - `process()` now catches exceptions thrown by `scheme.settle()` and returns them as error results instead of propagating unhandled
18
+
19
+ ### Added
20
+
21
+ - `isValidU64Amount()` — validates amount strings fit in a Sui u64 (format + magnitude check). The existing `isValidAmount()` remains format-only for chain-agnostic use.
22
+
8
23
  ## [0.1.0] - 2026-02-15
9
24
 
10
25
  ### Added
package/SECURITY.md CHANGED
@@ -4,10 +4,10 @@
4
4
 
5
5
  **Please do not open public issues for security vulnerabilities.**
6
6
 
7
- If you discover a security issue in s402, please report it privately:
7
+ If you discover a security issue in s402, please report it privately via either method:
8
8
 
9
- - **Email:** dannydevs@proton.me
10
- - **Subject line:** `[s402 security] <brief description>`
9
+ - **Email:** dannydevs@proton.me (subject: `[s402 security] <brief description>`)
10
+ - **GitHub:** [Open a private security advisory](https://github.com/s402-protocol/core/security/advisories/new)
11
11
 
12
12
  You will receive an acknowledgment within 48 hours. We aim to provide a fix or mitigation plan within 7 days of confirmation.
13
13
 
package/dist/http.d.mts CHANGED
@@ -20,10 +20,15 @@ declare function pickSettleResponseFields(obj: Record<string, unknown>): s402Set
20
20
  /** Decode settlement response from the `payment-response` header */
21
21
  declare function decodeSettleResponse(header: string): s402SettleResponse;
22
22
  /**
23
- * Check that a string represents a canonical non-negative integer (valid for Sui MIST amounts).
23
+ * Check that a string represents a canonical non-negative integer.
24
24
  * Rejects leading zeros ("007"), empty strings, negatives, decimals.
25
25
  * Accepts "0" as the only zero representation.
26
26
  *
27
+ * NOTE: This is a **format-only** check — it validates the string is a well-formed
28
+ * non-negative integer but does NOT enforce magnitude bounds. Arbitrarily large
29
+ * integers (e.g. 100+ digits) pass this check. For Sui-specific u64 validation,
30
+ * use `isValidU64Amount()` which also checks that the value fits in a u64.
31
+ *
27
32
  * A-13 (Semantic gap): "0" passes validation because it's a valid u64 on-chain.
28
33
  * However, amount="0" in payment requirements is semantically ambiguous — it could
29
34
  * mean "free" or be a misconfiguration. The s402 wire format intentionally allows it
@@ -32,6 +37,14 @@ declare function decodeSettleResponse(header: string): s402SettleResponse;
32
37
  * not at the protocol level.
33
38
  */
34
39
  declare function isValidAmount(s: string): boolean;
40
+ /**
41
+ * Check that a string represents a valid Sui u64 amount.
42
+ * Like `isValidAmount` but also rejects values exceeding u64 max (2^64 - 1).
43
+ *
44
+ * Use this in scheme implementations that target Sui's u64 amounts (MIST, etc.).
45
+ * The wire-format validator uses `isValidAmount` (format-only) to stay chain-agnostic.
46
+ */
47
+ declare function isValidU64Amount(s: string): boolean;
35
48
  /**
36
49
  * Validate mandate requirements sub-object.
37
50
  * Mandate is protocol-level (used for authorization decisions), so we validate fully.
@@ -75,4 +88,4 @@ declare function detectProtocol(headers: Headers): 's402' | 'x402' | 'unknown';
75
88
  */
76
89
  declare function extractRequirementsFromResponse(response: Response): s402PaymentRequirements | null;
77
90
  //#endregion
78
- export { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, pickPayloadFields, pickRequirementsFields, pickSettleResponseFields, validateEscrowShape, validateMandateShape, validatePrepaidShape, validateRequirementsShape, validateStreamShape, validateSubObjects, validateUnlockShape };
91
+ export { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, pickPayloadFields, pickRequirementsFields, pickSettleResponseFields, validateEscrowShape, validateMandateShape, validatePrepaidShape, validateRequirementsShape, validateStreamShape, validateSubObjects, validateUnlockShape };
package/dist/http.mjs CHANGED
@@ -56,10 +56,50 @@ const S402_REQUIREMENTS_KEYS = new Set([
56
56
  "prepaid",
57
57
  "extensions"
58
58
  ]);
59
+ /** Known keys for each sub-object type — used to strip extra keys at the trust boundary. */
60
+ const S402_SUB_OBJECT_KEYS = {
61
+ mandate: new Set([
62
+ "required",
63
+ "minPerTx",
64
+ "coinType"
65
+ ]),
66
+ stream: new Set([
67
+ "ratePerSecond",
68
+ "budgetCap",
69
+ "minDeposit",
70
+ "streamSetupUrl"
71
+ ]),
72
+ escrow: new Set([
73
+ "seller",
74
+ "arbiter",
75
+ "deadlineMs"
76
+ ]),
77
+ unlock: new Set([
78
+ "encryptionId",
79
+ "walrusBlobId",
80
+ "encryptionPackageId"
81
+ ]),
82
+ prepaid: new Set([
83
+ "ratePerCall",
84
+ "maxCalls",
85
+ "minDeposit",
86
+ "withdrawalDelayMs"
87
+ ])
88
+ };
89
+ /** Strip unknown keys from a sub-object, returning a clean copy. */
90
+ function pickSubObjectFields(key, value) {
91
+ const allowedKeys = S402_SUB_OBJECT_KEYS[key];
92
+ if (!allowedKeys || value == null || typeof value !== "object" || Array.isArray(value)) return value;
93
+ const obj = value;
94
+ const clean = {};
95
+ for (const k of allowedKeys) if (k in obj) clean[k] = obj[k];
96
+ return clean;
97
+ }
59
98
  /** Return a clean object with only known s402 requirement fields. */
60
99
  function pickRequirementsFields(obj) {
61
100
  const result = {};
62
- for (const key of S402_REQUIREMENTS_KEYS) if (key in obj) result[key] = obj[key];
101
+ for (const key of S402_REQUIREMENTS_KEYS) if (key in obj) if (key in S402_SUB_OBJECT_KEYS) result[key] = pickSubObjectFields(key, obj[key]);
102
+ else result[key] = obj[key];
63
103
  return result;
64
104
  }
65
105
  /** Decode payment requirements from the `payment-required` header */
@@ -172,10 +212,15 @@ const VALID_SCHEMES = new Set([
172
212
  "prepaid"
173
213
  ]);
174
214
  /**
175
- * Check that a string represents a canonical non-negative integer (valid for Sui MIST amounts).
215
+ * Check that a string represents a canonical non-negative integer.
176
216
  * Rejects leading zeros ("007"), empty strings, negatives, decimals.
177
217
  * Accepts "0" as the only zero representation.
178
218
  *
219
+ * NOTE: This is a **format-only** check — it validates the string is a well-formed
220
+ * non-negative integer but does NOT enforce magnitude bounds. Arbitrarily large
221
+ * integers (e.g. 100+ digits) pass this check. For Sui-specific u64 validation,
222
+ * use `isValidU64Amount()` which also checks that the value fits in a u64.
223
+ *
179
224
  * A-13 (Semantic gap): "0" passes validation because it's a valid u64 on-chain.
180
225
  * However, amount="0" in payment requirements is semantically ambiguous — it could
181
226
  * mean "free" or be a misconfiguration. The s402 wire format intentionally allows it
@@ -186,6 +231,21 @@ const VALID_SCHEMES = new Set([
186
231
  function isValidAmount(s) {
187
232
  return /^(0|[1-9][0-9]*)$/.test(s);
188
233
  }
234
+ /** Maximum value representable as a Sui u64: 2^64 - 1 */
235
+ const U64_MAX = "18446744073709551615";
236
+ /**
237
+ * Check that a string represents a valid Sui u64 amount.
238
+ * Like `isValidAmount` but also rejects values exceeding u64 max (2^64 - 1).
239
+ *
240
+ * Use this in scheme implementations that target Sui's u64 amounts (MIST, etc.).
241
+ * The wire-format validator uses `isValidAmount` (format-only) to stay chain-agnostic.
242
+ */
243
+ function isValidU64Amount(s) {
244
+ if (!isValidAmount(s)) return false;
245
+ if (s.length > 20) return false;
246
+ if (s.length < 20) return true;
247
+ return s <= U64_MAX;
248
+ }
189
249
  /** Helper: assert obj is a plain object (not null/array/primitive). */
190
250
  function assertPlainObject(value, label) {
191
251
  if (value == null || typeof value !== "object" || Array.isArray(value)) throw new s402Error("INVALID_PAYLOAD", `${label} must be a plain object, got ${Array.isArray(value) ? "array" : typeof value}`);
@@ -289,7 +349,7 @@ function validateRequirementsShape(obj) {
289
349
  const accepts = record.accepts;
290
350
  for (const scheme of accepts) if (typeof scheme !== "string") throw new s402Error("INVALID_PAYLOAD", `Invalid entry in accepts array: expected string, got ${typeof scheme}`);
291
351
  if (record.protocolFeeBps !== void 0) {
292
- if (typeof record.protocolFeeBps !== "number" || !Number.isFinite(record.protocolFeeBps) || record.protocolFeeBps < 0 || record.protocolFeeBps > 1e4) throw new s402Error("INVALID_PAYLOAD", `protocolFeeBps must be a finite number between 0 and 10000, got ${record.protocolFeeBps}`);
352
+ if (typeof record.protocolFeeBps !== "number" || !Number.isFinite(record.protocolFeeBps) || !Number.isInteger(record.protocolFeeBps) || record.protocolFeeBps < 0 || record.protocolFeeBps > 1e4) throw new s402Error("INVALID_PAYLOAD", `protocolFeeBps must be an integer between 0 and 10000, got ${record.protocolFeeBps}`);
293
353
  }
294
354
  if (record.expiresAt !== void 0) {
295
355
  if (typeof record.expiresAt !== "number" || !Number.isFinite(record.expiresAt)) throw new s402Error("INVALID_PAYLOAD", `expiresAt must be a finite number (Unix timestamp ms), got ${typeof record.expiresAt}`);
@@ -352,4 +412,4 @@ function extractRequirementsFromResponse(response) {
352
412
  }
353
413
 
354
414
  //#endregion
355
- export { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, pickPayloadFields, pickRequirementsFields, pickSettleResponseFields, validateEscrowShape, validateMandateShape, validatePrepaidShape, validateRequirementsShape, validateStreamShape, validateSubObjects, validateUnlockShape };
415
+ export { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, pickPayloadFields, pickRequirementsFields, pickSettleResponseFields, validateEscrowShape, validateMandateShape, validatePrepaidShape, validateRequirementsShape, validateStreamShape, validateSubObjects, validateUnlockShape };
package/dist/index.d.mts CHANGED
@@ -1,6 +1,6 @@
1
1
  import { createS402Error, s402Error, s402ErrorCode, s402ErrorCodeType, s402ErrorInfo } from "./errors.mjs";
2
2
  import { S402_HEADERS, S402_VERSION, s402Discovery, s402EscrowExtra, s402EscrowPayload, s402ExactPayload, s402Mandate, s402MandateRequirements, s402PaymentPayload, s402PaymentPayloadBase, s402PaymentRequirements, s402PaymentSession, s402PrepaidExtra, s402PrepaidPayload, s402RegistryQuery, s402Scheme, s402ServiceEntry, s402SettleResponse, s402SettlementMode, s402StreamExtra, s402StreamPayload, s402UnlockExtra, s402UnlockPayload, s402VerifyResponse } from "./types.mjs";
3
- import { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, validateRequirementsShape } from "./http.mjs";
3
+ import { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, validateRequirementsShape } from "./http.mjs";
4
4
 
5
5
  //#region src/scheme.d.ts
6
6
  /** Implemented by each scheme on the client side */
@@ -128,12 +128,12 @@ declare class s402Facilitator {
128
128
  register(network: string, scheme: s402FacilitatorScheme): this;
129
129
  /**
130
130
  * Verify a payment payload by dispatching to the correct scheme.
131
- * Includes expiration guard rejects expired requirements before verification.
131
+ * Includes expiration guard and scheme-mismatch check.
132
132
  */
133
133
  verify(payload: s402PaymentPayload, requirements: s402PaymentRequirements): Promise<s402VerifyResponse>;
134
134
  /**
135
135
  * Settle a payment by dispatching to the correct scheme.
136
- * Includes expiration guard rejects expired requirements before settlement.
136
+ * Includes expiration guard and scheme-mismatch check.
137
137
  */
138
138
  settle(payload: s402PaymentPayload, requirements: s402PaymentRequirements): Promise<s402SettleResponse>;
139
139
  /**
@@ -191,4 +191,4 @@ declare class s402ResourceServer {
191
191
  process(payload: s402PaymentPayload, requirements: s402PaymentRequirements): Promise<s402SettleResponse>;
192
192
  }
193
193
  //#endregion
194
- export { S402_HEADERS, S402_VERSION, createS402Error, decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, s402Client, type s402ClientScheme, type s402DirectScheme, type s402Discovery, s402Error, s402ErrorCode, type s402ErrorCodeType, type s402ErrorInfo, type s402EscrowExtra, type s402EscrowPayload, type s402ExactPayload, s402Facilitator, type s402FacilitatorScheme, type s402Mandate, type s402MandateRequirements, type s402PaymentPayload, type s402PaymentPayloadBase, type s402PaymentRequirements, type s402PaymentSession, type s402PrepaidExtra, type s402PrepaidPayload, type s402RegistryQuery, s402ResourceServer, type s402RouteConfig, type s402Scheme, type s402ServerScheme, type s402ServiceEntry, type s402SettleResponse, type s402SettlementMode, type s402StreamExtra, type s402StreamPayload, type s402UnlockExtra, type s402UnlockPayload, type s402VerifyResponse, validateRequirementsShape };
194
+ export { S402_HEADERS, S402_VERSION, createS402Error, decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, s402Client, type s402ClientScheme, type s402DirectScheme, type s402Discovery, s402Error, s402ErrorCode, type s402ErrorCodeType, type s402ErrorInfo, type s402EscrowExtra, type s402EscrowPayload, type s402ExactPayload, s402Facilitator, type s402FacilitatorScheme, type s402Mandate, type s402MandateRequirements, type s402PaymentPayload, type s402PaymentPayloadBase, type s402PaymentRequirements, type s402PaymentSession, type s402PrepaidExtra, type s402PrepaidPayload, type s402RegistryQuery, s402ResourceServer, type s402RouteConfig, type s402Scheme, type s402ServerScheme, type s402ServiceEntry, type s402SettleResponse, type s402SettlementMode, type s402StreamExtra, type s402StreamPayload, type s402UnlockExtra, type s402UnlockPayload, type s402VerifyResponse, validateRequirementsShape };
package/dist/index.mjs CHANGED
@@ -1,6 +1,6 @@
1
1
  import { S402_HEADERS, S402_VERSION } from "./types.mjs";
2
2
  import { createS402Error, s402Error, s402ErrorCode } from "./errors.mjs";
3
- import { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, validateRequirementsShape } from "./http.mjs";
3
+ import { decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, validateRequirementsShape } from "./http.mjs";
4
4
 
5
5
  //#region src/client.ts
6
6
  var s402Client = class {
@@ -138,29 +138,51 @@ var s402Facilitator = class {
138
138
  }
139
139
  /**
140
140
  * Verify a payment payload by dispatching to the correct scheme.
141
- * Includes expiration guard rejects expired requirements before verification.
141
+ * Includes expiration guard and scheme-mismatch check.
142
142
  */
143
143
  async verify(payload, requirements) {
144
- if (typeof requirements.expiresAt === "number" && Number.isFinite(requirements.expiresAt)) {
144
+ if (requirements.expiresAt != null) {
145
+ if (typeof requirements.expiresAt !== "number" || !Number.isFinite(requirements.expiresAt)) return {
146
+ valid: false,
147
+ invalidReason: `Invalid expiresAt value: expected finite number, got ${typeof requirements.expiresAt}`
148
+ };
145
149
  if (Date.now() > requirements.expiresAt) return {
146
150
  valid: false,
147
151
  invalidReason: `Payment requirements expired at ${new Date(requirements.expiresAt).toISOString()}`
148
152
  };
149
153
  }
154
+ if (requirements.accepts && requirements.accepts.length > 0) {
155
+ if (!requirements.accepts.includes(payload.scheme)) return {
156
+ valid: false,
157
+ invalidReason: `Scheme "${payload.scheme}" is not accepted by these requirements. Accepted: [${requirements.accepts.join(", ")}]`
158
+ };
159
+ }
150
160
  return this.resolveScheme(payload.scheme, requirements.network).verify(payload, requirements);
151
161
  }
152
162
  /**
153
163
  * Settle a payment by dispatching to the correct scheme.
154
- * Includes expiration guard rejects expired requirements before settlement.
164
+ * Includes expiration guard and scheme-mismatch check.
155
165
  */
156
166
  async settle(payload, requirements) {
157
- if (typeof requirements.expiresAt === "number" && Number.isFinite(requirements.expiresAt)) {
167
+ if (requirements.expiresAt != null) {
168
+ if (typeof requirements.expiresAt !== "number" || !Number.isFinite(requirements.expiresAt)) return {
169
+ success: false,
170
+ error: `Invalid expiresAt value: expected finite number, got ${typeof requirements.expiresAt}`,
171
+ errorCode: "INVALID_PAYLOAD"
172
+ };
158
173
  if (Date.now() > requirements.expiresAt) return {
159
174
  success: false,
160
175
  error: `Payment requirements expired at ${new Date(requirements.expiresAt).toISOString()}`,
161
176
  errorCode: "REQUIREMENTS_EXPIRED"
162
177
  };
163
178
  }
179
+ if (requirements.accepts && requirements.accepts.length > 0) {
180
+ if (!requirements.accepts.includes(payload.scheme)) return {
181
+ success: false,
182
+ error: `Scheme "${payload.scheme}" is not accepted by these requirements. Accepted: [${requirements.accepts.join(", ")}]`,
183
+ errorCode: "SCHEME_NOT_SUPPORTED"
184
+ };
185
+ }
164
186
  return this.resolveScheme(payload.scheme, requirements.network).settle(payload, requirements);
165
187
  }
166
188
  /**
@@ -203,7 +225,15 @@ var s402Facilitator = class {
203
225
  error: `Payment requirements expired during verification at ${new Date(requirements.expiresAt).toISOString()}`,
204
226
  errorCode: "REQUIREMENTS_EXPIRED"
205
227
  };
206
- return scheme.settle(payload, requirements);
228
+ try {
229
+ return await scheme.settle(payload, requirements);
230
+ } catch (e) {
231
+ return {
232
+ success: false,
233
+ error: e instanceof Error ? e.message : "Settlement failed with an unexpected error",
234
+ errorCode: "VERIFICATION_FAILED"
235
+ };
236
+ }
207
237
  }
208
238
  /**
209
239
  * Check if a scheme is supported for a network.
@@ -228,4 +258,4 @@ var s402Facilitator = class {
228
258
  };
229
259
 
230
260
  //#endregion
231
- export { S402_HEADERS, S402_VERSION, createS402Error, decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, s402Client, s402Error, s402ErrorCode, s402Facilitator, s402ResourceServer, validateRequirementsShape };
261
+ export { S402_HEADERS, S402_VERSION, createS402Error, decodePaymentPayload, decodePaymentRequired, decodeSettleResponse, detectProtocol, encodePaymentPayload, encodePaymentRequired, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, s402Client, s402Error, s402ErrorCode, s402Facilitator, s402ResourceServer, validateRequirementsShape };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "s402",
3
- "version": "0.1.1",
3
+ "version": "0.1.2",
4
4
  "type": "module",
5
5
  "description": "s402 — Sui-native HTTP 402 wire format. Types, HTTP encoding, and scheme registry for five payment schemes. Wire-compatible with x402. Zero runtime dependencies.",
6
6
  "license": "MIT",
@@ -78,22 +78,21 @@
78
78
  "default": "./dist/errors.mjs"
79
79
  }
80
80
  },
81
+ "devDependencies": {
82
+ "@vitest/coverage-v8": "^3.2.4",
83
+ "fast-check": "^4.5.3",
84
+ "tsdown": "^0.20.3",
85
+ "typescript": "^5.7.0",
86
+ "vitepress": "^1.6.4",
87
+ "vitest": "^3.0.5"
88
+ },
81
89
  "scripts": {
82
90
  "build": "tsdown",
83
91
  "typecheck": "tsc --noEmit",
84
92
  "test": "vitest run",
85
93
  "test:watch": "vitest",
86
- "prepublishOnly": "npm run build && npm run typecheck && npm run test",
87
94
  "docs:dev": "vitepress dev docs",
88
95
  "docs:build": "vitepress build docs",
89
96
  "docs:preview": "vitepress preview docs"
90
- },
91
- "devDependencies": {
92
- "@vitest/coverage-v8": "^3.2.4",
93
- "fast-check": "^4.5.3",
94
- "tsdown": "^0.20.3",
95
- "typescript": "^5.7.0",
96
- "vitepress": "^1.6.4",
97
- "vitest": "^3.0.5"
98
97
  }
99
- }
98
+ }