@wasit-dev/cli 0.8.0-beta.1 → 0.8.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,850 @@
1
+ /**
2
+ * `wasit init`: a `wasit.config.json` for one paid route of a service its
3
+ * operator runs (spec C; W3-2 slices 2 and 3).
4
+ *
5
+ * Every answer is a flag, so the same command works in a script, in
6
+ * PowerShell and in cmd.exe: no answer needs shell quoting (a body comes from
7
+ * a file). The file is written by core's config writer, which takes only data
8
+ * that is certain and checks the result with the validator `wasit run` reads
9
+ * the file with (Najmi, 2026-11-15). What the writer is not given, this
10
+ * command fills from a fixed fallback table (init-skeleton-plan.md section 6),
11
+ * and says so: after writing it prints what it read from the service, what was
12
+ * given, what was filled in by default, and what was NOT read.
13
+ *
14
+ * Reading the route (C2, slice 3) is the default: one unpaid request with the
15
+ * route's method and body (and the `WASIT_HEADER_*` headers `wasit run` would
16
+ * send), one redirect inside the origin at most, no payment, no signature, no
17
+ * key. Its 402 tells x402 from MPP and fills in the protocol, the network, the
18
+ * pin (receiving address and asset) and an MPP channel. A route that answers
19
+ * 200, 500 or 503, or nothing, is said in plain words and nothing is written;
20
+ * `--no-read` writes the route from the flags alone, as x402 (slice 2).
21
+ *
22
+ * The testnet key setup (C4, slice 5, `init-keys.ts`) comes last, for a route
23
+ * on Stellar testnet: with `--setup-keys`, or a yes at a terminal. It writes the
24
+ * key the route's payment checks read into `.env` (never into the config, and
25
+ * never printed) after checking that git will not commit `.env`.
26
+ *
27
+ * Nothing is sent and nothing is written without `--operated-by-me`: Wasit
28
+ * tests only services their operator runs. Every flag is checked before the
29
+ * route is asked anything. An existing config is added to, never overwritten
30
+ * silently; `--force` replaces it. A route it already has exactly as given, in
31
+ * the same environment, is left as it is, byte for byte, and the run goes on
32
+ * (to the key setup): init can be run again on the same route. Mainnet is not written in this version, and
33
+ * nothing that could hold a secret is: an endpoint's headers are not written (a
34
+ * credential goes in `WASIT_HEADER_*`). What the service answered is data:
35
+ * printed through the sanitiser, never followed or run.
36
+ *
37
+ * `executeInit` does not call `process.exit` and does not read the process:
38
+ * the environment and the output are passed in, so it can be tested in-process.
39
+ */
40
+ import { readFileSync, writeFileSync } from "node:fs";
41
+ import path from "node:path";
42
+ import { ConfigError, ConfigWriteError, ConfigurationError, NETWORK_CLASSES, chooseOffer, deniedEnvValues, describeOffer, headersFromEnv, isLoopbackUrl, networkClass, parseConfig, readRoute, sanitizeText, writeConfigText, } from "@wasit-dev/core";
43
+ import { GITIGNORE_QUESTION, KEY_SETUP_NETWORK, keySetupQuestion, notSetUpLines, otherNetworkLines, setUpTestKeys, } from "./init-keys.js";
44
+ export const DEFAULT_CONFIG_FILE = "wasit.config.json";
45
+ /** The network written when none is given or read (the fallback table). */
46
+ const DEFAULT_NETWORK = "stellar:testnet";
47
+ /** The environment written for a URL on this machine when none is given. */
48
+ const DEFAULT_ENVIRONMENT = "local";
49
+ /** The readiness wait written when `--ready-timeout` is not given: the loader's own default (config.ts, readService). */
50
+ const DEFAULT_READY_TIMEOUT_SECONDS = 60;
51
+ /** The loader's rule for an endpoint or environment name (config.ts, NAME). */
52
+ const NAME = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
53
+ const HTTP_METHODS = ["GET", "HEAD", "POST", "PUT", "PATCH", "DELETE", "OPTIONS"];
54
+ /** How often init asks for the method at a terminal before it takes the last answer and refuses it (exit 2). */
55
+ const METHOD_ATTEMPTS = 3;
56
+ const PROTOCOLS = ["x402", "mpp-charge", "mpp-channel"];
57
+ /** The most offers printed: the rest is counted. */
58
+ const MAX_OFFER_LINES = 10;
59
+ const NO_READ_HINT = "To write the route without reading it, run this again with --no-read.";
60
+ /** A refusal: printed, exit 2, nothing written. */
61
+ class InitRefusal extends Error {
62
+ }
63
+ function refuse(message) {
64
+ throw new InitRefusal(message);
65
+ }
66
+ /** A value for a message: one line, no control characters, bounded, quoted. */
67
+ function shown(value) {
68
+ const text = sanitizeText(String(value)).replace(/\s+/g, " ");
69
+ return JSON.stringify(text.length > 80 ? `${text.slice(0, 77)}...` : text);
70
+ }
71
+ function testNetworks() {
72
+ return [...NETWORK_CLASSES]
73
+ .filter(([, kind]) => kind === "test")
74
+ .map(([network]) => network)
75
+ .join(", ");
76
+ }
77
+ function errorCode(error) {
78
+ const code = error?.code;
79
+ return typeof code === "string" ? code : "an error";
80
+ }
81
+ /** Words of a query parameter's name that say it carries a credential (`api_key`, `access_token`, `X-Amz-Signature`, `sig`). */
82
+ const CREDENTIAL_WORDS = new Set([
83
+ "key",
84
+ "apikey",
85
+ "token",
86
+ "secret",
87
+ "password",
88
+ "passwd",
89
+ "pwd",
90
+ "auth",
91
+ "authorization",
92
+ "credential",
93
+ "credentials",
94
+ "signature",
95
+ "sig",
96
+ "session",
97
+ "sessionid",
98
+ "sid",
99
+ "cookie",
100
+ "jwt",
101
+ "bearer",
102
+ ]);
103
+ /** The loader's pattern for a key that names a secret (config.ts, FORBIDDEN_KEYS), on a name with its separators removed. */
104
+ const SECRET_NAME = /secret|privatekey|payerkey|commitment|passw|mnemonic|seed|apikey|accesskey|token|credential|signingkey|signer/;
105
+ /**
106
+ * The first query parameter of `url` named like a credential, or undefined.
107
+ * The config is committed and its paths are printed in reports, so such a
108
+ * query is not written. Only the name is read, never the value.
109
+ */
110
+ function credentialParameter(url) {
111
+ for (const name of url.searchParams.keys()) {
112
+ const words = name
113
+ .replace(/([a-z0-9])([A-Z])/g, "$1 $2")
114
+ .toLowerCase()
115
+ .split(/[^a-z0-9]+/)
116
+ .filter((word) => word !== "");
117
+ if (words.some((word) => CREDENTIAL_WORDS.has(word)) || SECRET_NAME.test(words.join("")))
118
+ return name;
119
+ }
120
+ return undefined;
121
+ }
122
+ /** The route's URL: http(s), no credentials, no fragment. The value typed is never echoed: it may hold a credential. */
123
+ function routeUrl(value) {
124
+ if (value === undefined || value.trim() === "") {
125
+ refuse("--url is required: the URL of one paid route of your service, e.g. --url http://127.0.0.1:3000/api/weather. " +
126
+ "Nothing was written.");
127
+ }
128
+ let url;
129
+ try {
130
+ url = new URL(value);
131
+ }
132
+ catch {
133
+ refuse("--url is not an absolute URL: include the scheme, e.g. http://127.0.0.1:3000/api/weather. Nothing was written.");
134
+ }
135
+ if (url.protocol !== "http:" && url.protocol !== "https:") {
136
+ refuse("--url must be an http or https URL. Nothing was written.");
137
+ }
138
+ if (url.username !== "" || url.password !== "") {
139
+ refuse("--url carries credentials (user:password@). The config is committed and its URLs are printed in reports: " +
140
+ "send a credential in a WASIT_HEADER_* variable instead. Nothing was written.");
141
+ }
142
+ if (url.hash !== "") {
143
+ refuse("--url carries a fragment (#...), which is never sent to a service. Leave it out. Nothing was written.");
144
+ }
145
+ const parameter = credentialParameter(url);
146
+ if (parameter !== undefined) {
147
+ refuse(`--url carries the query parameter ${shown(parameter)}, which is named like a credential. The config is committed ` +
148
+ "and its paths are printed in reports: send a credential in a WASIT_HEADER_* variable instead. Nothing was sent " +
149
+ "and nothing was written.");
150
+ }
151
+ return url;
152
+ }
153
+ /** The last part of the path, when it is a valid name: `/api/weather` gives `weather`. */
154
+ function nameFromPath(pathname) {
155
+ const last = pathname.split("/").filter((part) => part !== "").at(-1);
156
+ return last !== undefined && NAME.test(last) ? last : undefined;
157
+ }
158
+ function readJsonFile(file, flag, cwd) {
159
+ let text;
160
+ try {
161
+ text = readFileSync(path.resolve(cwd, file), "utf-8");
162
+ }
163
+ catch (error) {
164
+ refuse(`${flag}: cannot read ${shown(file)} (${errorCode(error)}). Nothing was written.`);
165
+ }
166
+ const source = text.charCodeAt(0) === 0xfeff ? text.slice(1) : text;
167
+ try {
168
+ return JSON.parse(source);
169
+ }
170
+ catch {
171
+ refuse(`${flag}: ${shown(file)} is not JSON. The body is written into the config as a JSON value. Nothing was written.`);
172
+ }
173
+ }
174
+ function rejectHeaders(values) {
175
+ if (values.length === 0)
176
+ return undefined;
177
+ const headers = {};
178
+ for (const value of values) {
179
+ const separator = value.indexOf(":");
180
+ if (separator < 1)
181
+ refuse(`--reject-header ${shown(value)} is not "Name: value". Nothing was written.`);
182
+ headers[value.slice(0, separator).trim()] = value.slice(separator + 1).trim();
183
+ }
184
+ return headers;
185
+ }
186
+ /** The file at the destination, as text, or undefined when there is none. */
187
+ function existingText(file) {
188
+ try {
189
+ return readFileSync(file, "utf-8");
190
+ }
191
+ catch (error) {
192
+ if (errorCode(error) === "ENOENT")
193
+ return undefined;
194
+ refuse(`cannot read the config ${shown(file)} (${errorCode(error)}). Nothing was written.`);
195
+ }
196
+ }
197
+ /**
198
+ * The environment the file already has under `name`, as the loader reads it
199
+ * and as the file writes it. A file that is not a valid config is refused here,
200
+ * before the route is asked anything, in the writer's words.
201
+ */
202
+ function existingEnvironment(text, name) {
203
+ if (text === undefined)
204
+ return undefined;
205
+ let parsed;
206
+ try {
207
+ parsed = parseConfig(text).environments[name];
208
+ }
209
+ catch (error) {
210
+ const why = error instanceof ConfigError ? error.message : "it is not valid JSON";
211
+ refuse(`The config already there is not valid, so init does not change it (${sanitizeText(why).replace(/\s+/g, " ")}). ` +
212
+ "Fix it, or replace it (--force). Nothing was sent and nothing was written.");
213
+ }
214
+ if (parsed === undefined)
215
+ return undefined;
216
+ const raw = JSON.parse(text.charCodeAt(0) === 0xfeff ? text.slice(1) : text);
217
+ return { parsed, rawBaseUrl: raw.environments[name].baseUrl };
218
+ }
219
+ /**
220
+ * The environment, the endpoint's path, and what became of the pin. A new
221
+ * environment's base URL is the route's origin, and it takes the pin read
222
+ * from the route. An environment the file already has is used as it is: the
223
+ * route must be under its base URL and on its network, its pin (or the lack of
224
+ * one) stays, and a route that pays another address than it pins is refused.
225
+ */
226
+ function environmentFor(name, url, network, pin, existing) {
227
+ const full = url.origin + url.pathname + url.search;
228
+ if (existing === undefined) {
229
+ return {
230
+ environment: { name, baseUrl: url.origin, network, operatedByMe: true, ...(pin === undefined ? {} : { pinned: pin }) },
231
+ path: url.pathname + url.search,
232
+ ...(pin === undefined ? {} : { pinLine: `pinned: payTo ${pin.payTo}, asset ${pin.asset} (wasit run pays only these)` }),
233
+ };
234
+ }
235
+ const { parsed, rawBaseUrl } = existing;
236
+ if (!full.startsWith(`${parsed.baseUrl}/`)) {
237
+ refuse(`The config already has the environment ${shown(name)} with the base URL ${shown(parsed.baseUrl)}, and this ` +
238
+ `route is not under it. Name another environment (--env), or replace the file (--force). Nothing was written.`);
239
+ }
240
+ if (parsed.operatedByMe !== true) {
241
+ refuse(`The config already has the environment ${shown(name)} without operatedByMe true, and init does not change it. ` +
242
+ `Name another environment (--env), or replace the file (--force). Nothing was written.`);
243
+ }
244
+ if (parsed.network !== network) {
245
+ refuse(`The config already has the environment ${shown(name)} on ${shown(parsed.network)}, and this route is written ` +
246
+ `on ${shown(network)}. Name another environment (--env), or replace the file (--force). Nothing was written.`);
247
+ }
248
+ let pinLine;
249
+ if (parsed.pinned !== undefined) {
250
+ if (pin !== undefined && (pin.payTo !== parsed.pinned.payTo || pin.asset !== parsed.pinned.asset)) {
251
+ refuse(`The config's environment ${shown(name)} pins payTo ${shown(parsed.pinned.payTo)} and asset ` +
252
+ `${shown(parsed.pinned.asset)}, and this route asks to be paid to ${shown(pin.payTo)} in ${shown(pin.asset)}. ` +
253
+ "init does not change a pin: name another environment (--env), or replace the file (--force). Nothing was written.");
254
+ }
255
+ pinLine = `pin: the environment's own (payTo ${parsed.pinned.payTo}, asset ${parsed.pinned.asset})`;
256
+ }
257
+ else if (pin !== undefined) {
258
+ pinLine = `no pin added: the environment ${name} is in the config without one, and init does not change it`;
259
+ }
260
+ return {
261
+ environment: {
262
+ name,
263
+ baseUrl: rawBaseUrl,
264
+ network: parsed.network,
265
+ operatedByMe: true,
266
+ ...(parsed.pinned === undefined ? {} : { pinned: parsed.pinned }),
267
+ },
268
+ path: full.slice(parsed.baseUrl.length),
269
+ ...(pinLine === undefined ? {} : { pinLine }),
270
+ };
271
+ }
272
+ function serviceFor(options, url, account) {
273
+ if (options.start === undefined) {
274
+ if (options.readyUrl !== undefined || options.readyTimeout !== undefined) {
275
+ refuse(`${options.readyUrl !== undefined ? "--ready-url" : "--ready-timeout"} is for the wait after the service starts: ` +
276
+ "give the command that starts it as well (--start). Nothing was written.");
277
+ }
278
+ return undefined;
279
+ }
280
+ account.given.push(`start: ${options.start}`);
281
+ let readyUrl;
282
+ if (options.readyUrl !== undefined) {
283
+ readyUrl = options.readyUrl;
284
+ account.given.push(`ready url: ${readyUrl}`);
285
+ }
286
+ else if (isLoopbackUrl(url.href)) {
287
+ readyUrl = url.href;
288
+ account.defaulted.push(`ready url: ${readyUrl} (the route's own URL)`);
289
+ }
290
+ else {
291
+ refuse("--start needs --ready-url when the route is not on this machine: the address on this machine (localhost, " +
292
+ "127.x.x.x or [::1]) the run waits for after starting the service. Nothing was written.");
293
+ }
294
+ let timeoutSeconds = DEFAULT_READY_TIMEOUT_SECONDS;
295
+ if (options.readyTimeout !== undefined) {
296
+ const value = Number(options.readyTimeout);
297
+ if (!/^\d+$/.test(options.readyTimeout) || value < 1 || value > 600) {
298
+ refuse("--ready-timeout must be a whole number of seconds from 1 to 600. Nothing was written.");
299
+ }
300
+ timeoutSeconds = value;
301
+ account.given.push(`ready timeout: ${timeoutSeconds} s`);
302
+ }
303
+ else {
304
+ account.defaulted.push(`ready timeout: ${timeoutSeconds} s`);
305
+ }
306
+ return { start: options.start, ready: { url: readyUrl, timeoutSeconds } };
307
+ }
308
+ function rejectFor(options, cwd, account) {
309
+ const headers = rejectHeaders(options.rejectHeader);
310
+ const body = options.rejectBodyFile === undefined ? undefined : readJsonFile(options.rejectBodyFile, "--reject-body-file", cwd);
311
+ if (headers === undefined && body === undefined) {
312
+ if (options.rejectNote !== undefined) {
313
+ refuse("--reject-note describes the request the route must refuse: give --reject-header or --reject-body-file. Nothing was written.");
314
+ }
315
+ return undefined;
316
+ }
317
+ account.given.push(`request to refuse: ${[
318
+ ...(headers === undefined ? [] : [`headers ${Object.keys(headers).join(", ")}`]),
319
+ ...(body === undefined ? [] : [`body from ${options.rejectBodyFile}`]),
320
+ ].join(" and ")}`);
321
+ return {
322
+ ...(headers === undefined ? {} : { headers }),
323
+ ...(body === undefined ? {} : { body }),
324
+ ...(options.rejectNote === undefined ? {} : { note: options.rejectNote }),
325
+ };
326
+ }
327
+ /** `--protocol` and `--network`, checked before anything is sent. */
328
+ function wantedFlags(options) {
329
+ if (options.protocol !== undefined && !PROTOCOLS.includes(options.protocol)) {
330
+ refuse(`--protocol ${shown(options.protocol)} is not one of ${PROTOCOLS.join(", ")}. Nothing was written.`);
331
+ }
332
+ if (options.network !== undefined) {
333
+ const kind = networkClass(options.network);
334
+ if (kind !== "test") {
335
+ refuse(`--network ${shown(options.network)} is ${kind === "mainnet-optin" ? "Stellar mainnet, which init does not write in this version" : "not on Wasit's list of test networks"}. ` +
336
+ `init writes one of: ${testNetworks()}. Nothing was written.`);
337
+ }
338
+ }
339
+ return {
340
+ ...(options.protocol === undefined ? {} : { protocol: options.protocol }),
341
+ ...(options.network === undefined ? {} : { network: options.network }),
342
+ };
343
+ }
344
+ /** The network of an x402 route whose network was not read: the flag, the environment's, or the default. */
345
+ function unreadNetwork(options, existing, environmentName, account, why) {
346
+ if (options.network !== undefined) {
347
+ account.given.push(`network: ${options.network}`);
348
+ return options.network;
349
+ }
350
+ if (existing !== undefined) {
351
+ account.defaulted.push(`network: ${existing.parsed.network} (the environment ${environmentName} in the config is on it)`);
352
+ return existing.parsed.network;
353
+ }
354
+ account.defaulted.push(`network: ${DEFAULT_NETWORK} (default; ${why})`);
355
+ return DEFAULT_NETWORK;
356
+ }
357
+ /** `--no-read` (slice 2): no request; x402 on the network the flags, the environment or the default give. */
358
+ function routeFromFlags(options, url, existing, environmentName, account) {
359
+ if (options.protocol !== undefined && options.protocol !== "x402") {
360
+ refuse("Without reading the route (--no-read), init writes x402 only: an MPP route is written from its challenge. " +
361
+ "Leave out --no-read. Nothing was written.");
362
+ }
363
+ account.given.push("read the route: no (--no-read)");
364
+ const network = unreadNetwork(options, existing, environmentName, account, "init does not read the network from your service");
365
+ if (options.protocol === undefined)
366
+ account.defaulted.push("protocol: x402 (without reading the route, init writes x402 only)");
367
+ else
368
+ account.given.push("protocol: x402");
369
+ account.notRead.push("whether the route answers 402, and its protocol, network, price, asset and receiving address: " +
370
+ "wasit run --read-only reads them");
371
+ return { protocol: "x402", network, url };
372
+ }
373
+ function offerLines(label, offers, room) {
374
+ const lines = offers.slice(0, Math.max(0, room)).map((offer) => `${label}: ${describeOffer(offer)}`);
375
+ const more = offers.length - lines.length;
376
+ return more > 0 ? [...lines, `${label}: ${more} more`] : lines;
377
+ }
378
+ /** Why a status that is not 402 is not a paywall, in plain words. */
379
+ function statusMessage(status) {
380
+ if (status === 200)
381
+ return "The paywall is not switched on: the route answered 200 without asking for payment.";
382
+ if (status === 500 || status === 503) {
383
+ return (`The paywall is not switched on or is misconfigured: the route answered ${status} instead of 402. A missing ` +
384
+ "payee or facilitator setting often answers this way: check the service's payment settings and its log.");
385
+ }
386
+ const hint = status === 404
387
+ ? ": check the path, and the method (--method)"
388
+ : status === 405
389
+ ? ": check the method (--method)"
390
+ : status === 401 || status === 403
391
+ ? ": it may need a credential, which init sends from a WASIT_HEADER_<NAME> variable, as wasit run does"
392
+ : "";
393
+ return `The route answered ${status}, not 402${hint}.`;
394
+ }
395
+ /** Slice 3: one unpaid request, and the way to pay its 402 offers. */
396
+ async function routeFromReading(options, context, url, method, body, existing, environmentName, wanted, account) {
397
+ let headers;
398
+ try {
399
+ headers = headersFromEnv(context.env);
400
+ }
401
+ catch (error) {
402
+ if (error instanceof ConfigError)
403
+ refuse(`${error.message} Nothing was sent and nothing was written.`);
404
+ throw error;
405
+ }
406
+ const headerNames = Object.keys(headers);
407
+ const sent = `${method} ${url.href}`;
408
+ let reading;
409
+ try {
410
+ reading = await readRoute(url.href, {
411
+ method,
412
+ ...(body === undefined ? {} : { body: typeof body === "string" ? body : JSON.stringify(body) }),
413
+ ...(headerNames.length === 0 ? {} : { headers }),
414
+ }, context.readTimeoutMs === undefined ? {} : { timeoutMs: context.readTimeoutMs });
415
+ }
416
+ catch (error) {
417
+ if (error instanceof ConfigurationError)
418
+ refuse(`${error.message} Nothing was written.`);
419
+ throw error;
420
+ }
421
+ switch (reading.kind) {
422
+ case "unreachable":
423
+ refuse(`init sent ${sent} and got no answer. ${reading.message} Start the service and run this again. ${NO_READ_HINT} Nothing was written.`);
424
+ case "redirect":
425
+ refuse(`init sent ${sent}. ${reading.message} Nothing was written.`);
426
+ case "status":
427
+ refuse(`init sent ${sent}. ${statusMessage(reading.status)} Nothing was written. ${NO_READ_HINT}`);
428
+ case "unreadable":
429
+ refuse([
430
+ `init sent ${sent}. The route answered 402, and init could not read how it asks to be paid:`,
431
+ ...reading.notes.map((note) => ` ${note}`),
432
+ `${NO_READ_HINT} It is then written as x402, and wasit run --read-only reports what it finds. Nothing was written.`,
433
+ ].join("\n"));
434
+ default:
435
+ break;
436
+ }
437
+ account.read.push(`one unpaid request: ${sent}` +
438
+ `${headerNames.length === 0 ? "" : ` with the WASIT_HEADER_* headers ${headerNames.join(", ")} (values not shown)`}` +
439
+ "; nothing was paid or signed");
440
+ const answered = new URL(reading.url);
441
+ if (answered.href !== url.href) {
442
+ const parameter = credentialParameter(answered);
443
+ if (parameter !== undefined) {
444
+ refuse(`init sent ${sent}. The route redirected once inside its origin, to a URL whose query carries the parameter ` +
445
+ `${shown(parameter)}, which is named like a credential: init does not write it into the config, which is ` +
446
+ "committed. Nothing was written.");
447
+ }
448
+ account.read.push(`the route redirected once inside its origin, to ${answered.pathname}${answered.search}: init wrote that path`);
449
+ }
450
+ if (wanted.protocol !== undefined)
451
+ account.given.push(`protocol: ${wanted.protocol}`);
452
+ if (reading.kind === "x402-v1") {
453
+ if (wanted.protocol !== undefined && wanted.protocol !== "x402") {
454
+ refuse(`init sent ${sent}. The route answered with an x402 v1 challenge, not ${wanted.protocol}. Nothing was written.`);
455
+ }
456
+ account.read.push("answer: 402 with an x402 v1 challenge in the body. Wasit grades x402 v2 only: wasit run reports this route " +
457
+ "as unsupported, not failed, and says how to move it to v2", "written: protocol x402");
458
+ const network = unreadNetwork(options, existing, environmentName, account, "init does not read the network from an x402 v1 challenge");
459
+ return { protocol: "x402", network, url: answered };
460
+ }
461
+ // A network the environment in the file is on chooses among the offers, when the route offers it.
462
+ const envNetwork = existing?.parsed.network;
463
+ const network = wanted.network ?? (envNetwork !== undefined && reading.offers.some((offer) => offer.network === envNetwork) ? envNetwork : undefined);
464
+ const choice = chooseOffer(reading.offers, { ...(wanted.protocol === undefined ? {} : { protocol: wanted.protocol }), ...(network === undefined ? {} : { network }) });
465
+ if (!choice.ok) {
466
+ refuse([
467
+ `init sent ${sent}. ${choice.reason}`,
468
+ ...offerLines(" offered", reading.offers, MAX_OFFER_LINES),
469
+ "Nothing was written.",
470
+ ].join("\n"));
471
+ }
472
+ if (wanted.network !== undefined)
473
+ account.given.push(`network: ${wanted.network}`);
474
+ const headersSeen = [
475
+ ...(reading.offers.some((offer) => offer.protocol === "x402") ? ["a PAYMENT-REQUIRED header (x402)"] : []),
476
+ ...(reading.offers.some((offer) => offer.protocol !== "x402") ? ["a WWW-Authenticate challenge (MPP)"] : []),
477
+ ];
478
+ account.read.push(`answer: 402 with ${headersSeen.join(" and ")}`, ...offerLines("offered", choice.offers, MAX_OFFER_LINES), ...offerLines("also offered, not written", choice.left, MAX_OFFER_LINES - choice.offers.length), ...reading.notes.map((note) => `note: ${note}`), `written: protocol ${choice.protocol}, network ${choice.network}`, ...(choice.channel === undefined ? [] : [`channel: ${choice.channel}`]), ...(choice.noPin === undefined ? [] : [`no pin: ${choice.noPin}`]));
479
+ return {
480
+ protocol: choice.protocol,
481
+ network: choice.network,
482
+ url: answered,
483
+ ...(choice.pin === undefined ? {} : { pin: choice.pin }),
484
+ ...(choice.channel === undefined ? {} : { channel: choice.channel }),
485
+ };
486
+ }
487
+ /** The shortest value of a secret variable the file check looks for: a shorter one would match by chance. */
488
+ const MIN_SECRET_LENGTH = 8;
489
+ /**
490
+ * Whether the new text holds the value of a variable Wasit keeps secret (a
491
+ * key, a `WASIT_HEADER_*` value, `WASIT_RPC_URL`) that the file did not hold
492
+ * before. The config is committed: a value of those must never reach it, from
493
+ * a flag or from the route's challenge.
494
+ */
495
+ function writesSecret(text, before, env) {
496
+ return deniedEnvValues(env).some((value) => {
497
+ if (value.length < MIN_SECRET_LENGTH)
498
+ return false;
499
+ const escaped = JSON.stringify(value).slice(1, -1);
500
+ return [value, escaped].some((form) => text.includes(form) && !(before ?? "").includes(form));
501
+ });
502
+ }
503
+ /** The flags a non-interactive run is missing, or the questions an interactive one asks: C1 and C5. */
504
+ async function completeAnswers(options, context) {
505
+ const ask = context.ask;
506
+ if (ask === undefined) {
507
+ if (options.url === undefined && !options.operatedByMe) {
508
+ refuse("--url is required (the URL of one paid route, e.g. --url http://127.0.0.1:3000/api/weather), and so is " +
509
+ "--operated-by-me: Wasit tests only services their operator runs. init asks nothing when it is not at a " +
510
+ "terminal. Nothing was written.");
511
+ }
512
+ return options;
513
+ }
514
+ const answer = async (question) => {
515
+ try {
516
+ return (await ask(question)).trim();
517
+ }
518
+ catch {
519
+ refuse("init was asking, and the input ended. Nothing was sent and nothing was written.");
520
+ }
521
+ };
522
+ let url = options.url;
523
+ if (url === undefined)
524
+ url = await answer("URL of one paid route of your service (e.g. http://127.0.0.1:3000/api/weather): ");
525
+ let operatedByMe = options.operatedByMe;
526
+ if (!operatedByMe) {
527
+ const reply = (await answer("Do you operate this service? Wasit tests only services their operator runs (yes/no): ")).toLowerCase();
528
+ operatedByMe = reply === "yes" || reply === "y";
529
+ }
530
+ // A URL that is not usable, or a service that is not theirs: no more questions; the main path refuses in its own words.
531
+ if (!operatedByMe)
532
+ return { ...options, ...(url === undefined || url === "" ? {} : { url }), operatedByMe };
533
+ routeUrl(url === "" ? undefined : url);
534
+ let method = options.method;
535
+ if (method === undefined) {
536
+ // A method that is not one of ours is asked again, a few times: a typo costs a retry, not the whole run.
537
+ let question = "HTTP method of the route [GET]: ";
538
+ for (let attempt = 1; attempt <= METHOD_ATTEMPTS; attempt += 1) {
539
+ const reply = await answer(question);
540
+ if (reply === "")
541
+ break;
542
+ method = reply;
543
+ if (HTTP_METHODS.includes(reply.toUpperCase()))
544
+ break;
545
+ // The last try is wrong too: refuse here, in the main path's words, before any other question.
546
+ if (attempt === METHOD_ATTEMPTS)
547
+ refuse(`--method ${shown(reply)} is not one of ${HTTP_METHODS.join(", ")}. Nothing was written.`);
548
+ question = `${shown(reply)} is not one of ${HTTP_METHODS.join(", ")}. HTTP method of the route [GET]: `;
549
+ }
550
+ }
551
+ let bodyFile = options.bodyFile;
552
+ if (bodyFile === undefined && method !== undefined && !["GET", "HEAD"].includes(method.toUpperCase())) {
553
+ const reply = await answer("JSON file with the request body (empty for none): ");
554
+ if (reply !== "")
555
+ bodyFile = reply;
556
+ }
557
+ let env = options.env;
558
+ if (env === undefined && url !== "") {
559
+ let loopback = true;
560
+ try {
561
+ loopback = isLoopbackUrl(new URL(url).href);
562
+ }
563
+ catch {
564
+ // routeUrl refuses a URL that does not parse, in its own words.
565
+ }
566
+ if (!loopback) {
567
+ const reply = await answer("Name for this environment (e.g. staging): ");
568
+ if (reply !== "")
569
+ env = reply;
570
+ }
571
+ }
572
+ let start = options.start;
573
+ if (start === undefined) {
574
+ const reply = await answer("Command that starts the service for wasit run --start (empty for none): ");
575
+ if (reply !== "")
576
+ start = reply;
577
+ }
578
+ return {
579
+ ...options,
580
+ ...(url === undefined || url === "" ? {} : { url }),
581
+ operatedByMe,
582
+ ...(method === undefined ? {} : { method }),
583
+ ...(bodyFile === undefined ? {} : { bodyFile }),
584
+ ...(env === undefined ? {} : { env }),
585
+ ...(start === undefined ? {} : { start }),
586
+ };
587
+ }
588
+ /** A yes or a no at the terminal, before the config is written: input that ends is a refusal. */
589
+ async function askYes(ask, question) {
590
+ let reply;
591
+ try {
592
+ reply = await ask(question);
593
+ }
594
+ catch {
595
+ refuse("init was asking, and the input ended. Nothing was written.");
596
+ }
597
+ const word = reply.trim().toLowerCase();
598
+ return word === "yes" || word === "y";
599
+ }
600
+ /**
601
+ * Whether the key setup runs for a route on the key setup's network: the flag,
602
+ * else the answer at a terminal (C1 step 8), else no (C5).
603
+ */
604
+ async function keySetupWanted(options, context, protocol, account) {
605
+ if (options.setupKeys === true) {
606
+ account.given.push("key setup: yes (--setup-keys)");
607
+ return { run: true, why: "--setup-keys" };
608
+ }
609
+ if (options.setupKeys === false) {
610
+ account.given.push("key setup: no (--no-setup-keys)");
611
+ return { run: false, why: "--no-setup-keys" };
612
+ }
613
+ if (context.ask === undefined) {
614
+ return { run: false, why: "init sets one up only with --setup-keys, or a yes at a terminal" };
615
+ }
616
+ const yes = await askYes(context.ask, keySetupQuestion(protocol));
617
+ account.given.push(`key setup: ${yes ? "yes" : "no"} (your answer)`);
618
+ return { run: yes, why: yes ? "your answer" : "you said no" };
619
+ }
620
+ /** A path for the next command: quoted when it has a space, which both PowerShell and cmd.exe read. */
621
+ function commandArgument(value) {
622
+ return /\s/.test(value) ? `"${value}"` : value;
623
+ }
624
+ /**
625
+ * Runs `wasit init`. Returns the exit code: 0 the file has the route (written
626
+ * now, or already there as given and left as it is); 2 nothing was written (a
627
+ * flag is missing or wrong, the service is not yours, the route is not a
628
+ * paywall init can read, or the writer refused the data). The key setup runs
629
+ * after the file is written and never changes the exit code: what
630
+ * it could not do is in its status table, with the command that finishes it
631
+ * (Najmi, 2026-11-27).
632
+ */
633
+ export async function executeInit(given, context) {
634
+ // A key the key setup makes is added here: no printed line may carry it.
635
+ const secrets = [...deniedEnvValues(context.env)];
636
+ const clean = (line) => sanitizeText(line, { redact: secrets });
637
+ const cwd = context.cwd ?? process.cwd();
638
+ try {
639
+ const options = await completeAnswers(given, context);
640
+ const url = routeUrl(options.url);
641
+ if (!options.operatedByMe) {
642
+ refuse(`Wasit tests only services their operator runs. If you operate the service at ${url.origin}, run this again ` +
643
+ "with --operated-by-me. Nothing was sent and nothing was written.");
644
+ }
645
+ const account = {
646
+ read: [],
647
+ given: [`url: ${url.href}`, "operated by you: yes (--operated-by-me)"],
648
+ defaulted: [],
649
+ notRead: [],
650
+ };
651
+ const method = (options.method ?? "GET").toUpperCase();
652
+ if (!HTTP_METHODS.includes(method)) {
653
+ refuse(`--method ${shown(options.method)} is not one of ${HTTP_METHODS.join(", ")}. Nothing was written.`);
654
+ }
655
+ if (options.method === undefined)
656
+ account.defaulted.push("method: GET");
657
+ else
658
+ account.given.push(`method: ${method}`);
659
+ const body = options.bodyFile === undefined ? undefined : readJsonFile(options.bodyFile, "--body-file", cwd);
660
+ if (body !== undefined) {
661
+ if (method === "GET" || method === "HEAD") {
662
+ refuse(`A request body cannot be sent with ${method}: name the method the route uses, e.g. --method POST. Nothing was written.`);
663
+ }
664
+ account.given.push(`body: from ${options.bodyFile}`);
665
+ }
666
+ let name;
667
+ if (options.name !== undefined) {
668
+ if (!NAME.test(options.name)) {
669
+ refuse("--name must be 1 to 64 letters, digits, dots, underscores or hyphens, starting with a letter or digit. Nothing was written.");
670
+ }
671
+ name = options.name;
672
+ account.given.push(`name: ${name}`);
673
+ }
674
+ else {
675
+ const derived = nameFromPath(url.pathname);
676
+ if (derived === undefined) {
677
+ refuse("init could not take a name from the route's path: give one with --name (1 to 64 letters, digits, dots, " +
678
+ "underscores or hyphens). Nothing was written.");
679
+ }
680
+ name = derived;
681
+ account.defaulted.push(`name: ${name} (from the path)`);
682
+ }
683
+ let environmentName;
684
+ if (options.env !== undefined) {
685
+ if (!NAME.test(options.env)) {
686
+ refuse("--env must be 1 to 64 letters, digits, dots, underscores or hyphens, starting with a letter or digit. Nothing was written.");
687
+ }
688
+ environmentName = options.env;
689
+ account.given.push(`environment: ${environmentName}`);
690
+ }
691
+ else if (isLoopbackUrl(url.href)) {
692
+ environmentName = DEFAULT_ENVIRONMENT;
693
+ account.defaulted.push(`environment: ${environmentName} (the URL is on this machine)`);
694
+ }
695
+ else {
696
+ refuse("The route is not on this machine: name its environment with --env, e.g. --env staging. Nothing was written.");
697
+ }
698
+ const service = serviceFor(options, url, account);
699
+ const reject = rejectFor(options, cwd, account);
700
+ const wanted = wantedFlags(options);
701
+ const configPath = path.resolve(cwd, options.config);
702
+ const before = existingText(configPath);
703
+ const existing = options.force ? undefined : existingEnvironment(before, environmentName);
704
+ // Every flag has been checked: only now is the route asked anything.
705
+ const route = options.read
706
+ ? await routeFromReading(options, context, url, method, body, existing, environmentName, wanted, account)
707
+ : routeFromFlags(options, url, existing, environmentName, account);
708
+ if (route.protocol !== "x402") {
709
+ if (method !== "GET") {
710
+ refuse(`The route answers with an MPP challenge, and wasit run sends an MPP endpoint a plain GET in this version: ` +
711
+ `this route was read with ${method}. Nothing was written.`);
712
+ }
713
+ if (reject !== undefined) {
714
+ refuse("--reject-header and --reject-body-file are for x402 (X402-11): an MPP endpoint has no request to refuse. Nothing was written.");
715
+ }
716
+ if (Object.keys(headersFromEnv(context.env)).length > 0) {
717
+ account.notRead.push("wasit run sends an MPP endpoint a plain GET without headers: while a WASIT_HEADER_* variable is set, it sends this endpoint nothing");
718
+ }
719
+ if (route.protocol === "mpp-channel") {
720
+ account.notRead.push("the channel's on-chain terms (expect: token, from, to, refundWaitingPeriod), which its challenge does not carry");
721
+ }
722
+ }
723
+ else if (reject === undefined) {
724
+ account.notRead.push("a request this route must refuse: X402-11 runs only with one (--reject-header or --reject-body-file)");
725
+ }
726
+ const { environment, path: endpointPath, pinLine } = environmentFor(environmentName, route.url, route.network, route.pin, existing);
727
+ if (pinLine !== undefined)
728
+ account.read.push(pinLine);
729
+ const endpoint = {
730
+ name,
731
+ protocol: route.protocol,
732
+ path: endpointPath,
733
+ method,
734
+ ...(body === undefined ? {} : { body }),
735
+ ...(reject === undefined ? {} : { reject }),
736
+ ...(route.channel === undefined ? {} : { channel: route.channel }),
737
+ };
738
+ let result;
739
+ try {
740
+ result = writeConfigText({ environment, endpoints: [endpoint], ...(service === undefined ? {} : { service }) }, { ...(before === undefined ? {} : { existing: before }), replace: options.force });
741
+ }
742
+ catch (error) {
743
+ if (error instanceof ConfigWriteError)
744
+ refuse(error.message);
745
+ throw error;
746
+ }
747
+ if (writesSecret(result.text, before, context.env)) {
748
+ refuse("init would write the value of a variable Wasit keeps secret (a key, a WASIT_HEADER_* value or WASIT_RPC_URL) " +
749
+ "into the config, which is committed. It came from a flag (--start, --reject-header, a body file) or from " +
750
+ "the route's challenge. Nothing was written.");
751
+ }
752
+ // C1 step 8: asked after the read, when the network is known, and before anything is written.
753
+ const keyStep = route.network === KEY_SETUP_NETWORK ? await keySetupWanted(options, context, route.protocol, account) : undefined;
754
+ if (keyStep === undefined && options.setupKeys === true) {
755
+ account.given.push(`key setup: --setup-keys (init sets up keys on ${KEY_SETUP_NETWORK} only)`);
756
+ }
757
+ const keys = context.keys;
758
+ if (keyStep?.run === true && keys === undefined)
759
+ throw new Error("the key setup was asked for, and init was given no way to run it");
760
+ // A file that already holds this route as given is left as it is, byte for byte (run again to set up the key, say).
761
+ if (result.changed) {
762
+ try {
763
+ writeFileSync(configPath, result.text, { flag: before === undefined ? "wx" : "w" });
764
+ }
765
+ catch (error) {
766
+ refuse(`cannot write the config ${shown(options.config)} (${errorCode(error)}). Nothing was written.`);
767
+ }
768
+ }
769
+ const shownFile = options.config;
770
+ const lines = [];
771
+ if (!result.changed) {
772
+ lines.push(`wasit init: ${shownFile} already has the endpoint ${name} as given, in the environment ${environmentName}: ` +
773
+ "the file was left as it is.");
774
+ }
775
+ else if (before === undefined) {
776
+ lines.push(`wasit init: wrote ${shownFile}: the environment ${environmentName} and the endpoint ${name}.`);
777
+ }
778
+ else if (options.force) {
779
+ lines.push(`wasit init: replaced ${shownFile} (--force): the environment ${environmentName} and the endpoint ${name}.`);
780
+ }
781
+ else {
782
+ lines.push(`wasit init: added the endpoint ${name} to ${shownFile}` +
783
+ `${result.environmentAdded ? `, with the new environment ${environmentName}` : `, in the environment ${environmentName}`}` +
784
+ `${service !== undefined && !result.serviceAdded ? " (its start command was already there)" : ""}.`);
785
+ }
786
+ if (account.read.length > 0)
787
+ lines.push("Read from your service:", ...account.read.map((line) => ` ${line}`));
788
+ lines.push("You gave:", ...account.given.map((line) => ` ${line}`));
789
+ if (account.defaulted.length > 0)
790
+ lines.push("Filled in by default:", ...account.defaulted.map((line) => ` ${line}`));
791
+ if (account.notRead.length > 0)
792
+ lines.push("Not read from your service:", ...account.notRead.map((line) => ` ${line}`));
793
+ for (const line of lines)
794
+ context.stdout(clean(line));
795
+ // The config is written: from here on nothing refuses, and what the key setup could not do is a line (exit 0).
796
+ if (keyStep === undefined) {
797
+ for (const line of otherNetworkLines(route.network, route.protocol))
798
+ context.stdout(clean(line));
799
+ }
800
+ else if (!keyStep.run || keys === undefined) {
801
+ for (const line of notSetUpLines(route.protocol, keyStep.why))
802
+ context.stdout(clean(line));
803
+ }
804
+ else {
805
+ const ask = context.ask;
806
+ await setUpTestKeys({
807
+ network: route.network,
808
+ protocol: route.protocol,
809
+ ...(route.channel === undefined ? {} : { channel: route.channel }),
810
+ ...(route.pin === undefined ? {} : { asset: route.pin.asset }),
811
+ cwd,
812
+ env: context.env,
813
+ // --setup-keys answers this one too; at a terminal it is asked, and input that ends is a no.
814
+ allowGitignore: options.setupKeys === true || ask === undefined
815
+ ? async () => true
816
+ : async () => {
817
+ try {
818
+ const word = (await ask(GITIGNORE_QUESTION)).trim().toLowerCase();
819
+ return word === "yes" || word === "y";
820
+ }
821
+ catch {
822
+ return false;
823
+ }
824
+ },
825
+ say: (line) => context.stdout(clean(line)),
826
+ redact: (value) => secrets.push(value),
827
+ }, keys);
828
+ }
829
+ const written = parseConfig(result.text);
830
+ const runsByDefault = written.defaultEnvironment === environmentName ||
831
+ (written.defaultEnvironment === undefined && Object.keys(written.environments).length === 1);
832
+ const next = [
833
+ route.protocol === "x402" ? "wasit run --read-only" : "wasit run --dry-run",
834
+ ...(options.config === DEFAULT_CONFIG_FILE ? [] : [`--config ${commandArgument(options.config)}`]),
835
+ ...(runsByDefault ? [] : [`--env ${environmentName}`]),
836
+ ].join(" ");
837
+ context.stdout(clean(`Next: ${next}`));
838
+ if (route.protocol !== "x402") {
839
+ context.stdout(clean(" (MPP has no read-only checks: the dry run prints what the payment tier would do, and signs nothing.)"));
840
+ }
841
+ return 0;
842
+ }
843
+ catch (error) {
844
+ if (error instanceof InitRefusal) {
845
+ context.stderr(clean(`wasit init: ${error.message}`));
846
+ return 2;
847
+ }
848
+ throw error;
849
+ }
850
+ }