@ninefish/cli 0.0.0-stage → 0.1.1

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.
Files changed (3) hide show
  1. package/README.md +193 -2
  2. package/dist/nf.js +3103 -0
  3. package/package.json +37 -3
package/dist/nf.js ADDED
@@ -0,0 +1,3103 @@
1
+ #!/usr/bin/env node
2
+
3
+ // src/io.ts
4
+ import { execFile as execFile2 } from "node:child_process";
5
+ import { chmodSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
6
+ import { createServer } from "node:http";
7
+ import { dirname } from "node:path";
8
+ import { createInterface } from "node:readline/promises";
9
+
10
+ // src/credentials.ts
11
+ import { execFile } from "node:child_process";
12
+ var SERVICE = "nf";
13
+ function run(command, args, input) {
14
+ return new Promise((resolve) => {
15
+ const child = execFile(command, args, { timeout: 1e4 }, (error, stdout) => {
16
+ const code = error ? typeof error.code === "number" ? error.code : 1 : 0;
17
+ resolve({ code, out: String(stdout) });
18
+ });
19
+ if (input !== void 0) {
20
+ child.stdin?.end(input);
21
+ }
22
+ });
23
+ }
24
+ function parse(text) {
25
+ try {
26
+ const value = JSON.parse(text);
27
+ return typeof value.access_token === "string" && typeof value.expires_at === "number" ? value : void 0;
28
+ } catch {
29
+ return void 0;
30
+ }
31
+ }
32
+ function macKeychain() {
33
+ return {
34
+ kind: "keychain",
35
+ async read(profile) {
36
+ const { code, out } = await run("security", [
37
+ "find-generic-password",
38
+ "-s",
39
+ SERVICE,
40
+ "-a",
41
+ profile,
42
+ "-w"
43
+ ]);
44
+ return code === 0 ? parse(out.trim()) : void 0;
45
+ },
46
+ async write(profile, tokens) {
47
+ const { code } = await run("security", [
48
+ "add-generic-password",
49
+ "-U",
50
+ "-s",
51
+ SERVICE,
52
+ "-a",
53
+ profile,
54
+ "-w",
55
+ JSON.stringify(tokens)
56
+ ]);
57
+ if (code !== 0) throw new Error("The keychain refused the tokens");
58
+ },
59
+ async remove(profile) {
60
+ await run("security", ["delete-generic-password", "-s", SERVICE, "-a", profile]);
61
+ }
62
+ };
63
+ }
64
+ function secretService() {
65
+ return {
66
+ kind: "secret-service",
67
+ async read(profile) {
68
+ const { code, out } = await run("secret-tool", [
69
+ "lookup",
70
+ "service",
71
+ SERVICE,
72
+ "profile",
73
+ profile
74
+ ]);
75
+ return code === 0 ? parse(out.trim()) : void 0;
76
+ },
77
+ async write(profile, tokens) {
78
+ const { code } = await run(
79
+ "secret-tool",
80
+ ["store", "--label", `nf ${profile}`, "service", SERVICE, "profile", profile],
81
+ JSON.stringify(tokens)
82
+ );
83
+ if (code !== 0) throw new Error("The Secret Service refused the tokens");
84
+ },
85
+ async remove(profile) {
86
+ await run("secret-tool", ["clear", "service", SERVICE, "profile", profile]);
87
+ }
88
+ };
89
+ }
90
+ function unavailableStore() {
91
+ const refuse = async () => {
92
+ throw new Error(
93
+ "No OS keychain here: nf keeps tokens in the macOS Keychain or the Secret Service (secret-tool)."
94
+ );
95
+ };
96
+ return {
97
+ kind: "unavailable",
98
+ read: async () => void 0,
99
+ write: refuse,
100
+ remove: async () => void 0
101
+ };
102
+ }
103
+ function platformStore(platform) {
104
+ if (platform === "darwin") return macKeychain();
105
+ if (platform === "linux") return secretService();
106
+ return unavailableStore();
107
+ }
108
+
109
+ // src/io.ts
110
+ function nodeIo() {
111
+ return {
112
+ stdout: (text) => {
113
+ process.stdout.write(text);
114
+ },
115
+ stderr: (text) => {
116
+ process.stderr.write(text);
117
+ },
118
+ isTTY: process.stdout.isTTY === true,
119
+ stdinTTY: process.stdin.isTTY === true,
120
+ ask: async (question) => {
121
+ const rl = createInterface({ input: process.stdin, output: process.stderr });
122
+ try {
123
+ return (await rl.question(question)).trim();
124
+ } finally {
125
+ rl.close();
126
+ }
127
+ },
128
+ readFile: (path) => {
129
+ try {
130
+ return readFileSync(path, "utf8");
131
+ } catch (error) {
132
+ if (error.code === "ENOENT") return void 0;
133
+ throw error;
134
+ }
135
+ },
136
+ readBytes: (path) => {
137
+ try {
138
+ return readFileSync(path);
139
+ } catch (error) {
140
+ if (error.code === "ENOENT") return void 0;
141
+ throw error;
142
+ }
143
+ },
144
+ writePrivateFile: (path, text) => {
145
+ mkdirSync(dirname(path), { recursive: true, mode: 448 });
146
+ writeFileSync(path, text, { mode: 384 });
147
+ chmodSync(path, 384);
148
+ },
149
+ fetch: (input, init) => fetch(input, init),
150
+ nodeVersion: process.version,
151
+ platform: process.platform,
152
+ tokens: platformStore(process.platform),
153
+ listenLoopback: () => new Promise((resolve, reject) => {
154
+ let answer = () => void 0;
155
+ const callback = new Promise((done) => {
156
+ answer = done;
157
+ });
158
+ const server = createServer((request, response) => {
159
+ const url = new URL(request.url ?? "/", "http://127.0.0.1");
160
+ if (url.pathname !== "/callback") {
161
+ response.writeHead(404).end();
162
+ return;
163
+ }
164
+ response.writeHead(200, {
165
+ "content-type": "text/plain; charset=utf-8",
166
+ "cache-control": "no-store"
167
+ }).end("Signed in. You can close this tab and go back to your terminal.\n");
168
+ answer(url.searchParams);
169
+ });
170
+ server.on("error", reject);
171
+ server.listen(0, "127.0.0.1", () => {
172
+ const address = server.address();
173
+ if (!address || typeof address === "string") return reject(new Error("no port"));
174
+ resolve({ port: address.port, callback, close: () => server.close() });
175
+ });
176
+ }),
177
+ openUrl: (url) => {
178
+ const opener = process.platform === "darwin" ? "open" : process.platform === "win32" ? "explorer" : "xdg-open";
179
+ execFile2(opener, [url], () => void 0);
180
+ }
181
+ };
182
+ }
183
+
184
+ // src/run.ts
185
+ import { parseArgs } from "node:util";
186
+
187
+ // src/exit-codes.ts
188
+ var EXIT = {
189
+ ok: 0,
190
+ error: 1,
191
+ usage: 2,
192
+ unauthenticated: 3,
193
+ notFound: 4,
194
+ conflict: 5,
195
+ stepUpRequired: 6,
196
+ config: 7,
197
+ forbidden: 8,
198
+ retryable: 9
199
+ };
200
+
201
+ // src/errors.ts
202
+ var CliError = class extends Error {
203
+ code;
204
+ exit;
205
+ remediation;
206
+ details;
207
+ retryable;
208
+ constructor(code, exit, message, options = {}) {
209
+ super(message);
210
+ this.name = "CliError";
211
+ this.code = code;
212
+ this.exit = exit;
213
+ this.remediation = options.remediation;
214
+ this.details = options.details;
215
+ this.retryable = options.retryable ?? false;
216
+ }
217
+ };
218
+ var usageError = (code, message, remediation) => new CliError(code, EXIT.usage, message, remediation === void 0 ? {} : { remediation });
219
+ var configError = (code, message, remediation) => new CliError(code, EXIT.config, message, remediation === void 0 ? {} : { remediation });
220
+
221
+ // src/login.ts
222
+ import { createHash, randomBytes } from "node:crypto";
223
+ var NF_CLI_CLIENT_ID = "nf-cli";
224
+ var SCOPE = "openid offline_access";
225
+ var DEVICE_GRANT = "urn:ietf:params:oauth:grant-type:device_code";
226
+ var LOGIN_TIMEOUT_MS = 5 * 6e4;
227
+ var b64 = (bytes) => bytes.toString("base64url");
228
+ async function post(io, url, form) {
229
+ let response;
230
+ try {
231
+ response = await io.fetch(url, {
232
+ method: "POST",
233
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
234
+ body: new URLSearchParams(form).toString(),
235
+ redirect: "error",
236
+ signal: AbortSignal.timeout(15e3)
237
+ });
238
+ } catch {
239
+ throw new CliError("network_error", EXIT.retryable, `Couldn't reach ${new URL(url).origin}`, {
240
+ retryable: true,
241
+ remediation: "Check your connection and try again."
242
+ });
243
+ }
244
+ let body = {};
245
+ try {
246
+ body = await response.json();
247
+ } catch {
248
+ body = {};
249
+ }
250
+ return { status: response.status, body };
251
+ }
252
+ function tokensFrom(body, context, now) {
253
+ if (!body.access_token || typeof body.expires_in !== "number")
254
+ throw new CliError("login_failed", EXIT.unauthenticated, "The sign-in answered no token");
255
+ return {
256
+ access_token: body.access_token,
257
+ ...body.refresh_token ? { refresh_token: body.refresh_token } : {},
258
+ expires_at: now + body.expires_in * 1e3,
259
+ api: context.api
260
+ };
261
+ }
262
+ function failed(body) {
263
+ return new CliError(
264
+ body.error ?? "login_failed",
265
+ EXIT.unauthenticated,
266
+ body.error_description ?? "Sign-in didn't complete",
267
+ { remediation: "Run `nf login` again." }
268
+ );
269
+ }
270
+ async function loginWithBrowser(context, io, now = Date.now, options = {}) {
271
+ const loopback = await io.listenLoopback();
272
+ try {
273
+ const verifier = b64(randomBytes(32));
274
+ const state = b64(randomBytes(16));
275
+ const redirectUri = `http://127.0.0.1:${loopback.port}/callback`;
276
+ const url = new URL("/authorize", context.auth);
277
+ url.search = new URLSearchParams({
278
+ response_type: "code",
279
+ client_id: NF_CLI_CLIENT_ID,
280
+ redirect_uri: redirectUri,
281
+ scope: SCOPE,
282
+ state,
283
+ nonce: b64(randomBytes(16)),
284
+ code_challenge: b64(createHash("sha256").update(verifier).digest()),
285
+ code_challenge_method: "S256",
286
+ // A fresh passkey, whatever the browser's session: the token's auth_time is the step-up.
287
+ ...options.stepUp ? { prompt: "login" } : {}
288
+ }).toString();
289
+ io.stderr(
290
+ options.stepUp ? `This needs your passkey again. Opening your browser; if it doesn't open, go to:
291
+ ${url.href}
292
+ ` : `Opening your browser to sign in. If it doesn't open, go to:
293
+ ${url.href}
294
+ `
295
+ );
296
+ io.openUrl(url.href);
297
+ const query = await Promise.race([
298
+ loopback.callback,
299
+ new Promise(
300
+ (_, reject) => setTimeout(
301
+ () => reject(
302
+ new CliError("timeout", EXIT.retryable, "Sign-in wasn't finished within 5 minutes", {
303
+ retryable: true,
304
+ remediation: "Run `nf login` again, or `nf login --device` on a machine with no browser."
305
+ })
306
+ ),
307
+ LOGIN_TIMEOUT_MS
308
+ ).unref()
309
+ )
310
+ ]);
311
+ if (query.get("state") !== state)
312
+ throw failed({ error_description: "The sign-in answer didn't match this request" });
313
+ if (query.get("iss") !== null && query.get("iss") !== new URL(context.auth).origin)
314
+ throw failed({ error_description: "The sign-in answer came from another issuer" });
315
+ if (query.get("error"))
316
+ throw failed({
317
+ error: query.get("error") ?? void 0,
318
+ error_description: query.get("error_description") ?? void 0
319
+ });
320
+ const code = query.get("code");
321
+ if (!code) throw failed({});
322
+ const { status, body } = await post(io, new URL("/token", context.auth).href, {
323
+ grant_type: "authorization_code",
324
+ code,
325
+ redirect_uri: redirectUri,
326
+ client_id: NF_CLI_CLIENT_ID,
327
+ code_verifier: verifier
328
+ });
329
+ if (status !== 200) throw failed(body);
330
+ return tokensFrom(body, context, now());
331
+ } finally {
332
+ loopback.close();
333
+ }
334
+ }
335
+ async function loginWithDevice(context, io, now = Date.now, sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms))) {
336
+ const started = await post(io, new URL("/device_authorization", context.auth).href, {
337
+ client_id: NF_CLI_CLIENT_ID,
338
+ scope: SCOPE
339
+ });
340
+ const device = started.body;
341
+ if (started.status !== 200 || !device.device_code || !device.user_code) throw failed(device);
342
+ io.stderr(
343
+ `On any device, go to ${device.verification_uri ?? `${context.auth}/device`} and enter
344
+
345
+ ${device.user_code}
346
+
347
+ Waiting for you to approve it\u2026
348
+ `
349
+ );
350
+ let interval = (device.interval ?? 5) * 1e3;
351
+ const deadline = now() + (device.expires_in ?? 600) * 1e3;
352
+ while (now() < deadline) {
353
+ await sleep(interval);
354
+ const { status, body } = await post(io, new URL("/token", context.auth).href, {
355
+ grant_type: DEVICE_GRANT,
356
+ device_code: device.device_code,
357
+ client_id: NF_CLI_CLIENT_ID
358
+ });
359
+ if (status === 200) return tokensFrom(body, context, now());
360
+ if (body.error === "authorization_pending") continue;
361
+ if (body.error === "slow_down") {
362
+ interval += 5e3;
363
+ continue;
364
+ }
365
+ throw failed(body);
366
+ }
367
+ throw new CliError(
368
+ "expired_token",
369
+ EXIT.unauthenticated,
370
+ "The device code expired before it was approved",
371
+ {
372
+ remediation: "Run `nf login --device` again."
373
+ }
374
+ );
375
+ }
376
+ async function refresh(context, io, tokens, now = Date.now) {
377
+ if (!tokens.refresh_token) return void 0;
378
+ const { status, body } = await post(io, new URL("/token", context.auth).href, {
379
+ grant_type: "refresh_token",
380
+ refresh_token: tokens.refresh_token,
381
+ client_id: NF_CLI_CLIENT_ID
382
+ });
383
+ if (status !== 200) return void 0;
384
+ return tokensFrom({ refresh_token: tokens.refresh_token, ...body }, context, now());
385
+ }
386
+ async function revoke(context, io, tokens) {
387
+ const token = tokens.refresh_token ?? tokens.access_token;
388
+ await post(io, new URL("/revoke", context.auth).href, {
389
+ token,
390
+ client_id: NF_CLI_CLIENT_ID
391
+ }).catch(() => void 0);
392
+ }
393
+
394
+ // src/api.ts
395
+ var BOOTSTRAP_ENV = "NF_BOOTSTRAP_CREDENTIAL";
396
+ function bootstrapCredential(context, env) {
397
+ if (context.stage === "prod" && env[BOOTSTRAP_ENV]) {
398
+ throw new CliError(
399
+ "bootstrap_credential_refused",
400
+ EXIT.unauthenticated,
401
+ "Prod refuses the bootstrap credential, so nf doesn't send it there",
402
+ {
403
+ remediation: "Unset it and run `nf login`."
404
+ }
405
+ );
406
+ }
407
+ const value = env[BOOTSTRAP_ENV];
408
+ if (!value || context.stage === "prod") {
409
+ throw new CliError("unauthenticated", EXIT.unauthenticated, "Not signed in", {
410
+ remediation: context.stage === "prod" ? "Run `nf login`." : `Run \`nf login\`, or set ${BOOTSTRAP_ENV} (dev only).`
411
+ });
412
+ }
413
+ return value;
414
+ }
415
+ async function credentialFor(context, env, io) {
416
+ const profile = context.profile.name;
417
+ const stored = await io.tokens.read(profile).catch(() => void 0);
418
+ if (stored && stored.api === context.api) {
419
+ if (stored.expires_at - 3e4 > Date.now())
420
+ return { bearer: stored.access_token, signedIn: true };
421
+ const renewed = await refresh(context, io, stored);
422
+ if (renewed) {
423
+ await io.tokens.write(profile, renewed);
424
+ return { bearer: renewed.access_token, signedIn: true };
425
+ }
426
+ await io.tokens.remove(profile);
427
+ if (!env[BOOTSTRAP_ENV])
428
+ throw new CliError("unauthenticated", EXIT.unauthenticated, "Your sign-in has ended", {
429
+ remediation: "Run `nf login`."
430
+ });
431
+ }
432
+ return { bearer: bootstrapCredential(context, env), signedIn: false };
433
+ }
434
+ function newIdempotencyKey() {
435
+ const bytes = crypto.getRandomValues(new Uint8Array(24));
436
+ return Buffer.from(bytes).toString("base64url");
437
+ }
438
+ function exitFor(status, code) {
439
+ if (code === "step_up_required") return EXIT.stepUpRequired;
440
+ if (status === 400 || status === 422) return EXIT.usage;
441
+ if (status === 401) return EXIT.unauthenticated;
442
+ if (status === 403) return EXIT.forbidden;
443
+ if (status === 404 || status === 410) return EXIT.notFound;
444
+ if (status === 409 || status === 412 || status === 428) return EXIT.conflict;
445
+ if (status === 429 || status >= 500) return EXIT.retryable;
446
+ return EXIT.error;
447
+ }
448
+ function isEnvelope(value) {
449
+ if (typeof value !== "object" || value === null) return false;
450
+ const v = value;
451
+ return typeof v.code === "string" && typeof v.message === "string" && typeof v.request_id === "string" && typeof v.retryable === "boolean";
452
+ }
453
+ var ApiError = class extends CliError {
454
+ envelope;
455
+ status;
456
+ constructor(status, envelope) {
457
+ const remediation = remediationFor(envelope.code);
458
+ super(envelope.code, exitFor(status, envelope.code), envelope.message, {
459
+ retryable: envelope.retryable,
460
+ ...envelope.details ? { details: envelope.details } : {},
461
+ ...remediation === void 0 ? {} : { remediation }
462
+ });
463
+ this.envelope = envelope;
464
+ this.status = status;
465
+ }
466
+ };
467
+ function remediationFor(code) {
468
+ switch (code) {
469
+ case "unauthenticated":
470
+ return "Run `nf login`.";
471
+ case "bootstrap_credential_refused":
472
+ return `Unset ${BOOTSTRAP_ENV}, then run \`nf login\`.`;
473
+ case "domain_txt_missing":
474
+ return "Publish the record from `nf domain instructions`. DNS can take minutes to propagate, so verify again shortly.";
475
+ case "version_mismatch":
476
+ return "It changed since nf read it. Run the command again.";
477
+ case "step_up_required":
478
+ return "This needs a passkey in the last five minutes: run `nf login`, then the command again. At a terminal nf asks for it in place.";
479
+ case "rate_limited":
480
+ case "service_unavailable":
481
+ case "internal_error":
482
+ return "Try again shortly.";
483
+ default:
484
+ return void 0;
485
+ }
486
+ }
487
+ var Api = class {
488
+ #options;
489
+ #credential;
490
+ /**
491
+ * The one step-up this run asks for, shared by every request that needs it. Each request
492
+ * is tried again once after it, so a refusal after a fresh passkey is reported, not looped on.
493
+ */
494
+ #steppedUp;
495
+ constructor(options) {
496
+ this.#options = options;
497
+ }
498
+ get(path, query = {}) {
499
+ return this.#send("GET", path, { query });
500
+ }
501
+ /** A POST; with no body, none is sent and no content type either. */
502
+ post(path, body, write = {}) {
503
+ return this.#send("POST", path, { ...write, ...body === void 0 ? {} : { body } });
504
+ }
505
+ patch(path, body, etag, write = {}) {
506
+ return this.#send("PATCH", path, { ...write, body, ifMatch: etag });
507
+ }
508
+ /** A PUT: the whole resource, conditional on `etag` when there is one to match. */
509
+ put(path, body, etag, write = {}) {
510
+ return this.#send("PUT", path, {
511
+ ...write,
512
+ body,
513
+ ...etag === void 0 ? {} : { ifMatch: etag }
514
+ });
515
+ }
516
+ /** A DELETE that answers the resource as it now is. */
517
+ deleteFor(path, etag) {
518
+ return this.#send("DELETE", path, etag === void 0 ? {} : { ifMatch: etag });
519
+ }
520
+ delete(path, etag, write = {}) {
521
+ return this.#send("DELETE", path, {
522
+ ...write,
523
+ ...etag === void 0 ? {} : { ifMatch: etag }
524
+ });
525
+ }
526
+ /** Every item of a list, following `next_cursor`, or the first `limit` of them. */
527
+ async list(path, limit2) {
528
+ const items = [];
529
+ let cursor;
530
+ do {
531
+ const want = limit2 === void 0 ? 100 : Math.min(100, limit2 - items.length);
532
+ const { body } = await this.get(path, { cursor, limit: String(want) });
533
+ items.push(...body.items);
534
+ cursor = body.next_cursor ?? void 0;
535
+ } while (cursor && (limit2 === void 0 || items.length < limit2));
536
+ return limit2 === void 0 ? items : items.slice(0, limit2);
537
+ }
538
+ async #send(method, path, options) {
539
+ const key = method === "GET" ? void 0 : options.idempotencyKey ?? newIdempotencyKey();
540
+ const sent = { ...options, ...key ? { idempotencyKey: key } : {} };
541
+ try {
542
+ return await this.#attempt(method, path, sent);
543
+ } catch (error) {
544
+ if (!await this.#mayStepUp(error)) throw error;
545
+ this.#steppedUp ??= this.#stepUp();
546
+ await this.#steppedUp;
547
+ return this.#attempt(method, path, sent);
548
+ }
549
+ }
550
+ /** Whether this refusal is one nf can answer in place: a step-up, at a terminal, signed in. */
551
+ async #mayStepUp(error) {
552
+ if (!(error instanceof ApiError) || error.envelope.code !== "step_up_required") return false;
553
+ if (!this.#options.stepUpInPlace || this.#options.io.tokens.kind === "unavailable")
554
+ return false;
555
+ return (await this.#credential)?.signedIn === true;
556
+ }
557
+ /** The browser sign-in, forced to a fresh passkey; its tokens replace the profile's. */
558
+ async #stepUp() {
559
+ const { context, io } = this.#options;
560
+ const tokens = await loginWithBrowser(context, io, Date.now, { stepUp: true });
561
+ await io.tokens.write(context.profile.name, tokens);
562
+ this.#credential = Promise.resolve({ bearer: tokens.access_token, signedIn: true });
563
+ }
564
+ async #attempt(method, path, options) {
565
+ const { context, io, requestId: requestId2, timeoutMs } = this.#options;
566
+ const url = new URL(path, context.api);
567
+ for (const [key, value] of Object.entries(options.query ?? {})) {
568
+ if (value !== void 0) url.searchParams.set(key, value);
569
+ }
570
+ this.#credential ??= credentialFor(context, this.#options.env, io);
571
+ const headers = {
572
+ accept: "application/json",
573
+ authorization: `Bearer ${(await this.#credential).bearer}`,
574
+ "x-request-id": requestId2,
575
+ "user-agent": "nf"
576
+ };
577
+ if (options.idempotencyKey !== void 0) headers["idempotency-key"] = options.idempotencyKey;
578
+ if (options.ifMatch !== void 0) headers["if-match"] = options.ifMatch;
579
+ if (options.body !== void 0) headers["content-type"] = "application/json";
580
+ let response;
581
+ try {
582
+ response = await io.fetch(url, {
583
+ method,
584
+ headers,
585
+ ...options.body === void 0 ? {} : { body: JSON.stringify(options.body) },
586
+ signal: AbortSignal.timeout(timeoutMs),
587
+ redirect: "error"
588
+ });
589
+ } catch (error) {
590
+ const timedOut = error?.name === "TimeoutError";
591
+ throw new CliError(
592
+ timedOut ? "timeout" : "network_error",
593
+ EXIT.retryable,
594
+ timedOut ? `No answer from ${context.api} within ${timeoutMs / 1e3}s` : `Couldn't reach ${context.api}`,
595
+ { retryable: true, remediation: "Check your connection and try again." }
596
+ );
597
+ }
598
+ const text = await response.text();
599
+ let body;
600
+ try {
601
+ body = text === "" ? void 0 : JSON.parse(text);
602
+ } catch {
603
+ body = void 0;
604
+ }
605
+ if (!response.ok) {
606
+ if (isEnvelope(body)) throw new ApiError(response.status, body);
607
+ throw new ApiError(response.status, {
608
+ code: response.status >= 500 ? "internal_error" : "unexpected_response",
609
+ message: `${context.api} answered ${response.status} with no error envelope`,
610
+ request_id: response.headers.get("x-request-id") ?? requestId2,
611
+ retryable: response.status >= 500
612
+ });
613
+ }
614
+ return { body, etag: response.headers.get("etag") ?? void 0 };
615
+ }
616
+ };
617
+ var pathSegment = encodeURIComponent;
618
+ var etagFor = (version2) => `"${version2}"`;
619
+
620
+ // src/config-write.ts
621
+ import { isMap, parseDocument } from "yaml";
622
+
623
+ // ../../packages/naming/stages.js
624
+ var STAGE_DOMAINS = {
625
+ dev: void 0,
626
+ prod: "nine.fish"
627
+ };
628
+ var AUTH_SUBDOMAIN = "auth";
629
+ var API_SUBDOMAIN = "api";
630
+ var SUPPORT_EMAIL = `support@${STAGE_DOMAINS.prod}`;
631
+ var LEGAL_ENTITY = Object.freeze({
632
+ name: "9F PTY LTD",
633
+ acn: "679 546 064",
634
+ abn: "83 679 546 064"
635
+ });
636
+ function isStage(value) {
637
+ return value === "dev" || value === "prod";
638
+ }
639
+ function authOrigin(stage) {
640
+ return `https://${AUTH_SUBDOMAIN}.${STAGE_DOMAINS[stage]}`;
641
+ }
642
+ function apiOrigin(stage) {
643
+ return `https://${API_SUBDOMAIN}.${STAGE_DOMAINS[stage]}`;
644
+ }
645
+
646
+ // src/config.ts
647
+ import { parse as parse2 } from "yaml";
648
+ var STAGES = true ? ["prod"] : ["dev", "prod"];
649
+ var BUILT_IN = Object.fromEntries(
650
+ STAGES.map((stage) => [stage, { stage }])
651
+ );
652
+ var SECRET_KEYS = /token|secret|password|key|credential|cookie/i;
653
+ function configPath(env) {
654
+ if (env.NF_CONFIG) return env.NF_CONFIG;
655
+ if (env.XDG_CONFIG_HOME) return `${env.XDG_CONFIG_HOME}/nf/config.yaml`;
656
+ const home = env.HOME || env.USERPROFILE;
657
+ return home ? `${home}/.config/nf/config.yaml` : void 0;
658
+ }
659
+ function isCi(env) {
660
+ const flag = (value) => value !== void 0 && !["", "0", "false"].includes(value.toLowerCase());
661
+ return flag(env.CI) || flag(env.GITHUB_ACTIONS);
662
+ }
663
+ function parseConfig(text, path) {
664
+ const fail = (message) => configError(
665
+ "config_invalid",
666
+ `${path}: ${message}`,
667
+ "Fix the file, or run `nf doctor` to see what nf reads."
668
+ );
669
+ let raw;
670
+ try {
671
+ raw = parse2(text);
672
+ } catch {
673
+ throw fail("not YAML");
674
+ }
675
+ if (raw === null || raw === void 0) return { profiles: {} };
676
+ if (typeof raw !== "object" || Array.isArray(raw))
677
+ throw fail("must be a mapping with `profile` and `profiles`");
678
+ const top = raw;
679
+ for (const key of Object.keys(top)) {
680
+ if (key !== "profile" && key !== "profiles") throw fail(`unknown key \`${key}\``);
681
+ }
682
+ if (top.profile !== void 0 && typeof top.profile !== "string")
683
+ throw fail("`profile` must be a profile name");
684
+ const profiles = {};
685
+ const listed = top.profiles ?? {};
686
+ if (typeof listed !== "object" || listed === null || Array.isArray(listed)) {
687
+ throw fail("`profiles` must map names to profiles");
688
+ }
689
+ for (const [name, value] of Object.entries(listed)) {
690
+ if (typeof value !== "object" || value === null || Array.isArray(value))
691
+ throw fail(`profile \`${name}\` must be a mapping`);
692
+ const entry = value;
693
+ for (const key of Object.keys(entry)) {
694
+ if (SECRET_KEYS.test(key)) {
695
+ throw fail(
696
+ `profile \`${name}\` has \`${key}\`: credentials are kept in the OS keychain, never in the config file`
697
+ );
698
+ }
699
+ if (key !== "stage" && key !== "org")
700
+ throw fail(`profile \`${name}\` has an unknown key \`${key}\``);
701
+ }
702
+ if (entry.stage === void 0) throw fail(`profile \`${name}\` needs a stage`);
703
+ if (typeof entry.stage !== "string" || !isStage(entry.stage) || !STAGES.includes(entry.stage))
704
+ throw fail(`profile \`${name}\`: stage must be ${STAGES.join(" or ")}`);
705
+ const builtIn = BUILT_IN[name];
706
+ if (builtIn && builtIn.stage !== entry.stage) {
707
+ throw fail(
708
+ `profile \`${name}\` must have stage ${builtIn.stage}: the built-in profiles are named for their stage`
709
+ );
710
+ }
711
+ if (entry.org !== void 0 && (typeof entry.org !== "string" || entry.org === "")) {
712
+ throw fail(`profile \`${name}\`: org must be an organisation id`);
713
+ }
714
+ profiles[name] = {
715
+ stage: entry.stage,
716
+ ...typeof entry.org === "string" ? { org: entry.org } : {}
717
+ };
718
+ }
719
+ if (top.profile !== void 0 && !profiles[top.profile] && !BUILT_IN[top.profile]) {
720
+ throw fail(`the selected profile \`${top.profile}\` isn't defined`);
721
+ }
722
+ return { ...top.profile === void 0 ? {} : { profile: top.profile }, profiles };
723
+ }
724
+ function loadConfig(env, io) {
725
+ const path = configPath(env);
726
+ if (!path) return { path, file: void 0 };
727
+ let text;
728
+ try {
729
+ text = io.readFile(path);
730
+ } catch {
731
+ throw configError("config_invalid", `${path}: can't be read`);
732
+ }
733
+ return { path, file: text === void 0 ? void 0 : parseConfig(text, path) };
734
+ }
735
+ function apiOverride(value) {
736
+ for (const stage of STAGES) {
737
+ if (value.replace(/\/+$/, "") === apiOrigin(stage)) return { api: apiOrigin(stage), stage };
738
+ }
739
+ let url;
740
+ try {
741
+ url = new URL(value);
742
+ } catch {
743
+ url = void 0;
744
+ }
745
+ if (STAGES.includes("dev") && url && url.protocol === "http:" && ["localhost", "127.0.0.1", "[::1]"].includes(url.hostname) && url.pathname === "/") {
746
+ return { api: url.origin, stage: "dev" };
747
+ }
748
+ throw configError(
749
+ "config_invalid",
750
+ STAGES.includes("dev") ? `NF_API must be ${STAGES.map(apiOrigin).join(", ")} or a loopback http:// origin` : `NF_API must be ${apiOrigin("prod")}`
751
+ );
752
+ }
753
+ function resolveContext(flags, env, io) {
754
+ const { path, file } = loadConfig(env, io);
755
+ const ci = isCi(env);
756
+ let profile;
757
+ if (flags.profile) profile = { name: flags.profile, source: "flag" };
758
+ else if (env.NF_PROFILE) profile = { name: env.NF_PROFILE, source: "env" };
759
+ else if (!ci && file?.profile) profile = { name: file.profile, source: "config" };
760
+ const override = env.NF_API ? apiOverride(env.NF_API) : void 0;
761
+ if (ci && !profile && !override) {
762
+ throw configError(
763
+ "stage_required_in_ci",
764
+ "In CI, nf never picks a stage for you",
765
+ `Name a profile with --profile or NF_PROFILE (built in: ${STAGES.join(", ")}), or set NF_API.`
766
+ );
767
+ }
768
+ profile ??= { name: override?.stage ?? "prod", source: "default" };
769
+ const chosen = file?.profiles[profile.name] ?? BUILT_IN[profile.name];
770
+ if (!chosen) {
771
+ throw configError(
772
+ "profile_not_found",
773
+ `No profile \`${profile.name}\`${path ? ` in ${path}` : ""}`,
774
+ `Built in: ${STAGES.join(", ")}; define others in the config file.`
775
+ );
776
+ }
777
+ if (override && override.stage !== chosen.stage) {
778
+ throw configError(
779
+ "config_invalid",
780
+ `NF_API is a ${override.stage} API, but profile \`${profile.name}\` is ${chosen.stage}`
781
+ );
782
+ }
783
+ let org;
784
+ if (flags.org) org = { value: flags.org, source: "flag" };
785
+ else if (env.NF_ORG) org = { value: env.NF_ORG, source: "env" };
786
+ else if (chosen.org) org = { value: chosen.org, source: "config" };
787
+ return {
788
+ profile,
789
+ stage: chosen.stage,
790
+ api: override?.api ?? apiOrigin(chosen.stage),
791
+ auth: authOrigin(chosen.stage),
792
+ ...org ? { org } : {},
793
+ ci,
794
+ interactive: !flags.noInteractive && !ci && io.stdinTTY && io.isTTY,
795
+ configPath: path,
796
+ configFound: file !== void 0
797
+ };
798
+ }
799
+
800
+ // src/config-write.ts
801
+ function setProfileOrg(context, orgId, io) {
802
+ const path = context.configPath;
803
+ if (!path) {
804
+ throw configError(
805
+ "config_invalid",
806
+ "No config file location: set HOME, XDG_CONFIG_HOME or NF_CONFIG"
807
+ );
808
+ }
809
+ const existing = io.readFile(path) ?? "";
810
+ const parsed = parseDocument(existing);
811
+ if (parsed.errors.length > 0) {
812
+ throw configError("config_invalid", `${path}: not YAML`);
813
+ }
814
+ const document = parsed;
815
+ if (document.contents === null) document.contents = document.createNode({});
816
+ if (!isMap(document.contents)) {
817
+ throw configError(
818
+ "config_invalid",
819
+ `${path}: must be a mapping with \`profile\` and \`profiles\``
820
+ );
821
+ }
822
+ const name = context.profile.name;
823
+ if (!document.hasIn(["profiles", name])) {
824
+ document.setIn(["profiles", name], document.createNode({ stage: context.stage }));
825
+ }
826
+ document.setIn(["profiles", name, "org"], orgId);
827
+ const text = document.toString();
828
+ parseConfig(text, path);
829
+ io.writePrivateFile(path, text);
830
+ return path;
831
+ }
832
+
833
+ // src/email.ts
834
+ var lower = (value) => value.trim().toLowerCase();
835
+ async function resolveDestination(api, org, value) {
836
+ const base = `/v1/orgs/${pathSegment(org)}/email/destinations`;
837
+ if (value.startsWith("dst_"))
838
+ return (await api.get(`${base}/${pathSegment(value)}`)).body;
839
+ const all = await api.list(base);
840
+ const found = all.find((d) => lower(d.address) === lower(value) && d.status !== "removed");
841
+ if (!found) throw notFound("destination", value);
842
+ return found;
843
+ }
844
+ async function resolveRoute(api, org, value) {
845
+ const base = `/v1/orgs/${pathSegment(org)}/email/routes`;
846
+ if (value.startsWith("rte_"))
847
+ return (await api.get(`${base}/${pathSegment(value)}`)).body;
848
+ const all = await api.list(base);
849
+ const found = all.find((r) => lower(r.address) === lower(value));
850
+ if (!found) throw notFound("route", value);
851
+ return found;
852
+ }
853
+ async function targetsOf(api, org, value) {
854
+ if (typeof value !== "string" || value.trim() === "")
855
+ throw usageError("to_required", "Pass --to <mailbox or person>");
856
+ const targets = [];
857
+ for (const part of value.split(",").map((s) => s.trim()).filter(Boolean)) {
858
+ if (part.startsWith("per_")) targets.push({ kind: "person", person_id: part });
859
+ else if (part.startsWith("rte_")) targets.push({ kind: "route", route_id: part });
860
+ else if (part.startsWith("dst_"))
861
+ targets.push({
862
+ kind: "destination",
863
+ destination_id: (await resolveDestination(api, org, part)).id
864
+ });
865
+ else if (part.includes("@")) targets.push({ kind: "address", address: part });
866
+ else
867
+ throw usageError(
868
+ "invalid_target",
869
+ `\`${part}\` isn't a target: give an address (me@example.net, or one of yours such as alex@example.com), a mailbox's id (dst_\u2026), a route's id (rte_\u2026) or a person's id (per_\u2026)`
870
+ );
871
+ }
872
+ return targets;
873
+ }
874
+ var records = (domain) => domain.records.map((r) => ({
875
+ type: r.type,
876
+ name: r.name,
877
+ value: r.priority === void 0 ? r.value : `${r.priority} ${r.value}`,
878
+ needed: r.required ? "yes" : "recommended"
879
+ }));
880
+ var domainRow = (d) => ({
881
+ domain: d.fqdn,
882
+ status: d.status,
883
+ mx: d.dns?.mx ?? "not checked",
884
+ dkim: d.dns?.dkim ?? "not checked",
885
+ dmarc: d.dns?.dmarc ?? "not checked",
886
+ "checked at": d.dns?.checked_at ?? ""
887
+ });
888
+ var destinationRow = (d) => ({
889
+ id: d.id,
890
+ address: d.address,
891
+ status: d.suppressed_reason ? `${d.status} (${d.suppressed_reason})` : d.status,
892
+ person: d.person_id ?? "",
893
+ "confirmed at": d.confirmed_at ?? ""
894
+ });
895
+ var targetText = (t, routes) => t.kind === "destination" ? t.destination_id : t.kind === "person" ? t.person_id : routes.get(t.route_id) ?? t.route_id;
896
+ var routeStatus = (r) => r.status === "pending" && r.waiting_for?.length ? `pending: waits for ${r.waiting_for.join(", ")} to confirm` : r.status ?? "active";
897
+ var routeRow = (r, routes = /* @__PURE__ */ new Map()) => ({
898
+ id: r.id,
899
+ address: r.address,
900
+ to: r.targets.map((t) => targetText(t, routes)).join(", "),
901
+ status: routeStatus(r),
902
+ updated: r.updated_at
903
+ });
904
+ var routeMade = (r) => r.status === "pending" && r.waiting_for?.length ? `${r.address} forwards once ${r.waiting_for.join(", ")} ${r.waiting_for.length === 1 ? "agrees" : "agree"}: each was emailed a link (nf email destination resend sends it again). Until then it forwards only to its other targets.` : `${r.address} forwards now.`;
905
+ async function runEmail(input) {
906
+ const { name, args, values, context, api } = input;
907
+ const [first = ""] = args;
908
+ const org = await selectedOrgId(context, api);
909
+ const email = `/v1/orgs/${pathSegment(org)}/email`;
910
+ const domainEmail = async () => {
911
+ const domain = await resolveDomain(api, org, first);
912
+ return `/v1/orgs/${pathSegment(org)}/domains/${pathSegment(domain.id)}/email`;
913
+ };
914
+ switch (name) {
915
+ case "email enable": {
916
+ const { body } = await api.post(await domainEmail());
917
+ return {
918
+ data: body,
919
+ table: [
920
+ `Forwarding is on for ${body.fqdn}. Publish these records at your DNS host; nf never changes your DNS.`,
921
+ "An existing MX for the domain sends its mail elsewhere: nf email check shows what DNS holds now.",
922
+ "",
923
+ ...records(body).map((r) => `${r.type} ${r.name} ${r.value} ${r.needed}`)
924
+ ].join("\n")
925
+ };
926
+ }
927
+ case "email show": {
928
+ const { body } = await api.get(await domainEmail());
929
+ return { data: body, table: [domainRow(body), ...records(body)] };
930
+ }
931
+ case "email check": {
932
+ const { body } = await api.post(`${await domainEmail()}/check`);
933
+ return { data: body, table: domainRow(body) };
934
+ }
935
+ case "email disable": {
936
+ await api.delete(await domainEmail());
937
+ return {
938
+ data: { disabled: first },
939
+ table: `Forwarding is off for ${first}. Its routes are kept; nf email enable turns it back on.`
940
+ };
941
+ }
942
+ case "email list": {
943
+ const all = await api.list(`${email}/domains`, parseLimit(values));
944
+ return { data: all, table: all.map(domainRow) };
945
+ }
946
+ case "email destination add": {
947
+ const person = values.person;
948
+ const { body } = await api.post(`${email}/destinations`, {
949
+ address: first,
950
+ ...typeof person === "string" ? { person_id: person } : {}
951
+ });
952
+ return {
953
+ data: body,
954
+ table: body.confirmation_sent ? `${body.destination.address} is pending: its owner was emailed a link to agree. Nothing is forwarded there until they do.` : `${body.destination.address} is pending, but the confirmation email didn't go out. Try nf email destination resend ${body.destination.id}.`
955
+ };
956
+ }
957
+ case "email destination list": {
958
+ const all = await api.list(`${email}/destinations`, parseLimit(values));
959
+ return { data: all, table: all.map(destinationRow) };
960
+ }
961
+ case "email destination show": {
962
+ const destination = await resolveDestination(api, org, first);
963
+ return { data: destination, table: destinationRow(destination) };
964
+ }
965
+ case "email destination resend": {
966
+ const destination = await resolveDestination(api, org, first);
967
+ const { body } = await api.post(`${email}/destinations/${pathSegment(destination.id)}/resend`);
968
+ return {
969
+ data: body,
970
+ table: body.confirmation_sent ? `Sent ${body.destination.address} its confirmation link again.` : `The confirmation email didn't go out. Try again later.`
971
+ };
972
+ }
973
+ case "email destination remove": {
974
+ const destination = await resolveDestination(api, org, first);
975
+ await api.delete(`${email}/destinations/${pathSegment(destination.id)}`);
976
+ return {
977
+ data: { removed: destination.id },
978
+ table: `Removed ${destination.address}. Routes skip it from now on.`
979
+ };
980
+ }
981
+ case "email route create": {
982
+ const targets = await targetsOf(api, org, values.to);
983
+ const { body } = await api.post(`${email}/routes`, {
984
+ address: first,
985
+ targets
986
+ });
987
+ return { data: body, table: routeMade(body) };
988
+ }
989
+ case "email route list": {
990
+ const all = await api.list(`${email}/routes`, parseLimit(values));
991
+ const addresses = new Map(all.map((r) => [r.id, r.address]));
992
+ return { data: all, table: all.map((r) => routeRow(r, addresses)) };
993
+ }
994
+ case "email route show": {
995
+ const route = await resolveRoute(api, org, first);
996
+ const addresses = /* @__PURE__ */ new Map();
997
+ for (const t of route.targets)
998
+ if (t.kind === "route")
999
+ addresses.set(
1000
+ t.route_id,
1001
+ (await api.get(`${email}/routes/${pathSegment(t.route_id)}`)).body.address
1002
+ );
1003
+ return { data: route, table: routeRow(route, addresses) };
1004
+ }
1005
+ case "email route update": {
1006
+ const route = await resolveRoute(api, org, first);
1007
+ const targets = await targetsOf(api, org, values.to);
1008
+ const { body } = await api.patch(
1009
+ `${email}/routes/${pathSegment(route.id)}`,
1010
+ { targets },
1011
+ etagFor(route.version)
1012
+ );
1013
+ return { data: body, table: routeMade(body) };
1014
+ }
1015
+ case "email route delete": {
1016
+ const route = await resolveRoute(api, org, first);
1017
+ await api.delete(`${email}/routes/${pathSegment(route.id)}`);
1018
+ return {
1019
+ data: { deleted: route.id },
1020
+ table: `Deleted the route for ${route.address}. Its mail is no longer forwarded.`
1021
+ };
1022
+ }
1023
+ }
1024
+ throw new CliError("internal", EXIT.error, `nf ${name} has no handler`);
1025
+ }
1026
+
1027
+ // src/platforms.ts
1028
+ async function resolvePlatform(api, org, value) {
1029
+ if (value.startsWith("plt_"))
1030
+ return (await api.get(`/v1/orgs/${pathSegment(org)}/platforms/${pathSegment(value)}`)).body;
1031
+ const all = await api.list(`/v1/orgs/${pathSegment(org)}/platforms`);
1032
+ const found = all.find((p) => p.name === value && p.status !== "removed");
1033
+ if (!found) throw notFound("platform", value);
1034
+ return found;
1035
+ }
1036
+ var platformRow = (p) => ({
1037
+ id: p.id,
1038
+ name: p.name,
1039
+ domain: p.domain,
1040
+ protocol: p.protocol ?? "oidc",
1041
+ status: p.status,
1042
+ client: p.client_type ?? "",
1043
+ callbacks: p.redirect_uris.length
1044
+ });
1045
+ function writeSecret(input, path, secret) {
1046
+ input.io.writePrivateFile(
1047
+ path,
1048
+ `${JSON.stringify({ client_id: secret.client_id, client_secret: secret.client_secret }, null, 2)}
1049
+ `
1050
+ );
1051
+ }
1052
+ function redacted(secret, path) {
1053
+ const { client_secret: _secret, ...rest } = secret;
1054
+ return { ...rest, client_secret_file: path };
1055
+ }
1056
+ function atTerminal(input) {
1057
+ const { context, values } = input;
1058
+ return context.interactive && values.json !== true && values.output === void 0;
1059
+ }
1060
+ function secretHasSomewhere(input, secretFile) {
1061
+ if (secretFile || atTerminal(input)) return;
1062
+ throw usageError(
1063
+ "secret_file_required",
1064
+ "A client secret is never printed to JSON or to output that isn't a terminal: pass --secret-file <path> to keep it, or --public for a platform with no secret"
1065
+ );
1066
+ }
1067
+ async function issuerState(api, org, platform) {
1068
+ if (platform.issuer) return { issuer: platform.issuer };
1069
+ const host = await api.list(`/v1/orgs/${org}/auth-hosts`).then((all) => all.find((h) => h.domain_id === platform.domain_id && h.status !== "removed")).catch(() => void 0);
1070
+ if (host?.status === "active") return { issuer: `https://${host.hostname}` };
1071
+ return host ? { issuer: null, pending: host } : { issuer: null };
1072
+ }
1073
+ function issuerText(state, domain) {
1074
+ if (state.issuer) return state.issuer;
1075
+ const host = state.pending?.hostname;
1076
+ return host ? `none yet: it will be https://${host} once nf domain check ${domain} activates ${host}` : `none yet: ${domain} has no sign-in host. Add one with nf auth-host add auth.${domain}, then nf domain check ${domain}`;
1077
+ }
1078
+ function pasteable(platform, state) {
1079
+ const base = state.issuer ?? (state.pending ? `https://${state.pending.hostname}` : void 0);
1080
+ const at = (path) => base ? `${base}${path}` : null;
1081
+ return {
1082
+ issuer: state.issuer,
1083
+ ...state.issuer ? {} : { issuer_when_active: base ?? null },
1084
+ discovery: at("/.well-known/openid-configuration"),
1085
+ client_id: platform.id,
1086
+ client_type: platform.client_type,
1087
+ authorization_endpoint: at("/authorize"),
1088
+ token_endpoint: at("/token"),
1089
+ userinfo_endpoint: at("/userinfo"),
1090
+ token_endpoint_auth_method: platform.client_type === "public" ? "none" : "client_secret_basic",
1091
+ pkce: "S256, required",
1092
+ callbacks: platform.redirect_uris,
1093
+ post_logout_redirect_uris: platform.post_logout_redirect_uris,
1094
+ // The `email` claim, at userinfo with the email scope.
1095
+ email: `<member name>@${platform.domain}`
1096
+ };
1097
+ }
1098
+ function samlPasteable(platform, state) {
1099
+ const base = platform.saml?.idp ? void 0 : state.issuer ?? (state.pending ? `https://${state.pending.hostname}` : void 0);
1100
+ const at = (path) => base ? `${base}/saml/${platform.id}${path}` : null;
1101
+ const idp = platform.saml?.idp;
1102
+ return {
1103
+ active: Boolean(idp ?? state.issuer),
1104
+ idp_entity_id: idp?.entity_id ?? at("/metadata"),
1105
+ metadata_url: idp?.metadata_url ?? at("/metadata"),
1106
+ sso_url: idp?.sso_url ?? at("/sso"),
1107
+ sso_bindings: "HTTP-Redirect, HTTP-POST",
1108
+ name_id: `<member name>@${platform.domain} (emailAddress)`,
1109
+ certificate: platform.saml?.certificate ?? null,
1110
+ sp_entity_id: platform.saml?.entity_id ?? "",
1111
+ acs_urls: platform.saml?.acs_urls ?? [],
1112
+ signed_requests: platform.saml?.request_certificates.length ? "required, checked against the certificate you gave" : "not required (no certificate given)",
1113
+ attributes: platform.saml?.attributes ?? []
1114
+ };
1115
+ }
1116
+ function urlText(url, active, state, domain) {
1117
+ if (!url) return issuerText(state, domain);
1118
+ if (active) return url;
1119
+ const host = state.pending?.hostname ?? "";
1120
+ return `${url} (once nf domain check ${domain} activates ${host})`;
1121
+ }
1122
+ function certificateText(certificate, metadataUrl) {
1123
+ if (certificate) return certificate.trimEnd();
1124
+ return metadataUrl ? `not made yet: it will be in ${metadataUrl} once that answers` : "not made yet: it will be in the metadata";
1125
+ }
1126
+ function lines(rows) {
1127
+ const width = Math.max(...rows.map(([label]) => label.length));
1128
+ return rows.map(([label, value]) => ` ${label.padEnd(width)} ${value}`).join("\n");
1129
+ }
1130
+ async function activeDomains(api, org) {
1131
+ return (await api.list(`/v1/orgs/${org}/domains`)).filter((d) => d.status === "active");
1132
+ }
1133
+ async function runPlatforms(input) {
1134
+ const { name, args, values, api, io } = input;
1135
+ const [first = "", second = ""] = args;
1136
+ const org = async () => pathSegment(await selectedOrgId(input.context, api));
1137
+ const secretFile = typeof values["secret-file"] === "string" ? values["secret-file"] : void 0;
1138
+ const prompting = atTerminal(input) && !!io.ask;
1139
+ const ask = async (question, fallback) => prompting && io.ask ? (await io.ask(question)).trim() || fallback : fallback;
1140
+ switch (name) {
1141
+ case "platform add": {
1142
+ if (values.saml === true) return addSaml(input);
1143
+ const samlOnly = ["entity-id", "acs", "sp-cert", "attributes"].find(
1144
+ (option) => values[option] !== void 0
1145
+ );
1146
+ if (samlOnly)
1147
+ throw usageError("invalid_option", `--${samlOnly} is for a SAML platform: add --saml`);
1148
+ const isPublic = values.public === true;
1149
+ const given = values.callback;
1150
+ let callbacks = Array.isArray(given) ? given : typeof given === "string" ? [given] : [];
1151
+ if (!prompting) {
1152
+ if (!first) throw usageError("missing_argument", "nf platform add needs <name>");
1153
+ if (typeof values.domain !== "string")
1154
+ throw usageError("missing_option", "nf platform add needs --domain <fqdn>");
1155
+ }
1156
+ if (!isPublic) secretHasSomewhere(input, secretFile);
1157
+ const platformName = first || await ask("Name for this platform? ", "");
1158
+ if (!platformName) throw usageError("missing_argument", "nf platform add needs <name>");
1159
+ const o = await org();
1160
+ let domain;
1161
+ if (typeof values.domain === "string") domain = await resolveDomain(api, o, values.domain);
1162
+ else {
1163
+ const choices = await activeDomains(api, o);
1164
+ const fallback = choices[0];
1165
+ if (!fallback)
1166
+ throw new CliError(
1167
+ "conflict",
1168
+ EXIT.conflict,
1169
+ "A platform goes on a verified domain, and this organisation has none yet: nf domain setup <domain>"
1170
+ );
1171
+ const listed = choices.length > 1 ? ` (${choices.map((d) => d.display_name).join(", ")})` : "";
1172
+ const answer = await ask(`Which domain? [${fallback.display_name}]${listed} `, "");
1173
+ domain = answer ? await resolveDomain(api, o, answer) : fallback;
1174
+ }
1175
+ if (callbacks.length === 0) {
1176
+ const answer = await ask("Callback address the platform gave you? ", "");
1177
+ if (answer) callbacks = [answer];
1178
+ }
1179
+ const { body } = await api.post(`/v1/orgs/${o}/platforms`, {
1180
+ name: platformName,
1181
+ domain_id: domain.id,
1182
+ client_type: isPublic ? "public" : "confidential",
1183
+ ...callbacks.length ? { redirect_uris: callbacks } : {}
1184
+ });
1185
+ const { platform, secret } = body;
1186
+ if (secret && secretFile) writeSecret(input, secretFile, secret);
1187
+ const state = await issuerState(api, o, { ...platform, domain_id: domain.id });
1188
+ const secretLine = !secret ? "none: a public client uses PKCE" : secretFile ? `in ${secretFile}, readable only by you` : secret.client_secret;
1189
+ const registered = platform.redirect_uris.length ? platform.redirect_uris.join(" ") : `none yet: nf platform callback add ${platform.name} <uri>`;
1190
+ const text = [
1191
+ `Added ${platform.name} on ${platform.domain ?? domain.name}. Every member can sign in to it. Paste these into the platform:`,
1192
+ lines([
1193
+ ["Issuer", issuerText(state, domain.name)],
1194
+ ["Client ID", platform.id],
1195
+ ["Client secret", secretLine],
1196
+ ["Callback", registered]
1197
+ ]),
1198
+ ...secret && !secretFile ? [
1199
+ `This secret is shown once and won't be shown again. To replace it: nf platform rotate-secret ${platform.name}.`
1200
+ ] : [],
1201
+ ...state.issuer ? [] : [
1202
+ `Nobody can sign in to it until ${domain.name} has an active sign-in host, which is its issuer.`
1203
+ ]
1204
+ ].join("\n");
1205
+ return {
1206
+ data: {
1207
+ platform,
1208
+ ...secret && secretFile ? { secret: redacted(secret, secretFile) } : {}
1209
+ },
1210
+ table: text
1211
+ };
1212
+ }
1213
+ case "platform list": {
1214
+ const all = await api.list(`/v1/orgs/${await org()}/platforms`, parseLimit(values));
1215
+ return { data: all, table: all.map(platformRow) };
1216
+ }
1217
+ case "platform show": {
1218
+ const o = await org();
1219
+ const platform = await resolvePlatform(api, o, first);
1220
+ const state = await issuerState(api, o, platform);
1221
+ if (platform.protocol === "saml") {
1222
+ const saml = samlPasteable(platform, state);
1223
+ const { active: _active, ...settings } = saml;
1224
+ const url = (value) => urlText(value, saml.active, state, platform.domain);
1225
+ const text = [
1226
+ lines([
1227
+ ["Name", platform.name],
1228
+ ["ID", platform.id],
1229
+ ["Domain", platform.domain],
1230
+ ["Protocol", "SAML 2.0"],
1231
+ ["Status", platform.status],
1232
+ ["IdP entity ID", url(saml.idp_entity_id)],
1233
+ ["Metadata URL", url(saml.metadata_url)],
1234
+ ["SSO URL", `${url(saml.sso_url)}`],
1235
+ ["SSO bindings", saml.sso_bindings],
1236
+ ["NameID", saml.name_id],
1237
+ ["SP entity ID", saml.sp_entity_id],
1238
+ ["ACS", saml.acs_urls.join(" ")],
1239
+ ["Signed requests", saml.signed_requests],
1240
+ ["Attributes", saml.attributes.join(" ") || "none beside the NameID"],
1241
+ [
1242
+ "Certificate",
1243
+ saml.certificate ? "(PEM, below)" : certificateText(null, saml.metadata_url)
1244
+ ]
1245
+ ]),
1246
+ ...saml.certificate ? [saml.certificate.trimEnd()] : []
1247
+ ].join("\n");
1248
+ return { data: { ...platform, saml_settings: settings }, table: text };
1249
+ }
1250
+ const { issuer_when_active: _when, ...oidc } = pasteable(platform, state);
1251
+ return {
1252
+ data: { ...platform, oidc: pasteable(platform, state) },
1253
+ table: {
1254
+ ...platformRow(platform),
1255
+ ...oidc,
1256
+ issuer: issuerText(state, platform.domain),
1257
+ discovery: oidc.discovery ?? "",
1258
+ authorization_endpoint: oidc.authorization_endpoint ?? "",
1259
+ token_endpoint: oidc.token_endpoint ?? "",
1260
+ userinfo_endpoint: oidc.userinfo_endpoint ?? "",
1261
+ callbacks: oidc.callbacks.join(" "),
1262
+ post_logout_redirect_uris: oidc.post_logout_redirect_uris.join(" ")
1263
+ }
1264
+ };
1265
+ }
1266
+ case "platform callback add":
1267
+ case "platform callback remove": {
1268
+ const o = await org();
1269
+ const platform = await resolvePlatform(api, o, first);
1270
+ if (platform.protocol === "saml")
1271
+ throw usageError(
1272
+ "invalid_option",
1273
+ `${platform.name} is a SAML platform: it has ACS addresses, not callbacks`
1274
+ );
1275
+ const uris = name === "platform callback add" ? [.../* @__PURE__ */ new Set([...platform.redirect_uris, second])] : platform.redirect_uris.filter((uri) => uri !== second);
1276
+ if (name === "platform callback remove" && uris.length === platform.redirect_uris.length)
1277
+ throw notFound("callback", second);
1278
+ const { body } = await api.patch(
1279
+ `/v1/orgs/${o}/platforms/${pathSegment(platform.id)}`,
1280
+ { redirect_uris: uris },
1281
+ etagFor(platform.version)
1282
+ );
1283
+ return {
1284
+ data: body,
1285
+ table: { platform: body.name, callbacks: body.redirect_uris.join(" ") }
1286
+ };
1287
+ }
1288
+ case "platform remove": {
1289
+ const o = await org();
1290
+ const platform = await resolvePlatform(api, o, first);
1291
+ await api.delete(
1292
+ `/v1/orgs/${o}/platforms/${pathSegment(platform.id)}`,
1293
+ etagFor(platform.version)
1294
+ );
1295
+ return { data: { removed: platform.id }, table: `Removed ${platform.name}` };
1296
+ }
1297
+ case "platform rotate-secret": {
1298
+ secretHasSomewhere(input, secretFile);
1299
+ const o = await org();
1300
+ const platform = await resolvePlatform(api, o, first);
1301
+ const { body } = await api.post(
1302
+ `/v1/orgs/${o}/platforms/${pathSegment(platform.id)}/secret`
1303
+ );
1304
+ const previous = body.previous_expires_at ? ` The previous one works until ${body.previous_expires_at}.` : "";
1305
+ if (secretFile) {
1306
+ writeSecret(input, secretFile, body);
1307
+ return {
1308
+ data: redacted(body, secretFile),
1309
+ table: `New secret for ${platform.name} in ${secretFile}.${previous}`
1310
+ };
1311
+ }
1312
+ return {
1313
+ data: { client_id: body.client_id, created_at: body.created_at },
1314
+ table: [
1315
+ `New secret for ${platform.name}:`,
1316
+ lines([
1317
+ ["Client ID", body.client_id],
1318
+ ["Client secret", body.client_secret]
1319
+ ]),
1320
+ `This secret is shown once and won't be shown again.${previous}`
1321
+ ].join("\n")
1322
+ };
1323
+ }
1324
+ }
1325
+ throw new CliError("internal", EXIT.error, `nf ${name} has no handler`);
1326
+ }
1327
+ async function addSaml(input) {
1328
+ const { args, values, api, io } = input;
1329
+ const [first = ""] = args;
1330
+ if (values.public === true || values.callback !== void 0 || values["secret-file"] !== void 0)
1331
+ throw usageError(
1332
+ "invalid_option",
1333
+ "A SAML platform takes no --public, --callback or --secret-file: give --entity-id and --acs"
1334
+ );
1335
+ const prompting = atTerminal(input) && !!io.ask;
1336
+ const ask = async (question) => prompting && io.ask ? (await io.ask(question)).trim() : "";
1337
+ const givenAcs = values.acs;
1338
+ let acs = Array.isArray(givenAcs) ? givenAcs : typeof givenAcs === "string" ? [givenAcs] : [];
1339
+ let entityId = typeof values["entity-id"] === "string" ? values["entity-id"] : "";
1340
+ if (!prompting) {
1341
+ if (!first) throw usageError("missing_argument", "nf platform add --saml needs <name>");
1342
+ if (typeof values.domain !== "string")
1343
+ throw usageError("missing_option", "nf platform add --saml needs --domain <fqdn>");
1344
+ if (!entityId || acs.length === 0)
1345
+ throw usageError("missing_option", "nf platform add --saml needs --entity-id and --acs");
1346
+ }
1347
+ const certPath = typeof values["sp-cert"] === "string" ? values["sp-cert"] : void 0;
1348
+ const pem = certPath === void 0 ? void 0 : io.readFile(certPath);
1349
+ if (certPath !== void 0 && pem === void 0)
1350
+ throw usageError("invalid_option", `No certificate file at ${certPath}`);
1351
+ const attributes = typeof values.attributes === "string" ? values.attributes.split(",").map((a) => a.trim()).filter(Boolean) : void 0;
1352
+ const platformName = first || await ask("Name for this platform? ");
1353
+ if (!platformName) throw usageError("missing_argument", "nf platform add --saml needs <name>");
1354
+ const o = pathSegment(await selectedOrgId(input.context, api));
1355
+ let domain;
1356
+ if (typeof values.domain === "string") domain = await resolveDomain(api, o, values.domain);
1357
+ else {
1358
+ const choices = await activeDomains(api, o);
1359
+ const fallback = choices[0];
1360
+ if (!fallback)
1361
+ throw new CliError(
1362
+ "conflict",
1363
+ EXIT.conflict,
1364
+ "A platform goes on a verified domain, and this organisation has none yet: nf domain setup <domain>"
1365
+ );
1366
+ const listed = choices.length > 1 ? ` (${choices.map((d) => d.display_name).join(", ")})` : "";
1367
+ const answer = await ask(`Which domain? [${fallback.display_name}]${listed} `);
1368
+ domain = answer ? await resolveDomain(api, o, answer) : fallback;
1369
+ }
1370
+ if (!entityId) entityId = await ask("Entity ID the platform gave you? ");
1371
+ if (!entityId) throw usageError("missing_option", "A SAML platform needs its entity ID");
1372
+ if (acs.length === 0) {
1373
+ const answer = await ask("ACS (reply) address the platform gave you? ");
1374
+ if (answer) acs = [answer];
1375
+ }
1376
+ if (acs.length === 0) throw usageError("missing_option", "A SAML platform needs its ACS address");
1377
+ const { body } = await api.post(`/v1/orgs/${o}/platforms`, {
1378
+ name: platformName,
1379
+ domain_id: domain.id,
1380
+ protocol: "saml",
1381
+ saml: {
1382
+ entity_id: entityId,
1383
+ acs_urls: acs,
1384
+ ...pem !== void 0 ? { request_certificates: [pem] } : {},
1385
+ ...attributes ? { attributes } : {}
1386
+ }
1387
+ });
1388
+ const { platform } = body;
1389
+ const state = await issuerState(api, o, { ...platform, domain_id: domain.id });
1390
+ const saml = samlPasteable({ ...platform, domain: platform.domain ?? domain.name }, state);
1391
+ const text = [
1392
+ `Added ${platform.name} on ${platform.domain ?? domain.name}, a SAML platform. Every member can sign in to it. Paste these into the platform:`,
1393
+ lines([
1394
+ ["IdP entity ID", urlText(saml.idp_entity_id, saml.active, state, domain.name)],
1395
+ ["Metadata URL", urlText(saml.metadata_url, saml.active, state, domain.name)],
1396
+ ["SSO URL", urlText(saml.sso_url, saml.active, state, domain.name)],
1397
+ ["NameID", saml.name_id],
1398
+ ["Certificate", saml.certificate ? "(PEM, below)" : certificateText(null, saml.metadata_url)]
1399
+ ]),
1400
+ ...saml.certificate ? [saml.certificate.trimEnd()] : [],
1401
+ ...saml.active ? [] : [
1402
+ `Nobody can sign in to it until ${domain.name} has an active sign-in host, which serves it.`
1403
+ ]
1404
+ ].join("\n");
1405
+ return { data: { platform }, table: text };
1406
+ }
1407
+
1408
+ // src/setup.ts
1409
+ async function runSetup(input) {
1410
+ const { name, args, values, context, api, io } = input;
1411
+ const org = pathSegment(await selectedOrgId(context, api));
1412
+ const fqdn = (args[0] ?? "").trim().toLowerCase().replace(/\.$/, "");
1413
+ const zone = values.zone === true;
1414
+ if (name === "domain check") {
1415
+ const domain2 = await resolveDomain(api, org, fqdn);
1416
+ const { body: body2 } = await api.post(
1417
+ `/v1/orgs/${org}/domains/${pathSegment(domain2.id)}/check`
1418
+ );
1419
+ return show(body2, zone);
1420
+ }
1421
+ const prompting = context.interactive && values.json !== true && values.output === void 0 && !!io.ask;
1422
+ const ask = async (question, fallback) => prompting && io.ask ? await io.ask(question) || fallback : fallback;
1423
+ let email = typeof values.email === "string" ? values.email === "yes" : void 0;
1424
+ if (email === void 0)
1425
+ email = /^y/i.test(await ask(`Forward mail sent to ${fqdn}? [Y/n] `, "y"));
1426
+ let routesText = typeof values.routes === "string" ? values.routes : void 0;
1427
+ if (email && routesText === void 0)
1428
+ routesText = await ask(
1429
+ "Forward which addresses? (such as hello=you@example.net, comma-separated; Enter for none) ",
1430
+ ""
1431
+ );
1432
+ const routes = parseRoutes(email ? routesText ?? "" : "");
1433
+ let host = typeof values.host === "string" ? values.host : void 0;
1434
+ if (host === void 0)
1435
+ host = await ask(
1436
+ `Host for sign-in and confirmations? [auth.${fqdn}] (none to skip) `,
1437
+ `auth.${fqdn}`
1438
+ );
1439
+ const hostname = host === "none" || host === "" ? void 0 : host.includes(".") ? host : `${host}.${fqdn}`;
1440
+ if (email && !hostname)
1441
+ throw usageError(
1442
+ "host_required",
1443
+ `Forwarding needs a host on ${fqdn}: new mailboxes confirm on it. Give one, such as auth.${fqdn}.`
1444
+ );
1445
+ let memberName = typeof values.name === "string" ? values.name : void 0;
1446
+ if (memberName === void 0)
1447
+ memberName = await ask("Your name at your domains, such as alex? (Enter to skip) ", "") || void 0;
1448
+ const billing = await api.get(`/v1/orgs/${org}/billing`).then((answer) => answer.body).catch(() => void 0);
1449
+ const domain = await claim(input, org, fqdn);
1450
+ await api.put(`/v1/orgs/${org}/domains/${pathSegment(domain.id)}/setup`, {
1451
+ email,
1452
+ ...routes.length ? { routes } : {},
1453
+ ...hostname ? { host: hostname } : {},
1454
+ ...memberName ? { name: memberName } : {}
1455
+ });
1456
+ const { body } = await api.get(
1457
+ `/v1/orgs/${org}/domains/${pathSegment(domain.id)}/records`
1458
+ );
1459
+ if (billing?.payment_method === "none")
1460
+ body.next = [
1461
+ "Add a card first, or the domain can't be verified: nf billing setup.",
1462
+ ...body.next ?? []
1463
+ ];
1464
+ return show(body, zone);
1465
+ }
1466
+ async function claim(input, org, fqdn) {
1467
+ try {
1468
+ const found = await resolveDomain(input.api, org, fqdn);
1469
+ if (found.status === "pending" || found.status === "active") return found;
1470
+ } catch (error) {
1471
+ if (!(error instanceof CliError) || error.exit !== EXIT.notFound) throw error;
1472
+ }
1473
+ return (await input.api.post(`/v1/orgs/${org}/domains`, { name: fqdn })).body;
1474
+ }
1475
+ function parseRoutes(text) {
1476
+ return text.split(",").map((part) => part.trim()).filter(Boolean).map((part) => {
1477
+ const [local = "", to = ""] = part.split("=").map((side) => side.trim());
1478
+ const bare = local.toLowerCase().replace(/@.*$/, "");
1479
+ if (!bare || !to.includes("@"))
1480
+ throw usageError(
1481
+ "invalid_option",
1482
+ `"${part}" isn't local=address, such as hello=me@example.net`
1483
+ );
1484
+ return { local: bare, to };
1485
+ });
1486
+ }
1487
+ function show(answer, zone) {
1488
+ const records2 = { ...answer, records: answer.records ?? [], next: answer.next ?? [] };
1489
+ if (zone) return { data: records2, table: zoneFile(records2) };
1490
+ const blocks = records2.records.map(
1491
+ (r) => [
1492
+ `${r.status.padEnd(8)} ${r.type.padEnd(5)} ${r.name}${r.required ? "" : " (recommended)"}`,
1493
+ ` ${r.priority === void 0 ? "" : `${r.priority} `}${r.value}`
1494
+ ].join("\n")
1495
+ );
1496
+ const next = records2.next.length ? ["", ...records2.next] : ["", `${records2.domain} is set up.`];
1497
+ return { data: records2, table: [...blocks, ...next].join("\n") };
1498
+ }
1499
+ function zoneFile(records2) {
1500
+ const lines2 = records2.records.map((r) => {
1501
+ const name = `${r.name}.`;
1502
+ if (r.type === "TXT") {
1503
+ const chunks = r.value.match(/.{1,255}/g) ?? [r.value];
1504
+ return `${name} 300 IN TXT ${chunks.map((c) => `"${c}"`).join(" ")}`;
1505
+ }
1506
+ if (r.type === "MX") return `${name} 300 IN MX ${r.priority ?? 10} ${r.value}.`;
1507
+ return `${name} 300 IN ${r.type} ${r.value}.`;
1508
+ });
1509
+ return [...lines2, ...records2.next.map((line) => `; ${line}`)].join("\n");
1510
+ }
1511
+
1512
+ // src/sign-in.ts
1513
+ var brandingRow = (b) => ({
1514
+ name: b.display_name,
1515
+ primary: b.primary_colour,
1516
+ background: b.background_colour,
1517
+ logo: b.logo ? `${b.logo.width}x${b.logo.height} PNG, ${b.logo.bytes} bytes` : "(none)",
1518
+ dark: b.dark ? `${b.dark.primary_colour} on ${b.dark.background_colour}` : "(none: the colours above in both modes)",
1519
+ "dark logo": b.dark_logo ? `${b.dark_logo.width}x${b.dark_logo.height} PNG, ${b.dark_logo.bytes} bytes` : "(none: the logo in both modes)",
1520
+ support: b.support_url ?? "",
1521
+ shown: b.shown ? "yes" : "no: the organisation needs an active verified domain"
1522
+ });
1523
+ var policyRow = (p) => ({
1524
+ passkeys: "always",
1525
+ "emailed links": p.email_links,
1526
+ ...p.version === void 0 ? { set: "no, the default" } : {}
1527
+ });
1528
+ var HOST_STATUS = {
1529
+ pending: "pending: the edge hasn't served it yet",
1530
+ active: "active",
1531
+ suspended: "suspended: its proof, record or certificate failed a check",
1532
+ removed: "removed"
1533
+ };
1534
+ function hostOutcome(h) {
1535
+ const lines2 = [
1536
+ `${h.hostname}: ${HOST_STATUS[h.status] ?? h.status}`,
1537
+ ...h.records.length ? [
1538
+ "",
1539
+ "Publish these records in the domain's DNS (nf never changes DNS):",
1540
+ ...h.records.map((r) => ` ${r.type.padEnd(6)} ${r.name} ${r.value} (${r.purpose})`)
1541
+ ] : ["", "The records to publish appear here once the edge has asked for the certificate."]
1542
+ ];
1543
+ return { data: h, table: lines2.join("\n") };
1544
+ }
1545
+ async function current(api, path) {
1546
+ try {
1547
+ const { body, etag } = await api.get(path);
1548
+ return { body, etag: etag ?? etagFor(body.version ?? 1) };
1549
+ } catch (error) {
1550
+ if (error.code === "not_found") return void 0;
1551
+ throw error;
1552
+ }
1553
+ }
1554
+ async function runSignIn(input) {
1555
+ const { name, values, context, api, io } = input;
1556
+ const org = encodeURIComponent(await selectedOrgId(context, api));
1557
+ const hostArg = () => (input.args[0] ?? "").trim().toLowerCase().replace(/\.$/, "");
1558
+ const brandDomain = typeof values.domain === "string" ? await resolveDomain(api, org, values.domain) : void 0;
1559
+ const branding = brandDomain ? `/v1/orgs/${org}/domains/${pathSegment(brandDomain.id)}/branding` : `/v1/orgs/${org}/branding`;
1560
+ const policy = `/v1/orgs/${org}/sign-in-policy`;
1561
+ const text = (key) => typeof values[key] === "string" ? values[key] : void 0;
1562
+ switch (name) {
1563
+ case "org branding show": {
1564
+ const found = await current(api, branding);
1565
+ if (!found)
1566
+ return {
1567
+ data: null,
1568
+ table: brandDomain ? `${brandDomain.name} has no brand of its own: its host shows the organisation's.` : "No sign-in branding yet. Set it with nf org branding set."
1569
+ };
1570
+ return { data: found.body, table: brandingRow(found.body) };
1571
+ }
1572
+ case "org branding set": {
1573
+ const read = (option) => {
1574
+ const path = text(option);
1575
+ const bytes = path === void 0 ? void 0 : io.readBytes(path);
1576
+ if (path !== void 0 && bytes === void 0)
1577
+ throw usageError("invalid_option", `No logo file at ${path}`);
1578
+ return bytes;
1579
+ };
1580
+ const logo = read("logo");
1581
+ const darkLogo = read("dark-logo");
1582
+ const darkPrimary = text("dark-primary")?.toLowerCase();
1583
+ const darkBackground = text("dark-background")?.toLowerCase();
1584
+ if (darkPrimary === void 0 !== (darkBackground === void 0))
1585
+ throw usageError(
1586
+ "invalid_option",
1587
+ "Give dark mode both colours: --dark-primary and --dark-background."
1588
+ );
1589
+ if (values["light-only"] === true && darkPrimary !== void 0)
1590
+ throw usageError(
1591
+ "invalid_option",
1592
+ "--light-only drops the dark colours: give one or the other."
1593
+ );
1594
+ const existing = await current(api, branding);
1595
+ const dark = darkPrimary !== void 0 && darkBackground !== void 0 ? { primary_colour: darkPrimary, background_colour: darkBackground } : values["light-only"] === true ? void 0 : existing?.body.dark;
1596
+ const { body: set } = await api.put(
1597
+ branding,
1598
+ {
1599
+ display_name: text("name"),
1600
+ primary_colour: text("primary")?.toLowerCase(),
1601
+ background_colour: text("background")?.toLowerCase(),
1602
+ ...dark ? { dark } : {},
1603
+ ...text("support-url") === void 0 ? {} : { support_url: text("support-url") }
1604
+ },
1605
+ existing?.etag
1606
+ );
1607
+ let body = set;
1608
+ for (const [path, bytes] of [
1609
+ ["logo", logo],
1610
+ ["dark-logo", darkLogo]
1611
+ ]) {
1612
+ if (bytes === void 0) continue;
1613
+ body = (await api.put(
1614
+ `${branding}/${path}`,
1615
+ { png_base64: Buffer.from(bytes).toString("base64") },
1616
+ etagFor(body.version)
1617
+ )).body;
1618
+ }
1619
+ return { data: body, table: brandingRow(body) };
1620
+ }
1621
+ case "org branding remove": {
1622
+ await api.delete(branding);
1623
+ return {
1624
+ data: { removed: brandDomain?.id },
1625
+ table: `${brandDomain?.name} shows the organisation's brand again.`
1626
+ };
1627
+ }
1628
+ case "org branding remove-logo": {
1629
+ const { body } = await api.deleteFor(
1630
+ `${branding}/${values.dark === true ? "dark-logo" : "logo"}`
1631
+ );
1632
+ return { data: body, table: brandingRow(body) };
1633
+ }
1634
+ case "org sign-in show": {
1635
+ const { body } = await api.get(policy);
1636
+ return { data: body, table: policyRow(body) };
1637
+ }
1638
+ case "org sign-in set": {
1639
+ const existing = await api.get(policy);
1640
+ const { body } = await api.put(
1641
+ policy,
1642
+ { email_links: text("email-links") },
1643
+ existing.body.version === void 0 ? void 0 : etagFor(existing.body.version)
1644
+ );
1645
+ return { data: body, table: policyRow(body) };
1646
+ }
1647
+ case "auth-host add": {
1648
+ const { body } = await api.post(`/v1/orgs/${org}/auth-hosts`, {
1649
+ hostname: input.args[0]
1650
+ });
1651
+ return hostOutcome(body);
1652
+ }
1653
+ case "auth-host list": {
1654
+ const all = await api.list(`/v1/orgs/${org}/auth-hosts`);
1655
+ return {
1656
+ data: all,
1657
+ table: all.map((h) => ({ hostname: h.hostname, status: h.status }))
1658
+ };
1659
+ }
1660
+ case "auth-host show": {
1661
+ const { body } = await api.get(
1662
+ `/v1/orgs/${org}/auth-hosts/${pathSegment(hostArg())}`
1663
+ );
1664
+ return hostOutcome(body);
1665
+ }
1666
+ case "auth-host check": {
1667
+ const { body } = await api.post(
1668
+ `/v1/orgs/${org}/auth-hosts/${pathSegment(hostArg())}/check`
1669
+ );
1670
+ return hostOutcome(body);
1671
+ }
1672
+ case "auth-host remove": {
1673
+ await api.delete(`/v1/orgs/${org}/auth-hosts/${pathSegment(hostArg())}`);
1674
+ return {
1675
+ data: { removed: hostArg() },
1676
+ table: `Removed ${hostArg()}. That domain's platforms sign no one in until it has a host again.`
1677
+ };
1678
+ }
1679
+ default:
1680
+ throw usageError("unknown_command", `nf ${name} isn't a sign-in command`);
1681
+ }
1682
+ }
1683
+
1684
+ // src/usage.ts
1685
+ var DATE = /^\d{4}-\d{2}-\d{2}(T[\d:.]+Z)?$/;
1686
+ async function runUsage(input) {
1687
+ const { values, context, api } = input;
1688
+ const query = {};
1689
+ for (const name of ["from", "to"]) {
1690
+ const value = values[name];
1691
+ if (value === void 0) continue;
1692
+ if (typeof value !== "string" || !DATE.test(value))
1693
+ throw usageError("invalid_option", `--${name} is a UTC date, like 2026-11-01`);
1694
+ query[name] = value;
1695
+ }
1696
+ const org = encodeURIComponent(await selectedOrgId(context, api));
1697
+ const { body } = await api.get(`/v1/orgs/${org}/usage`, query);
1698
+ const proposed = body.price_versions.some((v) => v.status === "proposal");
1699
+ const rows = body.lines.map((line) => ({
1700
+ meter: line.meter,
1701
+ month: line.month,
1702
+ quantity: line.unit === "hour" ? `${line.quantity} h` : line.quantity,
1703
+ rate: line.unit === "hour" ? `A$${line.rate_aud}/h` : `A$${line.rate_aud}`,
1704
+ monthly: line.monthly_equivalent_aud ? `A$${line.monthly_equivalent_aud}/mo` : "",
1705
+ amount: `A$${line.amount_aud}`
1706
+ }));
1707
+ const footer = `Total A$${body.total_aud}, exact: rounded only on an invoice${proposed ? ". Proposed rates" : ""}`;
1708
+ return {
1709
+ data: body,
1710
+ table: rows.length ? [...rows, { meter: footer }] : `No usage from ${body.from} to ${body.to}. ${footer}`
1711
+ };
1712
+ }
1713
+ function aud(cents) {
1714
+ const negative = cents.startsWith("-");
1715
+ const digits = (negative ? cents.slice(1) : cents).padStart(3, "0");
1716
+ return `${negative ? "-" : ""}A$${digits.slice(0, -2)}.${digits.slice(-2)}`;
1717
+ }
1718
+ async function runInvoices(input) {
1719
+ const org = encodeURIComponent(await selectedOrgId(input.context, input.api));
1720
+ const all = await input.api.list(`/v1/orgs/${org}/invoices`);
1721
+ return {
1722
+ data: all,
1723
+ table: all.length ? all.map((invoice) => ({
1724
+ invoice: invoice.id,
1725
+ period: invoice.period,
1726
+ status: invoice.status,
1727
+ total: aud(invoice.total_cents),
1728
+ issued: invoice.issued_at.slice(0, 10),
1729
+ paid: invoice.paid_at?.slice(0, 10) ?? ""
1730
+ })) : "No invoices yet. A month under A$10 carries forward; `nf usage show` has what's unbilled."
1731
+ };
1732
+ }
1733
+ async function runBilling(input) {
1734
+ const org = encodeURIComponent(await selectedOrgId(input.context, input.api));
1735
+ if (input.name === "billing setup") {
1736
+ const { body: body2 } = await input.api.post(`/v1/orgs/${org}/billing/setup`, {});
1737
+ return {
1738
+ data: body2,
1739
+ table: `Add a card on Stripe's page. It expires, and nf never sees the card:
1740
+
1741
+ ${body2.url}
1742
+
1743
+ Then \`nf billing show\` says when it is on file.`
1744
+ };
1745
+ }
1746
+ const { body } = await input.api.get(
1747
+ `/v1/orgs/${org}/billing`
1748
+ );
1749
+ return {
1750
+ data: body,
1751
+ table: body.payment_method === "on_file" ? "A card is on file. Invoices charge it." : "No card on file. An owner adds one with `nf billing setup` before anything billable starts."
1752
+ };
1753
+ }
1754
+
1755
+ // src/api-commands.ts
1756
+ var isId = (prefix, value) => value.startsWith(`${prefix}_`);
1757
+ function notFound(what, value) {
1758
+ return new CliError("not_found", EXIT.notFound, `No ${what} \`${value}\` that you can see`);
1759
+ }
1760
+ function parseLimit(values) {
1761
+ const raw = values.limit;
1762
+ if (raw === void 0) return void 0;
1763
+ const n = typeof raw === "string" && /^[1-9][0-9]{0,5}$/.test(raw) ? Number(raw) : Number.NaN;
1764
+ if (!Number.isInteger(n))
1765
+ throw usageError("invalid_option", "--limit must be a whole number from 1");
1766
+ return n;
1767
+ }
1768
+ async function resolveOrg(api, value) {
1769
+ if (isId("org", value))
1770
+ return (await api.get(`/v1/orgs/${pathSegment(value)}`)).body;
1771
+ const found = (await api.list("/v1/orgs")).find((o) => o.name === value);
1772
+ if (!found) throw notFound("organisation", value);
1773
+ return found;
1774
+ }
1775
+ async function selectedOrgId(context, api) {
1776
+ const value = context.org?.value;
1777
+ if (!value) {
1778
+ throw configError(
1779
+ "no_org_selected",
1780
+ "No organisation selected",
1781
+ "Run `nf org use <name>`, or pass --org."
1782
+ );
1783
+ }
1784
+ return isId("org", value) ? value : (await resolveOrg(api, value)).id;
1785
+ }
1786
+ var domainKey = (value) => value.toLowerCase().replace(/\.$/, "");
1787
+ async function resolveDomain(api, org, value) {
1788
+ if (isId("dom", value))
1789
+ return (await api.get(`/v1/orgs/${pathSegment(org)}/domains/${pathSegment(value)}`)).body;
1790
+ const key = domainKey(value);
1791
+ const all = await api.list(`/v1/orgs/${pathSegment(org)}/domains`);
1792
+ const named = all.filter((d) => domainKey(d.name) === key || domainKey(d.display_name) === key);
1793
+ const found = named.find((d) => d.status !== "removed") ?? named[0];
1794
+ if (!found) throw notFound("domain", value);
1795
+ return found;
1796
+ }
1797
+ var DOMAIN_STATUS = {
1798
+ active: "active",
1799
+ pending: "pending proof",
1800
+ expired: "expired",
1801
+ removed: "removed"
1802
+ };
1803
+ var domainRow2 = (d) => ({
1804
+ id: d.id,
1805
+ name: d.display_name,
1806
+ status: DOMAIN_STATUS[d.status] ?? d.status,
1807
+ ...d.status === "active" ? { verified: d.verified_at ?? "" } : { expires: d.expires_at ?? "" }
1808
+ });
1809
+ function instructions(d) {
1810
+ return [
1811
+ `Publish this DNS record for ${d.display_name}:`,
1812
+ "",
1813
+ ` name ${d.challenge.record_name}`,
1814
+ ` type ${d.challenge.record_type}`,
1815
+ ` value ${d.challenge.record_value}`,
1816
+ "",
1817
+ d.expires_at ? `The claim expires at ${d.expires_at} unless it is verified.` : "",
1818
+ `Then run: nf domain verify ${d.name}`
1819
+ ].filter((line, i, all) => line !== "" || all[i - 1] !== "").join("\n");
1820
+ }
1821
+ var orgRow = (o) => ({
1822
+ id: o.id,
1823
+ name: o.name,
1824
+ status: o.status,
1825
+ created: o.created_at
1826
+ });
1827
+ var memberRow = (m) => ({
1828
+ membership: m.id,
1829
+ person: m.person_id,
1830
+ role: m.role,
1831
+ status: m.status,
1832
+ names: (m.names ?? []).join(", "),
1833
+ since: m.created_at
1834
+ });
1835
+ var inviteRow = (i) => ({
1836
+ id: i.id,
1837
+ email: i.email,
1838
+ status: i.status,
1839
+ expires: i.expires_at
1840
+ });
1841
+ var auditRow = (a) => ({
1842
+ when: a.occurred_at,
1843
+ action: a.action,
1844
+ actor: a.actor.id ?? a.actor.type,
1845
+ target: a.target_id,
1846
+ summary: a.summary
1847
+ });
1848
+ var gone = (what, id) => ({
1849
+ data: { deleted: id },
1850
+ table: `Deleted ${what} ${id}`
1851
+ });
1852
+ async function runApiCommand(input) {
1853
+ const { name, args, values, context, api, io } = input;
1854
+ const limit2 = parseLimit(values);
1855
+ const [first = "", second = ""] = args;
1856
+ const org = async () => pathSegment(await selectedOrgId(context, api));
1857
+ if (name.startsWith("org branding ") || name.startsWith("org sign-in ") || name.startsWith("auth-host "))
1858
+ return runSignIn(input);
1859
+ if (name === "domain setup" || name === "domain check") return runSetup(input);
1860
+ if (name.startsWith("platform ")) return runPlatforms(input);
1861
+ if (name === "usage show") return runUsage(input);
1862
+ if (name === "billing invoices") return runInvoices(input);
1863
+ if (name === "billing show" || name === "billing setup") return runBilling(input);
1864
+ if (name === "email" || name.startsWith("email ")) return runEmail(input);
1865
+ switch (name) {
1866
+ case "whoami": {
1867
+ const { body } = await api.get("/v1/me");
1868
+ const who = { person: body.person?.id, name: body.person?.display_name };
1869
+ return {
1870
+ data: { ...body, stage: context.stage, api: context.api, org: context.org?.value ?? null },
1871
+ table: {
1872
+ ...who,
1873
+ "authenticated by": body.authenticated_by,
1874
+ stage: context.stage,
1875
+ api: context.api,
1876
+ org: context.org?.value ?? "(none: nf org use <name>)"
1877
+ }
1878
+ };
1879
+ }
1880
+ case "org create": {
1881
+ const { body } = await api.post("/v1/orgs", { name: first });
1882
+ const path = setProfileOrg(context, body.id, io);
1883
+ return {
1884
+ data: { ...body, profile: context.profile.name, config_path: path },
1885
+ table: orgRow(body)
1886
+ };
1887
+ }
1888
+ case "org list": {
1889
+ const all = await api.list("/v1/orgs", limit2);
1890
+ return { data: all, table: all.map(orgRow) };
1891
+ }
1892
+ case "org show": {
1893
+ const target = first ? await resolveOrg(api, first) : void 0;
1894
+ const body = target ?? (await api.get(`/v1/orgs/${await org()}`)).body;
1895
+ return { data: body, table: orgRow(body) };
1896
+ }
1897
+ case "org use": {
1898
+ const target = await resolveOrg(api, first);
1899
+ const path = setProfileOrg(context, target.id, io);
1900
+ return {
1901
+ data: { org: target, profile: context.profile.name, config_path: path },
1902
+ table: `Using ${target.name} (${target.id}) on profile ${context.profile.name}, in ${path}`
1903
+ };
1904
+ }
1905
+ case "person list": {
1906
+ const all = await api.list(`/v1/orgs/${await org()}/members`, limit2);
1907
+ return { data: all, table: all.map(memberRow) };
1908
+ }
1909
+ case "person invite": {
1910
+ const { body } = await api.post(`/v1/orgs/${await org()}/invites`, {
1911
+ email: first,
1912
+ ...typeof values.name === "string" ? { name: values.name } : {}
1913
+ });
1914
+ return { data: body, table: inviteRow(body) };
1915
+ }
1916
+ case "person suspend":
1917
+ case "person restore": {
1918
+ const path = `/v1/orgs/${await org()}/members/${pathSegment(first)}`;
1919
+ const current2 = await api.get(path);
1920
+ const status = name === "person suspend" ? "suspended" : "active";
1921
+ const { body } = await api.patch(
1922
+ path,
1923
+ { status },
1924
+ current2.etag ?? etagFor(current2.body.version)
1925
+ );
1926
+ return { data: body, table: memberRow(body) };
1927
+ }
1928
+ case "org transfer": {
1929
+ const { body } = await api.post(`/v1/orgs/${await org()}/transfer`, {
1930
+ membership_id: first
1931
+ });
1932
+ return { data: body, table: `Ownership moved to ${body.id}. You are a member now.` };
1933
+ }
1934
+ case "org leave": {
1935
+ const id = await org();
1936
+ await api.post(`/v1/orgs/${id}/leave`, {});
1937
+ return { data: { left: id }, table: `You left ${id}.` };
1938
+ }
1939
+ case "org close": {
1940
+ const { body } = await api.post(`/v1/orgs/${await org()}/close`, {
1941
+ name: String(values.confirm ?? "")
1942
+ });
1943
+ return { data: body, table: `Closed ${body.name}. Anything owed is invoiced now.` };
1944
+ }
1945
+ case "person remove": {
1946
+ await api.delete(`/v1/orgs/${await org()}/members/${pathSegment(first)}`);
1947
+ return gone("membership", first);
1948
+ }
1949
+ case "person name add": {
1950
+ const { body } = await api.post(
1951
+ `/v1/orgs/${await org()}/members/${pathSegment(first)}/names`,
1952
+ { name: second }
1953
+ );
1954
+ return { data: body, table: memberRow(body) };
1955
+ }
1956
+ case "person name remove": {
1957
+ const { body } = await api.deleteFor(
1958
+ `/v1/orgs/${await org()}/members/${pathSegment(first)}/names/${pathSegment(second)}`
1959
+ );
1960
+ return { data: body, table: memberRow(body) };
1961
+ }
1962
+ case "invite list": {
1963
+ const all = await api.list(`/v1/orgs/${await org()}/invites`, limit2);
1964
+ return { data: all, table: all.map(inviteRow) };
1965
+ }
1966
+ case "invite revoke": {
1967
+ await api.delete(`/v1/orgs/${await org()}/invites/${pathSegment(first)}`);
1968
+ return gone("invite", first);
1969
+ }
1970
+ case "domain add": {
1971
+ const { body } = await api.post(`/v1/orgs/${await org()}/domains`, {
1972
+ name: first
1973
+ });
1974
+ return { data: body, table: instructions(body) };
1975
+ }
1976
+ case "domain instructions": {
1977
+ const domain = await resolveDomain(api, await org(), first);
1978
+ if (domain.status !== "pending") {
1979
+ return {
1980
+ data: domain,
1981
+ table: `${domain.display_name} is ${DOMAIN_STATUS[domain.status] ?? domain.status}; there is nothing to publish.`
1982
+ };
1983
+ }
1984
+ return { data: domain, table: instructions(domain) };
1985
+ }
1986
+ case "domain verify": {
1987
+ const o = await org();
1988
+ const domain = await resolveDomain(api, o, first);
1989
+ const { body } = await api.post(
1990
+ `/v1/orgs/${o}/domains/${pathSegment(domain.id)}/verify`
1991
+ );
1992
+ return {
1993
+ data: body,
1994
+ table: `${body.display_name} is ${DOMAIN_STATUS[body.status] ?? body.status}.`
1995
+ };
1996
+ }
1997
+ case "domain list": {
1998
+ const all = await api.list(`/v1/orgs/${await org()}/domains`, limit2);
1999
+ return { data: all, table: all.map(domainRow2) };
2000
+ }
2001
+ case "domain show": {
2002
+ const domain = await resolveDomain(api, await org(), first);
2003
+ return { data: domain, table: domainRow2(domain) };
2004
+ }
2005
+ case "domain remove": {
2006
+ const o = await org();
2007
+ const domain = await resolveDomain(api, o, first);
2008
+ await api.delete(`/v1/orgs/${o}/domains/${pathSegment(domain.id)}`, etagFor(domain.version));
2009
+ return { data: { removed: domain.id }, table: `Removed the claim on ${domain.display_name}` };
2010
+ }
2011
+ case "audit list": {
2012
+ const all = await api.list(`/v1/orgs/${await org()}/audit`, limit2);
2013
+ return { data: all, table: all.map(auditRow) };
2014
+ }
2015
+ }
2016
+ throw new CliError("internal", EXIT.error, `nf ${name} has no handler`);
2017
+ }
2018
+
2019
+ // src/mark.ts
2020
+ var MARK_COLUMNS = 14;
2021
+ var MARK = [
2022
+ " \u2584\u2588\u2588\u2588\u2588\u2588\u2588\u2584",
2023
+ " \u2584\u2588\u2588\u2580\u2580\u2580\u2580\u2580\u2580\u2588\u2588\u2584",
2024
+ "\u2588\u2588\u2588 \u2584\u2584 \u2588\u2588\u2588",
2025
+ "\u2588\u2588\u2588 \u2588\u2588\u2588\u2588 \u2588\u2588\u2588",
2026
+ "\u2588\u2588\u2588 \u2580\u2580\u2580\u2580 \u2588\u2588\u2588",
2027
+ " \u2580\u2588\u2588\u2584\u2584\u2584\u2584\u2584\u2584\u2588\u2588\u2588",
2028
+ " \u2580\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2580",
2029
+ " \u2588\u2588\u2588\u2580",
2030
+ " \u2584\u2588\u2588\u2588",
2031
+ " \u2584\u2588\u2588\u2580"
2032
+ ];
2033
+
2034
+ // src/banner.ts
2035
+ var BLUE = "\x1B[38;2;29;61;231m";
2036
+ var RESET = "\x1B[0m";
2037
+ function banner(options) {
2038
+ const beside = { 3: "nine fish", 4: `nf ${options.version}` };
2039
+ return MARK.map((line, row) => {
2040
+ const mark = options.colour && line.trim() ? `${BLUE}${line}${RESET}` : line;
2041
+ const text = beside[row];
2042
+ return text ? `${mark}${" ".repeat(MARK_COLUMNS - [...line].length + 4)}${text}` : mark;
2043
+ }).join("\n").concat("\n");
2044
+ }
2045
+ function wantsColour(env, isTTY) {
2046
+ return isTTY && !env.NO_COLOR && env.TERM !== "dumb";
2047
+ }
2048
+
2049
+ // src/commands.ts
2050
+ var limit = {
2051
+ limit: {
2052
+ type: "string",
2053
+ value: "n",
2054
+ description: "Show at most this many (default: all)"
2055
+ }
2056
+ };
2057
+ var COMMANDS = [
2058
+ {
2059
+ path: ["login"],
2060
+ summary: "Sign in in the browser with a passkey",
2061
+ options: {
2062
+ device: { type: "boolean", description: "Use a device code, for a machine with no browser" }
2063
+ }
2064
+ },
2065
+ {
2066
+ path: ["logout"],
2067
+ summary: "Sign out and remove this profile's tokens"
2068
+ },
2069
+ { path: ["whoami"], summary: "Show who you are signed in as, and where" },
2070
+ {
2071
+ path: ["org", "create"],
2072
+ summary: "Create an organisation, and make it the one nf acts on",
2073
+ args: [{ name: "name" }]
2074
+ },
2075
+ {
2076
+ path: ["org", "use"],
2077
+ summary: "Make an organisation this profile's default",
2078
+ args: [{ name: "org" }]
2079
+ },
2080
+ {
2081
+ path: ["org", "list"],
2082
+ summary: "List the organisations you belong to",
2083
+ options: limit
2084
+ },
2085
+ {
2086
+ path: ["org", "show"],
2087
+ summary: "Show an organisation (default: the selected one)",
2088
+ args: [{ name: "org", optional: true }]
2089
+ },
2090
+ {
2091
+ path: ["org", "branding", "show"],
2092
+ summary: "Show the brand end users see when they sign in",
2093
+ options: {
2094
+ domain: {
2095
+ type: "string",
2096
+ value: "domain",
2097
+ description: "One verified domain's own brand, which its host and mail show instead of the default"
2098
+ }
2099
+ }
2100
+ },
2101
+ {
2102
+ path: ["org", "branding", "set"],
2103
+ summary: "Set the sign-in brand: name, colours, optional dark-mode colours and logos, and a support link; with --domain, that domain's own",
2104
+ options: {
2105
+ domain: {
2106
+ type: "string",
2107
+ value: "domain",
2108
+ description: "One verified domain's own brand, which its host and mail show instead of the default"
2109
+ },
2110
+ name: {
2111
+ type: "string",
2112
+ value: "display-name",
2113
+ required: true,
2114
+ description: "The name end users see, such as Acme"
2115
+ },
2116
+ primary: {
2117
+ type: "string",
2118
+ value: "#rrggbb",
2119
+ required: true,
2120
+ description: "Buttons and links; at least 3:1 against the background"
2121
+ },
2122
+ background: {
2123
+ type: "string",
2124
+ value: "#rrggbb",
2125
+ required: true,
2126
+ description: "The page background"
2127
+ },
2128
+ logo: {
2129
+ type: "string",
2130
+ value: "file.png",
2131
+ description: "A PNG of at most 256 KiB and 1024 px a side"
2132
+ },
2133
+ "dark-primary": {
2134
+ type: "string",
2135
+ value: "#rrggbb",
2136
+ description: "Dark mode's primary colour, with --dark-background: pages follow the viewer's system setting. Kept if left out"
2137
+ },
2138
+ "dark-background": {
2139
+ type: "string",
2140
+ value: "#rrggbb",
2141
+ description: "Dark mode's page background, with --dark-primary"
2142
+ },
2143
+ "dark-logo": {
2144
+ type: "string",
2145
+ value: "file.png",
2146
+ description: "A logo for dark mode, as --logo. Without one, the logo shows in both modes"
2147
+ },
2148
+ "light-only": {
2149
+ type: "boolean",
2150
+ description: "Drop the dark-mode colours: one palette for both modes"
2151
+ },
2152
+ "support-url": {
2153
+ type: "string",
2154
+ value: "url",
2155
+ description: "An https link on one of the organisation's verified domains (with --domain, on that one)"
2156
+ }
2157
+ }
2158
+ },
2159
+ {
2160
+ path: ["org", "branding", "remove-logo"],
2161
+ summary: "Remove the sign-in logo, or with --dark the logo for dark mode",
2162
+ options: {
2163
+ dark: {
2164
+ type: "boolean",
2165
+ description: "Remove only the logo for dark mode: the logo then shows in both modes"
2166
+ },
2167
+ domain: {
2168
+ type: "string",
2169
+ value: "domain",
2170
+ description: "One verified domain's own brand, which its host and mail show instead of the default"
2171
+ }
2172
+ }
2173
+ },
2174
+ {
2175
+ path: ["org", "branding", "remove"],
2176
+ summary: "Remove a domain's own brand; its host shows the organisation's again",
2177
+ options: {
2178
+ domain: {
2179
+ type: "string",
2180
+ value: "domain",
2181
+ required: true,
2182
+ description: "The verified domain whose own brand to remove"
2183
+ }
2184
+ }
2185
+ },
2186
+ {
2187
+ path: ["org", "sign-in", "show"],
2188
+ summary: "Show how returning members may sign in"
2189
+ },
2190
+ {
2191
+ path: ["org", "sign-in", "set"],
2192
+ summary: "Turn emailed sign-in links on or off for returning members (owner, step-up)",
2193
+ options: {
2194
+ "email-links": {
2195
+ type: "string",
2196
+ value: "enabled|disabled",
2197
+ required: true,
2198
+ choices: ["enabled", "disabled"],
2199
+ description: "Passkeys are always on; this is whether a link by email may sign a member in"
2200
+ }
2201
+ }
2202
+ },
2203
+ {
2204
+ path: ["org", "transfer"],
2205
+ summary: "Make another member the owner; you become a member (owner, step-up)",
2206
+ args: [{ name: "membership" }]
2207
+ },
2208
+ {
2209
+ path: ["org", "leave"],
2210
+ summary: "Leave the selected organisation. The last owner transfers or closes it first"
2211
+ },
2212
+ {
2213
+ path: ["org", "close"],
2214
+ summary: "Close the organisation once nothing billable is left, and settle its account",
2215
+ options: {
2216
+ confirm: {
2217
+ type: "string",
2218
+ value: "name",
2219
+ required: true,
2220
+ description: "The organisation's name, to confirm"
2221
+ }
2222
+ }
2223
+ },
2224
+ {
2225
+ path: ["billing", "setup"],
2226
+ summary: "Print a Stripe page where an owner adds a card (owner, step-up)"
2227
+ },
2228
+ {
2229
+ path: ["billing", "show"],
2230
+ summary: "Show whether a card is on file, which anything billable needs first"
2231
+ },
2232
+ {
2233
+ path: ["billing", "invoices"],
2234
+ summary: "List invoices, newest first. What isn't invoiced yet is in `nf usage show`"
2235
+ },
2236
+ {
2237
+ path: ["domain", "setup"],
2238
+ summary: "Set a domain up in one go: asks what it is for, then prints every DNS record it needs at once",
2239
+ args: [{ name: "fqdn" }],
2240
+ options: {
2241
+ email: {
2242
+ type: "string",
2243
+ value: "yes|no",
2244
+ choices: ["yes", "no"],
2245
+ description: "Forward mail sent to this domain"
2246
+ },
2247
+ routes: {
2248
+ type: "string",
2249
+ value: "local=address,\u2026",
2250
+ description: "Addresses to forward, such as hello=me@example.net (with --email yes)"
2251
+ },
2252
+ host: {
2253
+ type: "string",
2254
+ value: "name|none",
2255
+ description: "Its sign-in host, such as auth.<domain>, or none"
2256
+ },
2257
+ name: {
2258
+ type: "string",
2259
+ value: "name",
2260
+ description: "Your own member name, which platforms see at each of your domains"
2261
+ },
2262
+ zone: { type: "boolean", description: "Print the records as a zone file" }
2263
+ }
2264
+ },
2265
+ {
2266
+ path: ["domain", "check"],
2267
+ summary: "Carry a domain's setup on as far as its DNS allows, and show each record's status",
2268
+ args: [{ name: "domain" }],
2269
+ options: {
2270
+ zone: { type: "boolean", description: "Print the records as a zone file" }
2271
+ }
2272
+ },
2273
+ {
2274
+ path: ["domain", "add"],
2275
+ summary: "Claim a domain and get its TXT proof",
2276
+ args: [{ name: "fqdn" }]
2277
+ },
2278
+ {
2279
+ path: ["domain", "instructions"],
2280
+ summary: "Show the DNS record that proves a domain",
2281
+ args: [{ name: "fqdn" }]
2282
+ },
2283
+ {
2284
+ path: ["domain", "verify"],
2285
+ summary: "Check a domain's TXT proof and make it active",
2286
+ args: [{ name: "fqdn" }]
2287
+ },
2288
+ { path: ["domain", "list"], summary: "List domain claims", options: limit },
2289
+ { path: ["domain", "show"], summary: "Show a domain claim", args: [{ name: "fqdn" }] },
2290
+ {
2291
+ path: ["domain", "remove"],
2292
+ summary: "Remove a domain claim and free its name",
2293
+ args: [{ name: "fqdn" }]
2294
+ },
2295
+ {
2296
+ path: ["email", "route", "create"],
2297
+ summary: "Forward an address to mailboxes, people or another of your addresses. A new mailbox is emailed to agree (step-up), and the route forwards there once it does",
2298
+ args: [{ name: "address" }],
2299
+ options: {
2300
+ to: {
2301
+ type: "string",
2302
+ value: "targets",
2303
+ required: true,
2304
+ description: "Comma-separated: mailboxes (address or id), your own addresses (address or rte_ id) or people (id)"
2305
+ }
2306
+ }
2307
+ },
2308
+ { path: ["email", "route", "list"], summary: "List routes", options: limit },
2309
+ {
2310
+ path: ["email", "route", "show"],
2311
+ summary: "Show a route, and any mailbox it waits for",
2312
+ args: [{ name: "route" }]
2313
+ },
2314
+ {
2315
+ path: ["email", "route", "update"],
2316
+ summary: "Replace where a route forwards",
2317
+ args: [{ name: "route" }],
2318
+ options: {
2319
+ to: {
2320
+ type: "string",
2321
+ value: "targets",
2322
+ required: true,
2323
+ description: "Comma-separated: mailboxes (address or id), your own addresses (address or rte_ id) or people (id)"
2324
+ }
2325
+ }
2326
+ },
2327
+ {
2328
+ path: ["email", "route", "delete"],
2329
+ summary: "Delete a route; its address is no longer forwarded",
2330
+ args: [{ name: "route" }]
2331
+ },
2332
+ {
2333
+ path: ["email", "destination", "add"],
2334
+ summary: "Add a mailbox to forward to; its owner is emailed to agree (needs a recent passkey step-up)",
2335
+ args: [{ name: "email" }],
2336
+ options: {
2337
+ person: {
2338
+ type: "string",
2339
+ value: "person",
2340
+ description: "The member whose mailbox it is, so routes to that person reach it"
2341
+ }
2342
+ }
2343
+ },
2344
+ {
2345
+ path: ["email", "destination", "list"],
2346
+ summary: "List destination mailboxes",
2347
+ options: limit
2348
+ },
2349
+ {
2350
+ path: ["email", "destination", "show"],
2351
+ summary: "Show a destination: pending, confirmed, suppressed or removed",
2352
+ args: [{ name: "destination" }]
2353
+ },
2354
+ {
2355
+ path: ["email", "destination", "resend"],
2356
+ summary: "Email a pending destination's owner the link again",
2357
+ args: [{ name: "destination" }]
2358
+ },
2359
+ {
2360
+ path: ["email", "destination", "remove"],
2361
+ summary: "Stop forwarding to a mailbox",
2362
+ args: [{ name: "destination" }]
2363
+ },
2364
+ {
2365
+ path: ["email", "enable"],
2366
+ summary: "Turn on email forwarding for a verified domain, and print the MX and DKIM records to publish",
2367
+ args: [{ name: "fqdn" }]
2368
+ },
2369
+ {
2370
+ path: ["email", "list"],
2371
+ summary: "List the domains email forwarding is on for",
2372
+ options: limit
2373
+ },
2374
+ {
2375
+ path: ["email", "show"],
2376
+ summary: "Show a domain's forwarding records and what DNS was last seen to hold",
2377
+ args: [{ name: "fqdn" }]
2378
+ },
2379
+ {
2380
+ path: ["email", "check"],
2381
+ summary: "Look up a domain's MX, DKIM and DMARC records now",
2382
+ args: [{ name: "fqdn" }]
2383
+ },
2384
+ {
2385
+ path: ["email", "disable"],
2386
+ summary: "Stop forwarding a domain's mail; its routes are kept",
2387
+ args: [{ name: "fqdn" }]
2388
+ },
2389
+ {
2390
+ path: ["platform", "add"],
2391
+ summary: "Add a platform your members sign in to, on one of your verified domains: OIDC, or SAML with --saml. At a terminal it asks for what's missing",
2392
+ args: [{ name: "name", optional: true }],
2393
+ options: {
2394
+ domain: {
2395
+ type: "string",
2396
+ value: "fqdn",
2397
+ description: "The verified domain it is on: its email claim is the member's name at this domain"
2398
+ },
2399
+ saml: {
2400
+ type: "boolean",
2401
+ description: "A platform that signs in only with SAML 2.0: give its entity ID and ACS address"
2402
+ },
2403
+ "entity-id": {
2404
+ type: "string",
2405
+ value: "uri",
2406
+ description: "SAML: the entity ID the platform gave you"
2407
+ },
2408
+ acs: {
2409
+ type: "string",
2410
+ value: "url",
2411
+ multiple: true,
2412
+ description: "SAML: the ACS (reply) address the platform gave you, matched exactly (needs a recent passkey step-up)"
2413
+ },
2414
+ "sp-cert": {
2415
+ type: "string",
2416
+ value: "path",
2417
+ description: "SAML: a PEM certificate the platform signs its requests with; then every request must be signed"
2418
+ },
2419
+ attributes: {
2420
+ type: "string",
2421
+ value: "list",
2422
+ description: "SAML: what an assertion carries beside the NameID: email, display_name"
2423
+ },
2424
+ callback: {
2425
+ type: "string",
2426
+ value: "uri",
2427
+ multiple: true,
2428
+ description: "The callback address the platform gave you, registered exactly (needs a recent passkey step-up)"
2429
+ },
2430
+ public: {
2431
+ type: "boolean",
2432
+ description: "A public OIDC client (a native or browser app): no secret, PKCE only"
2433
+ },
2434
+ "secret-file": {
2435
+ type: "string",
2436
+ value: "path",
2437
+ description: "Write the client secret here, readable only by you. Without it the secret is shown once, at a terminal only"
2438
+ }
2439
+ }
2440
+ },
2441
+ { path: ["platform", "list"], summary: "List platforms", options: limit },
2442
+ {
2443
+ path: ["platform", "show"],
2444
+ summary: "Show a platform and what to paste into it: issuer, client ID and endpoints, or a SAML platform's metadata, SSO URL and certificate",
2445
+ args: [{ name: "platform" }]
2446
+ },
2447
+ {
2448
+ path: ["platform", "callback", "add"],
2449
+ summary: "Register an exact callback address (needs a recent passkey step-up)",
2450
+ args: [{ name: "platform" }, { name: "uri" }]
2451
+ },
2452
+ {
2453
+ path: ["platform", "callback", "remove"],
2454
+ summary: "Remove a callback address (needs a recent passkey step-up)",
2455
+ args: [{ name: "platform" }, { name: "uri" }]
2456
+ },
2457
+ {
2458
+ path: ["platform", "remove"],
2459
+ summary: "Remove a platform: sign-in and its billing stop, and its name is freed",
2460
+ args: [{ name: "platform" }]
2461
+ },
2462
+ {
2463
+ path: ["platform", "rotate-secret"],
2464
+ summary: "Replace a platform's client secret (needs a recent passkey step-up)",
2465
+ args: [{ name: "platform" }],
2466
+ options: {
2467
+ "secret-file": {
2468
+ type: "string",
2469
+ value: "path",
2470
+ description: "Write the new secret here, readable only by you. Without it the secret is shown once, at a terminal only"
2471
+ }
2472
+ }
2473
+ },
2474
+ {
2475
+ path: ["person", "invite"],
2476
+ summary: "Invite a person by email. They join as a member",
2477
+ args: [{ name: "email" }],
2478
+ options: {
2479
+ name: {
2480
+ type: "string",
2481
+ value: "name",
2482
+ description: "Their member name, which platforms see at each domain (needs a recent passkey step-up). Without it, an address on one of your domains gives its part before @"
2483
+ }
2484
+ }
2485
+ },
2486
+ {
2487
+ path: ["person", "list"],
2488
+ summary: "List the organisation's people",
2489
+ options: limit
2490
+ },
2491
+ {
2492
+ path: ["person", "suspend"],
2493
+ summary: "Suspend a membership: no new sign-ins or access until restored",
2494
+ args: [{ name: "membership" }]
2495
+ },
2496
+ {
2497
+ path: ["person", "restore"],
2498
+ summary: "Restore a suspended membership",
2499
+ args: [{ name: "membership" }]
2500
+ },
2501
+ {
2502
+ path: ["person", "remove"],
2503
+ summary: "Revoke a membership. The person and their audit history remain",
2504
+ args: [{ name: "membership" }]
2505
+ },
2506
+ {
2507
+ path: ["person", "name", "add"],
2508
+ summary: "Give a member a name, valid at every verified domain of the organisation; platforms see it as their email",
2509
+ args: [{ name: "membership" }, { name: "name" }]
2510
+ },
2511
+ {
2512
+ path: ["person", "name", "remove"],
2513
+ summary: "Take a name from a member",
2514
+ args: [{ name: "membership" }, { name: "name" }]
2515
+ },
2516
+ { path: ["invite", "list"], summary: "List invites", options: limit },
2517
+ {
2518
+ path: ["invite", "revoke"],
2519
+ summary: "Revoke a pending invite",
2520
+ args: [{ name: "invite" }]
2521
+ },
2522
+ {
2523
+ path: ["auth-host", "add"],
2524
+ summary: "Add a sign-in host under a verified domain, one per domain: that domain's platforms sign in there (step-up)",
2525
+ args: [{ name: "hostname" }]
2526
+ },
2527
+ {
2528
+ path: ["auth-host", "list"],
2529
+ summary: "List the organisation's sign-in hosts, one at most per verified domain"
2530
+ },
2531
+ {
2532
+ path: ["auth-host", "show"],
2533
+ summary: "Show a sign-in host, its status and the records to publish",
2534
+ args: [{ name: "hostname" }]
2535
+ },
2536
+ {
2537
+ path: ["auth-host", "check"],
2538
+ summary: "Check a host's certificate and activate it once issued; publish its CNAME first (step-up)",
2539
+ args: [{ name: "hostname" }]
2540
+ },
2541
+ {
2542
+ path: ["auth-host", "remove"],
2543
+ summary: "Remove a sign-in host (step-up)",
2544
+ args: [{ name: "hostname" }]
2545
+ },
2546
+ {
2547
+ path: ["usage", "show"],
2548
+ summary: "Show resource-hours and billable operations",
2549
+ options: {
2550
+ from: {
2551
+ type: "string",
2552
+ value: "date",
2553
+ description: "Start, inclusive (UTC); default the 1st of this month"
2554
+ },
2555
+ to: { type: "string", value: "date", description: "End, exclusive (UTC); default now" }
2556
+ }
2557
+ },
2558
+ {
2559
+ path: ["audit", "list"],
2560
+ summary: "List audited changes, newest first",
2561
+ options: limit
2562
+ },
2563
+ { path: ["doctor"], summary: "Check this machine's nf setup", local: true },
2564
+ { path: ["version"], summary: "Show nf's version", local: true },
2565
+ {
2566
+ path: ["help"],
2567
+ summary: "Show help for a command",
2568
+ args: [{ name: "command", optional: true }],
2569
+ local: true
2570
+ }
2571
+ ];
2572
+ var GROUPS = {
2573
+ org: "Your organisation: make it, choose it, brand it, hand it on or close it",
2574
+ "org branding": "The brand people see on the sign-in pages, for the organisation or one domain",
2575
+ "org sign-in": "How returning members may sign in",
2576
+ billing: "Your card, and the invoices charged to it",
2577
+ domain: "Your domains: set one up, then check its records",
2578
+ email: "Forwarding mail at your domains to the mailboxes you use",
2579
+ "email route": "Addresses at your domains and where they forward",
2580
+ "email destination": "Mailboxes mail is forwarded to, each confirmed by its owner",
2581
+ platform: "Platforms your members sign in to, over OpenID Connect or SAML",
2582
+ "platform callback": "Callback addresses an OpenID Connect platform may return to",
2583
+ person: "The people in your organisation",
2584
+ "person name": "Member names, which platforms see at each of your domains",
2585
+ invite: "Invites not yet accepted",
2586
+ "auth-host": "Hosts for sign-in and mailbox confirmations, such as auth.example.com: one per domain",
2587
+ usage: "Resource-hours and billable operations so far",
2588
+ audit: "Who changed what"
2589
+ };
2590
+ function resolveCommand(words) {
2591
+ const path = [];
2592
+ for (const word of words) {
2593
+ const next = [...path, word];
2594
+ const leaf = COMMANDS.find((c) => c.path.join(" ") === next.join(" "));
2595
+ if (leaf) return { kind: "leaf", command: leaf, rest: words.slice(next.length) };
2596
+ if (!COMMANDS.some((c) => startsWith(c.path, next))) return { kind: "unknown", path, word };
2597
+ path.push(word);
2598
+ }
2599
+ return { kind: "group", path };
2600
+ }
2601
+ function children(path) {
2602
+ return COMMANDS.filter((c) => startsWith(c.path, path) && c.path.length > path.length);
2603
+ }
2604
+ function startsWith(path, prefix) {
2605
+ return prefix.every((word, i) => path[i] === word);
2606
+ }
2607
+ function usageLine(command) {
2608
+ const parts = ["nf", ...command.path];
2609
+ for (const arg of command.args ?? [])
2610
+ parts.push(arg.optional ? `[${arg.name}]` : `<${arg.name}>`);
2611
+ for (const [name, option] of Object.entries(command.options ?? {})) {
2612
+ if (option.required)
2613
+ parts.push(option.type === "boolean" ? `--${name}` : `--${name} <${option.value ?? name}>`);
2614
+ }
2615
+ return parts.join(" ");
2616
+ }
2617
+
2618
+ // src/doctor.ts
2619
+ var MIN_NODE = 24;
2620
+ function doctor(flags, env, io) {
2621
+ const checks = [];
2622
+ const major = Number(/^v?(\d+)/.exec(io.nodeVersion)?.[1] ?? 0);
2623
+ checks.push({
2624
+ name: "node",
2625
+ status: major >= MIN_NODE ? "ok" : "fail",
2626
+ detail: major >= MIN_NODE ? io.nodeVersion : `${io.nodeVersion}: nf needs Node ${MIN_NODE} or later`
2627
+ });
2628
+ let configOk = true;
2629
+ try {
2630
+ const { path, file } = loadConfig(env, io);
2631
+ checks.push({
2632
+ name: "config",
2633
+ status: "ok",
2634
+ detail: !path ? "no home directory: built-in profiles only" : file ? path : `${path} (none: built-in profiles only)`
2635
+ });
2636
+ } catch (error) {
2637
+ configOk = false;
2638
+ checks.push({ name: "config", status: "fail", detail: messageOf(error) });
2639
+ }
2640
+ let context;
2641
+ if (configOk) {
2642
+ try {
2643
+ context = resolveContext(flags, env, io);
2644
+ checks.push({
2645
+ name: "profile",
2646
+ status: "ok",
2647
+ detail: `${context.profile.name} (${context.profile.source}): ${context.stage}, ${context.api}`
2648
+ });
2649
+ } catch (error) {
2650
+ checks.push({ name: "profile", status: "fail", detail: messageOf(error) });
2651
+ }
2652
+ } else {
2653
+ checks.push({
2654
+ name: "profile",
2655
+ status: "fail",
2656
+ detail: "not resolved: the config file is invalid"
2657
+ });
2658
+ }
2659
+ const ci = context?.ci ?? false;
2660
+ checks.push({
2661
+ name: "ci",
2662
+ status: "ok",
2663
+ detail: ci ? "detected: no prompts, and no default stage" : "not detected"
2664
+ });
2665
+ checks.push({
2666
+ name: "login",
2667
+ status: "ok",
2668
+ detail: "run `nf whoami` to see who you are signed in as, or `nf login`"
2669
+ });
2670
+ return {
2671
+ ok: checks.every((check) => check.status !== "fail"),
2672
+ checks,
2673
+ context: context ? {
2674
+ profile: context.profile.name,
2675
+ profile_source: context.profile.source,
2676
+ stage: context.stage,
2677
+ api: context.api,
2678
+ auth: context.auth,
2679
+ org: context.org?.value ?? null,
2680
+ ci: context.ci,
2681
+ interactive: context.interactive,
2682
+ config_path: context.configPath ?? null
2683
+ } : null
2684
+ };
2685
+ }
2686
+ function messageOf(error) {
2687
+ if (error instanceof CliError)
2688
+ return error.remediation ? `${error.message}. ${error.remediation}` : error.message;
2689
+ return error instanceof Error ? error.message : String(error);
2690
+ }
2691
+
2692
+ // src/globals.ts
2693
+ var GLOBAL_OPTIONS = {
2694
+ org: { type: "string", value: "id|name", description: "The organisation to act on" },
2695
+ profile: {
2696
+ type: "string",
2697
+ value: "name",
2698
+ description: "The profile to use: a built-in stage profile, or one from the config file"
2699
+ },
2700
+ "no-interactive": { type: "boolean", description: "Never prompt; fail instead" },
2701
+ timeout: {
2702
+ type: "string",
2703
+ value: "duration",
2704
+ description: "Give up after this long: 30, 30s, 2m, 1500ms"
2705
+ },
2706
+ "request-id": { type: "string", value: "id", description: "The request id to send and report" },
2707
+ json: { type: "boolean", description: "Write JSON (the same as --output json)" },
2708
+ output: { type: "string", short: "o", value: "format", description: "json, yaml or table" },
2709
+ help: { type: "boolean", short: "h", description: "Show help" },
2710
+ version: { type: "boolean", description: "Show nf's version" }
2711
+ };
2712
+ var DEFAULT_TIMEOUT_MS = 3e4;
2713
+ var MAX_TIMEOUT_MS = 36e5;
2714
+ function parseFormat(json, output) {
2715
+ if (output !== void 0 && (typeof output !== "string" || !["json", "yaml", "table"].includes(output))) {
2716
+ throw usageError("invalid_option", "--output must be json, yaml or table");
2717
+ }
2718
+ if (json === true && output !== void 0 && output !== "json") {
2719
+ throw usageError("invalid_option", `--json and --output ${output} disagree`);
2720
+ }
2721
+ return json === true ? "json" : output ?? "table";
2722
+ }
2723
+ function parseTimeout(value) {
2724
+ if (value === void 0) return DEFAULT_TIMEOUT_MS;
2725
+ const match = typeof value === "string" ? /^(\d+)(ms|s|m)?$/.exec(value) : null;
2726
+ const ms = match ? Number(match[1]) * { ms: 1, s: 1e3, m: 6e4 }[match[2] ?? "s"] : Number.NaN;
2727
+ if (!(ms > 0 && ms <= MAX_TIMEOUT_MS)) {
2728
+ throw usageError(
2729
+ "invalid_option",
2730
+ "--timeout must be a duration up to an hour, such as 30s or 2m"
2731
+ );
2732
+ }
2733
+ return ms;
2734
+ }
2735
+ var REQUEST_ID = /^[A-Za-z0-9._:-]{1,128}$/;
2736
+ var ID_ALPHABET = "0123456789abcdefghjkmnpqrstvwxyz";
2737
+ function newRequestId() {
2738
+ let bits = 0n;
2739
+ for (const byte of crypto.getRandomValues(new Uint8Array(16))) bits = bits << 8n | BigInt(byte);
2740
+ let body = "";
2741
+ for (let i = 0; i < 26; i++) {
2742
+ body = ID_ALPHABET.charAt(Number(bits & 31n)) + body;
2743
+ bits >>= 5n;
2744
+ }
2745
+ return `req_${body}`;
2746
+ }
2747
+ function requestId(value) {
2748
+ if (value === void 0) return newRequestId();
2749
+ if (typeof value !== "string" || !REQUEST_ID.test(value)) {
2750
+ throw usageError(
2751
+ "invalid_option",
2752
+ "--request-id may hold letters, digits and . _ : - (at most 128)"
2753
+ );
2754
+ }
2755
+ return value;
2756
+ }
2757
+
2758
+ // src/output.ts
2759
+ import { stringify } from "yaml";
2760
+ function render(data, format) {
2761
+ if (format === "json") return `${JSON.stringify(data, null, 2)}
2762
+ `;
2763
+ if (format === "yaml") return stringify(data);
2764
+ if (Array.isArray(data)) return table(data);
2765
+ if (data !== null && typeof data === "object") {
2766
+ const entries = Object.entries(data).map(([key, value]) => ({ key, value }));
2767
+ return table(entries, { header: false });
2768
+ }
2769
+ return `${String(data)}
2770
+ `;
2771
+ }
2772
+ function table(rows, options = {}) {
2773
+ if (rows.length === 0) return "";
2774
+ const columns = [...new Set(rows.flatMap((row) => Object.keys(row)))];
2775
+ const cell = (value) => value === void 0 || value === null ? "" : typeof value === "object" ? JSON.stringify(value) : String(value);
2776
+ const body = rows.map((row) => columns.map((column) => cell(row[column])));
2777
+ const lines2 = options.header === false ? body : [columns, ...body];
2778
+ const widths = columns.map(
2779
+ (_, i) => Math.max(...lines2.map((line) => [...line[i] ?? ""].length))
2780
+ );
2781
+ return lines2.map(
2782
+ (line) => line.map((value, i) => value.padEnd(widths[i] ?? 0)).join(" ").trimEnd()
2783
+ ).join("\n").concat("\n");
2784
+ }
2785
+
2786
+ // src/version.ts
2787
+ var VERSION = "0.1.1";
2788
+
2789
+ // src/help.ts
2790
+ function optionRows(options) {
2791
+ return Object.entries(options).map(([name, option]) => ({
2792
+ flag: ` ${option.short ? `-${option.short}, ` : ""}--${name}${option.type === "string" ? ` <${option.value ?? name}>` : ""}${option.multiple ? "..." : ""}`,
2793
+ description: option.description + (option.required ? " (required)" : "")
2794
+ }));
2795
+ }
2796
+ var indent = (rows) => table(rows, { header: false }).split("\n").map((line) => line ? ` ${line}` : line).join("\n");
2797
+ function topHelp(colour) {
2798
+ const seen = /* @__PURE__ */ new Set();
2799
+ const rows = [];
2800
+ for (const command of COMMANDS) {
2801
+ const [word = ""] = command.path;
2802
+ if (seen.has(word)) continue;
2803
+ seen.add(word);
2804
+ rows.push({
2805
+ name: word,
2806
+ summary: command.path.length === 1 ? command.summary : GROUPS[word] ?? ""
2807
+ });
2808
+ }
2809
+ return [
2810
+ banner({ colour, version: VERSION }),
2811
+ "Usage: nf <command> [options]\n",
2812
+ "Commands:",
2813
+ indent(rows),
2814
+ "Global options:",
2815
+ table(optionRows(GLOBAL_OPTIONS), { header: false }),
2816
+ "Run `nf help <command>` for a command's arguments and options.",
2817
+ "At a terminal nf asks for what you leave out; under --json or --no-interactive it never asks.\n"
2818
+ ].join("\n");
2819
+ }
2820
+ function groupHelp(path) {
2821
+ const rows = children(path).map((command) => ({
2822
+ usage: usageLine(command),
2823
+ summary: command.summary
2824
+ }));
2825
+ return [`${GROUPS[path.join(" ")] ?? path.join(" ")}
2826
+ `, "Usage:", indent(rows)].join("\n");
2827
+ }
2828
+ function commandHelp(command) {
2829
+ const parts = [`${command.summary}
2830
+ `, `Usage: ${usageLine(command)} [options]
2831
+ `];
2832
+ if (command.options)
2833
+ parts.push("Options:", table(optionRows(command.options), { header: false }));
2834
+ parts.push("Takes the global options too: see `nf --help`.");
2835
+ return `${parts.join("\n")}
2836
+ `;
2837
+ }
2838
+ function helpData() {
2839
+ const describe = (options) => Object.entries(options).map(([name, option]) => ({
2840
+ name: `--${name}`,
2841
+ ...option.short ? { short: `-${option.short}` } : {},
2842
+ type: option.type,
2843
+ required: option.required ?? false,
2844
+ ...option.choices ? { choices: option.choices } : {},
2845
+ description: option.description
2846
+ }));
2847
+ return {
2848
+ name: "nf",
2849
+ version: VERSION,
2850
+ commands: COMMANDS.map((command) => ({
2851
+ command: command.path.join(" "),
2852
+ usage: usageLine(command),
2853
+ summary: command.summary,
2854
+ options: describe(command.options ?? {})
2855
+ })),
2856
+ global_options: describe(GLOBAL_OPTIONS)
2857
+ };
2858
+ }
2859
+
2860
+ // src/session.ts
2861
+ async function runSession(name, values, context, env, io, requestId2, timeoutMs) {
2862
+ const profile = context.profile.name;
2863
+ if (name === "logout") {
2864
+ const stored = await io.tokens.read(profile);
2865
+ if (stored) await revoke(context, io, stored);
2866
+ await io.tokens.remove(profile);
2867
+ return {
2868
+ data: { signed_out: true, profile },
2869
+ table: stored ? `Signed out of ${profile}.` : `${profile} wasn't signed in.`
2870
+ };
2871
+ }
2872
+ if (io.tokens.kind === "unavailable")
2873
+ throw new CliError("no_keychain", EXIT.config, "There's no OS keychain to keep tokens in", {
2874
+ remediation: "nf keeps tokens only in the macOS Keychain or the Secret Service."
2875
+ });
2876
+ const tokens = values.device === true || !io.isTTY ? await loginWithDevice(context, io) : await loginWithBrowser(context, io);
2877
+ await io.tokens.write(profile, tokens);
2878
+ const api = new Api({ context, env, io, requestId: requestId2, timeoutMs });
2879
+ const { body } = await api.get("/v1/me");
2880
+ return {
2881
+ data: {
2882
+ signed_in: true,
2883
+ profile,
2884
+ person: body.person,
2885
+ expires_at: new Date(tokens.expires_at).toISOString()
2886
+ },
2887
+ table: `Signed in to ${context.stage} as ${body.person.display_name} (${body.person.id}).`
2888
+ };
2889
+ }
2890
+
2891
+ // src/run.ts
2892
+ var parseOptions = (options) => Object.fromEntries(
2893
+ Object.entries(options).map(([name, o]) => [
2894
+ name,
2895
+ {
2896
+ type: o.type,
2897
+ ...o.short ? { short: o.short } : {},
2898
+ ...o.multiple ? { multiple: true } : {}
2899
+ }
2900
+ ])
2901
+ );
2902
+ async function run2(argv, env, io) {
2903
+ const loose = parseArgs({
2904
+ args: [...argv],
2905
+ options: parseOptions(GLOBAL_OPTIONS),
2906
+ strict: false,
2907
+ allowPositionals: true
2908
+ });
2909
+ const looseValues = loose.values;
2910
+ let format = "table";
2911
+ let id = `req_${"0".repeat(26)}`;
2912
+ try {
2913
+ format = looseValues.json === true ? "json" : "table";
2914
+ format = parseFormat(looseValues.json, looseValues.output);
2915
+ id = requestId(looseValues["request-id"]);
2916
+ return await dispatch(argv, loose.positionals, looseValues, format, env, io, id);
2917
+ } catch (error) {
2918
+ return report(error, format, id, io);
2919
+ }
2920
+ }
2921
+ async function dispatch(argv, positionals, loose, format, env, io, id) {
2922
+ const human = format === "table";
2923
+ if (loose.version === true && positionals.length === 0) return version(format, io);
2924
+ if (positionals.length === 0) {
2925
+ io.stdout(human ? topHelp(wantsColour(env, io.isTTY)) : render(helpData(), format));
2926
+ return EXIT.ok;
2927
+ }
2928
+ const helpTarget = positionals[0] === "help" ? positionals.slice(1) : loose.help === true ? positionals : void 0;
2929
+ if (helpTarget) return help(helpTarget, format, env, io);
2930
+ const found = resolveCommand(positionals);
2931
+ if (found.kind === "unknown") throw unknown(found.path, found.word);
2932
+ if (found.kind === "group") {
2933
+ if (human) io.stderr(groupHelp(found.path));
2934
+ throw usageError(
2935
+ "missing_command",
2936
+ `nf ${found.path.join(" ")} needs a command`,
2937
+ `Run \`nf help ${found.path.join(" ")}\`.`
2938
+ );
2939
+ }
2940
+ const { command } = found;
2941
+ const parsed = strictParse(argv, command);
2942
+ const values = parsed.values;
2943
+ const args = parsed.positionals.slice(command.path.length);
2944
+ checkArgs(command, args, values);
2945
+ const timeoutMs = parseTimeout(values.timeout);
2946
+ const flags = {
2947
+ profile: values.profile,
2948
+ org: values.org,
2949
+ noInteractive: values["no-interactive"] === true
2950
+ };
2951
+ switch (command.path.join(" ")) {
2952
+ case "version":
2953
+ return version(format, io);
2954
+ case "doctor": {
2955
+ const result = doctor(flags, env, io);
2956
+ const rows = result.checks.map(({ name: name2, status, detail }) => ({
2957
+ check: name2,
2958
+ status,
2959
+ detail
2960
+ }));
2961
+ io.stdout(human ? render(rows, format) : render(result, format));
2962
+ return result.ok ? EXIT.ok : EXIT.error;
2963
+ }
2964
+ }
2965
+ const context = resolveContext(flags, env, io);
2966
+ const name = command.path.join(" ");
2967
+ if (name === "login" || name === "logout") {
2968
+ const outcome2 = await runSession(name, values, context, env, io, id, timeoutMs);
2969
+ if (!human) io.stdout(render(outcome2.data, format));
2970
+ else io.stdout(`${outcome2.table}
2971
+ `);
2972
+ return EXIT.ok;
2973
+ }
2974
+ const stepUpInPlace = context.interactive && human;
2975
+ const api = new Api({ context, env, io, requestId: id, timeoutMs, stepUpInPlace });
2976
+ const outcome = await runApiCommand({ name, args, values, context, api, io });
2977
+ if (!human) io.stdout(render(outcome.data, format));
2978
+ else if (typeof outcome.table === "string") io.stdout(`${outcome.table}
2979
+ `);
2980
+ else io.stdout(render(outcome.table, format));
2981
+ return EXIT.ok;
2982
+ }
2983
+ function strictParse(argv, command) {
2984
+ try {
2985
+ const parsed = parseArgs({
2986
+ args: [...argv],
2987
+ options: parseOptions({ ...GLOBAL_OPTIONS, ...command.options ?? {} }),
2988
+ strict: true,
2989
+ allowPositionals: true
2990
+ });
2991
+ return { values: parsed.values, positionals: parsed.positionals };
2992
+ } catch (error) {
2993
+ const message = error instanceof Error ? error.message.split("\n")[0] ?? "" : String(error);
2994
+ const code = error.code === "ERR_PARSE_ARGS_UNKNOWN_OPTION" ? "unknown_option" : "invalid_option";
2995
+ throw usageError(code, message, `Run \`nf help ${command.path.join(" ")}\`.`);
2996
+ }
2997
+ }
2998
+ function checkArgs(command, args, values) {
2999
+ const hint = `Usage: nf help ${command.path.join(" ")}`;
3000
+ const specs = command.args ?? [];
3001
+ const required = specs.filter((a) => !a.optional);
3002
+ if (args.length < required.length) {
3003
+ throw usageError(
3004
+ "missing_argument",
3005
+ `nf ${command.path.join(" ")} needs <${required[args.length]?.name}>`,
3006
+ hint
3007
+ );
3008
+ }
3009
+ if (args.length > specs.length && command.path[0] !== "help") {
3010
+ throw usageError(
3011
+ "unexpected_argument",
3012
+ `nf ${command.path.join(" ")} doesn't take \`${args[specs.length]}\``,
3013
+ hint
3014
+ );
3015
+ }
3016
+ for (const [name, option] of Object.entries(command.options ?? {})) {
3017
+ const value = values[name];
3018
+ if (option.required && value === void 0) {
3019
+ throw usageError(
3020
+ "missing_option",
3021
+ `nf ${command.path.join(" ")} needs --${name}${option.type === "boolean" ? "" : ` <${option.value ?? name}>`}`,
3022
+ hint
3023
+ );
3024
+ }
3025
+ if (option.choices && value !== void 0 && !option.choices.includes(String(value))) {
3026
+ throw usageError("invalid_option", `--${name} must be ${option.choices.join(" or ")}`, hint);
3027
+ }
3028
+ }
3029
+ }
3030
+ function help(target, format, env, io) {
3031
+ if (target.length === 0) {
3032
+ io.stdout(
3033
+ format === "table" ? topHelp(wantsColour(env, io.isTTY)) : render(helpData(), format)
3034
+ );
3035
+ return EXIT.ok;
3036
+ }
3037
+ const found = resolveCommand(target);
3038
+ if (found.kind === "unknown") throw unknown(found.path, found.word);
3039
+ if (format !== "table") {
3040
+ const all = helpData();
3041
+ const prefix = found.kind === "leaf" ? found.command.path.join(" ") : found.path.join(" ");
3042
+ io.stdout(
3043
+ render(
3044
+ { ...all, commands: all.commands.filter((c) => `${c.command} `.startsWith(`${prefix} `)) },
3045
+ format
3046
+ )
3047
+ );
3048
+ return EXIT.ok;
3049
+ }
3050
+ io.stdout(found.kind === "leaf" ? commandHelp(found.command) : groupHelp(found.path));
3051
+ return EXIT.ok;
3052
+ }
3053
+ function version(format, io) {
3054
+ io.stdout(
3055
+ format === "table" ? `nf ${VERSION}
3056
+ ` : render({ name: "nf", version: VERSION, node: io.nodeVersion }, format)
3057
+ );
3058
+ return EXIT.ok;
3059
+ }
3060
+ function unknown(path, word) {
3061
+ const where = path.length ? `nf ${path.join(" ")}` : "nf";
3062
+ const group = path.length && GROUPS[path.join(" ")] ? ` ${path.join(" ")}` : "";
3063
+ return usageError(
3064
+ "unknown_command",
3065
+ `${where} has no command \`${word}\``,
3066
+ `Run \`nf help${group}\`.`
3067
+ );
3068
+ }
3069
+ function report(error, format, id, io) {
3070
+ const known = error instanceof CliError ? error : new CliError(
3071
+ "internal",
3072
+ EXIT.error,
3073
+ error instanceof Error ? error.message : String(error)
3074
+ );
3075
+ const envelope = known instanceof ApiError ? known.envelope : void 0;
3076
+ if (format === "table") {
3077
+ io.stderr(
3078
+ `nf: ${known.message}
3079
+ ${known.remediation ? ` ${known.remediation}
3080
+ ` : ""}${envelope ? ` request ${envelope.request_id}
3081
+ ` : ""}`
3082
+ );
3083
+ } else if (envelope) {
3084
+ io.stdout(render(envelope, format));
3085
+ } else {
3086
+ io.stdout(
3087
+ render(
3088
+ {
3089
+ code: known.code,
3090
+ message: known.message,
3091
+ request_id: id,
3092
+ ...known.details ? { details: known.details } : {},
3093
+ retryable: known.retryable
3094
+ },
3095
+ format
3096
+ )
3097
+ );
3098
+ }
3099
+ return known.exit;
3100
+ }
3101
+
3102
+ // src/nf.ts
3103
+ process.exitCode = await run2(process.argv.slice(2), process.env, nodeIo());