direct-auth 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (110) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +486 -2
  3. package/dist/accounts.d.ts +118 -0
  4. package/dist/accounts.js +314 -0
  5. package/dist/apps.d.ts +85 -0
  6. package/dist/apps.js +449 -0
  7. package/dist/auth.d.ts +396 -0
  8. package/dist/auth.js +699 -0
  9. package/dist/base64.d.ts +20 -0
  10. package/dist/base64.js +45 -0
  11. package/dist/cli.d.ts +2 -0
  12. package/dist/cli.js +463 -0
  13. package/dist/client.d.ts +170 -0
  14. package/dist/client.js +438 -0
  15. package/dist/codes.d.ts +81 -0
  16. package/dist/codes.js +91 -0
  17. package/dist/crypto.d.ts +11 -0
  18. package/dist/crypto.js +37 -0
  19. package/dist/d1.d.ts +2 -0
  20. package/dist/d1.js +2 -0
  21. package/dist/db/limits.d.ts +16 -0
  22. package/dist/db/limits.js +23 -0
  23. package/dist/db/schema.d.ts +25 -0
  24. package/dist/db/schema.js +136 -0
  25. package/dist/db/sql.d.ts +52 -0
  26. package/dist/db/sql.js +121 -0
  27. package/dist/dns.d.ts +48 -0
  28. package/dist/dns.js +133 -0
  29. package/dist/env.d.ts +39 -0
  30. package/dist/env.js +169 -0
  31. package/dist/index.d.ts +19 -0
  32. package/dist/index.js +14 -0
  33. package/dist/init.d.ts +134 -0
  34. package/dist/init.js +912 -0
  35. package/dist/jwks.d.ts +18 -0
  36. package/dist/jwks.js +63 -0
  37. package/dist/jwt.d.ts +90 -0
  38. package/dist/jwt.js +99 -0
  39. package/dist/keys.d.ts +33 -0
  40. package/dist/keys.js +54 -0
  41. package/dist/messages.d.ts +26 -0
  42. package/dist/messages.js +57 -0
  43. package/dist/migrate-cli.d.ts +82 -0
  44. package/dist/migrate-cli.js +564 -0
  45. package/dist/migrate.d.ts +99 -0
  46. package/dist/migrate.js +396 -0
  47. package/dist/node.d.ts +16 -0
  48. package/dist/node.js +63 -0
  49. package/dist/passkeys.d.ts +126 -0
  50. package/dist/passkeys.js +383 -0
  51. package/dist/passwords.d.ts +53 -0
  52. package/dist/passwords.js +326 -0
  53. package/dist/pgwire.d.ts +86 -0
  54. package/dist/pgwire.js +445 -0
  55. package/dist/phone.d.ts +11 -0
  56. package/dist/phone.js +18 -0
  57. package/dist/postgres.d.ts +2 -0
  58. package/dist/postgres.js +2 -0
  59. package/dist/providers/apple-revoke.d.ts +55 -0
  60. package/dist/providers/apple-revoke.js +113 -0
  61. package/dist/providers/apple.d.ts +28 -0
  62. package/dist/providers/apple.js +51 -0
  63. package/dist/providers/github.d.ts +28 -0
  64. package/dist/providers/github.js +67 -0
  65. package/dist/providers/google.d.ts +23 -0
  66. package/dist/providers/google.js +47 -0
  67. package/dist/providers/identity.d.ts +24 -0
  68. package/dist/providers/identity.js +3 -0
  69. package/dist/proxy.d.ts +19 -0
  70. package/dist/proxy.js +43 -0
  71. package/dist/records.d.ts +91 -0
  72. package/dist/records.js +264 -0
  73. package/dist/scrypt.d.ts +26 -0
  74. package/dist/scrypt.js +179 -0
  75. package/dist/senders/aws.d.ts +13 -0
  76. package/dist/senders/aws.js +47 -0
  77. package/dist/senders/dev.d.ts +6 -0
  78. package/dist/senders/dev.js +13 -0
  79. package/dist/senders/index.d.ts +5 -0
  80. package/dist/senders/index.js +4 -0
  81. package/dist/senders/mail.d.ts +26 -0
  82. package/dist/senders/mail.js +66 -0
  83. package/dist/senders/sms.d.ts +34 -0
  84. package/dist/senders/sms.js +69 -0
  85. package/dist/senders/smtp.d.ts +32 -0
  86. package/dist/senders/smtp.js +145 -0
  87. package/dist/senders/types.d.ts +31 -0
  88. package/dist/senders/types.js +25 -0
  89. package/dist/server.d.ts +67 -0
  90. package/dist/server.js +494 -0
  91. package/dist/sessions.d.ts +74 -0
  92. package/dist/sessions.js +146 -0
  93. package/dist/skill.d.ts +25 -0
  94. package/dist/skill.js +66 -0
  95. package/dist/sources.d.ts +138 -0
  96. package/dist/sources.js +931 -0
  97. package/dist/sqlite.d.ts +2 -0
  98. package/dist/sqlite.js +2 -0
  99. package/dist/stores/d1.d.ts +22 -0
  100. package/dist/stores/d1.js +23 -0
  101. package/dist/stores/postgres.d.ts +33 -0
  102. package/dist/stores/postgres.js +71 -0
  103. package/dist/stores/sqlite.d.ts +27 -0
  104. package/dist/stores/sqlite.js +55 -0
  105. package/dist/supabase.d.ts +71 -0
  106. package/dist/supabase.js +283 -0
  107. package/dist/tui.d.ts +178 -0
  108. package/dist/tui.js +537 -0
  109. package/package.json +90 -4
  110. package/skills/direct-auth/SKILL.md +101 -0
