@routedock/routedock 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.
@@ -0,0 +1,148 @@
1
+ import type { Request, Response, NextFunction, RequestHandler } from 'express'
2
+ import { createX402Handler } from './x402Handler.js'
3
+ import { createMppChargeHandler } from './MppChargeHandler.js'
4
+ import { createMppSessionHandler } from './MppSessionHandler.js'
5
+ import type { RouteDockManifest, PaymentMode } from '../types.js'
6
+
7
+ export interface RouteDockMiddlewareOptions {
8
+ modes: PaymentMode[]
9
+ pricing: {
10
+ x402?: string
11
+ 'mpp-charge'?: string
12
+ 'mpp-session'?: { rate: string; channelContract: string }
13
+ }
14
+ asset: string
15
+ /** Stellar Asset Contract address for the payment asset */
16
+ assetContract: string
17
+ payee: string
18
+ network: 'testnet' | 'mainnet'
19
+ /** Private key (S...) of the server/payee account */
20
+ payeeSecretKey: string
21
+ /** Required for x402 mode */
22
+ facilitatorApiKey?: string
23
+ /** Required for mpp-session mode — ed25519 public key (G...) for verifying commitments */
24
+ commitmentPublicKey?: string
25
+ /** Full RouteDock manifest — served at /.well-known/routedock.json */
26
+ manifest: RouteDockManifest
27
+ /** Called after each successful on-chain settlement */
28
+ onSettled?: (txHash: string, amount: string, mode: string) => Promise<void>
29
+ }
30
+
31
+ /**
32
+ * Express middleware factory for RouteDock provider endpoints.
33
+ *
34
+ * Automatically serves /.well-known/routedock.json and enforces payment
35
+ * verification for all three modes (x402, mpp-charge, mpp-session).
36
+ *
37
+ * @example
38
+ * ```ts
39
+ * import { routedock } from '@routedock/sdk/provider'
40
+ *
41
+ * app.use('/price', routedock({
42
+ * modes: ['x402', 'mpp-charge'],
43
+ * pricing: { x402: '0.001', 'mpp-charge': '0.0008' },
44
+ * ...
45
+ * }))
46
+ * ```
47
+ */
48
+ export function routedock(opts: RouteDockMiddlewareOptions): RequestHandler {
49
+ const handlers: RequestHandler[] = []
50
+
51
+ if (opts.modes.includes('x402')) {
52
+ const x402Price = opts.pricing.x402
53
+ if (x402Price) {
54
+ handlers.push(
55
+ createX402Handler({
56
+ payeeSecretKey: opts.payeeSecretKey,
57
+ network: opts.network,
58
+ amount: x402Price,
59
+ assetContract: opts.assetContract,
60
+ ...(opts.facilitatorApiKey ? { facilitatorApiKey: opts.facilitatorApiKey } : {}),
61
+ manifest: opts.manifest,
62
+ ...(opts.onSettled ? { onSettled: opts.onSettled } : {}),
63
+ }),
64
+ )
65
+ }
66
+ }
67
+
68
+ if (opts.modes.includes('mpp-charge')) {
69
+ const chargePrice = opts.pricing['mpp-charge']
70
+ if (chargePrice) {
71
+ handlers.push(
72
+ createMppChargeHandler({
73
+ payeeSecretKey: opts.payeeSecretKey,
74
+ network: opts.network,
75
+ amount: chargePrice,
76
+ assetContract: opts.assetContract,
77
+ manifest: opts.manifest,
78
+ ...(opts.onSettled ? { onSettled: opts.onSettled } : {}),
79
+ }),
80
+ )
81
+ }
82
+ }
83
+
84
+ if (opts.modes.includes('mpp-session')) {
85
+ const sessionPricing = opts.pricing['mpp-session']
86
+ if (sessionPricing) {
87
+ if (!opts.commitmentPublicKey) {
88
+ throw new Error('routedock: mpp-session mode requires commitmentPublicKey')
89
+ }
90
+ handlers.push(
91
+ createMppSessionHandler({
92
+ payeeSecretKey: opts.payeeSecretKey,
93
+ network: opts.network,
94
+ channelContract: sessionPricing.channelContract,
95
+ rate: sessionPricing.rate,
96
+ assetContract: opts.assetContract,
97
+ manifest: opts.manifest,
98
+ commitmentPublicKey: opts.commitmentPublicKey,
99
+ ...(opts.onSettled ? { onSettled: opts.onSettled } : {}),
100
+ }),
101
+ )
102
+ }
103
+ }
104
+
105
+ return (req: Request, res: Response, next: NextFunction): void => {
106
+ // Serve manifest at /.well-known/routedock.json
107
+ if (req.path === '/.well-known/routedock.json') {
108
+ res.json(opts.manifest)
109
+ return
110
+ }
111
+
112
+ // No handlers — pass through
113
+ if (handlers.length === 0) {
114
+ next()
115
+ return
116
+ }
117
+
118
+ // Route to the correct handler based on request headers.
119
+ // x402 clients send `payment-signature` or `x-payment` headers.
120
+ // mppx clients send `authorization` with the mppx bearer scheme.
121
+ // On initial request (no payment), use the last handler (mppx returns
122
+ // WWW-Authenticate which x402 clients ignore; x402 only runs when its
123
+ // header is explicitly present).
124
+ const hasX402Header = !!(req.headers['payment-signature'] || req.headers['x-payment'])
125
+ const prefersX402 = req.headers['x-preferred-mode'] === 'x402'
126
+
127
+ let handler: RequestHandler | undefined
128
+ if (hasX402Header || prefersX402) {
129
+ handler = handlers[0]
130
+ } else {
131
+ handler = handlers[handlers.length - 1]
132
+ }
133
+
134
+ if (!handler) {
135
+ next()
136
+ return
137
+ }
138
+ void Promise.resolve()
139
+ .then(() => new Promise<void>((resolve, reject) => {
140
+ handler!(req, res, (handlerErr?: unknown) => {
141
+ if (handlerErr != null) reject(handlerErr)
142
+ else resolve()
143
+ })
144
+ }))
145
+ .then(() => next())
146
+ .catch((err) => next(err))
147
+ }
148
+ }
@@ -0,0 +1,112 @@
1
+ import type { Request, Response, NextFunction, RequestHandler } from 'express'
2
+ import { Keypair } from '@stellar/stellar-sdk'
3
+ import { ExactStellarScheme as ExactStellarFacilitatorScheme } from '@x402/stellar/exact/facilitator'
4
+ import { createEd25519Signer } from '@x402/stellar'
5
+ import {
6
+ decodePaymentSignatureHeader,
7
+ encodePaymentRequiredHeader,
8
+ encodePaymentResponseHeader,
9
+ } from '@x402/core/http'
10
+ import type { Network as X402Network } from '@x402/core/types'
11
+ import type { RouteDockManifest } from '../types.js'
12
+
13
+ type Network = 'testnet' | 'mainnet'
14
+
15
+ const CAIP2: Record<Network, X402Network> = {
16
+ testnet: 'stellar:testnet',
17
+ mainnet: 'stellar:pubnet',
18
+ }
19
+
20
+ export interface X402HandlerOptions {
21
+ payeeSecretKey: string
22
+ network: Network
23
+ amount: string
24
+ assetContract: string
25
+ facilitatorApiKey?: string
26
+ manifest: RouteDockManifest
27
+ onSettled?: (txHash: string, amount: string, mode: string) => Promise<void>
28
+ }
29
+
30
+ export function createX402Handler(opts: X402HandlerOptions): RequestHandler {
31
+ const caip2 = CAIP2[opts.network]
32
+ const payeeKeypair = Keypair.fromSecret(opts.payeeSecretKey)
33
+ const signer = createEd25519Signer(opts.payeeSecretKey, caip2)
34
+
35
+ const facilitatorScheme = new ExactStellarFacilitatorScheme([signer], {
36
+ areFeesSponsored: true,
37
+ })
38
+
39
+ const amountInBaseUnits = String(Math.round(parseFloat(opts.amount) * 1e7))
40
+ const requirements = {
41
+ scheme: 'exact' as const,
42
+ network: caip2,
43
+ asset: opts.assetContract,
44
+ amount: amountInBaseUnits,
45
+ payTo: opts.manifest.payee,
46
+ maxTimeoutSeconds: 60,
47
+ extra: {
48
+ areFeesSponsored: true,
49
+ facilitatorAddresses: [payeeKeypair.publicKey()],
50
+ },
51
+ }
52
+
53
+ return async (req: Request, res: Response, next: NextFunction): Promise<void> => {
54
+ try {
55
+ const paymentHeader = (req.headers['payment-signature'] ?? req.headers['x-payment']) as string | undefined
56
+
57
+ if (!paymentHeader) {
58
+ const x402Response = {
59
+ x402Version: 2,
60
+ resource: {
61
+ url: `${req.protocol}://${req.get('host') ?? ''}${req.originalUrl}`,
62
+ description: opts.manifest.name,
63
+ },
64
+ accepts: [requirements],
65
+ }
66
+ res
67
+ .status(402)
68
+ .setHeader('Content-Type', 'application/json')
69
+ .setHeader('X-Payment-Requirements', encodePaymentRequiredHeader(x402Response))
70
+ .json({ error: 'Payment Required' })
71
+ return
72
+ }
73
+
74
+ const payload = decodePaymentSignatureHeader(paymentHeader)
75
+ const verifyResult = await facilitatorScheme.verify(
76
+ payload as Parameters<typeof facilitatorScheme.verify>[0],
77
+ requirements,
78
+ )
79
+
80
+ if (!verifyResult.isValid) {
81
+ res.status(401).json({
82
+ error: 'Payment verification failed',
83
+ reason: (verifyResult as { invalidReason?: string }).invalidReason,
84
+ })
85
+ return
86
+ }
87
+
88
+ const settleResult = await facilitatorScheme.settle(
89
+ payload as Parameters<typeof facilitatorScheme.settle>[0],
90
+ requirements,
91
+ )
92
+
93
+ const txHash = (settleResult as { transaction?: string }).transaction ?? null
94
+ if (txHash && opts.onSettled) {
95
+ await opts.onSettled(txHash, opts.amount, 'x402')
96
+ }
97
+
98
+ if (settleResult) {
99
+ res.setHeader(
100
+ 'X-Payment-Response',
101
+ encodePaymentResponseHeader(
102
+ settleResult as Parameters<typeof encodePaymentResponseHeader>[0],
103
+ ),
104
+ )
105
+ }
106
+ next()
107
+ } catch (err) {
108
+ console.error('[x402] Settlement error:', err)
109
+ res.status(500).json({ error: 'Payment settlement failed' })
110
+ }
111
+ }
112
+ }
@@ -0,0 +1,159 @@
1
+ {
2
+ "$schema": "http://json-schema.org/draft-07/schema#",
3
+ "$id": "https://routedock.dev/schemas/routedock.schema.json",
4
+ "title": "RouteDock Manifest",
5
+ "description": "Discovery manifest served at /.well-known/routedock.json on every RouteDock provider endpoint",
6
+ "type": "object",
7
+ "required": [
8
+ "routedock",
9
+ "name",
10
+ "description",
11
+ "modes",
12
+ "network",
13
+ "asset",
14
+ "asset_contract",
15
+ "payee",
16
+ "pricing",
17
+ "endpoints",
18
+ "tags"
19
+ ],
20
+ "additionalProperties": false,
21
+ "properties": {
22
+ "routedock": {
23
+ "type": "string",
24
+ "const": "1.0",
25
+ "description": "Manifest schema version. Always '1.0' for this version."
26
+ },
27
+ "name": {
28
+ "type": "string",
29
+ "minLength": 1,
30
+ "maxLength": 120,
31
+ "description": "Human-readable provider name"
32
+ },
33
+ "description": {
34
+ "type": "string",
35
+ "minLength": 1,
36
+ "maxLength": 500,
37
+ "description": "Human-readable description of the provider's data or service"
38
+ },
39
+ "modes": {
40
+ "type": "array",
41
+ "minItems": 1,
42
+ "uniqueItems": true,
43
+ "items": {
44
+ "$ref": "#/definitions/PaymentMode"
45
+ },
46
+ "description": "Payment modes supported by this provider"
47
+ },
48
+ "network": {
49
+ "type": "string",
50
+ "enum": ["testnet", "mainnet"],
51
+ "description": "Stellar network this provider operates on"
52
+ },
53
+ "asset": {
54
+ "type": "string",
55
+ "description": "Asset ticker symbol (e.g. 'USDC')"
56
+ },
57
+ "asset_contract": {
58
+ "type": "string",
59
+ "description": "Stellar Asset Contract (SAC) address for the payment asset"
60
+ },
61
+ "payee": {
62
+ "type": "string",
63
+ "description": "Stellar address (G...) that receives payments"
64
+ },
65
+ "pricing": {
66
+ "type": "object",
67
+ "description": "Pricing configuration per supported payment mode",
68
+ "additionalProperties": false,
69
+ "properties": {
70
+ "x402": {
71
+ "$ref": "#/definitions/PricingConfig"
72
+ },
73
+ "mpp-charge": {
74
+ "$ref": "#/definitions/PricingConfig"
75
+ },
76
+ "mpp-session": {
77
+ "$ref": "#/definitions/SessionPricingConfig"
78
+ }
79
+ },
80
+ "minProperties": 1
81
+ },
82
+ "endpoints": {
83
+ "type": "object",
84
+ "description": "Map of endpoint name to HTTP method + path (e.g. { 'price': 'GET /price' })",
85
+ "additionalProperties": {
86
+ "type": "string"
87
+ },
88
+ "minProperties": 1
89
+ },
90
+ "tags": {
91
+ "type": "array",
92
+ "items": {
93
+ "type": "string",
94
+ "minLength": 1,
95
+ "maxLength": 64
96
+ },
97
+ "uniqueItems": true,
98
+ "description": "Capability tags indexed with trigram search in the provider registry"
99
+ }
100
+ },
101
+ "definitions": {
102
+ "PaymentMode": {
103
+ "type": "string",
104
+ "enum": ["x402", "mpp-charge", "mpp-session"],
105
+ "description": "A supported RouteDock payment mode"
106
+ },
107
+ "PricingConfig": {
108
+ "type": "object",
109
+ "description": "Per-request pricing for x402 or mpp-charge modes",
110
+ "required": ["amount", "per"],
111
+ "additionalProperties": false,
112
+ "properties": {
113
+ "amount": {
114
+ "type": "string",
115
+ "description": "Cost per request in the payment asset (decimal string, e.g. '0.001')"
116
+ },
117
+ "per": {
118
+ "type": "string",
119
+ "const": "request",
120
+ "description": "Billing unit — always 'request' for non-session modes"
121
+ },
122
+ "facilitator": {
123
+ "type": "string",
124
+ "description": "x402 facilitator URL (required for x402 mode). OpenZeppelin Channels endpoint."
125
+ }
126
+ }
127
+ },
128
+ "SessionPricingConfig": {
129
+ "type": "object",
130
+ "description": "Per-voucher pricing for mpp-session (one-way-channel) mode",
131
+ "required": ["rate", "per", "channel_contract", "min_deposit", "refund_waiting_period_ledgers"],
132
+ "additionalProperties": false,
133
+ "properties": {
134
+ "rate": {
135
+ "type": "string",
136
+ "description": "Cost per voucher in the payment asset (decimal string, e.g. '0.0001')"
137
+ },
138
+ "per": {
139
+ "type": "string",
140
+ "const": "voucher",
141
+ "description": "Billing unit — always 'voucher' for session mode"
142
+ },
143
+ "channel_contract": {
144
+ "type": "string",
145
+ "description": "Soroban contract address (C...) for the one-way-channel contract"
146
+ },
147
+ "min_deposit": {
148
+ "type": "string",
149
+ "description": "Minimum initial deposit to open a channel (decimal string)"
150
+ },
151
+ "refund_waiting_period_ledgers": {
152
+ "type": "integer",
153
+ "minimum": 1,
154
+ "description": "Ledgers the server has to settle before the funder can reclaim. Default: 17280 (~24h). Do not reduce in production."
155
+ }
156
+ }
157
+ }
158
+ }
159
+ }
@@ -0,0 +1,90 @@
1
+ import type { SupabaseClient } from '@supabase/supabase-js'
2
+ import type { SessionState } from '../types.js'
3
+ import { RouteDockSessionError } from '../types.js'
4
+
5
+ // ── Interface ──────────────────────────────────────────────────────────────────
6
+
7
+ export interface SessionStore {
8
+ get(channelId: string): Promise<SessionState | null>
9
+ /** Enforce monotonic invariant at application level before writing */
10
+ upsert(channelId: string, state: SessionState): Promise<void>
11
+ close(channelId: string): Promise<void>
12
+ }
13
+
14
+ // ── Supabase implementation ────────────────────────────────────────────────────
15
+
16
+ export class SupabaseSessionStore implements SessionStore {
17
+ constructor(private readonly supabase: SupabaseClient) {}
18
+
19
+ async get(channelId: string): Promise<SessionState | null> {
20
+ const { data, error } = await this.supabase
21
+ .from('sessions')
22
+ .select('*')
23
+ .eq('channel_id', channelId)
24
+ .maybeSingle()
25
+
26
+ if (error) throw new RouteDockSessionError(`SessionStore.get failed: ${error.message}`)
27
+ if (!data) return null
28
+
29
+ return {
30
+ channel_id: data.channel_id as string,
31
+ payee: data.payee as string,
32
+ payer: data.payer as string,
33
+ cumulative_amount: String(data.cumulative_amount),
34
+ last_signature: data.last_signature as string,
35
+ status: data.status as SessionState['status'],
36
+ opened_at: data.opened_at as string,
37
+ updated_at: data.updated_at as string,
38
+ settlement_tx_hash: data.settlement_tx_hash as string | null,
39
+ }
40
+ }
41
+
42
+ async upsert(channelId: string, state: SessionState): Promise<void> {
43
+ // Application-level monotonic invariant check — catches non-increasing
44
+ // amounts before hitting the DB trigger, giving a typed error.
45
+ const existing = await this.get(channelId)
46
+ if (existing) {
47
+ const prev = parseFloat(existing.cumulative_amount)
48
+ const next = parseFloat(state.cumulative_amount)
49
+ if (next <= prev) {
50
+ throw new RouteDockSessionError(
51
+ `cumulative_amount must be strictly increasing: ${next} <= ${prev}`,
52
+ )
53
+ }
54
+ }
55
+
56
+ const { error } = await this.supabase.from('sessions').upsert(
57
+ {
58
+ channel_id: state.channel_id,
59
+ payee: state.payee,
60
+ payer: state.payer,
61
+ cumulative_amount: state.cumulative_amount,
62
+ last_signature: state.last_signature,
63
+ status: state.status,
64
+ opened_at: state.opened_at,
65
+ updated_at: new Date().toISOString(),
66
+ settlement_tx_hash: state.settlement_tx_hash,
67
+ },
68
+ { onConflict: 'channel_id' },
69
+ )
70
+
71
+ if (error) {
72
+ // DB trigger will raise 'cumulative_amount must be strictly increasing'
73
+ if (error.message.includes('strictly increasing')) {
74
+ throw new RouteDockSessionError(
75
+ `cumulative_amount must be strictly increasing (DB): ${error.message}`,
76
+ )
77
+ }
78
+ throw new RouteDockSessionError(`SessionStore.upsert failed: ${error.message}`)
79
+ }
80
+ }
81
+
82
+ async close(channelId: string): Promise<void> {
83
+ const { error } = await this.supabase
84
+ .from('sessions')
85
+ .update({ status: 'closed', updated_at: new Date().toISOString() })
86
+ .eq('channel_id', channelId)
87
+
88
+ if (error) throw new RouteDockSessionError(`SessionStore.close failed: ${error.message}`)
89
+ }
90
+ }