@wasit-dev/cli 0.7.0 → 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,110 @@
1
+ /**
2
+ * The testnet key setup of `wasit init` (spec C4 with C7 rows 2, 3 and 5, and
3
+ * Najmi's decision of 2026-11-27 for the channel; W3-2 slice 5), for the route
4
+ * init has just written. It sets up, in the `.env` of the working directory
5
+ * that `wasit run` loads, the key the route's payment checks read: the x402
6
+ * payer (STELLAR_PRIVATE_KEY) or the MPP charge payer (MPP_PAYER_SECRET), with
7
+ * test XLM, the USDC trustline and test USDC. The steps, in this order:
8
+ *
9
+ * 1. The network. A network that is not a test network returns before a file
10
+ * is looked at or a key is made (C3: not reachable for any class but
11
+ * `test`). A test network of another chain gets the variable to set and the
12
+ * faucet, and no key.
13
+ * 2. `.env` protection. In a git repository `.env` must not be tracked
14
+ * (`git ls-files --error-unmatch`) and must be ignored (`git check-ignore`);
15
+ * when it is not ignored, `.env` is added to `.gitignore` only on a yes,
16
+ * then checked again. Outside a repository `.gitignore` gets `.env` all the
17
+ * same. In a repository git cannot answer for: no key. `DOTENV_CONFIG_PATH`
18
+ * set: no key, since wasit then reads another file.
19
+ * 3. Reuse, never overwrite. A variable that is set is kept, and its account is
20
+ * only read. One that `.env` has without a value is left as it is. One set
21
+ * to nothing in the environment init runs in hides `.env` from `wasit run`
22
+ * (dotenv never replaces a variable that is set, and run reads an empty one
23
+ * as no key): that is said, and no key is made.
24
+ * 4. A new key is made in memory and appended to `.env`: created readable by
25
+ * its owner only, never through a link, never rewritten, the file's own
26
+ * line ending kept. An existing `.env` keeps its permissions; one open to
27
+ * other users is said, with the `chmod` that closes it. It is read back,
28
+ * and only then funded: Friendbot, then
29
+ * the trustline and test USDC by a swap on the public test exchange. A step
30
+ * that fails is said with the command that finishes it later, and the rest
31
+ * goes on: the read-only checks need none of it.
32
+ * 5. MPP channel: no key is made (Najmi, 2026-11-27). The channel's server
33
+ * checks each commitment against the key the channel was opened with
34
+ * (`@stellar/mpp` 0.7.1 `channel/server/Channel.js`), which a new key is not.
35
+ *
36
+ * Only public addresses are printed. A generated secret goes to `.env` and to
37
+ * the caller's redaction list, nowhere else. Nothing here throws: the config is
38
+ * already written, so whatever went wrong becomes a line.
39
+ */
40
+ import { type FriendbotOutcome, type GeneratedWallet, type RouteProtocol, type UsdcSetupOutcome, type WalletStatus } from "@wasit-dev/core";
41
+ /** The only network init sets up keys on. */
42
+ export declare const KEY_SETUP_NETWORK = "stellar:testnet";
43
+ /** What git answered: its exit code (null when it did not run or did not finish) and what it printed. */
44
+ export interface GitAnswer {
45
+ readonly code: number | null;
46
+ readonly stdout: string;
47
+ }
48
+ /** The outside world of the key setup, passed in so the tests can stand in for it. */
49
+ export interface KeySetupDeps {
50
+ readonly git: (args: readonly string[], cwd: string) => Promise<GitAnswer>;
51
+ readonly generateWallet: () => GeneratedWallet;
52
+ readonly fund: (publicKey: string) => Promise<FriendbotOutcome>;
53
+ readonly status: (publicKey: string) => Promise<WalletStatus>;
54
+ readonly addUsdc: (secretKey: string, source: string) => Promise<UsdcSetupOutcome>;
55
+ readonly sleep: (ms: number) => Promise<void>;
56
+ }
57
+ export interface KeySetupRequest {
58
+ /** The network init wrote for the route. */
59
+ readonly network: string;
60
+ readonly protocol: RouteProtocol;
61
+ /** MPP channel: the channel contract the route bills through. */
62
+ readonly channel?: string;
63
+ /** The asset the route asks to be paid in, when init read one. */
64
+ readonly asset?: string;
65
+ /** Where `.env` and `.gitignore` are: the working directory, which `wasit run` loads `.env` from. */
66
+ readonly cwd: string;
67
+ readonly env: Readonly<Record<string, string | undefined>>;
68
+ /** Whether `.env` may be added to `.gitignore` in a repository that does not ignore it. */
69
+ readonly allowGitignore: () => Promise<boolean>;
70
+ /** Every line of the key setup, in order, as each step starts or ends. */
71
+ readonly say: (line: string) => void;
72
+ /** A value no printed line may carry: the secret of a key made here. */
73
+ readonly redact: (value: string) => void;
74
+ }
75
+ /**
76
+ * Runs git with the keys taken out of its environment, without the file
77
+ * system monitor (a repository's own config can name a program for it), and
78
+ * never longer than 10 s.
79
+ */
80
+ export declare function runGit(args: readonly string[], cwd: string): Promise<GitAnswer>;
81
+ /** The network side of the key setup, for real. */
82
+ export declare const LIVE_KEY_SETUP: KeySetupDeps;
83
+ type Role = {
84
+ readonly kind: "payer";
85
+ readonly variable: string;
86
+ readonly walletRole: "x402" | "mpp-charge";
87
+ } | {
88
+ readonly kind: "commitment";
89
+ readonly variable: string;
90
+ };
91
+ /** The key a route's payment checks read in `wasit run`. */
92
+ export declare function keyRoleFor(protocol: RouteProtocol): Role;
93
+ /** The question init asks at a terminal, before it writes the config, for a route on {@link KEY_SETUP_NETWORK}. */
94
+ export declare function keySetupQuestion(protocol: RouteProtocol): string;
95
+ /** The question when `.env` is not ignored in a git repository. */
96
+ export declare const GITIGNORE_QUESTION = ".env is not ignored by git. Add .env to .gitignore? (yes/no): ";
97
+ /** What a route on {@link KEY_SETUP_NETWORK} needs when the key setup did not run, and why it did not. */
98
+ export declare function notSetUpLines(protocol: RouteProtocol, why: string): string[];
99
+ /**
100
+ * What a route on a test network of another chain needs, with no key made: the
101
+ * variable `wasit run` reads, and the faucet (spec C3).
102
+ */
103
+ export declare function otherNetworkLines(network: string, protocol: RouteProtocol): string[];
104
+ /**
105
+ * The key setup for one route. Every line goes to `request.say` as it comes
106
+ * (what was done to keep `.env` out of git, each step, and the status table)
107
+ * and is returned as well, in the same order.
108
+ */
109
+ export declare function setUpTestKeys(request: KeySetupRequest, deps: KeySetupDeps): Promise<string[]>;
110
+ export {};
@@ -0,0 +1,539 @@
1
+ /**
2
+ * The testnet key setup of `wasit init` (spec C4 with C7 rows 2, 3 and 5, and
3
+ * Najmi's decision of 2026-11-27 for the channel; W3-2 slice 5), for the route
4
+ * init has just written. It sets up, in the `.env` of the working directory
5
+ * that `wasit run` loads, the key the route's payment checks read: the x402
6
+ * payer (STELLAR_PRIVATE_KEY) or the MPP charge payer (MPP_PAYER_SECRET), with
7
+ * test XLM, the USDC trustline and test USDC. The steps, in this order:
8
+ *
9
+ * 1. The network. A network that is not a test network returns before a file
10
+ * is looked at or a key is made (C3: not reachable for any class but
11
+ * `test`). A test network of another chain gets the variable to set and the
12
+ * faucet, and no key.
13
+ * 2. `.env` protection. In a git repository `.env` must not be tracked
14
+ * (`git ls-files --error-unmatch`) and must be ignored (`git check-ignore`);
15
+ * when it is not ignored, `.env` is added to `.gitignore` only on a yes,
16
+ * then checked again. Outside a repository `.gitignore` gets `.env` all the
17
+ * same. In a repository git cannot answer for: no key. `DOTENV_CONFIG_PATH`
18
+ * set: no key, since wasit then reads another file.
19
+ * 3. Reuse, never overwrite. A variable that is set is kept, and its account is
20
+ * only read. One that `.env` has without a value is left as it is. One set
21
+ * to nothing in the environment init runs in hides `.env` from `wasit run`
22
+ * (dotenv never replaces a variable that is set, and run reads an empty one
23
+ * as no key): that is said, and no key is made.
24
+ * 4. A new key is made in memory and appended to `.env`: created readable by
25
+ * its owner only, never through a link, never rewritten, the file's own
26
+ * line ending kept. An existing `.env` keeps its permissions; one open to
27
+ * other users is said, with the `chmod` that closes it. It is read back,
28
+ * and only then funded: Friendbot, then
29
+ * the trustline and test USDC by a swap on the public test exchange. A step
30
+ * that fails is said with the command that finishes it later, and the rest
31
+ * goes on: the read-only checks need none of it.
32
+ * 5. MPP channel: no key is made (Najmi, 2026-11-27). The channel's server
33
+ * checks each commitment against the key the channel was opened with
34
+ * (`@stellar/mpp` 0.7.1 `channel/server/Channel.js`), which a new key is not.
35
+ *
36
+ * Only public addresses are printed. A generated secret goes to `.env` and to
37
+ * the caller's redaction list, nowhere else. Nothing here throws: the config is
38
+ * already written, so whatever went wrong becomes a line.
39
+ */
40
+ import { execFile } from "node:child_process";
41
+ import { closeSync, constants, existsSync, lstatSync, openSync, readFileSync, writeSync } from "node:fs";
42
+ import path from "node:path";
43
+ import { parse as parseDotenv } from "dotenv";
44
+ import { TESTNET_SWAP_XLM, TESTNET_USDC_ISSUER, addTestnetUsdc, fundWithFriendbot, generateTestnetWallet, getTestnetWalletStatus, networkClass, paymentChainFor, publicKeyFromSecret, scrubEnv, } from "@wasit-dev/core";
45
+ import { MPP_COMMITMENT_KEY_ENV, MPP_PAYER_KEY_ENV } from "./run.js";
46
+ import { SERVE_NETWORKS } from "./serve.js";
47
+ /** The only network init sets up keys on. */
48
+ export const KEY_SETUP_NETWORK = "stellar:testnet";
49
+ const ENV_FILE = ".env";
50
+ const GITIGNORE_FILE = ".gitignore";
51
+ const FAUCET_URL = "https://faucet.circle.com";
52
+ /** How often, and how long apart, init looks for the account Friendbot has just made (the starter kit's 8 times, 1 s). */
53
+ const ACCOUNT_LOOKS = 8;
54
+ const ACCOUNT_LOOK_GAP_MS = 1_000;
55
+ /** The longest error text of a network service printed: it is the service's, not ours. */
56
+ const MAX_ERROR_LENGTH = 200;
57
+ /**
58
+ * Runs git with the keys taken out of its environment, without the file
59
+ * system monitor (a repository's own config can name a program for it), and
60
+ * never longer than 10 s.
61
+ */
62
+ export function runGit(args, cwd) {
63
+ return new Promise((resolve) => {
64
+ execFile("git", ["-c", "core.fsmonitor=false", ...args], { cwd, timeout: 10_000, windowsHide: true, env: { ...scrubEnv(process.env), GIT_OPTIONAL_LOCKS: "0" } }, (error, stdout) => {
65
+ const exit = error?.code;
66
+ resolve({ code: error === null ? 0 : typeof exit === "number" ? exit : null, stdout: String(stdout ?? "") });
67
+ });
68
+ });
69
+ }
70
+ /** The network side of the key setup, for real. */
71
+ export const LIVE_KEY_SETUP = {
72
+ git: runGit,
73
+ generateWallet: generateTestnetWallet,
74
+ fund: (publicKey) => fundWithFriendbot(publicKey),
75
+ status: getTestnetWalletStatus,
76
+ addUsdc: addTestnetUsdc,
77
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
78
+ };
79
+ /** The key a route's payment checks read in `wasit run`. */
80
+ export function keyRoleFor(protocol) {
81
+ if (protocol === "mpp-charge")
82
+ return { kind: "payer", variable: MPP_PAYER_KEY_ENV, walletRole: "mpp-charge" };
83
+ if (protocol === "mpp-channel")
84
+ return { kind: "commitment", variable: MPP_COMMITMENT_KEY_ENV };
85
+ return { kind: "payer", variable: paymentChainFor(KEY_SETUP_NETWORK).payerKeyEnv, walletRole: "x402" };
86
+ }
87
+ function messageOf(error) {
88
+ const text = (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim();
89
+ return text.length > MAX_ERROR_LENGTH ? `${text.slice(0, MAX_ERROR_LENGTH - 3)}...` : text;
90
+ }
91
+ function errorCode(error) {
92
+ const code = error?.code;
93
+ return typeof code === "string" ? code : "an error";
94
+ }
95
+ /** How to set up a payer by hand, with the commands that exist today. */
96
+ function byHand(role, hand = {}) {
97
+ return (`${hand.first === undefined ? "By hand" : `${hand.first}, by hand`}: wasit wallet create --role ${role.walletRole} ` +
98
+ `--fund makes a testnet key and prints it (not on a shared screen); put its ${role.variable} line in ` +
99
+ `${hand.file ?? ENV_FILE}, then run wasit wallet fund --role ${role.walletRole} --asset usdc.`);
100
+ }
101
+ /** The question init asks at a terminal, before it writes the config, for a route on {@link KEY_SETUP_NETWORK}. */
102
+ export function keySetupQuestion(protocol) {
103
+ const role = keyRoleFor(protocol);
104
+ if (role.kind === "commitment") {
105
+ return `Check the channel's commitment key (${role.variable} in .env)? init makes none (yes/no): `;
106
+ }
107
+ return (`Set up a test payer in .env (${role.variable})? If it is not set, init makes a Stellar testnet key (the secret ` +
108
+ `is never shown), funds it with Friendbot and swaps ${TESTNET_SWAP_XLM} test XLM for test USDC (yes/no): `);
109
+ }
110
+ /** The question when `.env` is not ignored in a git repository. */
111
+ export const GITIGNORE_QUESTION = ".env is not ignored by git. Add .env to .gitignore? (yes/no): ";
112
+ /** What a route on {@link KEY_SETUP_NETWORK} needs when the key setup did not run, and why it did not. */
113
+ export function notSetUpLines(protocol, why) {
114
+ const role = keyRoleFor(protocol);
115
+ if (role.kind === "commitment") {
116
+ return [
117
+ `Commitment key: not checked (${why}). The channel checks of wasit run read ${role.variable} from .env: the ` +
118
+ "secret of the commitment key the channel was opened with.",
119
+ ];
120
+ }
121
+ return [
122
+ `Test key: not set up (${why}). The payment checks of wasit run read ${role.variable} from .env: a Stellar ` +
123
+ `testnet key with test XLM, the USDC trustline and test USDC. ${byHand(role)}`,
124
+ ];
125
+ }
126
+ /**
127
+ * What a route on a test network of another chain needs, with no key made: the
128
+ * variable `wasit run` reads, and the faucet (spec C3).
129
+ */
130
+ export function otherNetworkLines(network, protocol) {
131
+ const chain = paymentChainFor(network);
132
+ const profile = SERVE_NETWORKS[network];
133
+ if (protocol !== "x402" || chain === undefined || profile === undefined) {
134
+ return [`Test key: init sets up keys on ${KEY_SETUP_NETWORK} only, and this route is on ${network}.`];
135
+ }
136
+ return [
137
+ `Test key: init sets up keys on ${KEY_SETUP_NETWORK} only. On ${profile.name} the payment checks of wasit run read ` +
138
+ `${chain.payerKeyEnv} from .env (keep .env in .gitignore): wasit wallet create --role x402 --network ${network} ` +
139
+ `makes one and prints it (not on a shared screen). Fund it with USDC at ${FAUCET_URL} (network ` +
140
+ `${profile.faucetNetwork}); it needs no ${profile.nativeToken}, since the facilitator pays the fee.`,
141
+ ];
142
+ }
143
+ function blocked(why, hand, lines = []) {
144
+ return { writable: false, lines, why, hand };
145
+ }
146
+ /** What must be true before a key goes into `.env` by hand, for each reason init wrote none. */
147
+ const ONCE_GIT_ANSWERS = { first: "Once git can tell that .env is ignored and not tracked" };
148
+ const ONCE_IGNORED = { first: "Once git ignores .env" };
149
+ /** A `.git` in this folder or a folder above it: a repository, whether or not git runs. */
150
+ function inRepositoryFolder(cwd) {
151
+ let dir = path.resolve(cwd);
152
+ for (;;) {
153
+ if (existsSync(path.join(dir, ".git")))
154
+ return true;
155
+ const parent = path.dirname(dir);
156
+ if (parent === dir)
157
+ return false;
158
+ dir = parent;
159
+ }
160
+ }
161
+ /**
162
+ * Appends one line to `file`, never rewriting what is there: created with
163
+ * `mode` when it is not there, never opened through a link, the file's own
164
+ * line ending kept, and a line break put first when the file does not end
165
+ * with one. Undefined when it worked, else why not.
166
+ */
167
+ function appendLine(file, line, mode) {
168
+ const name = path.basename(file);
169
+ let before = "";
170
+ try {
171
+ if (!lstatSync(file).isFile())
172
+ return `${name} is not a plain file (a link or a folder), and init writes only to a plain file`;
173
+ before = readFileSync(file, "utf-8");
174
+ }
175
+ catch (error) {
176
+ if (errorCode(error) !== "ENOENT")
177
+ return `cannot read ${name} (${errorCode(error)})`;
178
+ }
179
+ const eol = before.includes("\r\n") ? "\r\n" : "\n";
180
+ const text = `${before === "" || before.endsWith("\n") ? "" : eol}${line}${eol}`;
181
+ let fd;
182
+ try {
183
+ fd = openSync(file, constants.O_WRONLY | constants.O_APPEND | constants.O_CREAT | (constants.O_NOFOLLOW ?? 0), mode);
184
+ writeSync(fd, text);
185
+ }
186
+ catch (error) {
187
+ return `cannot write ${name} (${errorCode(error)})`;
188
+ }
189
+ finally {
190
+ if (fd !== undefined)
191
+ closeSync(fd);
192
+ }
193
+ return undefined;
194
+ }
195
+ /** Whether `.gitignore` has a line that is exactly `.env`. */
196
+ function gitignoreListsEnv(cwd) {
197
+ try {
198
+ return readFileSync(path.join(cwd, GITIGNORE_FILE), "utf-8")
199
+ .split(/\r?\n/)
200
+ .some((line) => line.trim() === ENV_FILE);
201
+ }
202
+ catch {
203
+ return false;
204
+ }
205
+ }
206
+ /** Step 2: may `.env` get a key? */
207
+ async function protectEnv(request, deps) {
208
+ const { cwd } = request;
209
+ if ((request.env["DOTENV_CONFIG_PATH"] ?? "").trim() !== "") {
210
+ return blocked("DOTENV_CONFIG_PATH is set, so wasit reads its keys from that file and not from .env here", {
211
+ file: "the file DOTENV_CONFIG_PATH names (keep that file out of git)",
212
+ });
213
+ }
214
+ const gitFailed = "this folder is in a git repository, and git could not say whether .env is tracked or ignored (is git installed?)";
215
+ const inside = await deps.git(["rev-parse", "--is-inside-work-tree"], cwd);
216
+ if (inside.code !== 0 || inside.stdout.trim() !== "true") {
217
+ if (inRepositoryFolder(cwd))
218
+ return blocked(gitFailed, ONCE_GIT_ANSWERS);
219
+ if (gitignoreListsEnv(cwd))
220
+ return { writable: true, lines: ["this folder is not a git repository; .gitignore lists .env"] };
221
+ const problem = appendLine(path.join(cwd, GITIGNORE_FILE), ENV_FILE, 0o666);
222
+ if (problem !== undefined) {
223
+ return blocked(`this folder is not a git repository, and init could not add .env to .gitignore: ${problem}`, {
224
+ first: "Once .gitignore lists .env",
225
+ });
226
+ }
227
+ return { writable: true, lines: ["this folder is not a git repository: init added .env to .gitignore all the same, for when it is one"] };
228
+ }
229
+ const tracked = await deps.git(["ls-files", "--error-unmatch", "--", ENV_FILE], cwd);
230
+ if (tracked.code === 0) {
231
+ return blocked(".env is tracked by git, so a key in it would be committed. Untrack it (git rm --cached .env, then commit) and add " +
232
+ ".env to .gitignore. A key it ever held is in the history: treat it as public", { first: "Once .env is untracked and ignored" });
233
+ }
234
+ if (tracked.code !== 1)
235
+ return blocked(gitFailed, ONCE_GIT_ANSWERS);
236
+ const ignored = await deps.git(["check-ignore", "-q", "--", ENV_FILE], cwd);
237
+ if (ignored.code === 0)
238
+ return { writable: true, lines: [".env is ignored by git and not tracked"] };
239
+ if (ignored.code !== 1)
240
+ return blocked(gitFailed, ONCE_GIT_ANSWERS);
241
+ if (!(await request.allowGitignore())) {
242
+ return blocked(".env is not ignored by git, and .gitignore was left as it is: add .env to .gitignore first", ONCE_IGNORED);
243
+ }
244
+ const problem = appendLine(path.join(cwd, GITIGNORE_FILE), ENV_FILE, 0o666);
245
+ if (problem !== undefined)
246
+ return blocked(`.env is not ignored by git, and init could not add it to .gitignore: ${problem}`, ONCE_IGNORED);
247
+ const again = await deps.git(["check-ignore", "-q", "--", ENV_FILE], cwd);
248
+ if (again.code !== 0) {
249
+ return blocked("init added .env to .gitignore, and git still does not ignore it (a rule such as !.env after it?)", ONCE_IGNORED, [
250
+ "init added .env to .gitignore",
251
+ ]);
252
+ }
253
+ return { writable: true, lines: ["init added .env to .gitignore, and git now ignores it (commit that change)"] };
254
+ }
255
+ /** The names `.env` defines; or why it cannot be read. */
256
+ function envFileNames(cwd) {
257
+ const file = path.join(cwd, ENV_FILE);
258
+ try {
259
+ if (!lstatSync(file).isFile())
260
+ return { problem: ".env is not a plain file (a link or a folder)" };
261
+ const parsed = parseDotenv(readFileSync(file, "utf-8"));
262
+ const names = new Set(Object.keys(parsed));
263
+ return { names, empty: new Set([...names].filter((name) => (parsed[name] ?? "").trim() === "")) };
264
+ }
265
+ catch (error) {
266
+ if (errorCode(error) === "ENOENT")
267
+ return { names: new Set(), empty: new Set() };
268
+ return { problem: `cannot read .env (${errorCode(error)})` };
269
+ }
270
+ }
271
+ /**
272
+ * Whether a variable set to nothing in the environment init runs in hides
273
+ * `.env` from `wasit run`: dotenv never replaces a variable that is set, and
274
+ * run reads an empty one as no key. "no line": `.env` does not name it, so a
275
+ * key added there would be hidden; "line": `.env` gives it a value that is
276
+ * hidden. Undefined when nothing is hidden, when `.env` names it with no value
277
+ * too (said as that), or when DOTENV_CONFIG_PATH points wasit at another file.
278
+ */
279
+ function hiddenByEnvironment(request, variable, file) {
280
+ const value = request.env[variable];
281
+ if (value === undefined || value.trim() !== "")
282
+ return undefined;
283
+ if ((request.env["DOTENV_CONFIG_PATH"] ?? "").trim() !== "")
284
+ return undefined;
285
+ if (!file.names.has(variable))
286
+ return "no line";
287
+ return file.empty.has(variable) ? undefined : "line";
288
+ }
289
+ /** How to clear a variable set to nothing, in the shells most builders use. */
290
+ function unsetHint(variable) {
291
+ return `bash or zsh: unset ${variable}; PowerShell: Remove-Item Env:${variable}`;
292
+ }
293
+ /** Why an empty variable in the environment makes init write no key. */
294
+ function emptyInEnvironment(variable) {
295
+ return (`${variable}: set to nothing in the environment init runs in (your shell, most likely), and init wrote none: .env ` +
296
+ "never replaces a variable that is set, and wasit run reads an empty one as no key.");
297
+ }
298
+ /** A value `.env` has that an empty variable in the environment hides from `wasit run`. */
299
+ function hiddenLine(variable) {
300
+ return (` ${variable}: in .env, and set to nothing in the environment init runs in (your shell, most likely), which ` +
301
+ `wins: wasit run reads that as no key. Unset it there (${unsetHint(variable)}); init does not change .env.`);
302
+ }
303
+ /**
304
+ * The permission bits of `file` when users other than its owner have any
305
+ * access to it, else undefined (and on Windows, whose files have no such bits).
306
+ */
307
+ function openToOthers(file) {
308
+ if (process.platform === "win32")
309
+ return undefined;
310
+ try {
311
+ const mode = lstatSync(file).mode & 0o777;
312
+ return (mode & 0o077) === 0 ? undefined : mode.toString(8);
313
+ }
314
+ catch {
315
+ return undefined;
316
+ }
317
+ }
318
+ /** A positive Stellar amount: any digit but 0. */
319
+ function positive(balance) {
320
+ return /[1-9]/.test(balance);
321
+ }
322
+ /** The status table's rows of one payer: XLM, the trustline, USDC, each ready or what is missing and how to finish it. */
323
+ function payerRows(role, status, problems, readError) {
324
+ if (status === undefined && readError !== undefined) {
325
+ return [` could not read the account (${readError}): wasit wallet status --role ${role.walletRole} checks it`];
326
+ }
327
+ const exists = status?.exists === true;
328
+ const xlm = status?.balances.find((balance) => balance.code === "XLM");
329
+ const usdc = status?.balances.find((balance) => balance.code === "USDC" && balance.issuer === TESTNET_USDC_ISSUER);
330
+ const fund = `wasit wallet fund --role ${role.walletRole}`;
331
+ const xlmRow = exists
332
+ ? `ready, ${xlm?.balance ?? "0"} XLM`
333
+ : `missing: ${problems.xlm ?? "the account does not exist on testnet yet"}. Later: ${fund}`;
334
+ const trustRow = usdc !== undefined
335
+ ? "ready"
336
+ : `missing${problems.trustline !== undefined ? `: ${problems.trustline}` : exists ? "" : ": it needs the account first"}. ` +
337
+ `Later: ${fund} --asset usdc`;
338
+ const usdcRow = usdc !== undefined && positive(usdc.balance)
339
+ ? `ready, ${usdc.balance} USDC`
340
+ : `missing${problems.usdc !== undefined ? `: ${problems.usdc}` : ""}. Get test USDC at ${FAUCET_URL} ` +
341
+ `(Stellar Testnet), pasting the address${usdc === undefined ? ", once the trustline is there" : ""}`;
342
+ return [` XLM: ${xlmRow}`, ` trustline: ${trustRow}`, ` USDC: ${usdcRow}`];
343
+ }
344
+ async function readStatus(deps, publicKey) {
345
+ try {
346
+ return { status: await deps.status(publicKey) };
347
+ }
348
+ catch (error) {
349
+ return { error: messageOf(error) };
350
+ }
351
+ }
352
+ /** A payer whose variable is set: kept, and its account only read (C4 step 2). */
353
+ async function existingPayer(role, value, deps, emit) {
354
+ let publicKey;
355
+ try {
356
+ publicKey = publicKeyFromSecret(value, role.variable);
357
+ }
358
+ catch {
359
+ emit(` ${role.variable}: set, and not a Stellar secret key (S...): init does not change it.`);
360
+ return;
361
+ }
362
+ emit(` ${role.variable}: set, kept (init never overwrites a key), address ${publicKey}`);
363
+ emit(" Reading its account on Stellar testnet ...");
364
+ const read = await readStatus(deps, publicKey);
365
+ for (const row of payerRows(role, read.status, {}, read.error))
366
+ emit(row);
367
+ }
368
+ /** A payer made here (C4 steps 3 and 4). */
369
+ async function newPayer(role, request, deps, emit) {
370
+ const file = path.join(request.cwd, ENV_FILE);
371
+ const wallet = deps.generateWallet();
372
+ request.redact(wallet.secretKey);
373
+ const problem = appendLine(file, `${role.variable}=${wallet.secretKey}`, 0o600);
374
+ if (problem !== undefined) {
375
+ emit(` ${role.variable}: not set: ${problem}. No key was kept and nothing was funded. ${byHand(role)}`);
376
+ return;
377
+ }
378
+ let readBack;
379
+ try {
380
+ readBack = parseDotenv(readFileSync(file, "utf-8"))[role.variable];
381
+ }
382
+ catch {
383
+ readBack = undefined;
384
+ }
385
+ if (readBack !== wallet.secretKey) {
386
+ emit(` ${role.variable}: init added it at the end of .env, and .env does not read it back as written (an unclosed ` +
387
+ "quote on a line before it?). Fix .env; nothing was funded.");
388
+ return;
389
+ }
390
+ emit(` ${role.variable}: new, written to .env (the secret is not shown), address ${wallet.publicKey}`);
391
+ const mode = openToOthers(file);
392
+ if (mode !== undefined) {
393
+ emit(` .env is open to other users of this computer (mode ${mode}), and it now holds the key: chmod 600 .env makes ` +
394
+ "it yours only. init leaves the file's permissions as they are.");
395
+ }
396
+ const problems = {};
397
+ emit(" Funding it with test XLM from Friendbot (the public testnet faucet) ...");
398
+ let funded = true;
399
+ try {
400
+ await deps.fund(wallet.publicKey);
401
+ }
402
+ catch (error) {
403
+ funded = false;
404
+ problems.xlm = `Friendbot did not fund it (${messageOf(error)})`;
405
+ }
406
+ let account;
407
+ if (funded) {
408
+ for (let look = 1; look <= ACCOUNT_LOOKS; look += 1) {
409
+ const read = await readStatus(deps, wallet.publicKey);
410
+ if (read.status?.exists === true) {
411
+ account = read.status;
412
+ break;
413
+ }
414
+ if (look === 1)
415
+ emit(" Waiting for the new account to appear on testnet ...");
416
+ if (look < ACCOUNT_LOOKS)
417
+ await deps.sleep(ACCOUNT_LOOK_GAP_MS);
418
+ }
419
+ if (account === undefined)
420
+ problems.xlm = "Friendbot answered, and the account did not appear on testnet in time";
421
+ }
422
+ if (account !== undefined) {
423
+ emit(` Adding the USDC trustline and swapping ${TESTNET_SWAP_XLM} test XLM for test USDC on the public test ` +
424
+ "exchange (up to a minute) ...");
425
+ try {
426
+ const outcome = await deps.addUsdc(wallet.secretKey, role.variable);
427
+ if (!outcome.swapped)
428
+ problems.usdc = `no swap: ${outcome.why}`;
429
+ }
430
+ catch (error) {
431
+ problems.trustline = messageOf(error);
432
+ }
433
+ }
434
+ const final = account === undefined ? {} : await readStatus(deps, wallet.publicKey);
435
+ for (const row of payerRows(role, final.status, problems, final.error))
436
+ emit(row);
437
+ }
438
+ /** The channel's commitment key: checked when it is set, never made (Najmi, 2026-11-27). */
439
+ function commitmentLines(role, request, file) {
440
+ const channel = request.channel === undefined ? "the route's channel" : `channel ${request.channel}`;
441
+ const value = (request.env[role.variable] ?? "").trim();
442
+ if (value !== "") {
443
+ if (!/^[0-9a-fA-F]{64}$/.test(value)) {
444
+ return [` ${role.variable}: set, and not 64 hex characters: init does not change it.`];
445
+ }
446
+ return [
447
+ ` ${role.variable}: set, kept. init cannot check that it is the key ${channel} was opened with: MPP-11, ` +
448
+ "MPP-12 and MPP-14 fail if it is not.",
449
+ ];
450
+ }
451
+ const which = `the secret (64 hex characters) of the commitment key ${channel} was opened with`;
452
+ const hidden = file === undefined ? undefined : hiddenByEnvironment(request, role.variable, file);
453
+ if (hidden === "line")
454
+ return [hiddenLine(role.variable)];
455
+ if (hidden === "no line") {
456
+ return [` ${emptyInEnvironment(role.variable)} Unset it there (${unsetHint(role.variable)}), then put in .env ${which}.`];
457
+ }
458
+ if (file?.names.has(role.variable) === true) {
459
+ return [` ${role.variable}: in .env without a value: init does not change it.`];
460
+ }
461
+ return [
462
+ ` ${role.variable}: not set. Put in .env ${which}. init makes none: the channel's server checks each commitment ` +
463
+ "against that key, and a new one would not match it.",
464
+ ];
465
+ }
466
+ /**
467
+ * The key setup for one route. Every line goes to `request.say` as it comes
468
+ * (what was done to keep `.env` out of git, each step, and the status table)
469
+ * and is returned as well, in the same order.
470
+ */
471
+ export async function setUpTestKeys(request, deps) {
472
+ const lines = [];
473
+ const emit = (line) => {
474
+ lines.push(line);
475
+ request.say(line);
476
+ };
477
+ // C3: never reachable for a class but `test`, before any file is read or any key is made.
478
+ if (networkClass(request.network) !== "test") {
479
+ emit("Test key: not set up: init sets up keys on test networks only, never for a mainnet.");
480
+ return lines;
481
+ }
482
+ if (request.network !== KEY_SETUP_NETWORK) {
483
+ for (const line of otherNetworkLines(request.network, request.protocol))
484
+ emit(line);
485
+ return lines;
486
+ }
487
+ const role = keyRoleFor(request.protocol);
488
+ emit(role.kind === "payer"
489
+ ? `Test key for the payment checks of wasit run (${KEY_SETUP_NETWORK}, in .env):`
490
+ : "Commitment key for the channel checks of wasit run (in .env):");
491
+ try {
492
+ const protection = await protectEnv(request, deps);
493
+ for (const line of protection.lines)
494
+ emit(` ${line}`);
495
+ if (!protection.writable)
496
+ emit(` .env: init writes no key into it: ${protection.why}.`);
497
+ const file = envFileNames(request.cwd);
498
+ if (role.kind === "commitment") {
499
+ for (const line of commitmentLines(role, request, "names" in file ? file : undefined))
500
+ emit(line);
501
+ return lines;
502
+ }
503
+ const value = (request.env[role.variable] ?? "").trim();
504
+ const hidden = "names" in file ? hiddenByEnvironment(request, role.variable, file) : undefined;
505
+ if (value !== "") {
506
+ await existingPayer(role, value, deps, emit);
507
+ }
508
+ else if ("problem" in file) {
509
+ emit(` ${role.variable}: not set, and init wrote none: ${file.problem}. ${byHand(role)}`);
510
+ }
511
+ else if (hidden === "line") {
512
+ emit(hiddenLine(role.variable));
513
+ }
514
+ else if (hidden === "no line") {
515
+ // Both must be true before a key goes into .env: the variable unset, and .env kept out of git.
516
+ const unset = `${role.variable} is unset there (${unsetHint(role.variable)})`;
517
+ const first = protection.writable || protection.hand.first === undefined ? `Once ${unset}` : `${protection.hand.first}, and ${unset}`;
518
+ emit(` ${emptyInEnvironment(role.variable)} ${byHand(role, { first })}`);
519
+ }
520
+ else if (file.names.has(role.variable)) {
521
+ emit(` ${role.variable}: in .env without a value: init does not change it. Fill it in, or delete the line.`);
522
+ }
523
+ else if (!protection.writable) {
524
+ emit(` ${role.variable}: not set, and init wrote none. ${byHand(role, protection.hand)}`);
525
+ }
526
+ else {
527
+ await newPayer(role, request, deps, emit);
528
+ }
529
+ const testUsdc = SERVE_NETWORKS[KEY_SETUP_NETWORK]?.asset;
530
+ if (request.asset !== undefined && request.asset !== testUsdc) {
531
+ emit(` note: the route asks to be paid in ${request.asset}, not in test USDC (${testUsdc}): init sets up test USDC only.`);
532
+ }
533
+ }
534
+ catch (error) {
535
+ emit(` init stopped the key setup on an unexpected error (${messageOf(error)}). Anything it wrote to .env stays ` +
536
+ "there; wasit wallet status shows the account.");
537
+ }
538
+ return lines;
539
+ }