@@ -0,0 +1,20 @@
1
+ /**
2
+ * Bytes, base64 and base64url, with nothing but what every runtime has (`btoa`, `atob`, `TextEncoder`): Node, Deno,
3
+ * Bun, Workers and browsers alike, so the senders run on all of them without a Buffer.
4
+ */
5
+ /**
6
+ * Bytes backed by a plain ArrayBuffer. WebCrypto and fetch take ArrayBuffer-backed views, which every array made
7
+ * here is; TypeScript 5.7 and later type a bare `Uint8Array` as possibly SharedArrayBuffer-backed, so the helpers
8
+ * say which kind they return.
9
+ */
10
+ export type Bytes = Uint8Array<ArrayBuffer>;
11
+ export declare function utf8(text: string): Bytes;
12
+ export declare function fromUtf8(bytes: Uint8Array): string;
13
+ export declare function concat(...parts: Uint8Array[]): Bytes;
14
+ export declare function base64(data: Uint8Array | string): string;
15
+ /** base64url without padding, as JWTs, VAPID keys and Web Push subscriptions write it. */
16
+ export declare function b64url(data: Uint8Array | string): string;
17
+ /** Either alphabet, padded or not: what a browser hands over is not always one or the other. */
18
+ export declare function fromBase64(text: string): Bytes;
19
+ /** The same decoder under the name the Web Push code reads best with. */
20
+ export declare const fromB64url: typeof fromBase64;
package/dist/base64.js ADDED
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Bytes, base64 and base64url, with nothing but what every runtime has (`btoa`, `atob`, `TextEncoder`): Node, Deno,
3
+ * Bun, Workers and browsers alike, so the senders run on all of them without a Buffer.
4
+ */
5
+ const encoder = new TextEncoder();
6
+ export function utf8(text) {
7
+ return encoder.encode(text);
8
+ }
9
+ export function fromUtf8(bytes) {
10
+ return new TextDecoder().decode(bytes);
11
+ }
12
+ export function concat(...parts) {
13
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
14
+ let at = 0;
15
+ for (const p of parts) {
16
+ out.set(p, at);
17
+ at += p.length;
18
+ }
19
+ return out;
20
+ }
21
+ function binary(bytes) {
22
+ // Chunked: String.fromCharCode(...bytes) on a large array overflows the call stack.
23
+ let bin = "";
24
+ for (let i = 0; i < bytes.length; i += 0x8000)
25
+ bin += String.fromCharCode(...bytes.subarray(i, i + 0x8000));
26
+ return bin;
27
+ }
28
+ export function base64(data) {
29
+ return btoa(binary(typeof data === "string" ? utf8(data) : data));
30
+ }
31
+ /** base64url without padding, as JWTs, VAPID keys and Web Push subscriptions write it. */
32
+ export function b64url(data) {
33
+ return base64(data).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
34
+ }
35
+ /** Either alphabet, padded or not: what a browser hands over is not always one or the other. */
36
+ export function fromBase64(text) {
37
+ const b64 = text.trim().replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
38
+ const bin = atob(b64 + "=".repeat((4 - (b64.length % 4)) % 4));
39
+ const out = new Uint8Array(bin.length);
40
+ for (let i = 0; i < bin.length; i += 1)
41
+ out[i] = bin.charCodeAt(i);
42
+ return out;
43
+ }
44
+ /** The same decoder under the name the Web Push code reads best with. */
45
+ export const fromB64url = fromBase64;
package/dist/cli.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/dist/cli.js ADDED
@@ -0,0 +1,463 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * direct-auth init [--env .env] [--no-check] what the server needs, asked step by step and checked, and taken to
4
+ * where the server runs
5
+ * direct-auth app [--url URL] the client added to the apps in this folder
6
+ * direct-auth skill [--dir DIR] the coding agents' skill copied into this project
7
+ * direct-auth keys [--json] [--add FILE] a new signing key; --add puts it at the front of FILE's list
8
+ * direct-auth dns <domain> [--sender NAME] the mail domain's SPF, DMARC and DKIM
9
+ * direct-auth supabase-sql [--prefix auth_] the SQL that moves a Supabase project's users over
10
+ * direct-auth migrate [--from SOURCE] the users moved: a dry run, the move, a check, the next steps
11
+ * direct-auth issuer <url> whether the sign-in answers at its address
12
+ * direct-auth supabase-trust the Supabase project trusts the issuer (Third-Party Auth)
13
+ *
14
+ * What is for a person (questions, advice, what was written) goes to stderr; stdout has only what a command makes
15
+ * (a key, the SQL, the DNS report), so `>> .env` and `> move.sql` take that and nothing else.
16
+ */
17
+ import { parseArgs } from "node:util";
18
+ import { createInterface } from "node:readline";
19
+ import { Stopped, addSigningKey, configured, init } from "./init.js";
20
+ import { app } from "./apps.js";
21
+ import { installSkill } from "./skill.js";
22
+ import { checkMailDns, dnsText, MAIL_SERVICES } from "./dns.js";
23
+ import { generateSigningKey } from "./keys.js";
24
+ import { supabaseMoveSql } from "./supabase.js";
25
+ import { Terminal, appsHeader, banner, chooseApps, chooseHost, chooseProviders, spin, stepScreen, style, summaryScreen, wrap } from "./tui.js";
26
+ import { migrate, trustIssuer } from "./migrate-cli.js";
27
+ import { issuerProblem } from "./records.js";
28
+ import { issuerOf } from "./init.js";
29
+ const HELP = `direct-auth init [--env PATH] [--no-check]
30
+ Asks where the server runs and the address of your sign-in (auth.example.com, or a URL), then the ways to sign
31
+ in: Sign in with Apple, Google, email codes, passwords, SMS codes, passkeys, guests. Takes each one's settings,
32
+ checks the Apple key with Apple, offers a test code by email or SMS, shows the DNS records it all needs (the
33
+ address, the mail sender's SPF, DKIM, DMARC) and checks them, makes them at Cloudflare with a token if you like,
34
+ makes the signing key, and writes it all to PATH (.env by default). On Supabase, a name of your own gets a small
35
+ Cloudflare Worker in front (auth-proxy/). For Supabase or Workers it offers to upload PATH as secrets. No value is
36
+ printed.
37
+
38
+ direct-auth app [--url URL] [--env PATH]
39
+ Run in an app's folder: finds the web, Android and iOS/macOS projects under it, and adds the client to those
40
+ checked (the npm package, JitPack and the Gradle dependency, the Swift package), once; the rest is printed as
41
+ steps. URL is the issuer (https://api.example.com/auth), read from PATH (.env) when it is there, or asked.
42
+ Without a terminal, every app found and the flags given, nothing is asked.
43
+
44
+ direct-auth skill [--dir DIR]
45
+ Copies the skill for coding agents (how to set direct-auth up, and the rules that keep keys out of code) into
46
+ .claude/skills/direct-auth, where Claude Code reads it; --dir for another agent's folder (.agents/skills). A copy
47
+ there that differs is replaced only after a yes. app and init offer it too. Or: npx skills add guillecura/direct-auth
48
+
49
+ direct-auth keys [--json] [--add FILE]
50
+ A new signing key, as a DIRECT_AUTH_SIGNING_KEYS= line (--json: the JSON array alone). With --add, the new key
51
+ goes at the front of FILE's DIRECT_AUTH_SIGNING_KEYS, the others kept: it signs from the next start, and the old
52
+ ones still verify. Take the last one out once an access token's lifetime (an hour) has passed.
53
+
54
+ direct-auth dns <domain> [--sender resend|postmark|mailgun|sendgrid|ses|smtp]
55
+ Checks the domain's mail records over DNS-over-HTTPS: SPF, DMARC, and DKIM at the sender's selectors. Prints
56
+ what is there and what is missing; exits 1 when SPF or DMARC is missing.
57
+
58
+ direct-auth supabase-sql [--prefix auth_] [--without-mfa] [--keep-unproven-passwords]
59
+ Prints the SQL that moves a Supabase project's users from Supabase Auth to direct-auth's tables (same ids), once,
60
+ for you to read and run: npx direct-auth supabase-sql > move.sql. No session comes over: everyone signs in again
61
+ (a guest gets back in once with the Supabase session its app kept). It stops if users have a second factor, which
62
+ direct-auth doesn't check, unless --without-mfa, and on a database it moved before. An address confirmed the
63
+ moment it signed up proves nothing, so its password stays behind unless --keep-unproven-passwords.
64
+
65
+ direct-auth migrate [--from SOURCE] [--file EXPORT] [--hashes FILE] [--hash-config FILE] [--db URL] [--prefix auth_] [--dry-run] [--yes] [--rollback FILE] [--issuer URL] [--without-mfa] [--keep-unproven-passwords]
66
+ Moves the users into direct-auth's tables. SOURCE is supabase, firebase, authjs, better-auth, clerk or auth0
67
+ (asked from a list without it). Supabase, Auth.js and Better Auth: their users' database, same ids. Firebase
68
+ (EXPORT: auth:export's JSON; --hash-config: the password hash parameters), Clerk (EXPORT: the dashboard's CSV)
69
+ and Auth0 (EXPORT: the NDJSON export; --hashes: its support's hashes file): the Postgres database the server
70
+ uses; an id that isn't a UUID gets one, the old in source_id. The URL from --db, DATABASE_URL, or asked (hidden). 1 connects; 2 is a dry run: users by provider, guests, passwords, passkeys, the banned left out,
71
+ the foreign keys it repoints, and each trigger, function, policy and view that needs a hand, by name; 3 writes
72
+ the way back (FILE, never over one there) and moves, in one transaction, after you type move (--yes: no
73
+ question); 4 checks the counts, a sample of users and the foreign keys. Then the next steps. Only counts and
74
+ masked ids are shown. It runs once, with Supabase Auth's sign-ins off before it; then the app's new version goes
75
+ to direct-auth, and everyone signs in again (a guest's app claims its account with its Supabase session).
76
+ A database elsewhere is reached over TLS with its certificate checked (sslrootcert=FILE, Supabase's CA, from
77
+ Database Settings › SSL Configuration), or with channel binding (SCRAM-SHA-256-PLUS), which proves nobody
78
+ is in between; a local one may go without.
79
+
80
+ direct-auth issuer <url>
81
+ Whether the sign-in answers at its address: its name in the DNS, and its openid-configuration naming it.
82
+
83
+ direct-auth supabase-trust --project REF --issuer URL [--yes]
84
+ The project trusts direct-auth's tokens as a Third-Party Auth issuer, through Supabase's Management API
85
+ (SUPABASE_ACCESS_TOKEN, or asked). Shows the change before making it.`;
86
+ const COMMANDS = ["init", "app", "skill", "keys", "dns", "supabase-sql", "migrate", "issuer", "supabase-trust"];
87
+ const { positionals, values } = (() => {
88
+ try {
89
+ return parseArgs({
90
+ allowPositionals: true,
91
+ options: {
92
+ help: { type: "boolean", short: "h" },
93
+ json: { type: "boolean" },
94
+ env: { type: "string" },
95
+ // Node reads --env-file anywhere on the command line, after the script too, and stops when the file isn't
96
+ // there: so it's --env here, and --env-file stays for the files that exist.
97
+ "env-file": { type: "string" },
98
+ "no-check": { type: "boolean" },
99
+ add: { type: "string" },
100
+ sender: { type: "string" },
101
+ prefix: { type: "string" },
102
+ url: { type: "string" },
103
+ dir: { type: "string" },
104
+ from: { type: "string" },
105
+ file: { type: "string" },
106
+ hashes: { type: "string" },
107
+ "hash-config": { type: "string" },
108
+ db: { type: "string" },
109
+ "dry-run": { type: "boolean" },
110
+ "without-mfa": { type: "boolean" },
111
+ "keep-unproven-passwords": { type: "boolean" },
112
+ yes: { type: "boolean", short: "y" },
113
+ rollback: { type: "string" },
114
+ issuer: { type: "string" },
115
+ project: { type: "string" },
116
+ },
117
+ });
118
+ }
119
+ catch (error) {
120
+ console.error(`${error instanceof Error ? error.message : String(error)}\n\n${HELP}`);
121
+ process.exit(1);
122
+ }
123
+ })();
124
+ const command = positionals[0];
125
+ if (values.help || !command || !COMMANDS.includes(command)) {
126
+ if (command && !values.help)
127
+ console.error(`Unknown command: ${command}\n`);
128
+ console.log(HELP);
129
+ process.exit(values.help ? 0 : 1);
130
+ }
131
+ try {
132
+ process.exitCode = await run(command);
133
+ }
134
+ catch (error) {
135
+ console.error(error instanceof Error ? error.message : String(error));
136
+ process.exitCode = 1;
137
+ }
138
+ finally {
139
+ // Done with the keyboard. A terminal's stdin, once read in raw mode and by readline, can keep the process open after
140
+ // the last screen; so an interactive run ends here, once what it wrote has gone out.
141
+ if (process.stdin.isTTY) {
142
+ process.stdin.setRawMode?.(false);
143
+ process.stdout.write("", () => process.stderr.write("", () => process.exit()));
144
+ }
145
+ }
146
+ async function run(command) {
147
+ switch (command) {
148
+ case "init":
149
+ return initCommand();
150
+ case "app":
151
+ return appCommand();
152
+ case "skill":
153
+ return skillCommand();
154
+ case "keys":
155
+ return keysCommand();
156
+ case "dns":
157
+ return dnsCommand();
158
+ case "migrate":
159
+ return migrateCommand();
160
+ case "issuer":
161
+ return issuerCommand();
162
+ case "supabase-trust":
163
+ return trustCommand();
164
+ default: {
165
+ const prefix = values.prefix ?? "auth_";
166
+ if (!/^[a-z_][a-z0-9_]*$/.test(prefix)) {
167
+ console.error("--prefix is a plain lowercase name, like auth_.");
168
+ return 1;
169
+ }
170
+ process.stdout.write(supabaseMoveSql({ prefix, allowMfaLoss: Boolean(values["without-mfa"]), keepUnprovenPasswords: Boolean(values["keep-unproven-passwords"]) }));
171
+ console.error("Read it before running it: the SQL editor, or psql -f. It runs once.");
172
+ return 0;
173
+ }
174
+ }
175
+ }
176
+ /** `direct-auth skill`: the package's skill copied into this project (a yes before replacing a copy that differs). */
177
+ async function skillCommand() {
178
+ const paint = style(!process.env.NO_COLOR && Boolean(process.stderr.isTTY));
179
+ const reader = lineReader(undefined, { endIsEnter: true });
180
+ try {
181
+ return await installSkill({ ask: reader.ask, say: (line, tone) => console.error(tone ? paint[tone](line) : line) }, { cwd: process.cwd(), dir: values.dir });
182
+ }
183
+ finally {
184
+ reader.pause();
185
+ }
186
+ }
187
+ async function keysCommand() {
188
+ if (values.add !== undefined) {
189
+ const { count } = await addSigningKey(values.add);
190
+ console.error(`A new signing key at the front of DIRECT_AUTH_SIGNING_KEYS in ${values.add} (${count} now). It signs once the server starts with it;\n` +
191
+ "the others still verify. Take the last one out after an hour, when the tokens it signed have expired.");
192
+ return 0;
193
+ }
194
+ const keys = JSON.stringify([await generateSigningKey()]);
195
+ console.log(values.json ? keys : `DIRECT_AUTH_SIGNING_KEYS=${keys}`);
196
+ // On stderr, so `direct-auth keys >> .env` appends the key and nothing else.
197
+ console.error("A private key: it stays on the server. A new one in place of the old signs everyone out; to rotate, use --add.");
198
+ return 0;
199
+ }
200
+ async function dnsCommand() {
201
+ const domain = positionals[1];
202
+ if (!domain || !/^[a-z0-9-]+(\.[a-z0-9-]+)+\.?$/i.test(domain)) {
203
+ console.error(`dns takes a domain: direct-auth dns example.com [--sender resend]\n\n${HELP}`);
204
+ return 1;
205
+ }
206
+ const sender = values.sender?.toLowerCase();
207
+ if (sender !== undefined && !MAIL_SERVICES.includes(sender)) {
208
+ console.error(`--sender is one of ${MAIL_SERVICES.join(", ")}, not ${values.sender}.`);
209
+ return 1;
210
+ }
211
+ const r = await checkMailDns(domain, { sender: sender });
212
+ console.log(dnsText(r).join("\n"));
213
+ if (!r.spf || !r.dmarc) {
214
+ console.error(`\nMissing ${[!r.spf && "SPF", !r.dmarc && "DMARC"].filter(Boolean).join(" and ")}: without them Gmail and others send the codes to spam, or refuse them.`);
215
+ return 1;
216
+ }
217
+ return 0;
218
+ }
219
+ /**
220
+ * The questions as lines. On a terminal readline draws the prompt, so editing the answer (a backspace) redraws the
221
+ * question too; piped answers (a script, a test) are read line by line, since readline's question() drops the ones
222
+ * that came early. The reader is made at the first question and closed before a screen with keys (`pause`), so a key
223
+ * goes to one or the other, never both; the next question makes another.
224
+ */
225
+ function lineReader(term, o) {
226
+ let rl;
227
+ let lines;
228
+ const pause = () => {
229
+ rl?.close();
230
+ rl = undefined;
231
+ };
232
+ let muted = false;
233
+ const ask = async (q) => {
234
+ if (!rl) {
235
+ rl = createInterface({ input: process.stdin, output: process.stderr, terminal: process.stdin.isTTY });
236
+ // Ctrl-C at a question: the terminal back, and out as an interrupt would be.
237
+ rl.on("SIGINT", () => {
238
+ pause();
239
+ term?.close();
240
+ process.stderr.write("\ndirect-auth: stopped, nothing written.\n");
241
+ process.exit(130);
242
+ });
243
+ lines = rl[Symbol.asyncIterator]();
244
+ // A secret's characters echo as dots: readline writes each through here.
245
+ const terminal = rl;
246
+ const write = terminal._writeToOutput.bind(rl);
247
+ terminal._writeToOutput = (out) => {
248
+ if (!muted)
249
+ return write(out);
250
+ if (out.startsWith(q0))
251
+ return write(q0 + "•".repeat(terminal.line.length));
252
+ if (out === "\r\n" || out === "\n")
253
+ return write(out);
254
+ write("•".repeat(Math.min(out.length, 1)));
255
+ };
256
+ }
257
+ q0 = q;
258
+ if (rl.terminal) {
259
+ rl.setPrompt(q);
260
+ rl.prompt();
261
+ // What was typed ahead of the questions answers the first, after it like any typed answer.
262
+ term?.replay();
263
+ }
264
+ else
265
+ process.stderr.write(q);
266
+ const next = await lines.next();
267
+ if (next.done) {
268
+ // `app` without a terminal or answers: every default (each app found, the flags given).
269
+ if (o.endIsEnter) {
270
+ process.stderr.write("\n");
271
+ return "";
272
+ }
273
+ throw new Error("init: no more answers");
274
+ }
275
+ // An answer from a pipe isn't echoed: the line ends here, so what is said next starts on its own.
276
+ if (rl && !rl.terminal)
277
+ process.stderr.write("\n");
278
+ return next.value;
279
+ };
280
+ let q0 = "";
281
+ const askSecret = async (q) => {
282
+ muted = !!process.stdin.isTTY;
283
+ try {
284
+ return await ask(q);
285
+ }
286
+ finally {
287
+ muted = false;
288
+ }
289
+ };
290
+ return { ask, askSecret, pause };
291
+ }
292
+ /**
293
+ * On a terminal (stdin and stderr both), a wizard: the welcome and the checklist with keys, then a screen for the
294
+ * server's questions and each provider's, where the server runs, and one for the end. Otherwise (a pipe, a script, a
295
+ * test) the same questions as lines, each provider a yes or no.
296
+ */
297
+ async function initCommand() {
298
+ const envFile = values.env ?? values["env-file"] ?? ".env";
299
+ const check = !values["no-check"];
300
+ const color = !process.env.NO_COLOR;
301
+ const wizard = Boolean(process.stdin.isTTY && process.stderr.isTTY);
302
+ const term = wizard ? new Terminal(process.stdin, process.stderr) : undefined;
303
+ // Coloured only on a terminal: a pipe or a log file gets the words alone.
304
+ const paint = style(color && Boolean(process.stderr.isTTY));
305
+ const stopped = (code) => {
306
+ term?.clear("");
307
+ console.error("direct-auth init: stopped, nothing written.");
308
+ return code;
309
+ };
310
+ const reader = lineReader(term, { endIsEnter: false });
311
+ try {
312
+ let providers;
313
+ if (term) {
314
+ // The screens with keys come before the line reader exists: no key goes to both.
315
+ providers = await chooseProviders(term, { color, envFile, configured: configured(envFile) });
316
+ if (providers === "quit" || providers === "interrupt")
317
+ return stopped(providers === "quit" ? 0 : 130);
318
+ }
319
+ else if (process.stderr.isTTY) {
320
+ process.stderr.write(banner(color));
321
+ }
322
+ const io = lineIO(reader, paint, color);
323
+ if (term) {
324
+ io.section = (p, n, of) => term.clear(stepScreen(p, n, of, color));
325
+ io.summary = (set, left, details) => term.clear(summaryScreen(set, left, color, details));
326
+ io.host = async (here) => {
327
+ reader.pause();
328
+ const host = await chooseHost(term, { color, envFile, here });
329
+ if (host === "quit" || host === "interrupt")
330
+ throw new Stopped(host === "quit" ? 0 : 130);
331
+ return host;
332
+ };
333
+ }
334
+ try {
335
+ return await init(io, { envFile, check, providers: Array.isArray(providers) ? providers : undefined });
336
+ }
337
+ catch (error) {
338
+ if (error instanceof Stopped)
339
+ return stopped(error.code);
340
+ throw error;
341
+ }
342
+ }
343
+ finally {
344
+ reader.pause();
345
+ term?.close();
346
+ }
347
+ }
348
+ /** Questions and lines on stderr, coloured on a terminal, with a spinner there for what takes a while. */
349
+ function lineIO(reader, paint, color) {
350
+ // On a terminal a long line is wrapped at a word, under its own indent, rather than cut by the terminal anywhere.
351
+ const fit = (line) => (process.stderr.isTTY ? line.split("\n").flatMap((l) => wrap(l, (process.stderr.columns ?? 80) - 1)) : [line]);
352
+ const io = {
353
+ ask: reader.ask,
354
+ askSecret: reader.askSecret,
355
+ say: (line, tone) => console.error(fit(line).map((l) => (tone ? paint[tone](l) : l)).join("\n")),
356
+ };
357
+ if (process.stderr.isTTY)
358
+ io.spin = (text) => spin(process.stderr, text, color);
359
+ return io;
360
+ }
361
+ /** `direct-auth migrate`: the four steps, with the questions on a terminal (the URL hidden) or none with flags. */
362
+ async function migrateCommand() {
363
+ const color = !process.env.NO_COLOR;
364
+ const paint = style(color && Boolean(process.stderr.isTTY));
365
+ const reader = lineReader(undefined, { endIsEnter: false });
366
+ const prefix = values.prefix ?? "auth_";
367
+ if (!/^[a-z_][a-z0-9_]*$/.test(prefix)) {
368
+ console.error("--prefix is a plain lowercase name, like auth_.");
369
+ return 1;
370
+ }
371
+ const { pgConnect, parseDatabaseUrl } = await import("./pgwire.js");
372
+ const io = lineIO(reader, paint, color);
373
+ io.say(paint.bold(paint.accent("direct-auth migrate")) + paint.dim(` ${values.from ? `from ${values.from}, ` : ""}into direct-auth's tables`));
374
+ try {
375
+ return await migrate(io, {
376
+ from: values.from,
377
+ file: values.file,
378
+ hashes: values.hashes,
379
+ hashConfig: values["hash-config"],
380
+ db: values.db ?? process.env.DATABASE_URL ?? process.env.SUPABASE_DB_URL,
381
+ prefix,
382
+ dryRun: Boolean(values["dry-run"]),
383
+ yes: Boolean(values.yes),
384
+ rollbackFile: values.rollback,
385
+ issuer: values.issuer ?? process.env.DIRECT_AUTH_ISSUER,
386
+ withoutMfa: Boolean(values["without-mfa"]),
387
+ keepUnprovenPasswords: Boolean(values["keep-unproven-passwords"]),
388
+ connect: async (url) => {
389
+ const c = await pgConnect(url);
390
+ return { query: c.query, shown: parseDatabaseUrl(url).shown, close: c.close, security: c.security.summary };
391
+ },
392
+ });
393
+ }
394
+ finally {
395
+ reader.pause();
396
+ }
397
+ }
398
+ async function issuerCommand() {
399
+ const issuer = positionals[1] && issuerOf(positionals[1]);
400
+ if (!issuer) {
401
+ console.error(`issuer takes the sign-in's address: direct-auth issuer https://auth.example.com/auth\n\n${HELP}`);
402
+ return 1;
403
+ }
404
+ const problem = await issuerProblem(issuer);
405
+ if (problem) {
406
+ console.error(`✗ ${problem}`);
407
+ return 1;
408
+ }
409
+ console.error(`✓ ${new URL(issuer).host} answers as ${issuer}.`);
410
+ return 0;
411
+ }
412
+ async function trustCommand() {
413
+ const issuer = values.issuer ?? process.env.DIRECT_AUTH_ISSUER;
414
+ if (!values.project || !/^[a-z0-9]{20}$/.test(values.project) || !issuer || !issuerOf(issuer)) {
415
+ console.error(`supabase-trust takes the project's ref and the issuer: --project abcdefghijklmnopqrst --issuer https://auth.example.com/auth\n\n${HELP}`);
416
+ return 1;
417
+ }
418
+ const color = !process.env.NO_COLOR;
419
+ const reader = lineReader(undefined, { endIsEnter: false });
420
+ try {
421
+ return await trustIssuer(lineIO(reader, style(color && Boolean(process.stderr.isTTY)), color), {
422
+ project: values.project,
423
+ issuer: issuerOf(issuer),
424
+ token: process.env.SUPABASE_ACCESS_TOKEN,
425
+ yes: Boolean(values.yes),
426
+ });
427
+ }
428
+ finally {
429
+ reader.pause();
430
+ }
431
+ }
432
+ /** `direct-auth app`: the apps checklist with keys on a terminal, plain questions otherwise; works with no keys at all. */
433
+ async function appCommand() {
434
+ const color = !process.env.NO_COLOR;
435
+ const wizard = Boolean(process.stdin.isTTY && process.stderr.isTTY);
436
+ const term = wizard ? new Terminal(process.stdin, process.stderr) : undefined;
437
+ const paint = style(color && Boolean(process.stderr.isTTY));
438
+ const reader = lineReader(term, { endIsEnter: true });
439
+ const io = { ask: reader.ask, say: (line, tone) => console.error(tone ? paint[tone](line) : line) };
440
+ if (term) {
441
+ io.apps = async (found) => {
442
+ const apps = await chooseApps(term, found, { color });
443
+ if (apps === "quit" || apps === "interrupt")
444
+ throw new Stopped(apps === "quit" ? 0 : 130);
445
+ return apps;
446
+ };
447
+ io.chosen = (apps) => term.clear(appsHeader(apps, color));
448
+ }
449
+ try {
450
+ return await app(io, { cwd: process.cwd(), url: values.url, envFile: values.env ?? values["env-file"] });
451
+ }
452
+ catch (error) {
453
+ if (!(error instanceof Stopped))
454
+ throw error;
455
+ term?.clear("");
456
+ console.error("direct-auth app: stopped, nothing changed.");
457
+ return error.code;
458
+ }
459
+ finally {
460
+ reader.pause();
461
+ term?.close();
462
+ }
463
+ }