s402 0.6.0 → 0.7.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.
- package/CHANGELOG.md +42 -0
- package/README.md +1 -1
- package/dist/compat/l402.d.mts +94 -0
- package/dist/compat/l402.mjs +225 -0
- package/dist/{compat-mpp.d.mts → compat/mpp.d.mts} +2 -2
- package/dist/{compat-mpp.mjs → compat/mpp.mjs} +4 -4
- package/dist/{compat.d.mts → compat/x402.d.mts} +3 -3
- package/dist/{compat.mjs → compat/x402.mjs} +5 -5
- package/dist/http.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.mjs +1 -1
- package/dist/test-utils.d.mts +1 -1
- package/package.json +17 -10
- /package/dist/{scheme-CKinOhyx.d.mts → scheme-M-z-UV0c.d.mts} +0 -0
package/CHANGELOG.md
CHANGED
|
@@ -5,6 +5,48 @@ 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
|
+
## [Unreleased]
|
|
9
|
+
|
|
10
|
+
## [0.7.0] - 2026-04-22
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- **`s402/compat-l402` — L402 read-path interop (DAN-344).** New entry point for consuming Lightning Labs' L402 (formerly LSAT) challenges as native s402 types. L402 is the oldest 402 dialect in production — shipping this turns the "universal read" positioning pillar from aspirational into airtight.
|
|
15
|
+
- `parseWwwAuthenticateL402(header)` — RFC 9110 auth-params parser accepting both `L402` and legacy `LSAT` auth-schemes (canonicalized to `L402` in output). Handles quoted-string + unquoted-token forms. Enforces required `macaroon` and `invoice` params.
|
|
16
|
+
- `decodeBolt11Summary(invoice)` — partial BOLT-11 decoder over the human-readable part only. Extracts network (`lightning:mainnet|testnet|regtest|signet`) and amount (converting m/u/n/p multipliers to millisatoshi with BigInt arithmetic). Rejects pico-BTC amounts not divisible by 10.
|
|
17
|
+
- `fromL402Challenge(challenge)` — translates an L402 challenge into `s402PaymentRequirements` with `scheme: 'exact'`, `asset: 'lightning:msat'`, sentinel `payTo: 'lightning:invoice'` (real destination lives in the invoice). Surfaces macaroon + invoice in `extensions.l402` for retry construction. Rejects amountless invoices as spec violations. Stamps a conservative `expiresAt = now + 60s` so that **S1 (stale payment rejection) stays load-bearing** for L402-derived requirements — the real BOLT-11 expiry tag is not decoded in v0.7 (scope deferral); the 60s floor guards against stale-invoice replay, with the tradeoff that long-expiry invoices trigger a re-fetch after 60s.
|
|
18
|
+
- **Signet prefix support**: recognizes both the canonical current-BOLT-11 prefix (`lntbs`, core-lightning + recent LND) and the legacy prefix (`lnsb`, older LND emissions). Both canonicalize to `lightning:signet` in the parsed output.
|
|
19
|
+
- **~20 unit tests** at `test/compat-l402.test.ts` covering all four multiplier classes, all four network prefixes, LSAT/L402 alias handling, amountless invoices, malformed HRPs, and end-to-end header-to-requirements flows.
|
|
20
|
+
- **Positioning document** at `docs/positioning.md` — canonical three-pillar USP: expressiveness (6 schemes), universal read (every 402 dialect), on-chain enforcement (Move invariants). Single source of truth for landing page, pitch, and grant copy.
|
|
21
|
+
- **Universal 402 Absorption** project tracker on Linear ([project link](https://linear.app/dannydevs/project/universal-402-absorption-f6e181082db4)) with child issues DAN-344 (L402), DAN-345 (MPP Session), DAN-346 (MPP write path), DAN-347 (Google AP2), DAN-348 (IETF reference impl), DAN-349 (ERC-7824 watch).
|
|
22
|
+
|
|
23
|
+
### Scope (intentionally deferred)
|
|
24
|
+
|
|
25
|
+
- **L402 write path** — emitting L402 challenges requires a Lightning node to mint BOLT-11 invoices; out of scope for a wire-format library. Teams that need emission should keep Aperture in the path.
|
|
26
|
+
- **Macaroon caveat decoding** — passed through opaque in v0.7; caveat introspection delegated to `node-macaroon` or equivalent.
|
|
27
|
+
- **Full BOLT-11 tagged-field decoding** — node pubkey, routing hints, payment hash, description. Lightning wallets already decode these; we do not duplicate their work.
|
|
28
|
+
- **BOLT-12 offers** — newer offer-based protocol, spec still evolving.
|
|
29
|
+
|
|
30
|
+
### Changed
|
|
31
|
+
|
|
32
|
+
- `docs/integrations.md` — added L402 compat-layer row (✅ v0.7).
|
|
33
|
+
- `docs/guide/upgrade-l402.md` — new migration guide covering consumption, coexistence via `Accept-Payment`, BOLT-11 multiplier table, and honest comparison with L402.
|
|
34
|
+
|
|
35
|
+
### Breaking
|
|
36
|
+
|
|
37
|
+
- **Minimum Node.js bumped to 20** (from 18). Node 18 reached end-of-life April 2025; `envelope.ts`'s `computeTxBinding` relies on `globalThis.crypto.subtle` which is only available unflagged in Node 19+. `engines.node` updated to `>=20`, CI matrix dropped Node 18, README/docs updated. Node 20 and Node 22 remain fully supported.
|
|
38
|
+
|
|
39
|
+
### Compatibility
|
|
40
|
+
|
|
41
|
+
- **Non-compat consumers are additive.** No changes to existing types, scheme interfaces, wire format, or conformance vectors.
|
|
42
|
+
- **Compat sub-path exports reorganized**: all three compat layers now live under `s402/compat/*` for symmetry and clearer intent.
|
|
43
|
+
- `s402/compat` → **`s402/compat/x402`** (breaking rename — x402 is now explicit, not the unlabeled default)
|
|
44
|
+
- `s402/compat-mpp` → **`s402/compat/mpp`**
|
|
45
|
+
- `s402/compat-l402` → **`s402/compat/l402`** (new in this release; shipped under the new path from day one)
|
|
46
|
+
- Source tree moved from flat `src/compat.ts`, `src/compat-mpp.ts`, `src/compat-l402.ts` to `src/compat/x402.ts`, `src/compat/mpp.ts`, `src/compat/l402.ts`. Pre-1.0 minor bump licenses the rename; no backward-compat aliases shipped — consumers update imports once.
|
|
47
|
+
- **Migration**: find-replace `'s402/compat'` → `'s402/compat/x402'`, `'s402/compat-mpp'` → `'s402/compat/mpp'`, `'s402/compat-l402'` → `'s402/compat/l402'`. Exported symbol names are unchanged.
|
|
48
|
+
- Root `s402` entry still pulls no compat bundle — compat layers remain opt-in.
|
|
49
|
+
|
|
8
50
|
## [0.6.0] - 2026-04-19
|
|
9
51
|
|
|
10
52
|
### Added
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ bun add s402
|
|
|
14
14
|
deno add npm:s402
|
|
15
15
|
```
|
|
16
16
|
|
|
17
|
-
> **ESM-only.** This package ships ES modules only (`"type": "module"`). Requires Node.js >=
|
|
17
|
+
> **ESM-only.** This package ships ES modules only (`"type": "module"`). Requires Node.js >= 20. CommonJS `require()` is not supported.
|
|
18
18
|
|
|
19
19
|
## Governing Principle
|
|
20
20
|
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
import { s402PaymentRequirements } from "../types.mjs";
|
|
2
|
+
|
|
3
|
+
//#region src/compat/l402.d.ts
|
|
4
|
+
/**
|
|
5
|
+
* Parsed `WWW-Authenticate: L402` (or legacy `LSAT`) challenge.
|
|
6
|
+
*
|
|
7
|
+
* Per Lightning Labs' spec, an L402 challenge carries exactly two required
|
|
8
|
+
* auth-params: the `macaroon` (opaque bearer token with caveats) and the
|
|
9
|
+
* `invoice` (BOLT-11 payment request). The client pays the invoice via Lightning,
|
|
10
|
+
* receives the preimage, and presents `Authorization: L402 <macaroon>:<preimage>`
|
|
11
|
+
* on the retry.
|
|
12
|
+
*/
|
|
13
|
+
interface L402Challenge {
|
|
14
|
+
/** Canonicalized auth-scheme — always `"L402"`, even if the wire said `LSAT`. */
|
|
15
|
+
scheme: 'L402';
|
|
16
|
+
/** Base64-encoded macaroon. Treated as opaque by this module. */
|
|
17
|
+
macaroon: string;
|
|
18
|
+
/** BOLT-11 invoice (bech32 `ln...`). */
|
|
19
|
+
invoice: string;
|
|
20
|
+
}
|
|
21
|
+
/**
|
|
22
|
+
* Decoded BOLT-11 human-readable part (HRP). Only fields the translator needs.
|
|
23
|
+
*
|
|
24
|
+
* `amountMsat` is `null` for amountless invoices — BOLT-11 allows these, but
|
|
25
|
+
* they are unusual in L402 contexts since Aperture embeds the price in the
|
|
26
|
+
* invoice. Callers translating to s402 typically reject amountless invoices.
|
|
27
|
+
*/
|
|
28
|
+
interface Bolt11Summary {
|
|
29
|
+
network: 'lightning:mainnet' | 'lightning:testnet' | 'lightning:regtest' | 'lightning:signet';
|
|
30
|
+
/** Amount in millisatoshi as a non-negative integer string, or `null` if the invoice specifies no amount. */
|
|
31
|
+
amountMsat: string | null;
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Parse a `WWW-Authenticate: L402 ...` header into an {@link L402Challenge}.
|
|
35
|
+
*
|
|
36
|
+
* Accepts both `L402` and legacy `LSAT` auth-schemes (case-insensitive) —
|
|
37
|
+
* Aperture in the wild still emits `LSAT` on older deployments. The output
|
|
38
|
+
* scheme is always canonicalized to `"L402"`.
|
|
39
|
+
*
|
|
40
|
+
* Returns `null` if the header is absent/empty or does not start with an L402
|
|
41
|
+
* auth-scheme. Throws `INVALID_PAYLOAD` if the scheme is present but required
|
|
42
|
+
* params (`macaroon`, `invoice`) are missing or malformed.
|
|
43
|
+
*
|
|
44
|
+
* @example
|
|
45
|
+
* ```ts
|
|
46
|
+
* const challenge = parseWwwAuthenticateL402(res.headers.get('WWW-Authenticate'));
|
|
47
|
+
* if (challenge) {
|
|
48
|
+
* const requirements = fromL402Challenge(challenge);
|
|
49
|
+
* // requirements.scheme === 'exact', requirements.network === 'lightning:mainnet', ...
|
|
50
|
+
* }
|
|
51
|
+
* ```
|
|
52
|
+
*/
|
|
53
|
+
declare function parseWwwAuthenticateL402(header: string | null | undefined): L402Challenge | null;
|
|
54
|
+
/**
|
|
55
|
+
* Decode the BOLT-11 human-readable part of a Lightning invoice into its
|
|
56
|
+
* network and amount components. This is a **partial** decoder — it reads only
|
|
57
|
+
* the HRP (up to the bech32 `1` separator) because full BOLT-11 decoding
|
|
58
|
+
* requires bech32 + tagged-field parsing (~500 LOC) and the translator only
|
|
59
|
+
* needs network + amount.
|
|
60
|
+
*
|
|
61
|
+
* BOLT-11 HRP grammar: `ln{prefix}{amount?}{multiplier?}` where
|
|
62
|
+
* - prefix ∈ {`bc`, `tb`, `bcrt`, `sb`} (mainnet/testnet/regtest/signet)
|
|
63
|
+
* - amount is a decimal integer (BTC units before multiplier)
|
|
64
|
+
* - multiplier ∈ {`m`, `u`, `n`, `p`} (milli/micro/nano/pico-BTC)
|
|
65
|
+
*
|
|
66
|
+
* Conversion to millisatoshi (msat = 10^-11 BTC):
|
|
67
|
+
* - no multiplier: `amount * 10^11` msat
|
|
68
|
+
* - `m`: `amount * 10^8` msat
|
|
69
|
+
* - `u`: `amount * 10^5` msat
|
|
70
|
+
* - `n`: `amount * 10^2` msat
|
|
71
|
+
* - `p`: `amount / 10` msat (amount must be multiple of 10)
|
|
72
|
+
*
|
|
73
|
+
* @throws {s402Error} `INVALID_PAYLOAD` if the HRP is malformed, the prefix is
|
|
74
|
+
* unknown, or a pico-BTC amount is not a multiple of 10.
|
|
75
|
+
*/
|
|
76
|
+
declare function decodeBolt11Summary(invoice: string): Bolt11Summary;
|
|
77
|
+
/**
|
|
78
|
+
* Translate an L402 challenge into s402 payment requirements using the `exact`
|
|
79
|
+
* scheme.
|
|
80
|
+
*
|
|
81
|
+
* The resulting requirements are consumable by a Lightning-aware s402 client.
|
|
82
|
+
* The `payTo` field is a sentinel (`"lightning:invoice"`) rather than a node
|
|
83
|
+
* pubkey because the true destination is inside the BOLT-11 invoice — which
|
|
84
|
+
* Lightning wallets decode themselves. The invoice and macaroon are surfaced
|
|
85
|
+
* under `extensions.l402` so the client can present them back on the retry
|
|
86
|
+
* (`Authorization: L402 <macaroon>:<preimage>`).
|
|
87
|
+
*
|
|
88
|
+
* @throws {s402Error} `INVALID_PAYLOAD` if the invoice HRP is malformed or the
|
|
89
|
+
* invoice is amountless (L402 challenges always specify a price in the
|
|
90
|
+
* invoice; an amountless invoice is a spec violation).
|
|
91
|
+
*/
|
|
92
|
+
declare function fromL402Challenge(challenge: L402Challenge): s402PaymentRequirements;
|
|
93
|
+
//#endregion
|
|
94
|
+
export { Bolt11Summary, L402Challenge, decodeBolt11Summary, fromL402Challenge, parseWwwAuthenticateL402 };
|
|
@@ -0,0 +1,225 @@
|
|
|
1
|
+
import { S402_VERSION } from "../types.mjs";
|
|
2
|
+
import { s402Error } from "../errors.mjs";
|
|
3
|
+
|
|
4
|
+
//#region src/compat/l402.ts
|
|
5
|
+
const TOKEN_CHARS = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
6
|
+
const L402_SCHEME_PATTERN = /^\s*(L402|LSAT)(?:\s+(.*))?$/i;
|
|
7
|
+
/**
|
|
8
|
+
* Parse a `WWW-Authenticate: L402 ...` header into an {@link L402Challenge}.
|
|
9
|
+
*
|
|
10
|
+
* Accepts both `L402` and legacy `LSAT` auth-schemes (case-insensitive) —
|
|
11
|
+
* Aperture in the wild still emits `LSAT` on older deployments. The output
|
|
12
|
+
* scheme is always canonicalized to `"L402"`.
|
|
13
|
+
*
|
|
14
|
+
* Returns `null` if the header is absent/empty or does not start with an L402
|
|
15
|
+
* auth-scheme. Throws `INVALID_PAYLOAD` if the scheme is present but required
|
|
16
|
+
* params (`macaroon`, `invoice`) are missing or malformed.
|
|
17
|
+
*
|
|
18
|
+
* @example
|
|
19
|
+
* ```ts
|
|
20
|
+
* const challenge = parseWwwAuthenticateL402(res.headers.get('WWW-Authenticate'));
|
|
21
|
+
* if (challenge) {
|
|
22
|
+
* const requirements = fromL402Challenge(challenge);
|
|
23
|
+
* // requirements.scheme === 'exact', requirements.network === 'lightning:mainnet', ...
|
|
24
|
+
* }
|
|
25
|
+
* ```
|
|
26
|
+
*/
|
|
27
|
+
function parseWwwAuthenticateL402(header) {
|
|
28
|
+
if (!header) return null;
|
|
29
|
+
const match = L402_SCHEME_PATTERN.exec(header);
|
|
30
|
+
if (!match) return null;
|
|
31
|
+
const paramString = (match[2] ?? "").trim();
|
|
32
|
+
if (paramString.length === 0) throw new s402Error("INVALID_PAYLOAD", "L402 challenge missing auth-params");
|
|
33
|
+
const params = parseAuthParams(paramString);
|
|
34
|
+
const macaroon = params.macaroon;
|
|
35
|
+
const invoice = params.invoice;
|
|
36
|
+
if (typeof macaroon !== "string" || macaroon.length === 0) throw new s402Error("INVALID_PAYLOAD", "L402 challenge missing \"macaroon\" auth-param");
|
|
37
|
+
if (typeof invoice !== "string" || invoice.length === 0) throw new s402Error("INVALID_PAYLOAD", "L402 challenge missing \"invoice\" auth-param");
|
|
38
|
+
return {
|
|
39
|
+
scheme: "L402",
|
|
40
|
+
macaroon,
|
|
41
|
+
invoice
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Parse RFC 9110 §11.2 `auth-params` (`token "=" ( token / quoted-string )`
|
|
46
|
+
* comma-separated). L402 uses the same grammar as MPP; this function mirrors
|
|
47
|
+
* the MPP parser in `compat-mpp` rather than sharing a helper because the two
|
|
48
|
+
* dialects may diverge on edge cases (e.g., L402 invoices have not historically
|
|
49
|
+
* been quoted in Aperture output, whereas MPP params are consistently quoted).
|
|
50
|
+
*/
|
|
51
|
+
function parseAuthParams(input) {
|
|
52
|
+
const out = {};
|
|
53
|
+
let i = 0;
|
|
54
|
+
const n = input.length;
|
|
55
|
+
while (i < n) {
|
|
56
|
+
while (i < n && (input[i] === " " || input[i] === " " || input[i] === ",")) i++;
|
|
57
|
+
if (i >= n) break;
|
|
58
|
+
const keyStart = i;
|
|
59
|
+
while (i < n && input[i] !== "=" && input[i] !== " " && input[i] !== " ") i++;
|
|
60
|
+
const key = input.slice(keyStart, i).toLowerCase();
|
|
61
|
+
if (key.length === 0 || !TOKEN_CHARS.test(key)) throw new s402Error("INVALID_PAYLOAD", `Malformed auth-param name at position ${keyStart}`);
|
|
62
|
+
while (i < n && (input[i] === " " || input[i] === " ")) i++;
|
|
63
|
+
if (input[i] !== "=") throw new s402Error("INVALID_PAYLOAD", `Missing "=" after auth-param "${key}"`);
|
|
64
|
+
i++;
|
|
65
|
+
while (i < n && (input[i] === " " || input[i] === " ")) i++;
|
|
66
|
+
let value;
|
|
67
|
+
if (input[i] === "\"") {
|
|
68
|
+
i++;
|
|
69
|
+
const valueStart = i;
|
|
70
|
+
let raw = "";
|
|
71
|
+
while (i < n && input[i] !== "\"") if (input[i] === "\\" && i + 1 < n) {
|
|
72
|
+
raw += input[i + 1];
|
|
73
|
+
i += 2;
|
|
74
|
+
} else {
|
|
75
|
+
raw += input[i];
|
|
76
|
+
i++;
|
|
77
|
+
}
|
|
78
|
+
if (input[i] !== "\"") throw new s402Error("INVALID_PAYLOAD", `Unterminated quoted-string starting at position ${valueStart}`);
|
|
79
|
+
i++;
|
|
80
|
+
value = raw;
|
|
81
|
+
} else {
|
|
82
|
+
const valueStart = i;
|
|
83
|
+
while (i < n && input[i] !== "," && input[i] !== " " && input[i] !== " ") i++;
|
|
84
|
+
value = input.slice(valueStart, i);
|
|
85
|
+
if (value.length === 0) throw new s402Error("INVALID_PAYLOAD", `Empty auth-param value for "${key}" at position ${valueStart}`);
|
|
86
|
+
}
|
|
87
|
+
out[key] = value;
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
91
|
+
const HRP_PATTERN = /^ln(bcrt|tbs|bc|tb|sb)(\d+)?([munp])?1[a-z0-9]+$/;
|
|
92
|
+
const NETWORK_BY_PREFIX = {
|
|
93
|
+
bc: "lightning:mainnet",
|
|
94
|
+
tb: "lightning:testnet",
|
|
95
|
+
bcrt: "lightning:regtest",
|
|
96
|
+
tbs: "lightning:signet",
|
|
97
|
+
sb: "lightning:signet"
|
|
98
|
+
};
|
|
99
|
+
/**
|
|
100
|
+
* Decode the BOLT-11 human-readable part of a Lightning invoice into its
|
|
101
|
+
* network and amount components. This is a **partial** decoder — it reads only
|
|
102
|
+
* the HRP (up to the bech32 `1` separator) because full BOLT-11 decoding
|
|
103
|
+
* requires bech32 + tagged-field parsing (~500 LOC) and the translator only
|
|
104
|
+
* needs network + amount.
|
|
105
|
+
*
|
|
106
|
+
* BOLT-11 HRP grammar: `ln{prefix}{amount?}{multiplier?}` where
|
|
107
|
+
* - prefix ∈ {`bc`, `tb`, `bcrt`, `sb`} (mainnet/testnet/regtest/signet)
|
|
108
|
+
* - amount is a decimal integer (BTC units before multiplier)
|
|
109
|
+
* - multiplier ∈ {`m`, `u`, `n`, `p`} (milli/micro/nano/pico-BTC)
|
|
110
|
+
*
|
|
111
|
+
* Conversion to millisatoshi (msat = 10^-11 BTC):
|
|
112
|
+
* - no multiplier: `amount * 10^11` msat
|
|
113
|
+
* - `m`: `amount * 10^8` msat
|
|
114
|
+
* - `u`: `amount * 10^5` msat
|
|
115
|
+
* - `n`: `amount * 10^2` msat
|
|
116
|
+
* - `p`: `amount / 10` msat (amount must be multiple of 10)
|
|
117
|
+
*
|
|
118
|
+
* @throws {s402Error} `INVALID_PAYLOAD` if the HRP is malformed, the prefix is
|
|
119
|
+
* unknown, or a pico-BTC amount is not a multiple of 10.
|
|
120
|
+
*/
|
|
121
|
+
function decodeBolt11Summary(invoice) {
|
|
122
|
+
if (typeof invoice !== "string" || invoice.length === 0) throw new s402Error("INVALID_PAYLOAD", "BOLT-11 invoice must be a non-empty string");
|
|
123
|
+
const lower = invoice.toLowerCase();
|
|
124
|
+
const match = HRP_PATTERN.exec(lower);
|
|
125
|
+
if (!match) throw new s402Error("INVALID_PAYLOAD", `Invoice does not match BOLT-11 HRP grammar (expected "ln(bc|tb|bcrt|sb){amount}{m|u|n|p}1..."): "${invoice}"`);
|
|
126
|
+
const prefix = match[1];
|
|
127
|
+
const amountPart = match[2];
|
|
128
|
+
const multiplier = match[3];
|
|
129
|
+
const network = NETWORK_BY_PREFIX[prefix];
|
|
130
|
+
if (!network) throw new s402Error("INVALID_PAYLOAD", `Unknown BOLT-11 network prefix: "${prefix}"`);
|
|
131
|
+
if (amountPart === void 0) {
|
|
132
|
+
if (multiplier !== void 0) throw new s402Error("INVALID_PAYLOAD", "BOLT-11 multiplier without amount");
|
|
133
|
+
return {
|
|
134
|
+
network,
|
|
135
|
+
amountMsat: null
|
|
136
|
+
};
|
|
137
|
+
}
|
|
138
|
+
const amount = BigInt(amountPart);
|
|
139
|
+
let amountMsat;
|
|
140
|
+
switch (multiplier) {
|
|
141
|
+
case void 0:
|
|
142
|
+
amountMsat = amount * 100000000000n;
|
|
143
|
+
break;
|
|
144
|
+
case "m":
|
|
145
|
+
amountMsat = amount * 100000000n;
|
|
146
|
+
break;
|
|
147
|
+
case "u":
|
|
148
|
+
amountMsat = amount * 100000n;
|
|
149
|
+
break;
|
|
150
|
+
case "n":
|
|
151
|
+
amountMsat = amount * 100n;
|
|
152
|
+
break;
|
|
153
|
+
case "p":
|
|
154
|
+
if (amount % 10n !== 0n) throw new s402Error("INVALID_PAYLOAD", `BOLT-11 pico-BTC amount must be a multiple of 10 (got ${amount}) — 1 msat is the minimum divisible unit`);
|
|
155
|
+
amountMsat = amount / 10n;
|
|
156
|
+
break;
|
|
157
|
+
default: throw new s402Error("INVALID_PAYLOAD", `Unknown BOLT-11 multiplier: "${multiplier}"`);
|
|
158
|
+
}
|
|
159
|
+
return {
|
|
160
|
+
network,
|
|
161
|
+
amountMsat: amountMsat.toString()
|
|
162
|
+
};
|
|
163
|
+
}
|
|
164
|
+
/**
|
|
165
|
+
* Sentinel payTo for Lightning — the actual payment destination is encoded in
|
|
166
|
+
* the invoice itself (BOLT-11 tagged fields carry node pubkey + payment hash).
|
|
167
|
+
* An s402 client paying an L402 challenge routes through a Lightning wallet
|
|
168
|
+
* that knows how to pay an invoice; the `payTo` field exists only to satisfy
|
|
169
|
+
* the s402 schema.
|
|
170
|
+
*/
|
|
171
|
+
const LIGHTNING_INVOICE_SENTINEL = "lightning:invoice";
|
|
172
|
+
/**
|
|
173
|
+
* Conservative default expiry window applied to L402-derived requirements.
|
|
174
|
+
*
|
|
175
|
+
* BOLT-11 invoices carry their own expiry as a tagged field (type `x`) past
|
|
176
|
+
* the `1` separator, defaulting to 3600 seconds per spec. This partial decoder
|
|
177
|
+
* reads only the HRP, so the real invoice expiry is not surfaced. To keep
|
|
178
|
+
* S1 (stale payment rejection) load-bearing for L402-derived requirements,
|
|
179
|
+
* we stamp a conservative 60s window: an s402 client that caches requirements
|
|
180
|
+
* longer than 60s must re-fetch the 402 response rather than reusing stale
|
|
181
|
+
* ones against a possibly-expired invoice.
|
|
182
|
+
*
|
|
183
|
+
* Tradeoff: a long-lived invoice (e.g., Aperture's default 1-hour expiry) is
|
|
184
|
+
* rejected by s402 after 60s even though the invoice is still payable. The
|
|
185
|
+
* re-fetch cost is one extra round-trip, not a payment failure.
|
|
186
|
+
*
|
|
187
|
+
* A future v0.8 full BOLT-11 decoder can read the `x` tag and use the real
|
|
188
|
+
* expiry. Until then, 60s is the safe floor.
|
|
189
|
+
*/
|
|
190
|
+
const L402_DEFAULT_EXPIRY_WINDOW_MS = 6e4;
|
|
191
|
+
/**
|
|
192
|
+
* Translate an L402 challenge into s402 payment requirements using the `exact`
|
|
193
|
+
* scheme.
|
|
194
|
+
*
|
|
195
|
+
* The resulting requirements are consumable by a Lightning-aware s402 client.
|
|
196
|
+
* The `payTo` field is a sentinel (`"lightning:invoice"`) rather than a node
|
|
197
|
+
* pubkey because the true destination is inside the BOLT-11 invoice — which
|
|
198
|
+
* Lightning wallets decode themselves. The invoice and macaroon are surfaced
|
|
199
|
+
* under `extensions.l402` so the client can present them back on the retry
|
|
200
|
+
* (`Authorization: L402 <macaroon>:<preimage>`).
|
|
201
|
+
*
|
|
202
|
+
* @throws {s402Error} `INVALID_PAYLOAD` if the invoice HRP is malformed or the
|
|
203
|
+
* invoice is amountless (L402 challenges always specify a price in the
|
|
204
|
+
* invoice; an amountless invoice is a spec violation).
|
|
205
|
+
*/
|
|
206
|
+
function fromL402Challenge(challenge) {
|
|
207
|
+
const summary = decodeBolt11Summary(challenge.invoice);
|
|
208
|
+
if (summary.amountMsat === null) throw new s402Error("INVALID_PAYLOAD", "L402 invoice is amountless — L402 challenges must specify an exact price via the BOLT-11 amount");
|
|
209
|
+
return {
|
|
210
|
+
s402Version: S402_VERSION,
|
|
211
|
+
accepts: ["exact"],
|
|
212
|
+
network: summary.network,
|
|
213
|
+
asset: "lightning:msat",
|
|
214
|
+
amount: summary.amountMsat,
|
|
215
|
+
payTo: LIGHTNING_INVOICE_SENTINEL,
|
|
216
|
+
expiresAt: Date.now() + L402_DEFAULT_EXPIRY_WINDOW_MS,
|
|
217
|
+
extensions: { l402: {
|
|
218
|
+
macaroon: challenge.macaroon,
|
|
219
|
+
invoice: challenge.invoice
|
|
220
|
+
} }
|
|
221
|
+
};
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
//#endregion
|
|
225
|
+
export { decodeBolt11Summary, fromL402Challenge, parseWwwAuthenticateL402 };
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { S402_VERSION } from "
|
|
2
|
-
import { s402Error } from "
|
|
3
|
-
import { isValidAmount } from "
|
|
1
|
+
import { S402_VERSION } from "../types.mjs";
|
|
2
|
+
import { s402Error } from "../errors.mjs";
|
|
3
|
+
import { isValidAmount } from "../http.mjs";
|
|
4
4
|
|
|
5
|
-
//#region src/compat
|
|
5
|
+
//#region src/compat/mpp.ts
|
|
6
6
|
const TOKEN_CHARS = /^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;
|
|
7
7
|
const AUTH_SCHEME_PATTERN = /^\s*Payment(?:\s+(.*))?$/i;
|
|
8
8
|
/**
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import { s402ExactPayload, s402PaymentPayload, s402PaymentRequirements } from "
|
|
1
|
+
import { s402ExactPayload, s402PaymentPayload, s402PaymentRequirements } from "../types.mjs";
|
|
2
2
|
|
|
3
|
-
//#region src/compat.d.ts
|
|
3
|
+
//#region src/compat/x402.d.ts
|
|
4
4
|
/**
|
|
5
5
|
* x402 PaymentRequirements shape — supports both V1 and V2 wire formats.
|
|
6
6
|
*
|
|
@@ -115,7 +115,7 @@ declare function fromX402Envelope(envelope: x402PaymentRequiredEnvelope, now?: n
|
|
|
115
115
|
*
|
|
116
116
|
* @example
|
|
117
117
|
* ```ts
|
|
118
|
-
* import { normalizeRequirements } from 's402/compat';
|
|
118
|
+
* import { normalizeRequirements } from 's402/compat/x402';
|
|
119
119
|
*
|
|
120
120
|
* // Works with any format — auto-detects s402 vs x402
|
|
121
121
|
* const rawJson = JSON.parse(atob(header));
|
|
@@ -1,8 +1,8 @@
|
|
|
1
|
-
import { S402_VERSION } from "
|
|
2
|
-
import { s402Error } from "
|
|
3
|
-
import { isValidAmount, pickRequirementsFields, validateRequirementsShape } from "
|
|
1
|
+
import { S402_VERSION } from "../types.mjs";
|
|
2
|
+
import { s402Error } from "../errors.mjs";
|
|
3
|
+
import { isValidAmount, pickRequirementsFields, validateRequirementsShape } from "../http.mjs";
|
|
4
4
|
|
|
5
|
-
//#region src/compat.ts
|
|
5
|
+
//#region src/compat/x402.ts
|
|
6
6
|
/**
|
|
7
7
|
* Convert inbound x402 requirements to s402 format.
|
|
8
8
|
* Handles both V1 (`maxAmountRequired`) and V2 (`amount`) wire formats.
|
|
@@ -137,7 +137,7 @@ function fromX402Envelope(envelope, now) {
|
|
|
137
137
|
*
|
|
138
138
|
* @example
|
|
139
139
|
* ```ts
|
|
140
|
-
* import { normalizeRequirements } from 's402/compat';
|
|
140
|
+
* import { normalizeRequirements } from 's402/compat/x402';
|
|
141
141
|
*
|
|
142
142
|
* // Works with any format — auto-detects s402 vs x402
|
|
143
143
|
* const rawJson = JSON.parse(atob(header));
|
package/dist/http.mjs
CHANGED
|
@@ -459,7 +459,7 @@ function validateSubObjects(record) {
|
|
|
459
459
|
function validateRequirementsShape(obj) {
|
|
460
460
|
if (obj == null || typeof obj !== "object") throw new s402Error("INVALID_PAYLOAD", "Payment requirements is not an object");
|
|
461
461
|
const record = obj;
|
|
462
|
-
if (record.s402Version === void 0) throw new s402Error("INVALID_PAYLOAD", "Missing s402Version. For x402 format, use normalizeRequirements() from s402/compat.");
|
|
462
|
+
if (record.s402Version === void 0) throw new s402Error("INVALID_PAYLOAD", "Missing s402Version. For x402 format, use normalizeRequirements() from s402/compat/x402.");
|
|
463
463
|
if (record.s402Version !== "1") throw new s402Error("INVALID_PAYLOAD", `Unsupported s402 version "${record.s402Version}". This library supports version "1".`);
|
|
464
464
|
const missing = [];
|
|
465
465
|
if (!Array.isArray(record.accepts)) missing.push("accepts (array)");
|
package/dist/index.d.mts
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
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, s402SettlementOverrides, s402StreamExtra, s402StreamPayload, s402UnlockExtra, s402UnlockPayload, s402UptoExtra, s402UptoPayload, s402VerifyResponse } from "./types.mjs";
|
|
3
3
|
import { MAX_BODY_BYTES, S402_CONTENT_TYPE, decodePayloadBody, decodePaymentPayload, decodePaymentRequired, decodeRequirementsBody, decodeSettleBody, decodeSettleResponse, detectProtocol, detectTransport, encodePayloadBody, encodePaymentPayload, encodePaymentRequired, encodeRequirementsBody, encodeSettleBody, encodeSettleResponse, extractRequirementsFromResponse, isValidAmount, isValidU64Amount, validateRequirementsShape } from "./http.mjs";
|
|
4
|
-
import { a as s402ServerScheme, i as s402RouteConfig, n as s402DirectScheme, o as s402SettlementVerification, r as s402FacilitatorScheme, t as s402ClientScheme } from "./scheme-
|
|
4
|
+
import { a as s402ServerScheme, i as s402RouteConfig, n as s402DirectScheme, o as s402SettlementVerification, r as s402FacilitatorScheme, t as s402ClientScheme } from "./scheme-M-z-UV0c.mjs";
|
|
5
5
|
import { S402_RECEIPT_HEADER, formatReceiptHeader, parseReceiptHeader, s402Receipt, s402ReceiptSigner, s402ReceiptVerifier } from "./receipts.mjs";
|
|
6
6
|
|
|
7
7
|
//#region src/client.d.ts
|
|
@@ -32,7 +32,7 @@ declare class s402Client {
|
|
|
32
32
|
* `accepts` array that we have a registered implementation for.
|
|
33
33
|
*
|
|
34
34
|
* Accepts typed s402PaymentRequirements only. For x402 input, normalize
|
|
35
|
-
* first via `normalizeRequirements()` from 's402/compat'.
|
|
35
|
+
* first via `normalizeRequirements()` from 's402/compat/x402'.
|
|
36
36
|
*
|
|
37
37
|
* @param requirements - Server's payment requirements (from a 402 response)
|
|
38
38
|
* @returns Payment payload ready to send in the `x-payment` header
|
package/dist/index.mjs
CHANGED
|
@@ -35,7 +35,7 @@ var s402Client = class {
|
|
|
35
35
|
* `accepts` array that we have a registered implementation for.
|
|
36
36
|
*
|
|
37
37
|
* Accepts typed s402PaymentRequirements only. For x402 input, normalize
|
|
38
|
-
* first via `normalizeRequirements()` from 's402/compat'.
|
|
38
|
+
* first via `normalizeRequirements()` from 's402/compat/x402'.
|
|
39
39
|
*
|
|
40
40
|
* @param requirements - Server's payment requirements (from a 402 response)
|
|
41
41
|
* @returns Payment payload ready to send in the `x-payment` header
|
package/dist/test-utils.d.mts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { s402PaymentPayload, s402PaymentRequirements, s402SettleResponse, s402VerifyResponse } from "./types.mjs";
|
|
2
|
-
import { a as s402ServerScheme, r as s402FacilitatorScheme, t as s402ClientScheme } from "./scheme-
|
|
2
|
+
import { a as s402ServerScheme, r as s402FacilitatorScheme, t as s402ClientScheme } from "./scheme-M-z-UV0c.mjs";
|
|
3
3
|
|
|
4
4
|
//#region src/test-utils.d.ts
|
|
5
5
|
/**
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "s402",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.7.0",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"description": "s402 — Chain-agnostic HTTP 402 wire format. Types, HTTP encoding, and scheme registry for six payment schemes. Wire-compatible with x402. Zero runtime dependencies.",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -32,7 +32,7 @@
|
|
|
32
32
|
"agent-payments"
|
|
33
33
|
],
|
|
34
34
|
"engines": {
|
|
35
|
-
"node": ">=
|
|
35
|
+
"node": ">=20"
|
|
36
36
|
},
|
|
37
37
|
"sideEffects": false,
|
|
38
38
|
"files": [
|
|
@@ -68,19 +68,26 @@
|
|
|
68
68
|
},
|
|
69
69
|
"default": "./dist/http.mjs"
|
|
70
70
|
},
|
|
71
|
-
"./compat": {
|
|
71
|
+
"./compat/x402": {
|
|
72
72
|
"import": {
|
|
73
|
-
"types": "./dist/compat.d.mts",
|
|
74
|
-
"default": "./dist/compat.mjs"
|
|
73
|
+
"types": "./dist/compat/x402.d.mts",
|
|
74
|
+
"default": "./dist/compat/x402.mjs"
|
|
75
75
|
},
|
|
76
|
-
"default": "./dist/compat.mjs"
|
|
76
|
+
"default": "./dist/compat/x402.mjs"
|
|
77
77
|
},
|
|
78
|
-
"./compat
|
|
78
|
+
"./compat/mpp": {
|
|
79
79
|
"import": {
|
|
80
|
-
"types": "./dist/compat
|
|
81
|
-
"default": "./dist/compat
|
|
80
|
+
"types": "./dist/compat/mpp.d.mts",
|
|
81
|
+
"default": "./dist/compat/mpp.mjs"
|
|
82
82
|
},
|
|
83
|
-
"default": "./dist/compat
|
|
83
|
+
"default": "./dist/compat/mpp.mjs"
|
|
84
|
+
},
|
|
85
|
+
"./compat/l402": {
|
|
86
|
+
"import": {
|
|
87
|
+
"types": "./dist/compat/l402.d.mts",
|
|
88
|
+
"default": "./dist/compat/l402.mjs"
|
|
89
|
+
},
|
|
90
|
+
"default": "./dist/compat/l402.mjs"
|
|
84
91
|
},
|
|
85
92
|
"./errors": {
|
|
86
93
|
"import": {
|
|
File without changes
|