@clawcash/forge 0.1.7 → 0.1.8
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/README.md +8 -2
- package/dist/index.cjs +139 -17
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +44 -4
- package/dist/index.d.ts +44 -4
- package/dist/index.js +137 -17
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -46,18 +46,24 @@ await mountAgentServices(app, [removeBackground], {
|
|
|
46
46
|
repo: "my-app",
|
|
47
47
|
baseUrl: process.env.FORGE_URL ?? "https://forge.clawca.sh",
|
|
48
48
|
},
|
|
49
|
+
gateway: { handle: "my-app" },
|
|
49
50
|
});
|
|
50
51
|
|
|
51
52
|
app.listen(3000);
|
|
52
53
|
```
|
|
53
54
|
|
|
54
|
-
|
|
55
|
+
The only env var a deployed merchant needs is `FORGE_API_KEY` (per-project key from the Forge dashboard). Everything else resolves automatically:
|
|
56
|
+
|
|
57
|
+
- **payTo** — `PAY_TO` env (optional override) → live Forge API → `payToFallback`.
|
|
58
|
+
- **Gateway URL** — defaults to `https://gateway.clawca.sh` (`GATEWAY_URL` to override).
|
|
59
|
+
- **Handle** — baked into the mount options by Forge codegen (`FORGE_HANDLE` to override).
|
|
60
|
+
- **Public base URL** — `PUBLIC_BASE_URL` env → platform vars (Railway, Render, Vercel, Fly, Heroku) → inferred from the first inbound probe and self-verified (the SDK fetches its own `/forge/health` at the candidate URL and checks the per-boot instance nonce before trusting it).
|
|
55
61
|
|
|
56
62
|
Agents call `POST /agent/remove-background` and pay via x402 when challenged with HTTP 402.
|
|
57
63
|
|
|
58
64
|
After mount, the merchant also exposes liveliness probes:
|
|
59
65
|
|
|
60
|
-
- `GET /forge/health` — process up + Forge mounted
|
|
66
|
+
- `GET /forge/health` — process up + Forge mounted (includes the instance nonce)
|
|
61
67
|
- `GET /forge/status` — readiness (`ready` needs fulfill secret + public URL + actions)
|
|
62
68
|
- `GET /.well-known/clawcash.json` — discovery
|
|
63
69
|
|
package/dist/index.cjs
CHANGED
|
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
|
|
|
21
21
|
var index_exports = {};
|
|
22
22
|
__export(index_exports, {
|
|
23
23
|
FORGE_GATEWAY_USER_ID: () => FORGE_GATEWAY_USER_ID,
|
|
24
|
+
PublicBaseUrlResolver: () => PublicBaseUrlResolver,
|
|
24
25
|
buildForgeSurfaceStatus: () => buildForgeSurfaceStatus,
|
|
25
26
|
buildWellKnownDocument: () => buildWellKnownDocument,
|
|
26
27
|
createContext: () => createContext,
|
|
@@ -38,6 +39,7 @@ __export(index_exports, {
|
|
|
38
39
|
mountAgentServices: () => mountAgentServices,
|
|
39
40
|
recordHeartbeatResult: () => recordHeartbeatResult,
|
|
40
41
|
requireForgeGateway: () => requireForgeGateway,
|
|
42
|
+
resolveBaseUrlFromEnv: () => resolveBaseUrlFromEnv,
|
|
41
43
|
resolvePayTo: () => resolvePayTo,
|
|
42
44
|
toKebabCase: () => toKebabCase,
|
|
43
45
|
waitUntil: () => waitUntil
|
|
@@ -88,6 +90,109 @@ var import_express2 = require("@x402/express");
|
|
|
88
90
|
var import_server = require("@x402/core/server");
|
|
89
91
|
var import_server2 = require("@x402/evm/exact/server");
|
|
90
92
|
|
|
93
|
+
// src/base-url.ts
|
|
94
|
+
var import_node_crypto = require("crypto");
|
|
95
|
+
function resolveBaseUrlFromEnv(explicit) {
|
|
96
|
+
const fromExplicit = explicit?.trim();
|
|
97
|
+
if (fromExplicit) return stripSlash(fromExplicit);
|
|
98
|
+
const fromEnv = process.env.PUBLIC_BASE_URL?.trim();
|
|
99
|
+
if (fromEnv) return stripSlash(fromEnv);
|
|
100
|
+
const railway = process.env.RAILWAY_PUBLIC_DOMAIN?.trim();
|
|
101
|
+
if (railway) return `https://${stripSlash(railway)}`;
|
|
102
|
+
const render = process.env.RENDER_EXTERNAL_URL?.trim();
|
|
103
|
+
if (render) return stripSlash(render);
|
|
104
|
+
const vercel = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() || process.env.VERCEL_URL?.trim();
|
|
105
|
+
if (vercel) return `https://${stripSlash(vercel)}`;
|
|
106
|
+
const fly = process.env.FLY_APP_NAME?.trim();
|
|
107
|
+
if (fly) return `https://${fly}.fly.dev`;
|
|
108
|
+
const heroku = process.env.HEROKU_APP_NAME?.trim();
|
|
109
|
+
if (heroku) return `https://${heroku}.herokuapp.com`;
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
function stripSlash(url) {
|
|
113
|
+
return url.replace(/\/$/, "");
|
|
114
|
+
}
|
|
115
|
+
var MAX_VERIFY_ATTEMPTS = 5;
|
|
116
|
+
var VERIFY_TIMEOUT_MS = 3e3;
|
|
117
|
+
var PublicBaseUrlResolver = class {
|
|
118
|
+
/** Per-boot nonce, echoed by /forge/health for self-verification. */
|
|
119
|
+
instanceNonce;
|
|
120
|
+
resolved;
|
|
121
|
+
verifying = false;
|
|
122
|
+
rejected = /* @__PURE__ */ new Set();
|
|
123
|
+
attempts = 0;
|
|
124
|
+
onResolved;
|
|
125
|
+
constructor(opts) {
|
|
126
|
+
this.instanceNonce = (0, import_node_crypto.randomBytes)(16).toString("hex");
|
|
127
|
+
this.resolved = opts.initial;
|
|
128
|
+
this.onResolved = opts.onResolved ?? null;
|
|
129
|
+
}
|
|
130
|
+
get() {
|
|
131
|
+
return this.resolved;
|
|
132
|
+
}
|
|
133
|
+
/**
|
|
134
|
+
* Feed an inbound Forge-surface request. No-op once resolved. Kicks off
|
|
135
|
+
* async self-verification of the candidate URL derived from the request.
|
|
136
|
+
*/
|
|
137
|
+
considerRequest(req) {
|
|
138
|
+
if (this.resolved || this.verifying) return;
|
|
139
|
+
if (this.attempts >= MAX_VERIFY_ATTEMPTS) return;
|
|
140
|
+
const candidate = candidateFromRequest(req);
|
|
141
|
+
if (!candidate || this.rejected.has(candidate)) return;
|
|
142
|
+
this.verifying = true;
|
|
143
|
+
this.attempts += 1;
|
|
144
|
+
void this.verify(candidate).then((ok) => {
|
|
145
|
+
if (ok) {
|
|
146
|
+
this.resolved = candidate;
|
|
147
|
+
console.log(`[forge] public base URL inferred and verified: ${candidate}`);
|
|
148
|
+
this.onResolved?.(candidate);
|
|
149
|
+
} else {
|
|
150
|
+
this.rejected.add(candidate);
|
|
151
|
+
console.warn(
|
|
152
|
+
`[forge] candidate base URL failed self-verification, ignoring: ${candidate}`
|
|
153
|
+
);
|
|
154
|
+
}
|
|
155
|
+
}).finally(() => {
|
|
156
|
+
this.verifying = false;
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
/** Fetch our own /forge/health at the candidate and match the boot nonce. */
|
|
160
|
+
async verify(candidate) {
|
|
161
|
+
try {
|
|
162
|
+
const controller = new AbortController();
|
|
163
|
+
const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);
|
|
164
|
+
const res = await fetch(`${candidate}/forge/health`, {
|
|
165
|
+
signal: controller.signal,
|
|
166
|
+
headers: { accept: "application/json" },
|
|
167
|
+
redirect: "manual"
|
|
168
|
+
});
|
|
169
|
+
clearTimeout(timer);
|
|
170
|
+
if (!res.ok) return false;
|
|
171
|
+
const json = await res.json();
|
|
172
|
+
return json.instance === this.instanceNonce;
|
|
173
|
+
} catch {
|
|
174
|
+
return false;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
};
|
|
178
|
+
function candidateFromRequest(req) {
|
|
179
|
+
const host = firstHeaderValue(req.headers["x-forwarded-host"]) ?? req.headers.host;
|
|
180
|
+
if (!host || !isValidHost(host)) return null;
|
|
181
|
+
const proto = firstHeaderValue(req.headers["x-forwarded-proto"]) ?? (req.protocol || "http");
|
|
182
|
+
if (proto !== "https" && proto !== "http") return null;
|
|
183
|
+
const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host);
|
|
184
|
+
if (proto === "http" && !isLocal) return null;
|
|
185
|
+
return `${proto}://${host}`;
|
|
186
|
+
}
|
|
187
|
+
function firstHeaderValue(value) {
|
|
188
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
189
|
+
const first = raw?.split(",")[0]?.trim();
|
|
190
|
+
return first || null;
|
|
191
|
+
}
|
|
192
|
+
function isValidHost(host) {
|
|
193
|
+
return /^[a-z0-9.-]+(:\d{1,5})?$/i.test(host) || /^\[[0-9a-f:]+\](:\d{1,5})?$/i.test(host);
|
|
194
|
+
}
|
|
195
|
+
|
|
91
196
|
// src/gateway.ts
|
|
92
197
|
async function heartbeatGateway(opts) {
|
|
93
198
|
const gateway = opts.gatewayUrl.replace(/\/$/, "");
|
|
@@ -209,7 +314,7 @@ async function resolvePayTo(opts) {
|
|
|
209
314
|
}
|
|
210
315
|
|
|
211
316
|
// src/status.ts
|
|
212
|
-
var PACKAGE_VERSION = "0.1.
|
|
317
|
+
var PACKAGE_VERSION = "0.1.8";
|
|
213
318
|
var lastHeartbeat = {
|
|
214
319
|
attempted: false,
|
|
215
320
|
ok: null,
|
|
@@ -271,6 +376,7 @@ function forgeSdkVersion() {
|
|
|
271
376
|
// src/mount.ts
|
|
272
377
|
var DEFAULT_NETWORK = "eip155:8453";
|
|
273
378
|
var DEFAULT_FACILITATOR_URL = "https://facilitator.xpay.sh";
|
|
379
|
+
var DEFAULT_GATEWAY_URL = "https://gateway.clawca.sh";
|
|
274
380
|
function asNetwork(value) {
|
|
275
381
|
return value ?? DEFAULT_NETWORK;
|
|
276
382
|
}
|
|
@@ -370,7 +476,7 @@ function mountFulfillmentRouter(app, services, options) {
|
|
|
370
476
|
function mountForgeStatusRoutes(app, services, options, opts) {
|
|
371
477
|
const getStatus = () => buildForgeSurfaceStatus({
|
|
372
478
|
handle: opts.handle,
|
|
373
|
-
publicBaseUrl: opts.
|
|
479
|
+
publicBaseUrl: opts.resolver.get(),
|
|
374
480
|
gatewayUrl: opts.gatewayUrl,
|
|
375
481
|
fulfillMounted: opts.fulfillMounted,
|
|
376
482
|
fulfillPath: opts.fulfillPath,
|
|
@@ -382,7 +488,8 @@ function mountForgeStatusRoutes(app, services, options, opts) {
|
|
|
382
488
|
price: s.payment.amount
|
|
383
489
|
}))
|
|
384
490
|
});
|
|
385
|
-
app.get("/forge/health", (
|
|
491
|
+
app.get("/forge/health", (req, res) => {
|
|
492
|
+
opts.resolver.considerRequest(req);
|
|
386
493
|
const status = getStatus();
|
|
387
494
|
res.json({
|
|
388
495
|
ok: true,
|
|
@@ -390,14 +497,18 @@ function mountForgeStatusRoutes(app, services, options, opts) {
|
|
|
390
497
|
ready: status.ready,
|
|
391
498
|
handle: status.handle,
|
|
392
499
|
version: status.version,
|
|
500
|
+
// Per-boot nonce so this instance can self-verify an inferred base URL.
|
|
501
|
+
instance: opts.resolver.instanceNonce,
|
|
393
502
|
actions: status.actions.map((a) => a.name)
|
|
394
503
|
});
|
|
395
504
|
});
|
|
396
|
-
app.get("/forge/status", (
|
|
505
|
+
app.get("/forge/status", (req, res) => {
|
|
506
|
+
opts.resolver.considerRequest(req);
|
|
397
507
|
const status = getStatus();
|
|
398
508
|
res.status(status.ready ? 200 : 503).json(status);
|
|
399
509
|
});
|
|
400
|
-
app.get("/.well-known/clawcash.json", (
|
|
510
|
+
app.get("/.well-known/clawcash.json", (req, res) => {
|
|
511
|
+
opts.resolver.considerRequest(req);
|
|
401
512
|
res.json(buildWellKnownDocument(getStatus()));
|
|
402
513
|
});
|
|
403
514
|
console.log(
|
|
@@ -472,23 +583,15 @@ async function mountAgentServices(app, services, options) {
|
|
|
472
583
|
getForgeApiKey(options.gateway?.registerSecret)
|
|
473
584
|
);
|
|
474
585
|
mountFulfillmentRouter(app, services, options);
|
|
475
|
-
const gatewayUrl = options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() ||
|
|
586
|
+
const gatewayUrl = options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL;
|
|
476
587
|
const handle = options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;
|
|
477
588
|
const registerSecret = options.gateway?.registerSecret?.trim() || process.env.FORGE_API_KEY?.trim() || process.env.GATEWAY_REGISTER_SECRET?.trim();
|
|
478
|
-
const
|
|
479
|
-
|
|
480
|
-
fulfillMounted,
|
|
481
|
-
fulfillPath,
|
|
482
|
-
agentBasePath: basePath,
|
|
483
|
-
handle,
|
|
484
|
-
publicBaseUrl,
|
|
485
|
-
gatewayUrl
|
|
486
|
-
});
|
|
487
|
-
if (gatewayUrl && handle && registerSecret && publicBaseUrl) {
|
|
589
|
+
const sendHeartbeat = (baseUrl) => {
|
|
590
|
+
if (!handle || !registerSecret) return;
|
|
488
591
|
void heartbeatGateway({
|
|
489
592
|
gatewayUrl,
|
|
490
593
|
handle,
|
|
491
|
-
baseUrl
|
|
594
|
+
baseUrl,
|
|
492
595
|
registerSecret
|
|
493
596
|
}).then(() => {
|
|
494
597
|
recordHeartbeatResult({ ok: true });
|
|
@@ -497,6 +600,23 @@ async function mountAgentServices(app, services, options) {
|
|
|
497
600
|
recordHeartbeatResult({ ok: false, error: message });
|
|
498
601
|
console.warn("[forge] gateway heartbeat skipped:", err);
|
|
499
602
|
});
|
|
603
|
+
};
|
|
604
|
+
const resolver = new PublicBaseUrlResolver({
|
|
605
|
+
initial: resolveBaseUrlFromEnv(options.gateway?.publicBaseUrl),
|
|
606
|
+
// Base URL learned late (inferred from the first probe): heartbeat now.
|
|
607
|
+
onResolved: sendHeartbeat
|
|
608
|
+
});
|
|
609
|
+
mountForgeStatusRoutes(app, services, options, {
|
|
610
|
+
fulfillMounted,
|
|
611
|
+
fulfillPath,
|
|
612
|
+
agentBasePath: basePath,
|
|
613
|
+
handle,
|
|
614
|
+
resolver,
|
|
615
|
+
gatewayUrl
|
|
616
|
+
});
|
|
617
|
+
const bootBaseUrl = resolver.get();
|
|
618
|
+
if (bootBaseUrl) {
|
|
619
|
+
sendHeartbeat(bootBaseUrl);
|
|
500
620
|
}
|
|
501
621
|
return router;
|
|
502
622
|
}
|
|
@@ -590,6 +710,7 @@ function generateSkillMarkdown(services, meta) {
|
|
|
590
710
|
// Annotate the CommonJS export names for ESM import in node:
|
|
591
711
|
0 && (module.exports = {
|
|
592
712
|
FORGE_GATEWAY_USER_ID,
|
|
713
|
+
PublicBaseUrlResolver,
|
|
593
714
|
buildForgeSurfaceStatus,
|
|
594
715
|
buildWellKnownDocument,
|
|
595
716
|
createContext,
|
|
@@ -607,6 +728,7 @@ function generateSkillMarkdown(services, meta) {
|
|
|
607
728
|
mountAgentServices,
|
|
608
729
|
recordHeartbeatResult,
|
|
609
730
|
requireForgeGateway,
|
|
731
|
+
resolveBaseUrlFromEnv,
|
|
610
732
|
resolvePayTo,
|
|
611
733
|
toKebabCase,
|
|
612
734
|
waitUntil
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/define.ts","../src/mount.ts","../src/gateway.ts","../src/gateway-auth.ts","../src/payto.ts","../src/status.ts","../src/skill.ts"],"sourcesContent":["export { defineAgentService, waitUntil, createContext, toKebabCase } from \"./define.js\";\nexport { mountAgentServices, createForgeRouter } from \"./mount.js\";\nexport { generateSkillMarkdown } from \"./skill.js\";\nexport { resolvePayTo, isZeroAddress } from \"./payto.js\";\nexport { heartbeatGateway } from \"./gateway.js\";\nexport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n forgeSdkVersion,\n getLastHeartbeat,\n recordHeartbeatResult,\n} from \"./status.js\";\nexport type { ForgeHeartbeatState, ForgeSurfaceStatus } from \"./status.js\";\nexport {\n isForgeGatewayRequest,\n requireForgeGateway,\n getForgeApiKey,\n getForgeGatewaySecret,\n forgeGatewayLoopbackHeaders,\n FORGE_GATEWAY_USER_ID,\n} from \"./gateway-auth.js\";\nexport type {\n SchemaFieldType,\n InputSchema,\n OutputSchema,\n PaymentConfig,\n WaitUntilOptions,\n AgentServiceContext,\n AgentServiceConfig,\n DefinedAgentService,\n MountOptions,\n ForgePayToSource,\n SkillMeta,\n} from \"./types.js\";\n","import type {\n AgentServiceConfig,\n AgentServiceContext,\n DefinedAgentService,\n WaitUntilOptions,\n} from \"./types.js\";\n\nexport async function waitUntil<T>(options: WaitUntilOptions<T>): Promise<T> {\n const intervalMs = options.intervalMs ?? 500;\n const timeoutMs = options.timeoutMs ?? 60_000;\n const started = Date.now();\n\n for (;;) {\n const value = await options.run();\n if (options.completedWhen(value)) {\n return value;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`waitUntil timed out after ${timeoutMs}ms`);\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n}\n\nexport function createContext(): AgentServiceContext {\n return {\n waitUntil,\n };\n}\n\n/** Convert snake_case or camelCase service name to kebab-case path segment. */\nexport function toKebabCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n}\n\nexport function defineAgentService<\n TInput extends Record<string, unknown> = Record<string, unknown>,\n TOutput extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: AgentServiceConfig<TInput, TOutput>,\n): DefinedAgentService<TInput, TOutput> {\n if (!config.name?.trim()) {\n throw new Error(\"defineAgentService: name is required\");\n }\n if (!config.execute) {\n throw new Error(\"defineAgentService: execute is required\");\n }\n\n return {\n ...config,\n __forge: true,\n path: toKebabCase(config.name),\n };\n}\n","import type { Application, Request, Response, NextFunction, Router } from \"express\";\nimport { Router as createRouter } from \"express\";\nimport { paymentMiddleware, x402ResourceServer } from \"@x402/express\";\nimport type { Network } from \"@x402/express\";\nimport { HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { createContext } from \"./define.js\";\nimport { heartbeatGateway } from \"./gateway.js\";\nimport {\n getForgeApiKey,\n requireForgeGateway,\n} from \"./gateway-auth.js\";\nimport { isZeroAddress, resolvePayTo } from \"./payto.js\";\nimport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n recordHeartbeatResult,\n} from \"./status.js\";\nimport type {\n DefinedAgentService,\n InputSchema,\n MountOptions,\n SchemaFieldType,\n} from \"./types.js\";\n\n/** Base mainnet — settled via the public XPay facilitator (no API keys). */\nconst DEFAULT_NETWORK = \"eip155:8453\" as const satisfies Network;\n/** Open facilitator: Base mainnet + Sepolia, no API keys. https://github.com/xpaysh/xpay-x402 */\nconst DEFAULT_FACILITATOR_URL = \"https://facilitator.xpay.sh\";\n\nfunction asNetwork(value: string | undefined): Network {\n return (value ?? DEFAULT_NETWORK) as Network;\n}\n\nfunction createFacilitatorClient(options: MountOptions): HTTPFacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,\n createAuthHeaders: options.createAuthHeaders,\n });\n}\n\nfunction validateInput(\n body: unknown,\n schema: InputSchema,\n): { ok: true; value: Record<string, unknown> } | { ok: false; error: string } {\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n return { ok: false, error: \"Request body must be a JSON object\" };\n }\n\n const input = body as Record<string, unknown>;\n const value: Record<string, unknown> = {};\n\n for (const [key, type] of Object.entries(schema)) {\n if (!(key in input) || input[key] === undefined || input[key] === null) {\n return { ok: false, error: `Missing required field: ${key}` };\n }\n const err = checkType(key, input[key], type);\n if (err) return { ok: false, error: err };\n value[key] = input[key];\n }\n\n return { ok: true, value };\n}\n\nfunction checkType(key: string, value: unknown, type: SchemaFieldType): string | null {\n switch (type) {\n case \"string\":\n case \"url\":\n if (typeof value !== \"string\" || !value.trim()) {\n return `Field ${key} must be a non-empty string`;\n }\n if (type === \"url\") {\n try {\n new URL(value);\n } catch {\n return `Field ${key} must be a valid URL`;\n }\n }\n return null;\n case \"number\":\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return `Field ${key} must be a number`;\n }\n return null;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n return `Field ${key} must be a boolean`;\n }\n return null;\n default:\n return null;\n }\n}\n\nfunction formatPrice(amount: string): string {\n const normalized = amount.startsWith(\"$\") ? amount.slice(1) : amount;\n return `$${normalized}`;\n}\n\nfunction mountFulfillmentRouter(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): void {\n const secret = getForgeApiKey(options.gateway?.registerSecret);\n if (!secret) {\n console.warn(\n \"[forge] /forge/fulfill not mounted — set FORGE_API_KEY (from Forge dashboard, min 16 chars) so the gateway can fulfill after payment\",\n );\n return;\n }\n\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n const gate = requireForgeGateway(secret);\n\n for (const service of services) {\n router.post(\n `/${service.path}`,\n gate,\n async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] fulfill ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n },\n );\n }\n\n app.use(fulfillPath, router);\n console.log(\n `[forge] fulfillment mounted at POST ${fulfillPath}/{action} (gateway secret)`,\n );\n}\n\nfunction mountForgeStatusRoutes(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n opts: {\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n },\n): void {\n const getStatus = () =>\n buildForgeSurfaceStatus({\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath: opts.fulfillPath,\n agentBasePath: opts.agentBasePath,\n skipPayment: Boolean(options.skipPayment),\n actions: services.map((s) => ({\n name: s.name,\n path: s.path,\n price: s.payment.amount,\n })),\n });\n\n app.get(\"/forge/health\", (_req: Request, res: Response) => {\n const status = getStatus();\n res.json({\n ok: true,\n forge: true as const,\n ready: status.ready,\n handle: status.handle,\n version: status.version,\n actions: status.actions.map((a) => a.name),\n });\n });\n\n app.get(\"/forge/status\", (_req: Request, res: Response) => {\n const status = getStatus();\n res.status(status.ready ? 200 : 503).json(status);\n });\n\n app.get(\"/.well-known/clawcash.json\", (_req: Request, res: Response) => {\n res.json(buildWellKnownDocument(getStatus()));\n });\n\n console.log(\n \"[forge] liveliness: GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json\",\n );\n}\n\n/**\n * Mount Forge agent services on an Express app.\n * - GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json — liveliness\n * - POST {basePath}/{kebab-name} — optional public x402 agent surface\n * - POST /forge/fulfill/{kebab-name} — private gateway fulfillment after payment\n *\n * payTo resolves automatically: PAY_TO env (optional) → Forge API → baked fallback.\n */\nexport async function mountAgentServices(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): Promise<Router> {\n let payTo = \"\";\n if (!options.skipPayment) {\n const fallback =\n options.payToFallback?.trim() || options.payTo?.trim() || \"\";\n payTo = await resolvePayTo({\n fallback,\n payTo: options.payTo,\n forge: options.forge,\n });\n if (isZeroAddress(payTo)) {\n throw new Error(\n \"mountAgentServices: resolved payTo is the zero address. Re-run Forge to provision a wallet.\",\n );\n }\n }\n\n const basePath = (options.basePath ?? \"/agent\").replace(/\\/$/, \"\") || \"/agent\";\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n\n const routes: RoutesConfig = {};\n\n for (const service of services) {\n const routePath = `/${service.path}`;\n const fullPath = `${basePath}${routePath}`;\n const network = asNetwork(service.payment.network);\n\n if (!options.skipPayment) {\n routes[`POST ${fullPath}`] = {\n accepts: {\n scheme: \"exact\",\n price: formatPrice(service.payment.amount),\n network,\n payTo,\n },\n description: service.description,\n mimeType: \"application/json\",\n };\n }\n\n router.post(routePath, async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n });\n }\n\n if (!options.skipPayment && Object.keys(routes).length > 0) {\n const facilitator = createFacilitatorClient(options);\n const networks = new Set(\n services.map((s) => asNetwork(s.payment.network)),\n );\n const resourceServer = new x402ResourceServer(facilitator);\n for (const network of networks) {\n resourceServer.register(network, new ExactEvmScheme());\n }\n app.use(paymentMiddleware(routes, resourceServer, undefined, undefined, true));\n }\n\n app.use(basePath, router);\n const fulfillMounted = Boolean(\n getForgeApiKey(options.gateway?.registerSecret),\n );\n mountFulfillmentRouter(app, services, options);\n\n const gatewayUrl =\n options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() || null;\n const handle =\n options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;\n const registerSecret =\n options.gateway?.registerSecret?.trim() ||\n process.env.FORGE_API_KEY?.trim() ||\n process.env.GATEWAY_REGISTER_SECRET?.trim();\n const publicBaseUrl =\n options.gateway?.publicBaseUrl?.trim() ||\n process.env.PUBLIC_BASE_URL?.trim() ||\n (process.env.RAILWAY_PUBLIC_DOMAIN\n ? `https://${process.env.RAILWAY_PUBLIC_DOMAIN}`\n : \"\") ||\n null;\n\n mountForgeStatusRoutes(app, services, options, {\n fulfillMounted,\n fulfillPath,\n agentBasePath: basePath,\n handle,\n publicBaseUrl,\n gatewayUrl,\n });\n\n if (gatewayUrl && handle && registerSecret && publicBaseUrl) {\n void heartbeatGateway({\n gatewayUrl,\n handle,\n baseUrl: publicBaseUrl,\n registerSecret,\n })\n .then(() => {\n recordHeartbeatResult({ ok: true });\n })\n .catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n recordHeartbeatResult({ ok: false, error: message });\n console.warn(\"[forge] gateway heartbeat skipped:\", err);\n });\n }\n\n return router;\n}\n\nexport function createForgeRouter(\n services: DefinedAgentService[],\n options: MountOptions,\n): (app: Application) => Promise<Router> {\n return (app) => mountAgentServices(app, services, options);\n}\n\nexport function forgeErrorHandler(\n err: unknown,\n _req: Request,\n res: Response,\n _next: NextFunction,\n): void {\n const message = err instanceof Error ? err.message : \"Internal error\";\n res.status(500).json({ error: message });\n}\n","/**\n * Notify ClawCash gateway of this merchant's live public base URL.\n * Full action registration still happens from Forge \"Go live\".\n */\nexport async function heartbeatGateway(opts: {\n gatewayUrl: string;\n handle: string;\n baseUrl: string;\n registerSecret: string;\n}): Promise<void> {\n const gateway = opts.gatewayUrl.replace(/\\/$/, \"\");\n const res = await fetch(`${gateway}/register/heartbeat`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${opts.registerSecret}`,\n },\n body: JSON.stringify({\n handle: opts.handle.trim().toLowerCase(),\n baseUrl: opts.baseUrl.replace(/\\/$/, \"\"),\n }),\n });\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `gateway heartbeat failed (${res.status}): ${text.slice(0, 240)}`,\n );\n }\n}\n","import type { NextFunction, Request, Response } from \"express\";\n\n/**\n * Per-project Forge API key for gateway → merchant fulfillment.\n * Merchants set FORGE_API_KEY from the Forge dashboard (never the shared\n * GATEWAY_REGISTER_SECRET — that is Forge↔gateway platform auth only).\n *\n * GATEWAY_REGISTER_SECRET is accepted as a deprecated fallback for older deploys.\n */\nexport function getForgeApiKey(explicit?: string | null): string | null {\n const value =\n (explicit ?? process.env.FORGE_API_KEY ?? process.env.GATEWAY_REGISTER_SECRET)?.trim();\n if (!value || value.length < 16) return null;\n return value;\n}\n\n/** @deprecated Use getForgeApiKey */\nexport function getForgeGatewaySecret(\n explicit?: string | null,\n): string | null {\n return getForgeApiKey(explicit);\n}\n\nexport function isForgeGatewayRequest(\n req: Request,\n secret?: string | null,\n): boolean {\n const expected = getForgeApiKey(secret);\n if (!expected) return false;\n const header = req.header(\"authorization\") ?? \"\";\n const bearer = header.toLowerCase().startsWith(\"bearer \")\n ? header.slice(7).trim()\n : \"\";\n const alt =\n req.header(\"x-forge-api-key\")?.trim() ||\n req.header(\"x-clawcash-gateway\")?.trim() ||\n \"\";\n return bearer === expected || alt === expected;\n}\n\n/** Synthetic user id for DB rows created by gateway-driven fulfillment. */\nexport const FORGE_GATEWAY_USER_ID = \"forge_gateway_agent\";\n\nexport function requireForgeGateway(\n secret?: string | null,\n): (req: Request, res: Response, next: NextFunction) => void {\n return (req, res, next) => {\n if (!isForgeGatewayRequest(req, secret)) {\n res.status(401).json({\n error:\n \"Unauthorized — Forge API key required (FORGE_API_KEY from Forge dashboard)\",\n });\n return;\n }\n next();\n };\n}\n\n/** Headers merchant execute() should send on loopback calls during fulfillment. */\nexport function forgeGatewayLoopbackHeaders(\n secret?: string | null,\n): Record<string, string> {\n const expected = getForgeApiKey(secret);\n if (!expected) return {};\n return {\n Authorization: `Bearer ${expected}`,\n \"X-Forge-Api-Key\": expected,\n };\n}\n","import type { ForgePayToSource } from \"./types.js\";\n\nexport type { ForgePayToSource };\n\nconst ZERO = /^0x0{40}$/i;\n\nexport function isZeroAddress(address: string | undefined | null): boolean {\n if (!address) return true;\n return ZERO.test(address.trim());\n}\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nfunction pickForgeBaseUrl(source?: ForgePayToSource): string | null {\n const fromEnv = process.env.FORGE_URL?.trim();\n if (fromEnv) return normalizeBaseUrl(fromEnv);\n\n const fromOpts = source?.baseUrl?.trim();\n if (!fromOpts) return null;\n\n const normalized = normalizeBaseUrl(fromOpts);\n // Never call a laptop Forge from a deployed merchant app.\n if (\n /localhost|127\\.0\\.0\\.1/i.test(normalized) &&\n process.env.NODE_ENV === \"production\"\n ) {\n return null;\n }\n return normalized;\n}\n\n/**\n * Resolve merchant payTo with minimal host config:\n * 1. `PAY_TO` env (optional override)\n * 2. Live address from Forge public API (when reachable)\n * 3. Baked-in fallback from the Forge PR\n */\nexport async function resolvePayTo(opts: {\n /** Baked-in address from Forge codegen (required fallback). */\n fallback: string;\n /** Optional explicit override (usually process.env.PAY_TO). */\n payTo?: string;\n forge?: ForgePayToSource;\n /** Fetch timeout ms. Defaults to 2500. */\n timeoutMs?: number;\n}): Promise<string> {\n const envOverride = process.env.PAY_TO?.trim();\n if (envOverride && !isZeroAddress(envOverride)) {\n return envOverride;\n }\n\n const explicit = opts.payTo?.trim();\n if (explicit && !isZeroAddress(explicit) && !opts.forge) {\n return explicit;\n }\n\n const baseUrl = pickForgeBaseUrl(opts.forge);\n if (baseUrl && opts.forge) {\n const url = `${baseUrl}/api/public/pay-to/${encodeURIComponent(opts.forge.owner)}/${encodeURIComponent(opts.forge.repo)}`;\n try {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n opts.timeoutMs ?? 2500,\n );\n const res = await fetch(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n clearTimeout(timer);\n if (res.ok) {\n const json = (await res.json()) as { address?: string };\n if (json.address && !isZeroAddress(json.address)) {\n return json.address.trim();\n }\n }\n } catch (err) {\n console.warn(\"[forge] live payTo fetch failed, using fallback:\", err);\n }\n }\n\n if (explicit && !isZeroAddress(explicit)) return explicit;\n if (opts.fallback && !isZeroAddress(opts.fallback)) return opts.fallback;\n\n throw new Error(\n \"resolvePayTo: no usable address (set Forge wallet / PAY_TO, or re-run Forge PR)\",\n );\n}\n","/**\n * Merchant-side Forge surface status — public probes for deploy / go-live checks.\n */\n\nexport type ForgeHeartbeatState = {\n attempted: boolean;\n ok: boolean | null;\n at: string | null;\n error: string | null;\n};\n\nexport type ForgeSurfaceStatus = {\n ok: boolean;\n forge: true;\n version: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n /** True when FORGE_API_KEY is set so /forge/fulfill is mounted. */\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n /** Env + fulfill ready — merchant can accept gateway fulfillment. */\n ready: boolean;\n heartbeat: ForgeHeartbeatState;\n endpoints: {\n health: string;\n status: string;\n wellKnown: string;\n fulfill: string;\n agent: string;\n };\n};\n\nconst PACKAGE_VERSION = \"0.1.7\";\n\nlet lastHeartbeat: ForgeHeartbeatState = {\n attempted: false,\n ok: null,\n at: null,\n error: null,\n};\n\nexport function recordHeartbeatResult(\n result: { ok: true } | { ok: false; error: string },\n): void {\n lastHeartbeat = {\n attempted: true,\n ok: result.ok,\n at: new Date().toISOString(),\n error: result.ok ? null : result.error,\n };\n}\n\nexport function getLastHeartbeat(): ForgeHeartbeatState {\n return { ...lastHeartbeat };\n}\n\nexport function buildForgeSurfaceStatus(opts: {\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n}): ForgeSurfaceStatus {\n const fulfillPath = opts.fulfillPath.replace(/\\/$/, \"\") || \"/forge/fulfill\";\n const agentBasePath = opts.agentBasePath.replace(/\\/$/, \"\") || \"/agent\";\n const ready =\n opts.fulfillMounted &&\n Boolean(opts.publicBaseUrl) &&\n opts.actions.length > 0;\n\n return {\n ok: true,\n forge: true,\n version: PACKAGE_VERSION,\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath,\n agentBasePath,\n skipPayment: opts.skipPayment,\n actions: opts.actions,\n ready,\n heartbeat: getLastHeartbeat(),\n endpoints: {\n health: \"/forge/health\",\n status: \"/forge/status\",\n wellKnown: \"/.well-known/clawcash.json\",\n fulfill: fulfillPath,\n agent: agentBasePath,\n },\n };\n}\n\nexport function buildWellKnownDocument(status: ForgeSurfaceStatus): {\n forge: true;\n version: string;\n health: string;\n status: string;\n handle: string | null;\n ready: boolean;\n} {\n return {\n forge: true,\n version: status.version,\n health: status.endpoints.health,\n status: status.endpoints.status,\n handle: status.handle,\n ready: status.ready,\n };\n}\n\nexport function forgeSdkVersion(): string {\n return PACKAGE_VERSION;\n}\n","import type { DefinedAgentService, SkillMeta } from \"./types.js\";\n\n/**\n * Generate a SKILL.md document for agents from defined Forge services.\n */\nexport function generateSkillMarkdown(\n services: DefinedAgentService[],\n meta: SkillMeta,\n): string {\n const base = meta.baseUrl.replace(/\\/$/, \"\");\n const lines: string[] = [\n `---`,\n `name: ${meta.name}`,\n `description: ${meta.description}`,\n `---`,\n ``,\n `# ${meta.name}`,\n ``,\n meta.description,\n ``,\n ];\n\n if (meta.homepage) {\n lines.push(`Homepage: ${meta.homepage}`, ``);\n }\n\n lines.push(\n `## How to use`,\n ``,\n `1. Read this skill.`,\n `2. Call the agent endpoint with a JSON body matching the input schema.`,\n `3. If you receive HTTP 402, pay via x402 (USDC) and retry with the payment header.`,\n `4. Use the returned output fields.`,\n ``,\n `## Services`,\n ``,\n );\n\n for (const service of services) {\n const path = `${base}/agent/${service.path}`;\n const price = service.payment.amount.startsWith(\"$\")\n ? service.payment.amount\n : `$${service.payment.amount}`;\n\n lines.push(\n `### \\`${service.name}\\``,\n ``,\n service.description,\n ``,\n `- **Method:** \\`POST\\``,\n `- **URL:** \\`${path}\\``,\n `- **Price:** ${price} ${service.payment.currency} via ${service.payment.protocols.join(\", \")}`,\n ``,\n `**Input**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Output**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.output).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Example**`,\n ``,\n \"```bash\",\n `curl -X POST ${path} \\\\`,\n ` -H \"Content-Type: application/json\" \\\\`,\n ` -d '${JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [\n k,\n t === \"url\" ? \"https://example.com/image.png\" : `example-${k}`,\n ]),\n ),\n )}'`,\n \"```\",\n ``,\n );\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,eAAsB,UAAa,SAA0C;AAC3E,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,UAAU,KAAK,IAAI;AAEzB,aAAS;AACP,UAAM,QAAQ,MAAM,QAAQ,IAAI;AAChC,QAAI,QAAQ,cAAc,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AACA,QAAI,KAAK,IAAI,IAAI,WAAW,WAAW;AACrC,YAAM,IAAI,MAAM,6BAA6B,SAAS,IAAI;AAAA,IAC5D;AACA,UAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,UAAU,CAAC;AAAA,EAChE;AACF;AAEO,SAAS,gBAAqC;AACnD,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAGO,SAAS,YAAY,MAAsB;AAChD,SAAO,KACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,MAAM,GAAG,EACjB,YAAY;AACjB;AAEO,SAAS,mBAId,QACsC;AACtC,MAAI,CAAC,OAAO,MAAM,KAAK,GAAG;AACxB,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACA,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AAAA,IACT,MAAM,YAAY,OAAO,IAAI;AAAA,EAC/B;AACF;;;ACvDA,qBAAuC;AACvC,IAAAA,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CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;AAAA,QAC9D;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,gBAAgB,IAAI;AAAA,MACpB;AAAA,MACA,SAAS,KAAK;AAAA,QACZ,OAAO;AAAA,UACL,OAAO,QAAQ,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAAA,YAC5C;AAAA,YACA,MAAM,QAAQ,kCAAkC,WAAW,CAAC;AAAA,UAC9D,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["import_express","import_server","createRouter"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/define.ts","../src/mount.ts","../src/base-url.ts","../src/gateway.ts","../src/gateway-auth.ts","../src/payto.ts","../src/status.ts","../src/skill.ts"],"sourcesContent":["export { defineAgentService, waitUntil, createContext, toKebabCase } from \"./define.js\";\nexport { mountAgentServices, createForgeRouter } from \"./mount.js\";\nexport { generateSkillMarkdown } from \"./skill.js\";\nexport { resolvePayTo, isZeroAddress } from \"./payto.js\";\nexport { resolveBaseUrlFromEnv, PublicBaseUrlResolver } from \"./base-url.js\";\nexport { heartbeatGateway } from \"./gateway.js\";\nexport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n forgeSdkVersion,\n getLastHeartbeat,\n recordHeartbeatResult,\n} from \"./status.js\";\nexport type { ForgeHeartbeatState, ForgeSurfaceStatus } from \"./status.js\";\nexport {\n isForgeGatewayRequest,\n requireForgeGateway,\n getForgeApiKey,\n getForgeGatewaySecret,\n forgeGatewayLoopbackHeaders,\n FORGE_GATEWAY_USER_ID,\n} from \"./gateway-auth.js\";\nexport type {\n SchemaFieldType,\n InputSchema,\n OutputSchema,\n PaymentConfig,\n WaitUntilOptions,\n AgentServiceContext,\n AgentServiceConfig,\n DefinedAgentService,\n MountOptions,\n ForgePayToSource,\n SkillMeta,\n} from \"./types.js\";\n","import type {\n AgentServiceConfig,\n AgentServiceContext,\n DefinedAgentService,\n WaitUntilOptions,\n} from \"./types.js\";\n\nexport async function waitUntil<T>(options: WaitUntilOptions<T>): Promise<T> {\n const intervalMs = options.intervalMs ?? 500;\n const timeoutMs = options.timeoutMs ?? 60_000;\n const started = Date.now();\n\n for (;;) {\n const value = await options.run();\n if (options.completedWhen(value)) {\n return value;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`waitUntil timed out after ${timeoutMs}ms`);\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n}\n\nexport function createContext(): AgentServiceContext {\n return {\n waitUntil,\n };\n}\n\n/** Convert snake_case or camelCase service name to kebab-case path segment. */\nexport function toKebabCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n}\n\nexport function defineAgentService<\n TInput extends Record<string, unknown> = Record<string, unknown>,\n TOutput extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: AgentServiceConfig<TInput, TOutput>,\n): DefinedAgentService<TInput, TOutput> {\n if (!config.name?.trim()) {\n throw new Error(\"defineAgentService: name is required\");\n }\n if (!config.execute) {\n throw new Error(\"defineAgentService: execute is required\");\n }\n\n return {\n ...config,\n __forge: true,\n path: toKebabCase(config.name),\n };\n}\n","import type { Application, Request, Response, NextFunction, Router } from \"express\";\nimport { Router as createRouter } from \"express\";\nimport { paymentMiddleware, x402ResourceServer } from \"@x402/express\";\nimport type { Network } from \"@x402/express\";\nimport { HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport {\n PublicBaseUrlResolver,\n resolveBaseUrlFromEnv,\n} from \"./base-url.js\";\nimport { createContext } from \"./define.js\";\nimport { heartbeatGateway } from \"./gateway.js\";\nimport {\n getForgeApiKey,\n requireForgeGateway,\n} from \"./gateway-auth.js\";\nimport { isZeroAddress, resolvePayTo } from \"./payto.js\";\nimport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n recordHeartbeatResult,\n} from \"./status.js\";\nimport type {\n DefinedAgentService,\n InputSchema,\n MountOptions,\n SchemaFieldType,\n} from \"./types.js\";\n\n/** Base mainnet — settled via the public XPay facilitator (no API keys). */\nconst DEFAULT_NETWORK = \"eip155:8453\" as const satisfies Network;\n/** Open facilitator: Base mainnet + Sepolia, no API keys. https://github.com/xpaysh/xpay-x402 */\nconst DEFAULT_FACILITATOR_URL = \"https://facilitator.xpay.sh\";\n/** ClawCash gateway — override with GATEWAY_URL or options.gateway.url. */\nconst DEFAULT_GATEWAY_URL = \"https://gateway.clawca.sh\";\n\nfunction asNetwork(value: string | undefined): Network {\n return (value ?? DEFAULT_NETWORK) as Network;\n}\n\nfunction createFacilitatorClient(options: MountOptions): HTTPFacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,\n createAuthHeaders: options.createAuthHeaders,\n });\n}\n\nfunction validateInput(\n body: unknown,\n schema: InputSchema,\n): { ok: true; value: Record<string, unknown> } | { ok: false; error: string } {\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n return { ok: false, error: \"Request body must be a JSON object\" };\n }\n\n const input = body as Record<string, unknown>;\n const value: Record<string, unknown> = {};\n\n for (const [key, type] of Object.entries(schema)) {\n if (!(key in input) || input[key] === undefined || input[key] === null) {\n return { ok: false, error: `Missing required field: ${key}` };\n }\n const err = checkType(key, input[key], type);\n if (err) return { ok: false, error: err };\n value[key] = input[key];\n }\n\n return { ok: true, value };\n}\n\nfunction checkType(key: string, value: unknown, type: SchemaFieldType): string | null {\n switch (type) {\n case \"string\":\n case \"url\":\n if (typeof value !== \"string\" || !value.trim()) {\n return `Field ${key} must be a non-empty string`;\n }\n if (type === \"url\") {\n try {\n new URL(value);\n } catch {\n return `Field ${key} must be a valid URL`;\n }\n }\n return null;\n case \"number\":\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return `Field ${key} must be a number`;\n }\n return null;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n return `Field ${key} must be a boolean`;\n }\n return null;\n default:\n return null;\n }\n}\n\nfunction formatPrice(amount: string): string {\n const normalized = amount.startsWith(\"$\") ? amount.slice(1) : amount;\n return `$${normalized}`;\n}\n\nfunction mountFulfillmentRouter(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): void {\n const secret = getForgeApiKey(options.gateway?.registerSecret);\n if (!secret) {\n console.warn(\n \"[forge] /forge/fulfill not mounted — set FORGE_API_KEY (from Forge dashboard, min 16 chars) so the gateway can fulfill after payment\",\n );\n return;\n }\n\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n const gate = requireForgeGateway(secret);\n\n for (const service of services) {\n router.post(\n `/${service.path}`,\n gate,\n async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] fulfill ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n },\n );\n }\n\n app.use(fulfillPath, router);\n console.log(\n `[forge] fulfillment mounted at POST ${fulfillPath}/{action} (gateway secret)`,\n );\n}\n\nfunction mountForgeStatusRoutes(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n opts: {\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n handle: string | null;\n resolver: PublicBaseUrlResolver;\n gatewayUrl: string | null;\n },\n): void {\n const getStatus = () =>\n buildForgeSurfaceStatus({\n handle: opts.handle,\n publicBaseUrl: opts.resolver.get(),\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath: opts.fulfillPath,\n agentBasePath: opts.agentBasePath,\n skipPayment: Boolean(options.skipPayment),\n actions: services.map((s) => ({\n name: s.name,\n path: s.path,\n price: s.payment.amount,\n })),\n });\n\n app.get(\"/forge/health\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n const status = getStatus();\n res.json({\n ok: true,\n forge: true as const,\n ready: status.ready,\n handle: status.handle,\n version: status.version,\n // Per-boot nonce so this instance can self-verify an inferred base URL.\n instance: opts.resolver.instanceNonce,\n actions: status.actions.map((a) => a.name),\n });\n });\n\n app.get(\"/forge/status\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n const status = getStatus();\n res.status(status.ready ? 200 : 503).json(status);\n });\n\n app.get(\"/.well-known/clawcash.json\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n res.json(buildWellKnownDocument(getStatus()));\n });\n\n console.log(\n \"[forge] liveliness: GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json\",\n );\n}\n\n/**\n * Mount Forge agent services on an Express app.\n * - GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json — liveliness\n * - POST {basePath}/{kebab-name} — optional public x402 agent surface\n * - POST /forge/fulfill/{kebab-name} — private gateway fulfillment after payment\n *\n * payTo resolves automatically: PAY_TO env (optional) → Forge API → baked fallback.\n */\nexport async function mountAgentServices(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): Promise<Router> {\n let payTo = \"\";\n if (!options.skipPayment) {\n const fallback =\n options.payToFallback?.trim() || options.payTo?.trim() || \"\";\n payTo = await resolvePayTo({\n fallback,\n payTo: options.payTo,\n forge: options.forge,\n });\n if (isZeroAddress(payTo)) {\n throw new Error(\n \"mountAgentServices: resolved payTo is the zero address. Re-run Forge to provision a wallet.\",\n );\n }\n }\n\n const basePath = (options.basePath ?? \"/agent\").replace(/\\/$/, \"\") || \"/agent\";\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n\n const routes: RoutesConfig = {};\n\n for (const service of services) {\n const routePath = `/${service.path}`;\n const fullPath = `${basePath}${routePath}`;\n const network = asNetwork(service.payment.network);\n\n if (!options.skipPayment) {\n routes[`POST ${fullPath}`] = {\n accepts: {\n scheme: \"exact\",\n price: formatPrice(service.payment.amount),\n network,\n payTo,\n },\n description: service.description,\n mimeType: \"application/json\",\n };\n }\n\n router.post(routePath, async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n });\n }\n\n if (!options.skipPayment && Object.keys(routes).length > 0) {\n const facilitator = createFacilitatorClient(options);\n const networks = new Set(\n services.map((s) => asNetwork(s.payment.network)),\n );\n const resourceServer = new x402ResourceServer(facilitator);\n for (const network of networks) {\n resourceServer.register(network, new ExactEvmScheme());\n }\n app.use(paymentMiddleware(routes, resourceServer, undefined, undefined, true));\n }\n\n app.use(basePath, router);\n const fulfillMounted = Boolean(\n getForgeApiKey(options.gateway?.registerSecret),\n );\n mountFulfillmentRouter(app, services, options);\n\n const gatewayUrl =\n options.gateway?.url?.trim() ||\n process.env.GATEWAY_URL?.trim() ||\n DEFAULT_GATEWAY_URL;\n const handle =\n options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;\n const registerSecret =\n options.gateway?.registerSecret?.trim() ||\n process.env.FORGE_API_KEY?.trim() ||\n process.env.GATEWAY_REGISTER_SECRET?.trim();\n\n const sendHeartbeat = (baseUrl: string) => {\n if (!handle || !registerSecret) return;\n void heartbeatGateway({\n gatewayUrl,\n handle,\n baseUrl,\n registerSecret,\n })\n .then(() => {\n recordHeartbeatResult({ ok: true });\n })\n .catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n recordHeartbeatResult({ ok: false, error: message });\n console.warn(\"[forge] gateway heartbeat skipped:\", err);\n });\n };\n\n const resolver = new PublicBaseUrlResolver({\n initial: resolveBaseUrlFromEnv(options.gateway?.publicBaseUrl),\n // Base URL learned late (inferred from the first probe): heartbeat now.\n onResolved: sendHeartbeat,\n });\n\n mountForgeStatusRoutes(app, services, options, {\n fulfillMounted,\n fulfillPath,\n agentBasePath: basePath,\n handle,\n resolver,\n gatewayUrl,\n });\n\n const bootBaseUrl = resolver.get();\n if (bootBaseUrl) {\n sendHeartbeat(bootBaseUrl);\n }\n\n return router;\n}\n\nexport function createForgeRouter(\n services: DefinedAgentService[],\n options: MountOptions,\n): (app: Application) => Promise<Router> {\n return (app) => mountAgentServices(app, services, options);\n}\n\nexport function forgeErrorHandler(\n err: unknown,\n _req: Request,\n res: Response,\n _next: NextFunction,\n): void {\n const message = err instanceof Error ? err.message : \"Internal error\";\n res.status(500).json({ error: message });\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { Request } from \"express\";\n\n/**\n * Public base URL resolution, in trust order:\n * 1. PUBLIC_BASE_URL env — explicit override.\n * 2. Platform-provided vars (Railway, Render, Vercel, Fly, Heroku) — set by\n * the host, not by request input, so safe to trust as-is.\n * 3. Lazy inference from the first inbound request to the Forge surface\n * (X-Forwarded-Proto + Host). Host is attacker-controlled, so a candidate\n * is only accepted after self-verification: we fetch our own\n * /forge/health at the candidate URL and check it returns this\n * instance's boot nonce.\n */\n\nexport function resolveBaseUrlFromEnv(explicit?: string): string | null {\n const fromExplicit = explicit?.trim();\n if (fromExplicit) return stripSlash(fromExplicit);\n\n const fromEnv = process.env.PUBLIC_BASE_URL?.trim();\n if (fromEnv) return stripSlash(fromEnv);\n\n const railway = process.env.RAILWAY_PUBLIC_DOMAIN?.trim();\n if (railway) return `https://${stripSlash(railway)}`;\n\n const render = process.env.RENDER_EXTERNAL_URL?.trim();\n if (render) return stripSlash(render);\n\n const vercel =\n process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() ||\n process.env.VERCEL_URL?.trim();\n if (vercel) return `https://${stripSlash(vercel)}`;\n\n const fly = process.env.FLY_APP_NAME?.trim();\n if (fly) return `https://${fly}.fly.dev`;\n\n const heroku = process.env.HEROKU_APP_NAME?.trim();\n if (heroku) return `https://${heroku}.herokuapp.com`;\n\n return null;\n}\n\nfunction stripSlash(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nconst MAX_VERIFY_ATTEMPTS = 5;\nconst VERIFY_TIMEOUT_MS = 3000;\n\nexport class PublicBaseUrlResolver {\n /** Per-boot nonce, echoed by /forge/health for self-verification. */\n readonly instanceNonce: string;\n\n private resolved: string | null;\n private verifying = false;\n private rejected = new Set<string>();\n private attempts = 0;\n private onResolved: ((baseUrl: string) => void) | null;\n\n constructor(opts: {\n /** URL already known from env/platform vars (trusted, no verification). */\n initial: string | null;\n /** Called once when a base URL first becomes known via inference. */\n onResolved?: (baseUrl: string) => void;\n }) {\n this.instanceNonce = randomBytes(16).toString(\"hex\");\n this.resolved = opts.initial;\n this.onResolved = opts.onResolved ?? null;\n }\n\n get(): string | null {\n return this.resolved;\n }\n\n /**\n * Feed an inbound Forge-surface request. No-op once resolved. Kicks off\n * async self-verification of the candidate URL derived from the request.\n */\n considerRequest(req: Request): void {\n if (this.resolved || this.verifying) return;\n if (this.attempts >= MAX_VERIFY_ATTEMPTS) return;\n\n const candidate = candidateFromRequest(req);\n if (!candidate || this.rejected.has(candidate)) return;\n\n this.verifying = true;\n this.attempts += 1;\n void this.verify(candidate)\n .then((ok) => {\n if (ok) {\n this.resolved = candidate;\n console.log(`[forge] public base URL inferred and verified: ${candidate}`);\n this.onResolved?.(candidate);\n } else {\n this.rejected.add(candidate);\n console.warn(\n `[forge] candidate base URL failed self-verification, ignoring: ${candidate}`,\n );\n }\n })\n .finally(() => {\n this.verifying = false;\n });\n }\n\n /** Fetch our own /forge/health at the candidate and match the boot nonce. */\n private async verify(candidate: string): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);\n const res = await fetch(`${candidate}/forge/health`, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n redirect: \"manual\",\n });\n clearTimeout(timer);\n if (!res.ok) return false;\n const json = (await res.json()) as { instance?: string };\n return json.instance === this.instanceNonce;\n } catch {\n return false;\n }\n }\n}\n\nfunction candidateFromRequest(req: Request): string | null {\n const host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) ?? req.headers.host;\n if (!host || !isValidHost(host)) return null;\n\n const proto =\n firstHeaderValue(req.headers[\"x-forwarded-proto\"]) ??\n (req.protocol || \"http\");\n if (proto !== \"https\" && proto !== \"http\") return null;\n\n const isLocal = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/i.test(host);\n // A deployed merchant is always behind HTTPS; only allow http locally.\n if (proto === \"http\" && !isLocal) return null;\n\n return `${proto}://${host}`;\n}\n\nfunction firstHeaderValue(value: string | string[] | undefined): string | null {\n const raw = Array.isArray(value) ? value[0] : value;\n const first = raw?.split(\",\")[0]?.trim();\n return first || null;\n}\n\nfunction isValidHost(host: string): boolean {\n // hostname with optional port; rejects paths, spaces, credentials\n return /^[a-z0-9.-]+(:\\d{1,5})?$/i.test(host) || /^\\[[0-9a-f:]+\\](:\\d{1,5})?$/i.test(host);\n}\n","/**\n * Notify ClawCash gateway of this merchant's live public base URL.\n * Full action registration still happens from Forge \"Go live\".\n */\nexport async function heartbeatGateway(opts: {\n gatewayUrl: string;\n handle: string;\n baseUrl: string;\n registerSecret: string;\n}): Promise<void> {\n const gateway = opts.gatewayUrl.replace(/\\/$/, \"\");\n const res = await fetch(`${gateway}/register/heartbeat`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${opts.registerSecret}`,\n },\n body: JSON.stringify({\n handle: opts.handle.trim().toLowerCase(),\n baseUrl: opts.baseUrl.replace(/\\/$/, \"\"),\n }),\n });\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `gateway heartbeat failed (${res.status}): ${text.slice(0, 240)}`,\n );\n }\n}\n","import type { NextFunction, Request, Response } from \"express\";\n\n/**\n * Per-project Forge API key for gateway → merchant fulfillment.\n * Merchants set FORGE_API_KEY from the Forge dashboard (never the shared\n * GATEWAY_REGISTER_SECRET — that is Forge↔gateway platform auth only).\n *\n * GATEWAY_REGISTER_SECRET is accepted as a deprecated fallback for older deploys.\n */\nexport function getForgeApiKey(explicit?: string | null): string | null {\n const value =\n (explicit ?? process.env.FORGE_API_KEY ?? process.env.GATEWAY_REGISTER_SECRET)?.trim();\n if (!value || value.length < 16) return null;\n return value;\n}\n\n/** @deprecated Use getForgeApiKey */\nexport function getForgeGatewaySecret(\n explicit?: string | null,\n): string | null {\n return getForgeApiKey(explicit);\n}\n\nexport function isForgeGatewayRequest(\n req: Request,\n secret?: string | null,\n): boolean {\n const expected = getForgeApiKey(secret);\n if (!expected) return false;\n const header = req.header(\"authorization\") ?? \"\";\n const bearer = header.toLowerCase().startsWith(\"bearer \")\n ? header.slice(7).trim()\n : \"\";\n const alt =\n req.header(\"x-forge-api-key\")?.trim() ||\n req.header(\"x-clawcash-gateway\")?.trim() ||\n \"\";\n return bearer === expected || alt === expected;\n}\n\n/** Synthetic user id for DB rows created by gateway-driven fulfillment. */\nexport const FORGE_GATEWAY_USER_ID = \"forge_gateway_agent\";\n\nexport function requireForgeGateway(\n secret?: string | null,\n): (req: Request, res: Response, next: NextFunction) => void {\n return (req, res, next) => {\n if (!isForgeGatewayRequest(req, secret)) {\n res.status(401).json({\n error:\n \"Unauthorized — Forge API key required (FORGE_API_KEY from Forge dashboard)\",\n });\n return;\n }\n next();\n };\n}\n\n/** Headers merchant execute() should send on loopback calls during fulfillment. */\nexport function forgeGatewayLoopbackHeaders(\n secret?: string | null,\n): Record<string, string> {\n const expected = getForgeApiKey(secret);\n if (!expected) return {};\n return {\n Authorization: `Bearer ${expected}`,\n \"X-Forge-Api-Key\": expected,\n };\n}\n","import type { ForgePayToSource } from \"./types.js\";\n\nexport type { ForgePayToSource };\n\nconst ZERO = /^0x0{40}$/i;\n\nexport function isZeroAddress(address: string | undefined | null): boolean {\n if (!address) return true;\n return ZERO.test(address.trim());\n}\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nfunction pickForgeBaseUrl(source?: ForgePayToSource): string | null {\n const fromEnv = process.env.FORGE_URL?.trim();\n if (fromEnv) return normalizeBaseUrl(fromEnv);\n\n const fromOpts = source?.baseUrl?.trim();\n if (!fromOpts) return null;\n\n const normalized = normalizeBaseUrl(fromOpts);\n // Never call a laptop Forge from a deployed merchant app.\n if (\n /localhost|127\\.0\\.0\\.1/i.test(normalized) &&\n process.env.NODE_ENV === \"production\"\n ) {\n return null;\n }\n return normalized;\n}\n\n/**\n * Resolve merchant payTo with minimal host config:\n * 1. `PAY_TO` env (optional override)\n * 2. Live address from Forge public API (when reachable)\n * 3. Baked-in fallback from the Forge PR\n */\nexport async function resolvePayTo(opts: {\n /** Baked-in address from Forge codegen (required fallback). */\n fallback: string;\n /** Optional explicit override (usually process.env.PAY_TO). */\n payTo?: string;\n forge?: ForgePayToSource;\n /** Fetch timeout ms. Defaults to 2500. */\n timeoutMs?: number;\n}): Promise<string> {\n const envOverride = process.env.PAY_TO?.trim();\n if (envOverride && !isZeroAddress(envOverride)) {\n return envOverride;\n }\n\n const explicit = opts.payTo?.trim();\n if (explicit && !isZeroAddress(explicit) && !opts.forge) {\n return explicit;\n }\n\n const baseUrl = pickForgeBaseUrl(opts.forge);\n if (baseUrl && opts.forge) {\n const url = `${baseUrl}/api/public/pay-to/${encodeURIComponent(opts.forge.owner)}/${encodeURIComponent(opts.forge.repo)}`;\n try {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n opts.timeoutMs ?? 2500,\n );\n const res = await fetch(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n clearTimeout(timer);\n if (res.ok) {\n const json = (await res.json()) as { address?: string };\n if (json.address && !isZeroAddress(json.address)) {\n return json.address.trim();\n }\n }\n } catch (err) {\n console.warn(\"[forge] live payTo fetch failed, using fallback:\", err);\n }\n }\n\n if (explicit && !isZeroAddress(explicit)) return explicit;\n if (opts.fallback && !isZeroAddress(opts.fallback)) return opts.fallback;\n\n throw new Error(\n \"resolvePayTo: no usable address (set Forge wallet / PAY_TO, or re-run Forge PR)\",\n );\n}\n","/**\n * Merchant-side Forge surface status — public probes for deploy / go-live checks.\n */\n\nexport type ForgeHeartbeatState = {\n attempted: boolean;\n ok: boolean | null;\n at: string | null;\n error: string | null;\n};\n\nexport type ForgeSurfaceStatus = {\n ok: boolean;\n forge: true;\n version: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n /** True when FORGE_API_KEY is set so /forge/fulfill is mounted. */\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n /** Env + fulfill ready — merchant can accept gateway fulfillment. */\n ready: boolean;\n heartbeat: ForgeHeartbeatState;\n endpoints: {\n health: string;\n status: string;\n wellKnown: string;\n fulfill: string;\n agent: string;\n };\n};\n\nconst PACKAGE_VERSION = \"0.1.8\";\n\nlet lastHeartbeat: ForgeHeartbeatState = {\n attempted: false,\n ok: null,\n at: null,\n error: null,\n};\n\nexport function recordHeartbeatResult(\n result: { ok: true } | { ok: false; error: string },\n): void {\n lastHeartbeat = {\n attempted: true,\n ok: result.ok,\n at: new Date().toISOString(),\n error: result.ok ? null : result.error,\n };\n}\n\nexport function getLastHeartbeat(): ForgeHeartbeatState {\n return { ...lastHeartbeat };\n}\n\nexport function buildForgeSurfaceStatus(opts: {\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n}): ForgeSurfaceStatus {\n const fulfillPath = opts.fulfillPath.replace(/\\/$/, \"\") || \"/forge/fulfill\";\n const agentBasePath = opts.agentBasePath.replace(/\\/$/, \"\") || \"/agent\";\n const ready =\n opts.fulfillMounted &&\n Boolean(opts.publicBaseUrl) &&\n opts.actions.length > 0;\n\n return {\n ok: true,\n forge: true,\n version: PACKAGE_VERSION,\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath,\n agentBasePath,\n skipPayment: opts.skipPayment,\n actions: opts.actions,\n ready,\n heartbeat: getLastHeartbeat(),\n endpoints: {\n health: \"/forge/health\",\n status: \"/forge/status\",\n wellKnown: \"/.well-known/clawcash.json\",\n fulfill: fulfillPath,\n agent: agentBasePath,\n },\n };\n}\n\nexport function buildWellKnownDocument(status: ForgeSurfaceStatus): {\n forge: true;\n version: string;\n health: string;\n status: string;\n handle: string | null;\n ready: boolean;\n} {\n return {\n forge: true,\n version: status.version,\n health: status.endpoints.health,\n status: status.endpoints.status,\n handle: status.handle,\n ready: status.ready,\n };\n}\n\nexport function forgeSdkVersion(): string {\n return PACKAGE_VERSION;\n}\n","import type { DefinedAgentService, SkillMeta } from \"./types.js\";\n\n/**\n * Generate a SKILL.md document for agents from defined Forge services.\n */\nexport function generateSkillMarkdown(\n services: DefinedAgentService[],\n meta: SkillMeta,\n): string {\n const base = meta.baseUrl.replace(/\\/$/, \"\");\n const lines: string[] = [\n `---`,\n `name: ${meta.name}`,\n `description: ${meta.description}`,\n `---`,\n ``,\n `# ${meta.name}`,\n ``,\n meta.description,\n ``,\n ];\n\n if (meta.homepage) {\n lines.push(`Homepage: ${meta.homepage}`, ``);\n }\n\n lines.push(\n `## How to use`,\n ``,\n `1. Read this skill.`,\n `2. Call the agent endpoint with a JSON body matching the input schema.`,\n `3. If you receive HTTP 402, pay via x402 (USDC) and retry with the payment header.`,\n `4. Use the returned output fields.`,\n ``,\n `## Services`,\n ``,\n );\n\n for (const service of services) {\n const path = `${base}/agent/${service.path}`;\n const price = service.payment.amount.startsWith(\"$\")\n ? service.payment.amount\n : `$${service.payment.amount}`;\n\n lines.push(\n `### \\`${service.name}\\``,\n ``,\n service.description,\n ``,\n `- **Method:** \\`POST\\``,\n `- **URL:** \\`${path}\\``,\n `- **Price:** ${price} ${service.payment.currency} via ${service.payment.protocols.join(\", \")}`,\n ``,\n `**Input**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Output**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.output).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Example**`,\n ``,\n \"```bash\",\n `curl -X POST ${path} \\\\`,\n ` -H \"Content-Type: application/json\" \\\\`,\n ` -d '${JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [\n k,\n t === \"url\" ? \"https://example.com/image.png\" : `example-${k}`,\n ]),\n ),\n )}'`,\n \"```\",\n ``,\n );\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACOA,eAAsB,UAAa,SAA0C;AAC3E,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,UAAU,KAAK,IAAI;AAEzB,aAAS;AACP,UAAM,QAAQ,MAAM,QAAQ,IAAI;AAChC,QAAI,QAAQ,cAAc,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AACA,QAAI,KAAK,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,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;AAAA,QAC9D;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,gBAAgB,IAAI;AAAA,MACpB;AAAA,MACA,SAAS,KAAK;AAAA,QACZ,OAAO;AAAA,UACL,OAAO,QAAQ,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAAA,YAC5C;AAAA,YACA,MAAM,QAAQ,kCAAkC,WAAW,CAAC;AAAA,UAC9D,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":["import_express","import_server","createRouter"]}
|
package/dist/index.d.cts
CHANGED
|
@@ -72,15 +72,19 @@ interface MountOptions {
|
|
|
72
72
|
/** Skip x402 (local dev only). Defaults to false. */
|
|
73
73
|
skipPayment?: boolean;
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
75
|
+
* Gateway heartbeat after mount. Only FORGE_API_KEY is required as env;
|
|
76
|
+
* the URL defaults to the ClawCash gateway, the handle is baked by Forge
|
|
77
|
+
* codegen, and the public base URL is resolved from platform vars or
|
|
78
|
+
* inferred (self-verified) from the first inbound probe.
|
|
77
79
|
*/
|
|
78
80
|
gateway?: {
|
|
81
|
+
/** Defaults to https://gateway.clawca.sh (or GATEWAY_URL env). */
|
|
79
82
|
url?: string;
|
|
83
|
+
/** Merchant handle — baked by Forge codegen (or FORGE_HANDLE env). */
|
|
80
84
|
handle?: string;
|
|
81
85
|
/** @deprecated Prefer FORGE_API_KEY env — per-project key from Forge dashboard. */
|
|
82
86
|
registerSecret?: string;
|
|
83
|
-
/** Merchant public base URL
|
|
87
|
+
/** Merchant public base URL. Usually omitted — resolved automatically. */
|
|
84
88
|
publicBaseUrl?: string;
|
|
85
89
|
};
|
|
86
90
|
/**
|
|
@@ -135,6 +139,42 @@ declare function resolvePayTo(opts: {
|
|
|
135
139
|
timeoutMs?: number;
|
|
136
140
|
}): Promise<string>;
|
|
137
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Public base URL resolution, in trust order:
|
|
144
|
+
* 1. PUBLIC_BASE_URL env — explicit override.
|
|
145
|
+
* 2. Platform-provided vars (Railway, Render, Vercel, Fly, Heroku) — set by
|
|
146
|
+
* the host, not by request input, so safe to trust as-is.
|
|
147
|
+
* 3. Lazy inference from the first inbound request to the Forge surface
|
|
148
|
+
* (X-Forwarded-Proto + Host). Host is attacker-controlled, so a candidate
|
|
149
|
+
* is only accepted after self-verification: we fetch our own
|
|
150
|
+
* /forge/health at the candidate URL and check it returns this
|
|
151
|
+
* instance's boot nonce.
|
|
152
|
+
*/
|
|
153
|
+
declare function resolveBaseUrlFromEnv(explicit?: string): string | null;
|
|
154
|
+
declare class PublicBaseUrlResolver {
|
|
155
|
+
/** Per-boot nonce, echoed by /forge/health for self-verification. */
|
|
156
|
+
readonly instanceNonce: string;
|
|
157
|
+
private resolved;
|
|
158
|
+
private verifying;
|
|
159
|
+
private rejected;
|
|
160
|
+
private attempts;
|
|
161
|
+
private onResolved;
|
|
162
|
+
constructor(opts: {
|
|
163
|
+
/** URL already known from env/platform vars (trusted, no verification). */
|
|
164
|
+
initial: string | null;
|
|
165
|
+
/** Called once when a base URL first becomes known via inference. */
|
|
166
|
+
onResolved?: (baseUrl: string) => void;
|
|
167
|
+
});
|
|
168
|
+
get(): string | null;
|
|
169
|
+
/**
|
|
170
|
+
* Feed an inbound Forge-surface request. No-op once resolved. Kicks off
|
|
171
|
+
* async self-verification of the candidate URL derived from the request.
|
|
172
|
+
*/
|
|
173
|
+
considerRequest(req: Request): void;
|
|
174
|
+
/** Fetch our own /forge/health at the candidate and match the boot nonce. */
|
|
175
|
+
private verify;
|
|
176
|
+
}
|
|
177
|
+
|
|
138
178
|
/**
|
|
139
179
|
* Notify ClawCash gateway of this merchant's live public base URL.
|
|
140
180
|
* Full action registration still happens from Forge "Go live".
|
|
@@ -231,4 +271,4 @@ declare function requireForgeGateway(secret?: string | null): (req: Request, res
|
|
|
231
271
|
/** Headers merchant execute() should send on loopback calls during fulfillment. */
|
|
232
272
|
declare function forgeGatewayLoopbackHeaders(secret?: string | null): Record<string, string>;
|
|
233
273
|
|
|
234
|
-
export { type AgentServiceConfig, type AgentServiceContext, type DefinedAgentService, FORGE_GATEWAY_USER_ID, type ForgeHeartbeatState, type ForgePayToSource, type ForgeSurfaceStatus, type InputSchema, type MountOptions, type OutputSchema, type PaymentConfig, type SchemaFieldType, type SkillMeta, type WaitUntilOptions, buildForgeSurfaceStatus, buildWellKnownDocument, createContext, createForgeRouter, defineAgentService, forgeGatewayLoopbackHeaders, forgeSdkVersion, generateSkillMarkdown, getForgeApiKey, getForgeGatewaySecret, getLastHeartbeat, heartbeatGateway, isForgeGatewayRequest, isZeroAddress, mountAgentServices, recordHeartbeatResult, requireForgeGateway, resolvePayTo, toKebabCase, waitUntil };
|
|
274
|
+
export { type AgentServiceConfig, type AgentServiceContext, type DefinedAgentService, FORGE_GATEWAY_USER_ID, type ForgeHeartbeatState, type ForgePayToSource, type ForgeSurfaceStatus, type InputSchema, type MountOptions, type OutputSchema, type PaymentConfig, PublicBaseUrlResolver, type SchemaFieldType, type SkillMeta, type WaitUntilOptions, buildForgeSurfaceStatus, buildWellKnownDocument, createContext, createForgeRouter, defineAgentService, forgeGatewayLoopbackHeaders, forgeSdkVersion, generateSkillMarkdown, getForgeApiKey, getForgeGatewaySecret, getLastHeartbeat, heartbeatGateway, isForgeGatewayRequest, isZeroAddress, mountAgentServices, recordHeartbeatResult, requireForgeGateway, resolveBaseUrlFromEnv, resolvePayTo, toKebabCase, waitUntil };
|
package/dist/index.d.ts
CHANGED
|
@@ -72,15 +72,19 @@ interface MountOptions {
|
|
|
72
72
|
/** Skip x402 (local dev only). Defaults to false. */
|
|
73
73
|
skipPayment?: boolean;
|
|
74
74
|
/**
|
|
75
|
-
*
|
|
76
|
-
*
|
|
75
|
+
* Gateway heartbeat after mount. Only FORGE_API_KEY is required as env;
|
|
76
|
+
* the URL defaults to the ClawCash gateway, the handle is baked by Forge
|
|
77
|
+
* codegen, and the public base URL is resolved from platform vars or
|
|
78
|
+
* inferred (self-verified) from the first inbound probe.
|
|
77
79
|
*/
|
|
78
80
|
gateway?: {
|
|
81
|
+
/** Defaults to https://gateway.clawca.sh (or GATEWAY_URL env). */
|
|
79
82
|
url?: string;
|
|
83
|
+
/** Merchant handle — baked by Forge codegen (or FORGE_HANDLE env). */
|
|
80
84
|
handle?: string;
|
|
81
85
|
/** @deprecated Prefer FORGE_API_KEY env — per-project key from Forge dashboard. */
|
|
82
86
|
registerSecret?: string;
|
|
83
|
-
/** Merchant public base URL
|
|
87
|
+
/** Merchant public base URL. Usually omitted — resolved automatically. */
|
|
84
88
|
publicBaseUrl?: string;
|
|
85
89
|
};
|
|
86
90
|
/**
|
|
@@ -135,6 +139,42 @@ declare function resolvePayTo(opts: {
|
|
|
135
139
|
timeoutMs?: number;
|
|
136
140
|
}): Promise<string>;
|
|
137
141
|
|
|
142
|
+
/**
|
|
143
|
+
* Public base URL resolution, in trust order:
|
|
144
|
+
* 1. PUBLIC_BASE_URL env — explicit override.
|
|
145
|
+
* 2. Platform-provided vars (Railway, Render, Vercel, Fly, Heroku) — set by
|
|
146
|
+
* the host, not by request input, so safe to trust as-is.
|
|
147
|
+
* 3. Lazy inference from the first inbound request to the Forge surface
|
|
148
|
+
* (X-Forwarded-Proto + Host). Host is attacker-controlled, so a candidate
|
|
149
|
+
* is only accepted after self-verification: we fetch our own
|
|
150
|
+
* /forge/health at the candidate URL and check it returns this
|
|
151
|
+
* instance's boot nonce.
|
|
152
|
+
*/
|
|
153
|
+
declare function resolveBaseUrlFromEnv(explicit?: string): string | null;
|
|
154
|
+
declare class PublicBaseUrlResolver {
|
|
155
|
+
/** Per-boot nonce, echoed by /forge/health for self-verification. */
|
|
156
|
+
readonly instanceNonce: string;
|
|
157
|
+
private resolved;
|
|
158
|
+
private verifying;
|
|
159
|
+
private rejected;
|
|
160
|
+
private attempts;
|
|
161
|
+
private onResolved;
|
|
162
|
+
constructor(opts: {
|
|
163
|
+
/** URL already known from env/platform vars (trusted, no verification). */
|
|
164
|
+
initial: string | null;
|
|
165
|
+
/** Called once when a base URL first becomes known via inference. */
|
|
166
|
+
onResolved?: (baseUrl: string) => void;
|
|
167
|
+
});
|
|
168
|
+
get(): string | null;
|
|
169
|
+
/**
|
|
170
|
+
* Feed an inbound Forge-surface request. No-op once resolved. Kicks off
|
|
171
|
+
* async self-verification of the candidate URL derived from the request.
|
|
172
|
+
*/
|
|
173
|
+
considerRequest(req: Request): void;
|
|
174
|
+
/** Fetch our own /forge/health at the candidate and match the boot nonce. */
|
|
175
|
+
private verify;
|
|
176
|
+
}
|
|
177
|
+
|
|
138
178
|
/**
|
|
139
179
|
* Notify ClawCash gateway of this merchant's live public base URL.
|
|
140
180
|
* Full action registration still happens from Forge "Go live".
|
|
@@ -231,4 +271,4 @@ declare function requireForgeGateway(secret?: string | null): (req: Request, res
|
|
|
231
271
|
/** Headers merchant execute() should send on loopback calls during fulfillment. */
|
|
232
272
|
declare function forgeGatewayLoopbackHeaders(secret?: string | null): Record<string, string>;
|
|
233
273
|
|
|
234
|
-
export { type AgentServiceConfig, type AgentServiceContext, type DefinedAgentService, FORGE_GATEWAY_USER_ID, type ForgeHeartbeatState, type ForgePayToSource, type ForgeSurfaceStatus, type InputSchema, type MountOptions, type OutputSchema, type PaymentConfig, type SchemaFieldType, type SkillMeta, type WaitUntilOptions, buildForgeSurfaceStatus, buildWellKnownDocument, createContext, createForgeRouter, defineAgentService, forgeGatewayLoopbackHeaders, forgeSdkVersion, generateSkillMarkdown, getForgeApiKey, getForgeGatewaySecret, getLastHeartbeat, heartbeatGateway, isForgeGatewayRequest, isZeroAddress, mountAgentServices, recordHeartbeatResult, requireForgeGateway, resolvePayTo, toKebabCase, waitUntil };
|
|
274
|
+
export { type AgentServiceConfig, type AgentServiceContext, type DefinedAgentService, FORGE_GATEWAY_USER_ID, type ForgeHeartbeatState, type ForgePayToSource, type ForgeSurfaceStatus, type InputSchema, type MountOptions, type OutputSchema, type PaymentConfig, PublicBaseUrlResolver, type SchemaFieldType, type SkillMeta, type WaitUntilOptions, buildForgeSurfaceStatus, buildWellKnownDocument, createContext, createForgeRouter, defineAgentService, forgeGatewayLoopbackHeaders, forgeSdkVersion, generateSkillMarkdown, getForgeApiKey, getForgeGatewaySecret, getLastHeartbeat, heartbeatGateway, isForgeGatewayRequest, isZeroAddress, mountAgentServices, recordHeartbeatResult, requireForgeGateway, resolveBaseUrlFromEnv, resolvePayTo, toKebabCase, waitUntil };
|
package/dist/index.js
CHANGED
|
@@ -42,6 +42,109 @@ import { paymentMiddleware, x402ResourceServer } from "@x402/express";
|
|
|
42
42
|
import { HTTPFacilitatorClient } from "@x402/core/server";
|
|
43
43
|
import { ExactEvmScheme } from "@x402/evm/exact/server";
|
|
44
44
|
|
|
45
|
+
// src/base-url.ts
|
|
46
|
+
import { randomBytes } from "crypto";
|
|
47
|
+
function resolveBaseUrlFromEnv(explicit) {
|
|
48
|
+
const fromExplicit = explicit?.trim();
|
|
49
|
+
if (fromExplicit) return stripSlash(fromExplicit);
|
|
50
|
+
const fromEnv = process.env.PUBLIC_BASE_URL?.trim();
|
|
51
|
+
if (fromEnv) return stripSlash(fromEnv);
|
|
52
|
+
const railway = process.env.RAILWAY_PUBLIC_DOMAIN?.trim();
|
|
53
|
+
if (railway) return `https://${stripSlash(railway)}`;
|
|
54
|
+
const render = process.env.RENDER_EXTERNAL_URL?.trim();
|
|
55
|
+
if (render) return stripSlash(render);
|
|
56
|
+
const vercel = process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() || process.env.VERCEL_URL?.trim();
|
|
57
|
+
if (vercel) return `https://${stripSlash(vercel)}`;
|
|
58
|
+
const fly = process.env.FLY_APP_NAME?.trim();
|
|
59
|
+
if (fly) return `https://${fly}.fly.dev`;
|
|
60
|
+
const heroku = process.env.HEROKU_APP_NAME?.trim();
|
|
61
|
+
if (heroku) return `https://${heroku}.herokuapp.com`;
|
|
62
|
+
return null;
|
|
63
|
+
}
|
|
64
|
+
function stripSlash(url) {
|
|
65
|
+
return url.replace(/\/$/, "");
|
|
66
|
+
}
|
|
67
|
+
var MAX_VERIFY_ATTEMPTS = 5;
|
|
68
|
+
var VERIFY_TIMEOUT_MS = 3e3;
|
|
69
|
+
var PublicBaseUrlResolver = class {
|
|
70
|
+
/** Per-boot nonce, echoed by /forge/health for self-verification. */
|
|
71
|
+
instanceNonce;
|
|
72
|
+
resolved;
|
|
73
|
+
verifying = false;
|
|
74
|
+
rejected = /* @__PURE__ */ new Set();
|
|
75
|
+
attempts = 0;
|
|
76
|
+
onResolved;
|
|
77
|
+
constructor(opts) {
|
|
78
|
+
this.instanceNonce = randomBytes(16).toString("hex");
|
|
79
|
+
this.resolved = opts.initial;
|
|
80
|
+
this.onResolved = opts.onResolved ?? null;
|
|
81
|
+
}
|
|
82
|
+
get() {
|
|
83
|
+
return this.resolved;
|
|
84
|
+
}
|
|
85
|
+
/**
|
|
86
|
+
* Feed an inbound Forge-surface request. No-op once resolved. Kicks off
|
|
87
|
+
* async self-verification of the candidate URL derived from the request.
|
|
88
|
+
*/
|
|
89
|
+
considerRequest(req) {
|
|
90
|
+
if (this.resolved || this.verifying) return;
|
|
91
|
+
if (this.attempts >= MAX_VERIFY_ATTEMPTS) return;
|
|
92
|
+
const candidate = candidateFromRequest(req);
|
|
93
|
+
if (!candidate || this.rejected.has(candidate)) return;
|
|
94
|
+
this.verifying = true;
|
|
95
|
+
this.attempts += 1;
|
|
96
|
+
void this.verify(candidate).then((ok) => {
|
|
97
|
+
if (ok) {
|
|
98
|
+
this.resolved = candidate;
|
|
99
|
+
console.log(`[forge] public base URL inferred and verified: ${candidate}`);
|
|
100
|
+
this.onResolved?.(candidate);
|
|
101
|
+
} else {
|
|
102
|
+
this.rejected.add(candidate);
|
|
103
|
+
console.warn(
|
|
104
|
+
`[forge] candidate base URL failed self-verification, ignoring: ${candidate}`
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
}).finally(() => {
|
|
108
|
+
this.verifying = false;
|
|
109
|
+
});
|
|
110
|
+
}
|
|
111
|
+
/** Fetch our own /forge/health at the candidate and match the boot nonce. */
|
|
112
|
+
async verify(candidate) {
|
|
113
|
+
try {
|
|
114
|
+
const controller = new AbortController();
|
|
115
|
+
const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);
|
|
116
|
+
const res = await fetch(`${candidate}/forge/health`, {
|
|
117
|
+
signal: controller.signal,
|
|
118
|
+
headers: { accept: "application/json" },
|
|
119
|
+
redirect: "manual"
|
|
120
|
+
});
|
|
121
|
+
clearTimeout(timer);
|
|
122
|
+
if (!res.ok) return false;
|
|
123
|
+
const json = await res.json();
|
|
124
|
+
return json.instance === this.instanceNonce;
|
|
125
|
+
} catch {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
};
|
|
130
|
+
function candidateFromRequest(req) {
|
|
131
|
+
const host = firstHeaderValue(req.headers["x-forwarded-host"]) ?? req.headers.host;
|
|
132
|
+
if (!host || !isValidHost(host)) return null;
|
|
133
|
+
const proto = firstHeaderValue(req.headers["x-forwarded-proto"]) ?? (req.protocol || "http");
|
|
134
|
+
if (proto !== "https" && proto !== "http") return null;
|
|
135
|
+
const isLocal = /^(localhost|127\.0\.0\.1|\[::1\])(:\d+)?$/i.test(host);
|
|
136
|
+
if (proto === "http" && !isLocal) return null;
|
|
137
|
+
return `${proto}://${host}`;
|
|
138
|
+
}
|
|
139
|
+
function firstHeaderValue(value) {
|
|
140
|
+
const raw = Array.isArray(value) ? value[0] : value;
|
|
141
|
+
const first = raw?.split(",")[0]?.trim();
|
|
142
|
+
return first || null;
|
|
143
|
+
}
|
|
144
|
+
function isValidHost(host) {
|
|
145
|
+
return /^[a-z0-9.-]+(:\d{1,5})?$/i.test(host) || /^\[[0-9a-f:]+\](:\d{1,5})?$/i.test(host);
|
|
146
|
+
}
|
|
147
|
+
|
|
45
148
|
// src/gateway.ts
|
|
46
149
|
async function heartbeatGateway(opts) {
|
|
47
150
|
const gateway = opts.gatewayUrl.replace(/\/$/, "");
|
|
@@ -163,7 +266,7 @@ async function resolvePayTo(opts) {
|
|
|
163
266
|
}
|
|
164
267
|
|
|
165
268
|
// src/status.ts
|
|
166
|
-
var PACKAGE_VERSION = "0.1.
|
|
269
|
+
var PACKAGE_VERSION = "0.1.8";
|
|
167
270
|
var lastHeartbeat = {
|
|
168
271
|
attempted: false,
|
|
169
272
|
ok: null,
|
|
@@ -225,6 +328,7 @@ function forgeSdkVersion() {
|
|
|
225
328
|
// src/mount.ts
|
|
226
329
|
var DEFAULT_NETWORK = "eip155:8453";
|
|
227
330
|
var DEFAULT_FACILITATOR_URL = "https://facilitator.xpay.sh";
|
|
331
|
+
var DEFAULT_GATEWAY_URL = "https://gateway.clawca.sh";
|
|
228
332
|
function asNetwork(value) {
|
|
229
333
|
return value ?? DEFAULT_NETWORK;
|
|
230
334
|
}
|
|
@@ -324,7 +428,7 @@ function mountFulfillmentRouter(app, services, options) {
|
|
|
324
428
|
function mountForgeStatusRoutes(app, services, options, opts) {
|
|
325
429
|
const getStatus = () => buildForgeSurfaceStatus({
|
|
326
430
|
handle: opts.handle,
|
|
327
|
-
publicBaseUrl: opts.
|
|
431
|
+
publicBaseUrl: opts.resolver.get(),
|
|
328
432
|
gatewayUrl: opts.gatewayUrl,
|
|
329
433
|
fulfillMounted: opts.fulfillMounted,
|
|
330
434
|
fulfillPath: opts.fulfillPath,
|
|
@@ -336,7 +440,8 @@ function mountForgeStatusRoutes(app, services, options, opts) {
|
|
|
336
440
|
price: s.payment.amount
|
|
337
441
|
}))
|
|
338
442
|
});
|
|
339
|
-
app.get("/forge/health", (
|
|
443
|
+
app.get("/forge/health", (req, res) => {
|
|
444
|
+
opts.resolver.considerRequest(req);
|
|
340
445
|
const status = getStatus();
|
|
341
446
|
res.json({
|
|
342
447
|
ok: true,
|
|
@@ -344,14 +449,18 @@ function mountForgeStatusRoutes(app, services, options, opts) {
|
|
|
344
449
|
ready: status.ready,
|
|
345
450
|
handle: status.handle,
|
|
346
451
|
version: status.version,
|
|
452
|
+
// Per-boot nonce so this instance can self-verify an inferred base URL.
|
|
453
|
+
instance: opts.resolver.instanceNonce,
|
|
347
454
|
actions: status.actions.map((a) => a.name)
|
|
348
455
|
});
|
|
349
456
|
});
|
|
350
|
-
app.get("/forge/status", (
|
|
457
|
+
app.get("/forge/status", (req, res) => {
|
|
458
|
+
opts.resolver.considerRequest(req);
|
|
351
459
|
const status = getStatus();
|
|
352
460
|
res.status(status.ready ? 200 : 503).json(status);
|
|
353
461
|
});
|
|
354
|
-
app.get("/.well-known/clawcash.json", (
|
|
462
|
+
app.get("/.well-known/clawcash.json", (req, res) => {
|
|
463
|
+
opts.resolver.considerRequest(req);
|
|
355
464
|
res.json(buildWellKnownDocument(getStatus()));
|
|
356
465
|
});
|
|
357
466
|
console.log(
|
|
@@ -426,23 +535,15 @@ async function mountAgentServices(app, services, options) {
|
|
|
426
535
|
getForgeApiKey(options.gateway?.registerSecret)
|
|
427
536
|
);
|
|
428
537
|
mountFulfillmentRouter(app, services, options);
|
|
429
|
-
const gatewayUrl = options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() ||
|
|
538
|
+
const gatewayUrl = options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() || DEFAULT_GATEWAY_URL;
|
|
430
539
|
const handle = options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;
|
|
431
540
|
const registerSecret = options.gateway?.registerSecret?.trim() || process.env.FORGE_API_KEY?.trim() || process.env.GATEWAY_REGISTER_SECRET?.trim();
|
|
432
|
-
const
|
|
433
|
-
|
|
434
|
-
fulfillMounted,
|
|
435
|
-
fulfillPath,
|
|
436
|
-
agentBasePath: basePath,
|
|
437
|
-
handle,
|
|
438
|
-
publicBaseUrl,
|
|
439
|
-
gatewayUrl
|
|
440
|
-
});
|
|
441
|
-
if (gatewayUrl && handle && registerSecret && publicBaseUrl) {
|
|
541
|
+
const sendHeartbeat = (baseUrl) => {
|
|
542
|
+
if (!handle || !registerSecret) return;
|
|
442
543
|
void heartbeatGateway({
|
|
443
544
|
gatewayUrl,
|
|
444
545
|
handle,
|
|
445
|
-
baseUrl
|
|
546
|
+
baseUrl,
|
|
446
547
|
registerSecret
|
|
447
548
|
}).then(() => {
|
|
448
549
|
recordHeartbeatResult({ ok: true });
|
|
@@ -451,6 +552,23 @@ async function mountAgentServices(app, services, options) {
|
|
|
451
552
|
recordHeartbeatResult({ ok: false, error: message });
|
|
452
553
|
console.warn("[forge] gateway heartbeat skipped:", err);
|
|
453
554
|
});
|
|
555
|
+
};
|
|
556
|
+
const resolver = new PublicBaseUrlResolver({
|
|
557
|
+
initial: resolveBaseUrlFromEnv(options.gateway?.publicBaseUrl),
|
|
558
|
+
// Base URL learned late (inferred from the first probe): heartbeat now.
|
|
559
|
+
onResolved: sendHeartbeat
|
|
560
|
+
});
|
|
561
|
+
mountForgeStatusRoutes(app, services, options, {
|
|
562
|
+
fulfillMounted,
|
|
563
|
+
fulfillPath,
|
|
564
|
+
agentBasePath: basePath,
|
|
565
|
+
handle,
|
|
566
|
+
resolver,
|
|
567
|
+
gatewayUrl
|
|
568
|
+
});
|
|
569
|
+
const bootBaseUrl = resolver.get();
|
|
570
|
+
if (bootBaseUrl) {
|
|
571
|
+
sendHeartbeat(bootBaseUrl);
|
|
454
572
|
}
|
|
455
573
|
return router;
|
|
456
574
|
}
|
|
@@ -543,6 +661,7 @@ function generateSkillMarkdown(services, meta) {
|
|
|
543
661
|
}
|
|
544
662
|
export {
|
|
545
663
|
FORGE_GATEWAY_USER_ID,
|
|
664
|
+
PublicBaseUrlResolver,
|
|
546
665
|
buildForgeSurfaceStatus,
|
|
547
666
|
buildWellKnownDocument,
|
|
548
667
|
createContext,
|
|
@@ -560,6 +679,7 @@ export {
|
|
|
560
679
|
mountAgentServices,
|
|
561
680
|
recordHeartbeatResult,
|
|
562
681
|
requireForgeGateway,
|
|
682
|
+
resolveBaseUrlFromEnv,
|
|
563
683
|
resolvePayTo,
|
|
564
684
|
toKebabCase,
|
|
565
685
|
waitUntil
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/define.ts","../src/mount.ts","../src/gateway.ts","../src/gateway-auth.ts","../src/payto.ts","../src/status.ts","../src/skill.ts"],"sourcesContent":["import type {\n AgentServiceConfig,\n AgentServiceContext,\n DefinedAgentService,\n WaitUntilOptions,\n} from \"./types.js\";\n\nexport async function waitUntil<T>(options: WaitUntilOptions<T>): Promise<T> {\n const intervalMs = options.intervalMs ?? 500;\n const timeoutMs = options.timeoutMs ?? 60_000;\n const started = Date.now();\n\n for (;;) {\n const value = await options.run();\n if (options.completedWhen(value)) {\n return value;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`waitUntil timed out after ${timeoutMs}ms`);\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n}\n\nexport function createContext(): AgentServiceContext {\n return {\n waitUntil,\n };\n}\n\n/** Convert snake_case or camelCase service name to kebab-case path segment. */\nexport function toKebabCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n}\n\nexport function defineAgentService<\n TInput extends Record<string, unknown> = Record<string, unknown>,\n TOutput extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: AgentServiceConfig<TInput, TOutput>,\n): DefinedAgentService<TInput, TOutput> {\n if (!config.name?.trim()) {\n throw new Error(\"defineAgentService: name is required\");\n }\n if (!config.execute) {\n throw new Error(\"defineAgentService: execute is required\");\n }\n\n return {\n ...config,\n __forge: true,\n path: toKebabCase(config.name),\n };\n}\n","import type { Application, Request, Response, NextFunction, Router } from \"express\";\nimport { Router as createRouter } from \"express\";\nimport { paymentMiddleware, x402ResourceServer } from \"@x402/express\";\nimport type { Network } from \"@x402/express\";\nimport { HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport { createContext } from \"./define.js\";\nimport { heartbeatGateway } from \"./gateway.js\";\nimport {\n getForgeApiKey,\n requireForgeGateway,\n} from \"./gateway-auth.js\";\nimport { isZeroAddress, resolvePayTo } from \"./payto.js\";\nimport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n recordHeartbeatResult,\n} from \"./status.js\";\nimport type {\n DefinedAgentService,\n InputSchema,\n MountOptions,\n SchemaFieldType,\n} from \"./types.js\";\n\n/** Base mainnet — settled via the public XPay facilitator (no API keys). */\nconst DEFAULT_NETWORK = \"eip155:8453\" as const satisfies Network;\n/** Open facilitator: Base mainnet + Sepolia, no API keys. https://github.com/xpaysh/xpay-x402 */\nconst DEFAULT_FACILITATOR_URL = \"https://facilitator.xpay.sh\";\n\nfunction asNetwork(value: string | undefined): Network {\n return (value ?? DEFAULT_NETWORK) as Network;\n}\n\nfunction createFacilitatorClient(options: MountOptions): HTTPFacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,\n createAuthHeaders: options.createAuthHeaders,\n });\n}\n\nfunction validateInput(\n body: unknown,\n schema: InputSchema,\n): { ok: true; value: Record<string, unknown> } | { ok: false; error: string } {\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n return { ok: false, error: \"Request body must be a JSON object\" };\n }\n\n const input = body as Record<string, unknown>;\n const value: Record<string, unknown> = {};\n\n for (const [key, type] of Object.entries(schema)) {\n if (!(key in input) || input[key] === undefined || input[key] === null) {\n return { ok: false, error: `Missing required field: ${key}` };\n }\n const err = checkType(key, input[key], type);\n if (err) return { ok: false, error: err };\n value[key] = input[key];\n }\n\n return { ok: true, value };\n}\n\nfunction checkType(key: string, value: unknown, type: SchemaFieldType): string | null {\n switch (type) {\n case \"string\":\n case \"url\":\n if (typeof value !== \"string\" || !value.trim()) {\n return `Field ${key} must be a non-empty string`;\n }\n if (type === \"url\") {\n try {\n new URL(value);\n } catch {\n return `Field ${key} must be a valid URL`;\n }\n }\n return null;\n case \"number\":\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return `Field ${key} must be a number`;\n }\n return null;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n return `Field ${key} must be a boolean`;\n }\n return null;\n default:\n return null;\n }\n}\n\nfunction formatPrice(amount: string): string {\n const normalized = amount.startsWith(\"$\") ? amount.slice(1) : amount;\n return `$${normalized}`;\n}\n\nfunction mountFulfillmentRouter(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): void {\n const secret = getForgeApiKey(options.gateway?.registerSecret);\n if (!secret) {\n console.warn(\n \"[forge] /forge/fulfill not mounted — set FORGE_API_KEY (from Forge dashboard, min 16 chars) so the gateway can fulfill after payment\",\n );\n return;\n }\n\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n const gate = requireForgeGateway(secret);\n\n for (const service of services) {\n router.post(\n `/${service.path}`,\n gate,\n async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] fulfill ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n },\n );\n }\n\n app.use(fulfillPath, router);\n console.log(\n `[forge] fulfillment mounted at POST ${fulfillPath}/{action} (gateway secret)`,\n );\n}\n\nfunction mountForgeStatusRoutes(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n opts: {\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n },\n): void {\n const getStatus = () =>\n buildForgeSurfaceStatus({\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath: opts.fulfillPath,\n agentBasePath: opts.agentBasePath,\n skipPayment: Boolean(options.skipPayment),\n actions: services.map((s) => ({\n name: s.name,\n path: s.path,\n price: s.payment.amount,\n })),\n });\n\n app.get(\"/forge/health\", (_req: Request, res: Response) => {\n const status = getStatus();\n res.json({\n ok: true,\n forge: true as const,\n ready: status.ready,\n handle: status.handle,\n version: status.version,\n actions: status.actions.map((a) => a.name),\n });\n });\n\n app.get(\"/forge/status\", (_req: Request, res: Response) => {\n const status = getStatus();\n res.status(status.ready ? 200 : 503).json(status);\n });\n\n app.get(\"/.well-known/clawcash.json\", (_req: Request, res: Response) => {\n res.json(buildWellKnownDocument(getStatus()));\n });\n\n console.log(\n \"[forge] liveliness: GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json\",\n );\n}\n\n/**\n * Mount Forge agent services on an Express app.\n * - GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json — liveliness\n * - POST {basePath}/{kebab-name} — optional public x402 agent surface\n * - POST /forge/fulfill/{kebab-name} — private gateway fulfillment after payment\n *\n * payTo resolves automatically: PAY_TO env (optional) → Forge API → baked fallback.\n */\nexport async function mountAgentServices(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): Promise<Router> {\n let payTo = \"\";\n if (!options.skipPayment) {\n const fallback =\n options.payToFallback?.trim() || options.payTo?.trim() || \"\";\n payTo = await resolvePayTo({\n fallback,\n payTo: options.payTo,\n forge: options.forge,\n });\n if (isZeroAddress(payTo)) {\n throw new Error(\n \"mountAgentServices: resolved payTo is the zero address. Re-run Forge to provision a wallet.\",\n );\n }\n }\n\n const basePath = (options.basePath ?? \"/agent\").replace(/\\/$/, \"\") || \"/agent\";\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n\n const routes: RoutesConfig = {};\n\n for (const service of services) {\n const routePath = `/${service.path}`;\n const fullPath = `${basePath}${routePath}`;\n const network = asNetwork(service.payment.network);\n\n if (!options.skipPayment) {\n routes[`POST ${fullPath}`] = {\n accepts: {\n scheme: \"exact\",\n price: formatPrice(service.payment.amount),\n network,\n payTo,\n },\n description: service.description,\n mimeType: \"application/json\",\n };\n }\n\n router.post(routePath, async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n });\n }\n\n if (!options.skipPayment && Object.keys(routes).length > 0) {\n const facilitator = createFacilitatorClient(options);\n const networks = new Set(\n services.map((s) => asNetwork(s.payment.network)),\n );\n const resourceServer = new x402ResourceServer(facilitator);\n for (const network of networks) {\n resourceServer.register(network, new ExactEvmScheme());\n }\n app.use(paymentMiddleware(routes, resourceServer, undefined, undefined, true));\n }\n\n app.use(basePath, router);\n const fulfillMounted = Boolean(\n getForgeApiKey(options.gateway?.registerSecret),\n );\n mountFulfillmentRouter(app, services, options);\n\n const gatewayUrl =\n options.gateway?.url?.trim() || process.env.GATEWAY_URL?.trim() || null;\n const handle =\n options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;\n const registerSecret =\n options.gateway?.registerSecret?.trim() ||\n process.env.FORGE_API_KEY?.trim() ||\n process.env.GATEWAY_REGISTER_SECRET?.trim();\n const publicBaseUrl =\n options.gateway?.publicBaseUrl?.trim() ||\n process.env.PUBLIC_BASE_URL?.trim() ||\n (process.env.RAILWAY_PUBLIC_DOMAIN\n ? `https://${process.env.RAILWAY_PUBLIC_DOMAIN}`\n : \"\") ||\n null;\n\n mountForgeStatusRoutes(app, services, options, {\n fulfillMounted,\n fulfillPath,\n agentBasePath: basePath,\n handle,\n publicBaseUrl,\n gatewayUrl,\n });\n\n if (gatewayUrl && handle && registerSecret && publicBaseUrl) {\n void heartbeatGateway({\n gatewayUrl,\n handle,\n baseUrl: publicBaseUrl,\n registerSecret,\n })\n .then(() => {\n recordHeartbeatResult({ ok: true });\n })\n .catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n recordHeartbeatResult({ ok: false, error: message });\n console.warn(\"[forge] gateway heartbeat skipped:\", err);\n });\n }\n\n return router;\n}\n\nexport function createForgeRouter(\n services: DefinedAgentService[],\n options: MountOptions,\n): (app: Application) => Promise<Router> {\n return (app) => mountAgentServices(app, services, options);\n}\n\nexport function forgeErrorHandler(\n err: unknown,\n _req: Request,\n res: Response,\n _next: NextFunction,\n): void {\n const message = err instanceof Error ? err.message : \"Internal error\";\n res.status(500).json({ error: message });\n}\n","/**\n * Notify ClawCash gateway of this merchant's live public base URL.\n * Full action registration still happens from Forge \"Go live\".\n */\nexport async function heartbeatGateway(opts: {\n gatewayUrl: string;\n handle: string;\n baseUrl: string;\n registerSecret: string;\n}): Promise<void> {\n const gateway = opts.gatewayUrl.replace(/\\/$/, \"\");\n const res = await fetch(`${gateway}/register/heartbeat`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${opts.registerSecret}`,\n },\n body: JSON.stringify({\n handle: opts.handle.trim().toLowerCase(),\n baseUrl: opts.baseUrl.replace(/\\/$/, \"\"),\n }),\n });\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `gateway heartbeat failed (${res.status}): ${text.slice(0, 240)}`,\n );\n }\n}\n","import type { NextFunction, Request, Response } from \"express\";\n\n/**\n * Per-project Forge API key for gateway → merchant fulfillment.\n * Merchants set FORGE_API_KEY from the Forge dashboard (never the shared\n * GATEWAY_REGISTER_SECRET — that is Forge↔gateway platform auth only).\n *\n * GATEWAY_REGISTER_SECRET is accepted as a deprecated fallback for older deploys.\n */\nexport function getForgeApiKey(explicit?: string | null): string | null {\n const value =\n (explicit ?? process.env.FORGE_API_KEY ?? process.env.GATEWAY_REGISTER_SECRET)?.trim();\n if (!value || value.length < 16) return null;\n return value;\n}\n\n/** @deprecated Use getForgeApiKey */\nexport function getForgeGatewaySecret(\n explicit?: string | null,\n): string | null {\n return getForgeApiKey(explicit);\n}\n\nexport function isForgeGatewayRequest(\n req: Request,\n secret?: string | null,\n): boolean {\n const expected = getForgeApiKey(secret);\n if (!expected) return false;\n const header = req.header(\"authorization\") ?? \"\";\n const bearer = header.toLowerCase().startsWith(\"bearer \")\n ? header.slice(7).trim()\n : \"\";\n const alt =\n req.header(\"x-forge-api-key\")?.trim() ||\n req.header(\"x-clawcash-gateway\")?.trim() ||\n \"\";\n return bearer === expected || alt === expected;\n}\n\n/** Synthetic user id for DB rows created by gateway-driven fulfillment. */\nexport const FORGE_GATEWAY_USER_ID = \"forge_gateway_agent\";\n\nexport function requireForgeGateway(\n secret?: string | null,\n): (req: Request, res: Response, next: NextFunction) => void {\n return (req, res, next) => {\n if (!isForgeGatewayRequest(req, secret)) {\n res.status(401).json({\n error:\n \"Unauthorized — Forge API key required (FORGE_API_KEY from Forge dashboard)\",\n });\n return;\n }\n next();\n };\n}\n\n/** Headers merchant execute() should send on loopback calls during fulfillment. */\nexport function forgeGatewayLoopbackHeaders(\n secret?: string | null,\n): Record<string, string> {\n const expected = getForgeApiKey(secret);\n if (!expected) return {};\n return {\n Authorization: `Bearer ${expected}`,\n \"X-Forge-Api-Key\": expected,\n };\n}\n","import type { ForgePayToSource } from \"./types.js\";\n\nexport type { ForgePayToSource };\n\nconst ZERO = /^0x0{40}$/i;\n\nexport function isZeroAddress(address: string | undefined | null): boolean {\n if (!address) return true;\n return ZERO.test(address.trim());\n}\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nfunction pickForgeBaseUrl(source?: ForgePayToSource): string | null {\n const fromEnv = process.env.FORGE_URL?.trim();\n if (fromEnv) return normalizeBaseUrl(fromEnv);\n\n const fromOpts = source?.baseUrl?.trim();\n if (!fromOpts) return null;\n\n const normalized = normalizeBaseUrl(fromOpts);\n // Never call a laptop Forge from a deployed merchant app.\n if (\n /localhost|127\\.0\\.0\\.1/i.test(normalized) &&\n process.env.NODE_ENV === \"production\"\n ) {\n return null;\n }\n return normalized;\n}\n\n/**\n * Resolve merchant payTo with minimal host config:\n * 1. `PAY_TO` env (optional override)\n * 2. Live address from Forge public API (when reachable)\n * 3. Baked-in fallback from the Forge PR\n */\nexport async function resolvePayTo(opts: {\n /** Baked-in address from Forge codegen (required fallback). */\n fallback: string;\n /** Optional explicit override (usually process.env.PAY_TO). */\n payTo?: string;\n forge?: ForgePayToSource;\n /** Fetch timeout ms. Defaults to 2500. */\n timeoutMs?: number;\n}): Promise<string> {\n const envOverride = process.env.PAY_TO?.trim();\n if (envOverride && !isZeroAddress(envOverride)) {\n return envOverride;\n }\n\n const explicit = opts.payTo?.trim();\n if (explicit && !isZeroAddress(explicit) && !opts.forge) {\n return explicit;\n }\n\n const baseUrl = pickForgeBaseUrl(opts.forge);\n if (baseUrl && opts.forge) {\n const url = `${baseUrl}/api/public/pay-to/${encodeURIComponent(opts.forge.owner)}/${encodeURIComponent(opts.forge.repo)}`;\n try {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n opts.timeoutMs ?? 2500,\n );\n const res = await fetch(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n clearTimeout(timer);\n if (res.ok) {\n const json = (await res.json()) as { address?: string };\n if (json.address && !isZeroAddress(json.address)) {\n return json.address.trim();\n }\n }\n } catch (err) {\n console.warn(\"[forge] live payTo fetch failed, using fallback:\", err);\n }\n }\n\n if (explicit && !isZeroAddress(explicit)) return explicit;\n if (opts.fallback && !isZeroAddress(opts.fallback)) return opts.fallback;\n\n throw new Error(\n \"resolvePayTo: no usable address (set Forge wallet / PAY_TO, or re-run Forge PR)\",\n );\n}\n","/**\n * Merchant-side Forge surface status — public probes for deploy / go-live checks.\n */\n\nexport type ForgeHeartbeatState = {\n attempted: boolean;\n ok: boolean | null;\n at: string | null;\n error: string | null;\n};\n\nexport type ForgeSurfaceStatus = {\n ok: boolean;\n forge: true;\n version: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n /** True when FORGE_API_KEY is set so /forge/fulfill is mounted. */\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n /** Env + fulfill ready — merchant can accept gateway fulfillment. */\n ready: boolean;\n heartbeat: ForgeHeartbeatState;\n endpoints: {\n health: string;\n status: string;\n wellKnown: string;\n fulfill: string;\n agent: string;\n };\n};\n\nconst PACKAGE_VERSION = \"0.1.7\";\n\nlet lastHeartbeat: ForgeHeartbeatState = {\n attempted: false,\n ok: null,\n at: null,\n error: null,\n};\n\nexport function recordHeartbeatResult(\n result: { ok: true } | { ok: false; error: string },\n): void {\n lastHeartbeat = {\n attempted: true,\n ok: result.ok,\n at: new Date().toISOString(),\n error: result.ok ? null : result.error,\n };\n}\n\nexport function getLastHeartbeat(): ForgeHeartbeatState {\n return { ...lastHeartbeat };\n}\n\nexport function buildForgeSurfaceStatus(opts: {\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n}): ForgeSurfaceStatus {\n const fulfillPath = opts.fulfillPath.replace(/\\/$/, \"\") || \"/forge/fulfill\";\n const agentBasePath = opts.agentBasePath.replace(/\\/$/, \"\") || \"/agent\";\n const ready =\n opts.fulfillMounted &&\n Boolean(opts.publicBaseUrl) &&\n opts.actions.length > 0;\n\n return {\n ok: true,\n forge: true,\n version: PACKAGE_VERSION,\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath,\n agentBasePath,\n skipPayment: opts.skipPayment,\n actions: opts.actions,\n ready,\n heartbeat: getLastHeartbeat(),\n endpoints: {\n health: \"/forge/health\",\n status: \"/forge/status\",\n wellKnown: \"/.well-known/clawcash.json\",\n fulfill: fulfillPath,\n agent: agentBasePath,\n },\n };\n}\n\nexport function buildWellKnownDocument(status: ForgeSurfaceStatus): {\n forge: true;\n version: string;\n health: string;\n status: string;\n handle: string | null;\n ready: boolean;\n} {\n return {\n forge: true,\n version: status.version,\n health: status.endpoints.health,\n status: status.endpoints.status,\n handle: status.handle,\n ready: status.ready,\n };\n}\n\nexport function forgeSdkVersion(): string {\n return PACKAGE_VERSION;\n}\n","import type { DefinedAgentService, SkillMeta } from \"./types.js\";\n\n/**\n * Generate a SKILL.md document for agents from defined Forge services.\n */\nexport function generateSkillMarkdown(\n services: DefinedAgentService[],\n meta: SkillMeta,\n): string {\n const base = meta.baseUrl.replace(/\\/$/, \"\");\n const lines: string[] = [\n `---`,\n `name: ${meta.name}`,\n `description: ${meta.description}`,\n `---`,\n ``,\n `# ${meta.name}`,\n ``,\n meta.description,\n ``,\n ];\n\n if (meta.homepage) {\n lines.push(`Homepage: ${meta.homepage}`, ``);\n }\n\n lines.push(\n `## How to use`,\n ``,\n `1. Read this skill.`,\n `2. Call the agent endpoint with a JSON body matching the input schema.`,\n `3. If you receive HTTP 402, pay via x402 (USDC) and retry with the payment header.`,\n `4. Use the returned output fields.`,\n ``,\n `## Services`,\n ``,\n );\n\n for (const service of services) {\n const path = `${base}/agent/${service.path}`;\n const price = service.payment.amount.startsWith(\"$\")\n ? service.payment.amount\n : `$${service.payment.amount}`;\n\n lines.push(\n `### \\`${service.name}\\``,\n ``,\n service.description,\n ``,\n `- **Method:** \\`POST\\``,\n `- **URL:** \\`${path}\\``,\n `- **Price:** ${price} ${service.payment.currency} via ${service.payment.protocols.join(\", \")}`,\n ``,\n `**Input**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Output**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.output).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Example**`,\n ``,\n \"```bash\",\n `curl -X POST ${path} \\\\`,\n ` -H \"Content-Type: application/json\" \\\\`,\n ` -d '${JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [\n k,\n t === \"url\" ? \"https://example.com/image.png\" : `example-${k}`,\n ]),\n ),\n )}'`,\n \"```\",\n ``,\n );\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAOA,eAAsB,UAAa,SAA0C;AAC3E,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,UAAU,KAAK,IAAI;AAEzB,aAAS;AACP,UAAM,QAAQ,MAAM,QAAQ,IAAI;AAChC,QAAI,QAAQ,cAAc,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AACA,QAAI,KAAK,IAAI,IAAI,WAAW,WAAW;AACrC,YAAM,IAAI,MAAM,6BAA6B,SAAS,IAAI;AAAA,IAC5D;AACA,UAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,UAAU,CAAC;AAAA,EAChE;AACF;AAEO,SAAS,gBAAqC;AACnD,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAGO,SAAS,YAAY,MAAsB;AAChD,SAAO,KACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,MAAM,GAAG,EACjB,YAAY;AACjB;AAEO,SAAS,mBAId,QACsC;AACtC,MAAI,CAAC,OAAO,MAAM,KAAK,GAAG;AACxB,UAAM,IAAI,MAAM,sCAAsC;AAAA,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CAAC,GAAG,CAAC;AAAA,QAC7D;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,KAAK;AAAA,QACH,OAAO;AAAA,UACL,OAAO,QAAQ,QAAQ,MAAM,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM,CAAC,GAAG,IAAI,CAAC,GAAG,CAAC;AAAA,QAC9D;AAAA,QACA;AAAA,QACA;AAAA,MACF;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,gBAAgB,IAAI;AAAA,MACpB;AAAA,MACA,SAAS,KAAK;AAAA,QACZ,OAAO;AAAA,UACL,OAAO,QAAQ,QAAQ,KAAK,EAAE,IAAI,CAAC,CAAC,GAAG,CAAC,MAAM;AAAA,YAC5C;AAAA,YACA,MAAM,QAAQ,kCAAkC,WAAW,CAAC;AAAA,UAC9D,CAAC;AAAA,QACH;AAAA,MACF,CAAC;AAAA,MACD;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,MAAM,KAAK,IAAI;AACxB;","names":[]}
|
|
1
|
+
{"version":3,"sources":["../src/define.ts","../src/mount.ts","../src/base-url.ts","../src/gateway.ts","../src/gateway-auth.ts","../src/payto.ts","../src/status.ts","../src/skill.ts"],"sourcesContent":["import type {\n AgentServiceConfig,\n AgentServiceContext,\n DefinedAgentService,\n WaitUntilOptions,\n} from \"./types.js\";\n\nexport async function waitUntil<T>(options: WaitUntilOptions<T>): Promise<T> {\n const intervalMs = options.intervalMs ?? 500;\n const timeoutMs = options.timeoutMs ?? 60_000;\n const started = Date.now();\n\n for (;;) {\n const value = await options.run();\n if (options.completedWhen(value)) {\n return value;\n }\n if (Date.now() - started >= timeoutMs) {\n throw new Error(`waitUntil timed out after ${timeoutMs}ms`);\n }\n await new Promise((resolve) => setTimeout(resolve, intervalMs));\n }\n}\n\nexport function createContext(): AgentServiceContext {\n return {\n waitUntil,\n };\n}\n\n/** Convert snake_case or camelCase service name to kebab-case path segment. */\nexport function toKebabCase(name: string): string {\n return name\n .replace(/([a-z0-9])([A-Z])/g, \"$1-$2\")\n .replace(/_/g, \"-\")\n .toLowerCase();\n}\n\nexport function defineAgentService<\n TInput extends Record<string, unknown> = Record<string, unknown>,\n TOutput extends Record<string, unknown> = Record<string, unknown>,\n>(\n config: AgentServiceConfig<TInput, TOutput>,\n): DefinedAgentService<TInput, TOutput> {\n if (!config.name?.trim()) {\n throw new Error(\"defineAgentService: name is required\");\n }\n if (!config.execute) {\n throw new Error(\"defineAgentService: execute is required\");\n }\n\n return {\n ...config,\n __forge: true,\n path: toKebabCase(config.name),\n };\n}\n","import type { Application, Request, Response, NextFunction, Router } from \"express\";\nimport { Router as createRouter } from \"express\";\nimport { paymentMiddleware, x402ResourceServer } from \"@x402/express\";\nimport type { Network } from \"@x402/express\";\nimport { HTTPFacilitatorClient } from \"@x402/core/server\";\nimport type { RoutesConfig } from \"@x402/core/server\";\nimport { ExactEvmScheme } from \"@x402/evm/exact/server\";\nimport {\n PublicBaseUrlResolver,\n resolveBaseUrlFromEnv,\n} from \"./base-url.js\";\nimport { createContext } from \"./define.js\";\nimport { heartbeatGateway } from \"./gateway.js\";\nimport {\n getForgeApiKey,\n requireForgeGateway,\n} from \"./gateway-auth.js\";\nimport { isZeroAddress, resolvePayTo } from \"./payto.js\";\nimport {\n buildForgeSurfaceStatus,\n buildWellKnownDocument,\n recordHeartbeatResult,\n} from \"./status.js\";\nimport type {\n DefinedAgentService,\n InputSchema,\n MountOptions,\n SchemaFieldType,\n} from \"./types.js\";\n\n/** Base mainnet — settled via the public XPay facilitator (no API keys). */\nconst DEFAULT_NETWORK = \"eip155:8453\" as const satisfies Network;\n/** Open facilitator: Base mainnet + Sepolia, no API keys. https://github.com/xpaysh/xpay-x402 */\nconst DEFAULT_FACILITATOR_URL = \"https://facilitator.xpay.sh\";\n/** ClawCash gateway — override with GATEWAY_URL or options.gateway.url. */\nconst DEFAULT_GATEWAY_URL = \"https://gateway.clawca.sh\";\n\nfunction asNetwork(value: string | undefined): Network {\n return (value ?? DEFAULT_NETWORK) as Network;\n}\n\nfunction createFacilitatorClient(options: MountOptions): HTTPFacilitatorClient {\n return new HTTPFacilitatorClient({\n url: options.facilitatorUrl ?? DEFAULT_FACILITATOR_URL,\n createAuthHeaders: options.createAuthHeaders,\n });\n}\n\nfunction validateInput(\n body: unknown,\n schema: InputSchema,\n): { ok: true; value: Record<string, unknown> } | { ok: false; error: string } {\n if (!body || typeof body !== \"object\" || Array.isArray(body)) {\n return { ok: false, error: \"Request body must be a JSON object\" };\n }\n\n const input = body as Record<string, unknown>;\n const value: Record<string, unknown> = {};\n\n for (const [key, type] of Object.entries(schema)) {\n if (!(key in input) || input[key] === undefined || input[key] === null) {\n return { ok: false, error: `Missing required field: ${key}` };\n }\n const err = checkType(key, input[key], type);\n if (err) return { ok: false, error: err };\n value[key] = input[key];\n }\n\n return { ok: true, value };\n}\n\nfunction checkType(key: string, value: unknown, type: SchemaFieldType): string | null {\n switch (type) {\n case \"string\":\n case \"url\":\n if (typeof value !== \"string\" || !value.trim()) {\n return `Field ${key} must be a non-empty string`;\n }\n if (type === \"url\") {\n try {\n new URL(value);\n } catch {\n return `Field ${key} must be a valid URL`;\n }\n }\n return null;\n case \"number\":\n if (typeof value !== \"number\" || Number.isNaN(value)) {\n return `Field ${key} must be a number`;\n }\n return null;\n case \"boolean\":\n if (typeof value !== \"boolean\") {\n return `Field ${key} must be a boolean`;\n }\n return null;\n default:\n return null;\n }\n}\n\nfunction formatPrice(amount: string): string {\n const normalized = amount.startsWith(\"$\") ? amount.slice(1) : amount;\n return `$${normalized}`;\n}\n\nfunction mountFulfillmentRouter(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): void {\n const secret = getForgeApiKey(options.gateway?.registerSecret);\n if (!secret) {\n console.warn(\n \"[forge] /forge/fulfill not mounted — set FORGE_API_KEY (from Forge dashboard, min 16 chars) so the gateway can fulfill after payment\",\n );\n return;\n }\n\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n const gate = requireForgeGateway(secret);\n\n for (const service of services) {\n router.post(\n `/${service.path}`,\n gate,\n async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] fulfill ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n },\n );\n }\n\n app.use(fulfillPath, router);\n console.log(\n `[forge] fulfillment mounted at POST ${fulfillPath}/{action} (gateway secret)`,\n );\n}\n\nfunction mountForgeStatusRoutes(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n opts: {\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n handle: string | null;\n resolver: PublicBaseUrlResolver;\n gatewayUrl: string | null;\n },\n): void {\n const getStatus = () =>\n buildForgeSurfaceStatus({\n handle: opts.handle,\n publicBaseUrl: opts.resolver.get(),\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath: opts.fulfillPath,\n agentBasePath: opts.agentBasePath,\n skipPayment: Boolean(options.skipPayment),\n actions: services.map((s) => ({\n name: s.name,\n path: s.path,\n price: s.payment.amount,\n })),\n });\n\n app.get(\"/forge/health\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n const status = getStatus();\n res.json({\n ok: true,\n forge: true as const,\n ready: status.ready,\n handle: status.handle,\n version: status.version,\n // Per-boot nonce so this instance can self-verify an inferred base URL.\n instance: opts.resolver.instanceNonce,\n actions: status.actions.map((a) => a.name),\n });\n });\n\n app.get(\"/forge/status\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n const status = getStatus();\n res.status(status.ready ? 200 : 503).json(status);\n });\n\n app.get(\"/.well-known/clawcash.json\", (req: Request, res: Response) => {\n opts.resolver.considerRequest(req);\n res.json(buildWellKnownDocument(getStatus()));\n });\n\n console.log(\n \"[forge] liveliness: GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json\",\n );\n}\n\n/**\n * Mount Forge agent services on an Express app.\n * - GET /forge/health, GET /forge/status, GET /.well-known/clawcash.json — liveliness\n * - POST {basePath}/{kebab-name} — optional public x402 agent surface\n * - POST /forge/fulfill/{kebab-name} — private gateway fulfillment after payment\n *\n * payTo resolves automatically: PAY_TO env (optional) → Forge API → baked fallback.\n */\nexport async function mountAgentServices(\n app: Application,\n services: DefinedAgentService[],\n options: MountOptions,\n): Promise<Router> {\n let payTo = \"\";\n if (!options.skipPayment) {\n const fallback =\n options.payToFallback?.trim() || options.payTo?.trim() || \"\";\n payTo = await resolvePayTo({\n fallback,\n payTo: options.payTo,\n forge: options.forge,\n });\n if (isZeroAddress(payTo)) {\n throw new Error(\n \"mountAgentServices: resolved payTo is the zero address. Re-run Forge to provision a wallet.\",\n );\n }\n }\n\n const basePath = (options.basePath ?? \"/agent\").replace(/\\/$/, \"\") || \"/agent\";\n const fulfillPath =\n (options.fulfillPath ?? \"/forge/fulfill\").replace(/\\/$/, \"\") ||\n \"/forge/fulfill\";\n const router = createRouter();\n const context = createContext();\n\n const routes: RoutesConfig = {};\n\n for (const service of services) {\n const routePath = `/${service.path}`;\n const fullPath = `${basePath}${routePath}`;\n const network = asNetwork(service.payment.network);\n\n if (!options.skipPayment) {\n routes[`POST ${fullPath}`] = {\n accepts: {\n scheme: \"exact\",\n price: formatPrice(service.payment.amount),\n network,\n payTo,\n },\n description: service.description,\n mimeType: \"application/json\",\n };\n }\n\n router.post(routePath, async (req: Request, res: Response) => {\n try {\n const validated = validateInput(req.body, service.input);\n if (!validated.ok) {\n res.status(400).json({ error: validated.error });\n return;\n }\n\n const output = await service.execute(validated.value, context);\n res.json(output);\n } catch (err) {\n const message = err instanceof Error ? err.message : \"Internal error\";\n console.error(`[forge] ${service.name} failed:`, err);\n res.status(500).json({ error: message });\n }\n });\n }\n\n if (!options.skipPayment && Object.keys(routes).length > 0) {\n const facilitator = createFacilitatorClient(options);\n const networks = new Set(\n services.map((s) => asNetwork(s.payment.network)),\n );\n const resourceServer = new x402ResourceServer(facilitator);\n for (const network of networks) {\n resourceServer.register(network, new ExactEvmScheme());\n }\n app.use(paymentMiddleware(routes, resourceServer, undefined, undefined, true));\n }\n\n app.use(basePath, router);\n const fulfillMounted = Boolean(\n getForgeApiKey(options.gateway?.registerSecret),\n );\n mountFulfillmentRouter(app, services, options);\n\n const gatewayUrl =\n options.gateway?.url?.trim() ||\n process.env.GATEWAY_URL?.trim() ||\n DEFAULT_GATEWAY_URL;\n const handle =\n options.gateway?.handle?.trim() || process.env.FORGE_HANDLE?.trim() || null;\n const registerSecret =\n options.gateway?.registerSecret?.trim() ||\n process.env.FORGE_API_KEY?.trim() ||\n process.env.GATEWAY_REGISTER_SECRET?.trim();\n\n const sendHeartbeat = (baseUrl: string) => {\n if (!handle || !registerSecret) return;\n void heartbeatGateway({\n gatewayUrl,\n handle,\n baseUrl,\n registerSecret,\n })\n .then(() => {\n recordHeartbeatResult({ ok: true });\n })\n .catch((err) => {\n const message = err instanceof Error ? err.message : String(err);\n recordHeartbeatResult({ ok: false, error: message });\n console.warn(\"[forge] gateway heartbeat skipped:\", err);\n });\n };\n\n const resolver = new PublicBaseUrlResolver({\n initial: resolveBaseUrlFromEnv(options.gateway?.publicBaseUrl),\n // Base URL learned late (inferred from the first probe): heartbeat now.\n onResolved: sendHeartbeat,\n });\n\n mountForgeStatusRoutes(app, services, options, {\n fulfillMounted,\n fulfillPath,\n agentBasePath: basePath,\n handle,\n resolver,\n gatewayUrl,\n });\n\n const bootBaseUrl = resolver.get();\n if (bootBaseUrl) {\n sendHeartbeat(bootBaseUrl);\n }\n\n return router;\n}\n\nexport function createForgeRouter(\n services: DefinedAgentService[],\n options: MountOptions,\n): (app: Application) => Promise<Router> {\n return (app) => mountAgentServices(app, services, options);\n}\n\nexport function forgeErrorHandler(\n err: unknown,\n _req: Request,\n res: Response,\n _next: NextFunction,\n): void {\n const message = err instanceof Error ? err.message : \"Internal error\";\n res.status(500).json({ error: message });\n}\n","import { randomBytes } from \"node:crypto\";\nimport type { Request } from \"express\";\n\n/**\n * Public base URL resolution, in trust order:\n * 1. PUBLIC_BASE_URL env — explicit override.\n * 2. Platform-provided vars (Railway, Render, Vercel, Fly, Heroku) — set by\n * the host, not by request input, so safe to trust as-is.\n * 3. Lazy inference from the first inbound request to the Forge surface\n * (X-Forwarded-Proto + Host). Host is attacker-controlled, so a candidate\n * is only accepted after self-verification: we fetch our own\n * /forge/health at the candidate URL and check it returns this\n * instance's boot nonce.\n */\n\nexport function resolveBaseUrlFromEnv(explicit?: string): string | null {\n const fromExplicit = explicit?.trim();\n if (fromExplicit) return stripSlash(fromExplicit);\n\n const fromEnv = process.env.PUBLIC_BASE_URL?.trim();\n if (fromEnv) return stripSlash(fromEnv);\n\n const railway = process.env.RAILWAY_PUBLIC_DOMAIN?.trim();\n if (railway) return `https://${stripSlash(railway)}`;\n\n const render = process.env.RENDER_EXTERNAL_URL?.trim();\n if (render) return stripSlash(render);\n\n const vercel =\n process.env.VERCEL_PROJECT_PRODUCTION_URL?.trim() ||\n process.env.VERCEL_URL?.trim();\n if (vercel) return `https://${stripSlash(vercel)}`;\n\n const fly = process.env.FLY_APP_NAME?.trim();\n if (fly) return `https://${fly}.fly.dev`;\n\n const heroku = process.env.HEROKU_APP_NAME?.trim();\n if (heroku) return `https://${heroku}.herokuapp.com`;\n\n return null;\n}\n\nfunction stripSlash(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nconst MAX_VERIFY_ATTEMPTS = 5;\nconst VERIFY_TIMEOUT_MS = 3000;\n\nexport class PublicBaseUrlResolver {\n /** Per-boot nonce, echoed by /forge/health for self-verification. */\n readonly instanceNonce: string;\n\n private resolved: string | null;\n private verifying = false;\n private rejected = new Set<string>();\n private attempts = 0;\n private onResolved: ((baseUrl: string) => void) | null;\n\n constructor(opts: {\n /** URL already known from env/platform vars (trusted, no verification). */\n initial: string | null;\n /** Called once when a base URL first becomes known via inference. */\n onResolved?: (baseUrl: string) => void;\n }) {\n this.instanceNonce = randomBytes(16).toString(\"hex\");\n this.resolved = opts.initial;\n this.onResolved = opts.onResolved ?? null;\n }\n\n get(): string | null {\n return this.resolved;\n }\n\n /**\n * Feed an inbound Forge-surface request. No-op once resolved. Kicks off\n * async self-verification of the candidate URL derived from the request.\n */\n considerRequest(req: Request): void {\n if (this.resolved || this.verifying) return;\n if (this.attempts >= MAX_VERIFY_ATTEMPTS) return;\n\n const candidate = candidateFromRequest(req);\n if (!candidate || this.rejected.has(candidate)) return;\n\n this.verifying = true;\n this.attempts += 1;\n void this.verify(candidate)\n .then((ok) => {\n if (ok) {\n this.resolved = candidate;\n console.log(`[forge] public base URL inferred and verified: ${candidate}`);\n this.onResolved?.(candidate);\n } else {\n this.rejected.add(candidate);\n console.warn(\n `[forge] candidate base URL failed self-verification, ignoring: ${candidate}`,\n );\n }\n })\n .finally(() => {\n this.verifying = false;\n });\n }\n\n /** Fetch our own /forge/health at the candidate and match the boot nonce. */\n private async verify(candidate: string): Promise<boolean> {\n try {\n const controller = new AbortController();\n const timer = setTimeout(() => controller.abort(), VERIFY_TIMEOUT_MS);\n const res = await fetch(`${candidate}/forge/health`, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n redirect: \"manual\",\n });\n clearTimeout(timer);\n if (!res.ok) return false;\n const json = (await res.json()) as { instance?: string };\n return json.instance === this.instanceNonce;\n } catch {\n return false;\n }\n }\n}\n\nfunction candidateFromRequest(req: Request): string | null {\n const host = firstHeaderValue(req.headers[\"x-forwarded-host\"]) ?? req.headers.host;\n if (!host || !isValidHost(host)) return null;\n\n const proto =\n firstHeaderValue(req.headers[\"x-forwarded-proto\"]) ??\n (req.protocol || \"http\");\n if (proto !== \"https\" && proto !== \"http\") return null;\n\n const isLocal = /^(localhost|127\\.0\\.0\\.1|\\[::1\\])(:\\d+)?$/i.test(host);\n // A deployed merchant is always behind HTTPS; only allow http locally.\n if (proto === \"http\" && !isLocal) return null;\n\n return `${proto}://${host}`;\n}\n\nfunction firstHeaderValue(value: string | string[] | undefined): string | null {\n const raw = Array.isArray(value) ? value[0] : value;\n const first = raw?.split(\",\")[0]?.trim();\n return first || null;\n}\n\nfunction isValidHost(host: string): boolean {\n // hostname with optional port; rejects paths, spaces, credentials\n return /^[a-z0-9.-]+(:\\d{1,5})?$/i.test(host) || /^\\[[0-9a-f:]+\\](:\\d{1,5})?$/i.test(host);\n}\n","/**\n * Notify ClawCash gateway of this merchant's live public base URL.\n * Full action registration still happens from Forge \"Go live\".\n */\nexport async function heartbeatGateway(opts: {\n gatewayUrl: string;\n handle: string;\n baseUrl: string;\n registerSecret: string;\n}): Promise<void> {\n const gateway = opts.gatewayUrl.replace(/\\/$/, \"\");\n const res = await fetch(`${gateway}/register/heartbeat`, {\n method: \"POST\",\n headers: {\n \"content-type\": \"application/json\",\n authorization: `Bearer ${opts.registerSecret}`,\n },\n body: JSON.stringify({\n handle: opts.handle.trim().toLowerCase(),\n baseUrl: opts.baseUrl.replace(/\\/$/, \"\"),\n }),\n });\n if (!res.ok) {\n const text = await res.text();\n throw new Error(\n `gateway heartbeat failed (${res.status}): ${text.slice(0, 240)}`,\n );\n }\n}\n","import type { NextFunction, Request, Response } from \"express\";\n\n/**\n * Per-project Forge API key for gateway → merchant fulfillment.\n * Merchants set FORGE_API_KEY from the Forge dashboard (never the shared\n * GATEWAY_REGISTER_SECRET — that is Forge↔gateway platform auth only).\n *\n * GATEWAY_REGISTER_SECRET is accepted as a deprecated fallback for older deploys.\n */\nexport function getForgeApiKey(explicit?: string | null): string | null {\n const value =\n (explicit ?? process.env.FORGE_API_KEY ?? process.env.GATEWAY_REGISTER_SECRET)?.trim();\n if (!value || value.length < 16) return null;\n return value;\n}\n\n/** @deprecated Use getForgeApiKey */\nexport function getForgeGatewaySecret(\n explicit?: string | null,\n): string | null {\n return getForgeApiKey(explicit);\n}\n\nexport function isForgeGatewayRequest(\n req: Request,\n secret?: string | null,\n): boolean {\n const expected = getForgeApiKey(secret);\n if (!expected) return false;\n const header = req.header(\"authorization\") ?? \"\";\n const bearer = header.toLowerCase().startsWith(\"bearer \")\n ? header.slice(7).trim()\n : \"\";\n const alt =\n req.header(\"x-forge-api-key\")?.trim() ||\n req.header(\"x-clawcash-gateway\")?.trim() ||\n \"\";\n return bearer === expected || alt === expected;\n}\n\n/** Synthetic user id for DB rows created by gateway-driven fulfillment. */\nexport const FORGE_GATEWAY_USER_ID = \"forge_gateway_agent\";\n\nexport function requireForgeGateway(\n secret?: string | null,\n): (req: Request, res: Response, next: NextFunction) => void {\n return (req, res, next) => {\n if (!isForgeGatewayRequest(req, secret)) {\n res.status(401).json({\n error:\n \"Unauthorized — Forge API key required (FORGE_API_KEY from Forge dashboard)\",\n });\n return;\n }\n next();\n };\n}\n\n/** Headers merchant execute() should send on loopback calls during fulfillment. */\nexport function forgeGatewayLoopbackHeaders(\n secret?: string | null,\n): Record<string, string> {\n const expected = getForgeApiKey(secret);\n if (!expected) return {};\n return {\n Authorization: `Bearer ${expected}`,\n \"X-Forge-Api-Key\": expected,\n };\n}\n","import type { ForgePayToSource } from \"./types.js\";\n\nexport type { ForgePayToSource };\n\nconst ZERO = /^0x0{40}$/i;\n\nexport function isZeroAddress(address: string | undefined | null): boolean {\n if (!address) return true;\n return ZERO.test(address.trim());\n}\n\nfunction normalizeBaseUrl(url: string): string {\n return url.replace(/\\/$/, \"\");\n}\n\nfunction pickForgeBaseUrl(source?: ForgePayToSource): string | null {\n const fromEnv = process.env.FORGE_URL?.trim();\n if (fromEnv) return normalizeBaseUrl(fromEnv);\n\n const fromOpts = source?.baseUrl?.trim();\n if (!fromOpts) return null;\n\n const normalized = normalizeBaseUrl(fromOpts);\n // Never call a laptop Forge from a deployed merchant app.\n if (\n /localhost|127\\.0\\.0\\.1/i.test(normalized) &&\n process.env.NODE_ENV === \"production\"\n ) {\n return null;\n }\n return normalized;\n}\n\n/**\n * Resolve merchant payTo with minimal host config:\n * 1. `PAY_TO` env (optional override)\n * 2. Live address from Forge public API (when reachable)\n * 3. Baked-in fallback from the Forge PR\n */\nexport async function resolvePayTo(opts: {\n /** Baked-in address from Forge codegen (required fallback). */\n fallback: string;\n /** Optional explicit override (usually process.env.PAY_TO). */\n payTo?: string;\n forge?: ForgePayToSource;\n /** Fetch timeout ms. Defaults to 2500. */\n timeoutMs?: number;\n}): Promise<string> {\n const envOverride = process.env.PAY_TO?.trim();\n if (envOverride && !isZeroAddress(envOverride)) {\n return envOverride;\n }\n\n const explicit = opts.payTo?.trim();\n if (explicit && !isZeroAddress(explicit) && !opts.forge) {\n return explicit;\n }\n\n const baseUrl = pickForgeBaseUrl(opts.forge);\n if (baseUrl && opts.forge) {\n const url = `${baseUrl}/api/public/pay-to/${encodeURIComponent(opts.forge.owner)}/${encodeURIComponent(opts.forge.repo)}`;\n try {\n const controller = new AbortController();\n const timer = setTimeout(\n () => controller.abort(),\n opts.timeoutMs ?? 2500,\n );\n const res = await fetch(url, {\n signal: controller.signal,\n headers: { accept: \"application/json\" },\n });\n clearTimeout(timer);\n if (res.ok) {\n const json = (await res.json()) as { address?: string };\n if (json.address && !isZeroAddress(json.address)) {\n return json.address.trim();\n }\n }\n } catch (err) {\n console.warn(\"[forge] live payTo fetch failed, using fallback:\", err);\n }\n }\n\n if (explicit && !isZeroAddress(explicit)) return explicit;\n if (opts.fallback && !isZeroAddress(opts.fallback)) return opts.fallback;\n\n throw new Error(\n \"resolvePayTo: no usable address (set Forge wallet / PAY_TO, or re-run Forge PR)\",\n );\n}\n","/**\n * Merchant-side Forge surface status — public probes for deploy / go-live checks.\n */\n\nexport type ForgeHeartbeatState = {\n attempted: boolean;\n ok: boolean | null;\n at: string | null;\n error: string | null;\n};\n\nexport type ForgeSurfaceStatus = {\n ok: boolean;\n forge: true;\n version: string;\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n /** True when FORGE_API_KEY is set so /forge/fulfill is mounted. */\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n /** Env + fulfill ready — merchant can accept gateway fulfillment. */\n ready: boolean;\n heartbeat: ForgeHeartbeatState;\n endpoints: {\n health: string;\n status: string;\n wellKnown: string;\n fulfill: string;\n agent: string;\n };\n};\n\nconst PACKAGE_VERSION = \"0.1.8\";\n\nlet lastHeartbeat: ForgeHeartbeatState = {\n attempted: false,\n ok: null,\n at: null,\n error: null,\n};\n\nexport function recordHeartbeatResult(\n result: { ok: true } | { ok: false; error: string },\n): void {\n lastHeartbeat = {\n attempted: true,\n ok: result.ok,\n at: new Date().toISOString(),\n error: result.ok ? null : result.error,\n };\n}\n\nexport function getLastHeartbeat(): ForgeHeartbeatState {\n return { ...lastHeartbeat };\n}\n\nexport function buildForgeSurfaceStatus(opts: {\n handle: string | null;\n publicBaseUrl: string | null;\n gatewayUrl: string | null;\n fulfillMounted: boolean;\n fulfillPath: string;\n agentBasePath: string;\n skipPayment: boolean;\n actions: Array<{ name: string; path: string; price: string }>;\n}): ForgeSurfaceStatus {\n const fulfillPath = opts.fulfillPath.replace(/\\/$/, \"\") || \"/forge/fulfill\";\n const agentBasePath = opts.agentBasePath.replace(/\\/$/, \"\") || \"/agent\";\n const ready =\n opts.fulfillMounted &&\n Boolean(opts.publicBaseUrl) &&\n opts.actions.length > 0;\n\n return {\n ok: true,\n forge: true,\n version: PACKAGE_VERSION,\n handle: opts.handle,\n publicBaseUrl: opts.publicBaseUrl,\n gatewayUrl: opts.gatewayUrl,\n fulfillMounted: opts.fulfillMounted,\n fulfillPath,\n agentBasePath,\n skipPayment: opts.skipPayment,\n actions: opts.actions,\n ready,\n heartbeat: getLastHeartbeat(),\n endpoints: {\n health: \"/forge/health\",\n status: \"/forge/status\",\n wellKnown: \"/.well-known/clawcash.json\",\n fulfill: fulfillPath,\n agent: agentBasePath,\n },\n };\n}\n\nexport function buildWellKnownDocument(status: ForgeSurfaceStatus): {\n forge: true;\n version: string;\n health: string;\n status: string;\n handle: string | null;\n ready: boolean;\n} {\n return {\n forge: true,\n version: status.version,\n health: status.endpoints.health,\n status: status.endpoints.status,\n handle: status.handle,\n ready: status.ready,\n };\n}\n\nexport function forgeSdkVersion(): string {\n return PACKAGE_VERSION;\n}\n","import type { DefinedAgentService, SkillMeta } from \"./types.js\";\n\n/**\n * Generate a SKILL.md document for agents from defined Forge services.\n */\nexport function generateSkillMarkdown(\n services: DefinedAgentService[],\n meta: SkillMeta,\n): string {\n const base = meta.baseUrl.replace(/\\/$/, \"\");\n const lines: string[] = [\n `---`,\n `name: ${meta.name}`,\n `description: ${meta.description}`,\n `---`,\n ``,\n `# ${meta.name}`,\n ``,\n meta.description,\n ``,\n ];\n\n if (meta.homepage) {\n lines.push(`Homepage: ${meta.homepage}`, ``);\n }\n\n lines.push(\n `## How to use`,\n ``,\n `1. Read this skill.`,\n `2. Call the agent endpoint with a JSON body matching the input schema.`,\n `3. If you receive HTTP 402, pay via x402 (USDC) and retry with the payment header.`,\n `4. Use the returned output fields.`,\n ``,\n `## Services`,\n ``,\n );\n\n for (const service of services) {\n const path = `${base}/agent/${service.path}`;\n const price = service.payment.amount.startsWith(\"$\")\n ? service.payment.amount\n : `$${service.payment.amount}`;\n\n lines.push(\n `### \\`${service.name}\\``,\n ``,\n service.description,\n ``,\n `- **Method:** \\`POST\\``,\n `- **URL:** \\`${path}\\``,\n `- **Price:** ${price} ${service.payment.currency} via ${service.payment.protocols.join(\", \")}`,\n ``,\n `**Input**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Output**`,\n ``,\n \"```json\",\n JSON.stringify(\n Object.fromEntries(\n Object.entries(service.output).map(([k, t]) => [k, `<${t}>`]),\n ),\n null,\n 2,\n ),\n \"```\",\n ``,\n `**Example**`,\n ``,\n \"```bash\",\n `curl -X POST ${path} \\\\`,\n ` -H \"Content-Type: application/json\" \\\\`,\n ` -d '${JSON.stringify(\n Object.fromEntries(\n Object.entries(service.input).map(([k, t]) => [\n k,\n t === \"url\" ? \"https://example.com/image.png\" : `example-${k}`,\n ]),\n ),\n )}'`,\n \"```\",\n ``,\n );\n }\n\n return lines.join(\"\\n\");\n}\n"],"mappings":";AAOA,eAAsB,UAAa,SAA0C;AAC3E,QAAM,aAAa,QAAQ,cAAc;AACzC,QAAM,YAAY,QAAQ,aAAa;AACvC,QAAM,UAAU,KAAK,IAAI;AAEzB,aAAS;AACP,UAAM,QAAQ,MAAM,QAAQ,IAAI;AAChC,QAAI,QAAQ,cAAc,KAAK,GAAG;AAChC,aAAO;AAAA,IACT;AACA,QAAI,KAAK,IAAI,IAAI,WAAW,WAAW;AACrC,YAAM,IAAI,MAAM,6BAA6B,SAAS,IAAI;AAAA,IAC5D;AACA,UAAM,IAAI,QAAQ,CAAC,YAAY,WAAW,SAAS,UAAU,CAAC;AAAA,EAChE;AACF;AAEO,SAAS,gBAAqC;AACnD,SAAO;AAAA,IACL;AAAA,EACF;AACF;AAGO,SAAS,YAAY,MAAsB;AAChD,SAAO,KACJ,QAAQ,sBAAsB,OAAO,EACrC,QAAQ,MAAM,GAAG,EACjB,YAAY;AACjB;AAEO,SAAS,mBAId,QACsC;AACtC,MAAI,CAAC,OAAO,MAAM,KAAK,GAAG;AACxB,UAAM,IAAI,MAAM,sCAAsC;AAAA,EACxD;AACA,MAAI,CAAC,OAAO,SAAS;AACnB,UAAM,IAAI,MAAM,yCAAyC;AAAA,EAC3D;AAEA,SAAO;AAAA,IACL,GAAG;AAAA,IACH,SAAS;AAAA,IACT,MAAM,YAAY,OAAO,IAAI;AAAA,EAC/B;AACF;;;ACvDA,SAAS,UAAU,oBAAoB;AACvC,SAAS,mBAAmB,0BAA0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