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
package/dist/init.js ADDED
@@ -0,0 +1,912 @@
1
+ /**
2
+ * `direct-auth init`: what a new project's server needs, asked one way of signing in at a time, checked, and written
3
+ * to an env file (`.env` unless told otherwise) under the names `authFromEnv` reads. What is there already is kept
4
+ * unless the person says otherwise; nothing secret is ever printed, only the names.
5
+ *
6
+ * Checked as it comes: the Apple `.p8` must load, and (unless `--no-check`) Apple is asked once whether it takes the
7
+ * key for each client ID; the mail and SMS settings must make a sender, which can send a test code to an address or
8
+ * number typed here; the mail domain's DNS is looked at for SPF, DMARC and DKIM.
9
+ *
10
+ * Every value goes in on one line, unquoted: the `.p8` as its PEM with the line breaks taken out (the server reads it
11
+ * either way), the signing keys as a JSON array. Every env-file reader (Node, Deno, `supabase secrets set
12
+ * --env-file`, `wrangler secret bulk`) takes that.
13
+ */
14
+ import { chmodSync, existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs";
15
+ import { basename, dirname, join } from "node:path";
16
+ import { homedir } from "node:os";
17
+ import { spawn, spawnSync } from "node:child_process";
18
+ import { fromBase64, fromUtf8 } from "./base64.js";
19
+ import { generateSigningKey } from "./keys.js";
20
+ import { appleRevoker } from "./providers/apple-revoke.js";
21
+ import { mailFromEnv, smsFromEnv } from "./env.js";
22
+ import { renderCode } from "./messages.js";
23
+ import { normalizePhone, allowedPrefix } from "./phone.js";
24
+ import { randomCode } from "./crypto.js";
25
+ import { domainOf } from "./dns.js";
26
+ import { b64url } from "./base64.js";
27
+ import { cloudflare, issuerProblem, mailRecords, missing, onCloudflare, planCloudflare, recordLines, serverRecords, waitFor } from "./records.js";
28
+ import { proxyFiles } from "./proxy.js";
29
+ import { offerSkill } from "./skill.js";
30
+ export const PROVIDER_IDS = ["apple", "google", "github", "email", "passwords", "sms", "passkeys", "guests"];
31
+ export const HOSTS = [
32
+ { id: "server", label: "My own server or VPS", detail: "it reads the env file: nothing to upload" },
33
+ { id: "supabase", label: "Supabase Edge Functions", detail: "supabase secrets set" },
34
+ { id: "workers", label: "Cloudflare Workers", detail: "wrangler secret bulk" },
35
+ { id: "later", label: "Later / other", detail: "the ways to do it, printed" },
36
+ ];
37
+ /** Thrown by a screen left with q (code 0) or Ctrl-C (130): nothing is written. */
38
+ export class Stopped extends Error {
39
+ code;
40
+ constructor(code) {
41
+ super("stopped");
42
+ this.code = code;
43
+ }
44
+ }
45
+ export const system = {
46
+ has: (command) => !spawnSync(command, ["--version"], { stdio: "ignore", shell: process.platform === "win32" }).error,
47
+ run: (command, args, cwd) => new Promise((resolve) => {
48
+ const child = spawn(command, args, { cwd, stdio: ["ignore", "pipe", "pipe"], shell: process.platform === "win32" });
49
+ let output = "";
50
+ child.stdout.on("data", (c) => (output += c.toString()));
51
+ child.stderr.on("data", (c) => (output += c.toString()));
52
+ child.on("error", (e) => resolve({ code: null, output: e.message }));
53
+ child.on("close", (code) => resolve({ code, output }));
54
+ }),
55
+ };
56
+ /** The variable that says a provider is on. */
57
+ const MARK = {
58
+ apple: "APPLE_CLIENT_IDS",
59
+ google: "GOOGLE_CLIENT_IDS",
60
+ github: "GITHUB_CLIENT_ID",
61
+ email: "MAIL_SENDER",
62
+ passwords: "PASSWORDS",
63
+ sms: "SMS_SENDER",
64
+ passkeys: "PASSKEY_RP_ID",
65
+ guests: "GUESTS",
66
+ };
67
+ const NAMES = {
68
+ apple: "Sign in with Apple",
69
+ google: "Google",
70
+ github: "GitHub",
71
+ email: "Email codes",
72
+ passwords: "Passwords",
73
+ sms: "SMS codes",
74
+ passkeys: "Passkeys",
75
+ guests: "Guests",
76
+ };
77
+ const AWS = [
78
+ { name: "AWS_REGION", question: "AWS region", fallback: "us-east-1", wrong: (v) => (/^[a-z]{2}(-[a-z]+)+-\d$/.test(v) ? undefined : "like us-east-1") },
79
+ { name: "AWS_ACCESS_KEY_ID", question: "AWS access key ID (IAM › Users › Security credentials)", secret: true },
80
+ { name: "AWS_SECRET_ACCESS_KEY", question: "AWS secret access key", secret: true },
81
+ ];
82
+ export const MAIL_SENDERS = [
83
+ { id: "resend", label: "Resend", fields: [{ name: "RESEND_API_KEY", question: "Resend API key (API Keys, sending access)", secret: true, wrong: (v) => (v.startsWith("re_") ? undefined : "it starts with re_") }] },
84
+ { id: "postmark", label: "Postmark", fields: [{ name: "POSTMARK_SERVER_TOKEN", question: "Postmark server API token (the server › API Tokens)", secret: true }] },
85
+ {
86
+ id: "mailgun",
87
+ label: "Mailgun",
88
+ fields: [
89
+ { name: "MAILGUN_API_KEY", question: "Mailgun API key (API Security › Mailgun API keys)", secret: true },
90
+ { name: "MAILGUN_DOMAIN", question: "The domain it sends from, as Mailgun lists it", wrong: (v) => (/^[a-z0-9.-]+\.[a-z]{2,}$/i.test(v) ? undefined : "a domain, like mg.example.com") },
91
+ { name: "MAILGUN_REGION", question: "Region, us or eu", fallback: "us", wrong: (v) => (v === "us" || v === "eu" ? undefined : "us or eu") },
92
+ ],
93
+ },
94
+ { id: "sendgrid", label: "SendGrid", fields: [{ name: "SENDGRID_API_KEY", question: "SendGrid API key (Settings › API Keys, Mail Send)", secret: true, wrong: (v) => (v.startsWith("SG.") ? undefined : "it starts with SG.") }] },
95
+ { id: "ses", label: "Amazon SES", fields: AWS },
96
+ {
97
+ id: "smtp",
98
+ label: "SMTP (any mail server or relay; not on Workers)",
99
+ fields: [
100
+ { name: "SMTP_HOST", question: "SMTP host", wrong: (v) => (/^[a-z0-9.-]+$/i.test(v) ? undefined : "a host name, like smtp.example.com") },
101
+ { name: "SMTP_PORT", question: "Port, 465 (TLS) or 587 (STARTTLS)", fallback: "587", wrong: (v) => (/^\d{2,5}$/.test(v) ? undefined : "a port number") },
102
+ { name: "SMTP_USER", question: "User", optional: true },
103
+ { name: "SMTP_PASS", question: "Password", secret: true, optional: true },
104
+ ],
105
+ },
106
+ { id: "dev", label: "Development: the code in the server's log, nothing sent", fields: [] },
107
+ ];
108
+ export const SMS_SENDERS = [
109
+ {
110
+ id: "twilio",
111
+ label: "Twilio",
112
+ fields: [
113
+ { name: "TWILIO_ACCOUNT_SID", question: "Account SID (the console's home page)", wrong: (v) => (/^AC[0-9a-f]{32}$/i.test(v) ? undefined : "AC and 32 characters") },
114
+ { name: "TWILIO_AUTH_TOKEN", question: "Auth token", secret: true },
115
+ { name: "TWILIO_FROM", question: "The sender: your Twilio number (+1…) or a Messaging Service SID (MG…)", wrong: (v) => (/^(\+\d{6,15}|MG[0-9a-f]{32})$/i.test(v) ? undefined : "+ and the number, or MG and 32 characters") },
116
+ ],
117
+ },
118
+ {
119
+ id: "vonage",
120
+ label: "Vonage",
121
+ fields: [
122
+ { name: "VONAGE_API_KEY", question: "API key (the dashboard's home page)" },
123
+ { name: "VONAGE_API_SECRET", question: "API secret", secret: true },
124
+ { name: "VONAGE_FROM", question: "The sender: a number, or a name of up to 11 letters" },
125
+ ],
126
+ },
127
+ { id: "sns", label: "Amazon SNS", fields: [...AWS, { name: "SNS_SENDER_ID", question: "Sender ID, where the country allows one", optional: true }] },
128
+ {
129
+ id: "sms-gateway",
130
+ label: "SMS Gateway for Android (your own phone sends them)",
131
+ fields: [
132
+ { name: "SMS_GATEWAY_URL", question: "The gateway's URL", fallback: "https://api.sms-gate.app/3rdparty/v1", wrong: (v) => (/^https?:\/\/\S+$/.test(v) ? undefined : "an http(s) address") },
133
+ { name: "SMS_GATEWAY_USERNAME", question: "Username" },
134
+ { name: "SMS_GATEWAY_PASSWORD", question: "Password", secret: true },
135
+ ],
136
+ },
137
+ { id: "dev", label: "Development: the code in the server's log, nothing sent", fields: [] },
138
+ ];
139
+ /** The providers the env file has turned on. */
140
+ export function configured(envFile) {
141
+ const env = readEnvFile(envFile);
142
+ return PROVIDER_IDS.filter((p) => env[MARK[p]]);
143
+ }
144
+ export async function init(io, o) {
145
+ const env = readEnvFile(o.envFile);
146
+ const out = {};
147
+ const cwd = o.cwd ?? process.cwd();
148
+ const f = o.fetch ?? fetch;
149
+ const sys = o.system ?? system;
150
+ const steps = o.providers && PROVIDER_IDS.filter((p) => o.providers.includes(p));
151
+ const set = [];
152
+ /** A line for each step done, for the summary: "Resend, from hello@acme.dev". */
153
+ const details = {};
154
+ /** What the server will read: the file as it is, with this run's answers over it. */
155
+ const vars = () => ({ ...env, ...out });
156
+ const records = (what, rs, zoneName) => dnsRecords(io, what, rs, { zoneName, check: o.check, f, env });
157
+ // Where the server runs comes first: it says what an address of your own takes.
158
+ const where = await whereRuns(io, hostHere(cwd));
159
+ // The server: the sign-in's address (the issuer) and the name the codes' messages say.
160
+ io.section?.("server", 0, steps?.length ?? 0);
161
+ if (!steps)
162
+ io.say(`The settings go to ${o.envFile}${Object.keys(env).length ? " (what it has stays unless you replace it)" : ""}.`);
163
+ if (!steps)
164
+ io.say("The address of your sign-in: where the apps sign in, and the issuer every token names.");
165
+ io.say(" On a name of your own (auth.example.com), moving the server later is pointing that name elsewhere: nobody signs in again.", "dim");
166
+ const fnUrl = supabaseIssuer(cwd) ?? (env.DIRECT_AUTH_ISSUER && /\.supabase\.co\//.test(env.DIRECT_AUTH_ISSUER) ? env.DIRECT_AUTH_ISSUER : undefined);
167
+ if (where === "supabase")
168
+ io.say(` Or Enter for the Edge Function's own: ${fnUrl ?? "https://<ref>.supabase.co/functions/v1/auth"}`, "dim");
169
+ const address = await answer(io, "The address of your sign-in", {
170
+ fallback: env.DIRECT_AUTH_ISSUER ?? (where === "supabase" ? fnUrl : undefined),
171
+ wrong: (v) => (issuerOf(v) ? undefined : "a name like auth.example.com, or a URL like https://api.example.com/auth (http only for localhost)"),
172
+ });
173
+ out.DIRECT_AUTH_ISSUER = issuerOf(address);
174
+ const issuerUrl = new URL(out.DIRECT_AUTH_ISSUER);
175
+ const host = issuerUrl.hostname;
176
+ const own = ownName(host);
177
+ io.say(` The issuer: ${out.DIRECT_AUTH_ISSUER}`, "dim");
178
+ out.DIRECT_AUTH_APP_NAME = await answer(io, "Your app's name, as the codes' messages say it", { fallback: env.DIRECT_AUTH_APP_NAME ?? appName(host) });
179
+ details.server = out.DIRECT_AUTH_ISSUER;
180
+ // The address of your own, as where the server runs needs it.
181
+ if (own) {
182
+ io.say("");
183
+ if (where === "server") {
184
+ const ip = await answer(io, `The server's public IP, for ${host} (empty: later)`, {
185
+ optional: true,
186
+ fallback: env.DIRECT_AUTH_SERVER_IP,
187
+ wrong: (v) => (/^(\d{1,3}\.){3}\d{1,3}$|^[0-9a-f:]+:[0-9a-f:]*$/i.test(v) ? undefined : "an IPv4 or IPv6 address, like 203.0.113.4"),
188
+ });
189
+ if (ip)
190
+ await records(`${host}, at your server`, serverRecords(host, ip), host);
191
+ else
192
+ io.say(` Once it runs: an A record for ${host} to its IP (or a CNAME to its host name).`, "note");
193
+ }
194
+ else if (where === "supabase") {
195
+ await supabaseProxy(io, { host, issuer: out.DIRECT_AUTH_ISSUER, fnUrl, env, out, cwd, sys, f });
196
+ }
197
+ else if (where === "workers") {
198
+ io.say(` In the Worker's wrangler.toml, so Cloudflare serves it at ${host} (and makes its DNS record and certificate):`);
199
+ io.say(` routes = [{ pattern = "${host}", custom_domain = true }]`, "code");
200
+ }
201
+ else
202
+ io.say(` Once the server runs: ${host} pointed at it (an A record to its IP, or a CNAME to its host name).`, "note");
203
+ }
204
+ /** Whether to set this one up: as chosen beforehand (its section opened), or asked. */
205
+ const wants = async (p) => {
206
+ if (!steps) {
207
+ io.say("");
208
+ return env[MARK[p]] ? yes(io, `${NAMES[p]}: configured. Change it?`, false) : yes(io, `${NAMES[p]}?`, false);
209
+ }
210
+ if (!steps.includes(p))
211
+ return false;
212
+ io.section?.(p, steps.indexOf(p) + 1, steps.length);
213
+ return true;
214
+ };
215
+ // Sign in with Apple. Tried again after a refusal, the answers just given are the defaults.
216
+ let appleIds = env.APPLE_CLIENT_IDS;
217
+ let pem = env.APPLE_PRIVATE_KEY;
218
+ let keyId = env.APPLE_KEY_ID;
219
+ let teamId = env.APPLE_TEAM_ID;
220
+ apple: if (await wants("apple"))
221
+ for (;;) {
222
+ appleIds = list(await answer(io, "Bundle IDs and Services IDs that sign in, comma separated", {
223
+ fallback: appleIds,
224
+ wrong: (v) => (list(v).every((id) => /^[A-Za-z0-9-]+(\.[A-Za-z0-9-]+)+$/.test(id)) ? undefined : "like com.example.app, com.example.web"),
225
+ })).join(",");
226
+ io.say(" Deleting an account revokes Sign in with Apple (App Store guideline 5.1.1(v)): that takes a key.");
227
+ io.say(" Certificates, Identifiers & Profiles › Keys › +, with Sign in with Apple on; download the .p8.", "dim");
228
+ const path = await answer(io, "The .p8 key file", {
229
+ optional: Boolean(pem),
230
+ hint: pem ? "Enter keeps the key you have" : undefined,
231
+ wrong: (p) => (existsSync(p) ? undefined : "no such file"),
232
+ });
233
+ const key = path ? oneLinePem(readFileSync(path, "utf8")) : pem;
234
+ if (!(await loads(key))) {
235
+ io.say(" That is not a Sign in with Apple key (a .p8 with a PRIVATE KEY inside).", "bad");
236
+ if (await again(io, "Apple"))
237
+ continue;
238
+ break apple;
239
+ }
240
+ pem = key;
241
+ const guess = path ? /^AuthKey_([A-Z0-9]{10})\.p8$/.exec(basename(path))?.[1] : undefined;
242
+ const id10 = (v) => (/^[A-Z0-9]{10}$/.test(v) ? undefined : "10 letters and digits");
243
+ keyId = await answer(io, "Key ID", { fallback: guess ?? keyId, wrong: id10 });
244
+ teamId = await answer(io, "Team ID (Membership details)", { fallback: teamId, wrong: id10 });
245
+ if (o.check && !(await appleTakes(io, { teamId, keyId, privateKey: pem, fetch: f }, list(appleIds)))) {
246
+ if (await again(io, "Apple"))
247
+ continue;
248
+ break apple;
249
+ }
250
+ Object.assign(out, { APPLE_CLIENT_IDS: appleIds, APPLE_KEY_ID: keyId, APPLE_TEAM_ID: teamId, APPLE_PRIVATE_KEY: pem });
251
+ set.push("apple");
252
+ details.apple = list(appleIds).join(", ");
253
+ break;
254
+ }
255
+ // Google
256
+ if (await wants("google")) {
257
+ io.say(" Google Cloud › APIs & Services › Credentials: the OAuth client IDs of your apps (iOS, Android, web).");
258
+ io.say(" Android's Credential Manager signs in with the web client's ID: list that one too.", "dim");
259
+ const ids = await answer(io, "Client IDs, comma separated", {
260
+ fallback: env.GOOGLE_CLIENT_IDS,
261
+ wrong: (v) => (list(v).every((id) => /^[\w-]+\.apps\.googleusercontent\.com$/.test(id)) ? undefined : "each ends in .apps.googleusercontent.com"),
262
+ });
263
+ out.GOOGLE_CLIENT_IDS = list(ids).join(",");
264
+ set.push("google");
265
+ details.google = `${list(ids).length} client ID${list(ids).length === 1 ? "" : "s"}`;
266
+ }
267
+ // GitHub
268
+ if (await wants("github")) {
269
+ io.say(" GitHub › Settings › Developer settings › OAuth Apps › New OAuth App (or the organization's own).");
270
+ io.say(" Homepage URL: your site. Authorization callback URL: where your app takes the way back, a page of the", "dim");
271
+ io.say(" web app (https://app.example.com/auth/github) or the mobile app's link (myapp://github, an App Link).", "dim");
272
+ io.say(" Then Generate a new client secret: GitHub shows it once.", "dim");
273
+ await ask(io, { name: "GITHUB_CLIENT_ID", question: "Client ID", wrong: (v) => (/^[\w.-]{10,40}$/.test(v) ? undefined : "the Client ID the app's page shows (Ov23li…)") }, env, out);
274
+ await ask(io, { name: "GITHUB_CLIENT_SECRET", question: "Client secret", secret: true, wrong: (v) => (/^[0-9a-f]{40}$/i.test(v) ? undefined : "40 hexadecimal characters") }, env, out);
275
+ set.push("github");
276
+ details.github = out.GITHUB_CLIENT_ID ?? "";
277
+ }
278
+ // Email codes
279
+ if (await wants("email")) {
280
+ const sender = await pickOne(io, "Which sends the email?", MAIL_SENDERS, env.MAIL_SENDER);
281
+ out.MAIL_SENDER = sender.id;
282
+ if (sender.id === "dev") {
283
+ devNote(io, out);
284
+ details.email = "development: codes in the server's log";
285
+ }
286
+ else {
287
+ out.MAIL_FROM = await answer(io, "From, like Acme <hello@acme.com>", { fallback: env.MAIL_FROM, wrong: (v) => (domainOf(v) ? undefined : "an address, with a name before it if you like") });
288
+ const from = domainOf(out.MAIL_FROM);
289
+ for (const field of sender.fields) {
290
+ const fallback = field.name === "MAILGUN_DOMAIN" ? (env.MAILGUN_DOMAIN ?? from) : undefined;
291
+ await ask(io, { ...field, fallback: fallback ?? field.fallback }, env, out);
292
+ }
293
+ const made = senderOf(io, () => mailFromEnv(vars()));
294
+ if (made) {
295
+ const to = await answer(io, "Send a test code to (an email address; empty skips)", { optional: true, wrong: (v) => (/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v) ? undefined : "an email address") });
296
+ if (to)
297
+ await testSend(io, made, "email", to, out.DIRECT_AUTH_APP_NAME, secretsOf(vars()));
298
+ const domain = sender.id === "mailgun" ? (out.MAILGUN_DOMAIN ?? from) : from;
299
+ if (o.check) {
300
+ // The sender is asked for its own records (its DKIM key, its bounce domain), then the DNS for each.
301
+ const r = await mailRecords(sender.id, domain, vars(), f);
302
+ if (r.note)
303
+ io.say(` ${r.note}`, "note");
304
+ await records(`mail from ${domain}`, r.records, domain);
305
+ }
306
+ else
307
+ io.say(` The DNS mail from ${domain} needs: npx direct-auth dns ${domain} --sender ${sender.id}`, "dim");
308
+ }
309
+ details.email = `${sender.label.replace(/ \(.*$/, "")}, from ${domainOf(out.MAIL_FROM) ?? ""}`;
310
+ }
311
+ set.push("email");
312
+ }
313
+ // Passwords: on top of email codes, which prove the address at sign-up and reset.
314
+ if (await wants("passwords")) {
315
+ if (!vars().MAIL_SENDER)
316
+ io.say(" Passwords need email codes (sign-up and reset prove the address with one): set up email codes, then this.", "bad");
317
+ else {
318
+ io.say(" Email and password, on top of the codes. Stored as PBKDF2-SHA256; Supabase's bcrypt hashes are taken as they are.");
319
+ io.say(" An address must take a code before its password works: nobody can claim someone else's email with one.", "dim");
320
+ out.PASSWORDS = "1";
321
+ out.PASSWORD_MIN_LENGTH = await answer(io, "Shortest password allowed", { fallback: env.PASSWORD_MIN_LENGTH ?? "8", wrong: (v) => (/^\d+$/.test(v) && Number(v) >= 6 && Number(v) <= 64 ? undefined : "a number from 6 to 64") });
322
+ set.push("passwords");
323
+ details.passwords = `${out.PASSWORD_MIN_LENGTH} characters or more`;
324
+ }
325
+ }
326
+ // SMS codes
327
+ if (await wants("sms")) {
328
+ const sender = await pickOne(io, "Which sends the SMS?", SMS_SENDERS, env.SMS_SENDER);
329
+ out.SMS_SENDER = sender.id;
330
+ io.say(" SMS goes only to the countries you list: bots that ask codes for premium numbers (SMS pumping) can't run up your bill.");
331
+ out.SMS_COUNTRIES = list(await answer(io, "Calling codes it may send to, comma separated (+598, +54)", {
332
+ fallback: env.SMS_COUNTRIES,
333
+ wrong: (v) => (list(v).length && list(v).every((c) => /^\+[1-9]\d{0,3}$/.test(c)) ? undefined : "+ and the country's calling code, like +598, +1"),
334
+ })).join(",");
335
+ if (sender.id === "dev")
336
+ devNote(io, out);
337
+ else {
338
+ for (const field of sender.fields) {
339
+ const fallback = field.name === "TWILIO_FROM" ? (env.TWILIO_FROM ?? env.TWILIO_MESSAGING_SERVICE_SID) : undefined;
340
+ await ask(io, { ...field, fallback: fallback ?? field.fallback }, env, out);
341
+ }
342
+ // One question for Twilio's sender: a Messaging Service SID goes under its own name, and the other is emptied.
343
+ if (sender.id === "twilio" && out.TWILIO_FROM?.startsWith("MG")) {
344
+ out.TWILIO_MESSAGING_SERVICE_SID = out.TWILIO_FROM;
345
+ if (env.TWILIO_FROM)
346
+ out.TWILIO_FROM = "";
347
+ else
348
+ delete out.TWILIO_FROM;
349
+ }
350
+ else if (sender.id === "twilio" && env.TWILIO_MESSAGING_SERVICE_SID)
351
+ out.TWILIO_MESSAGING_SERVICE_SID = "";
352
+ const made = senderOf(io, () => smsFromEnv(vars()));
353
+ if (made) {
354
+ const countries = list(out.SMS_COUNTRIES);
355
+ const to = await answer(io, "Send a test SMS to (a number with its country code; empty skips)", {
356
+ optional: true,
357
+ wrong: (v) => {
358
+ const n = normalizePhone(v);
359
+ if (!n)
360
+ return "a number like +598 99 123 456";
361
+ return allowedPrefix(n, countries) ? undefined : `not in ${countries.join(", ")}`;
362
+ },
363
+ });
364
+ if (to)
365
+ await testSend(io, made, "sms", normalizePhone(to), out.DIRECT_AUTH_APP_NAME, secretsOf(vars()));
366
+ }
367
+ }
368
+ set.push("sms");
369
+ details.sms = `${sender.label.replace(/ \(.*$/, "")}, to ${list(out.SMS_COUNTRIES).join(" ")}`;
370
+ }
371
+ // Passkeys
372
+ if (await wants("passkeys")) {
373
+ io.say(" The relying party is the domain passkeys belong to: your site's, which the apps link to (webcredentials, assetlinks.json).");
374
+ out.PASSKEY_RP_ID = await answer(io, "Domain (rp id)", {
375
+ fallback: env.PASSKEY_RP_ID ?? siteDomain(host),
376
+ wrong: (v) => (/^[a-z0-9-]+(\.[a-z0-9-]+)+$|^localhost$/.test(v) ? undefined : "a domain, like example.com"),
377
+ });
378
+ out.PASSKEY_RP_NAME = await answer(io, "Name the passkey prompts show", { fallback: env.PASSKEY_RP_NAME ?? out.DIRECT_AUTH_APP_NAME });
379
+ io.say(" Origins: the web pages that use passkeys (https://example.com), and each Android app as android:apk-key-hash:<its signing certificate's SHA-256, base64url>.", "dim");
380
+ out.PASSKEY_ORIGINS = list(await answer(io, "Origins, comma separated", {
381
+ fallback: env.PASSKEY_ORIGINS ?? `https://${out.PASSKEY_RP_ID}`,
382
+ wrong: (v) => (list(v).every((x) => /^https:\/\/[^\s/]+$|^http:\/\/localhost(:\d+)?$|^android:apk-key-hash:[\w-]{43}$/.test(x)) ? undefined : "https://example.com or android:apk-key-hash:…"),
383
+ })).join(",");
384
+ set.push("passkeys");
385
+ details.passkeys = `for ${out.PASSKEY_RP_ID}`;
386
+ }
387
+ // Guests
388
+ if (await wants("guests")) {
389
+ io.say(" People start without signing in (POST /guest); linking Apple, Google, an email or a passkey later keeps their id and data.");
390
+ io.say(" The access token says is_anonymous, as Supabase's did: policies can tell guests apart.", "dim");
391
+ out.GUESTS = "1";
392
+ out.GUEST_DAYS = await answer(io, "Delete guests unused for how many days (0 keeps them)", { fallback: env.GUEST_DAYS ?? "30", wrong: (v) => (/^\d{1,4}$/.test(v) ? undefined : "a number of days") });
393
+ if (out.GUEST_DAYS === "0")
394
+ out.GUEST_DAYS = "";
395
+ set.push("guests");
396
+ details.guests = out.GUEST_DAYS ? `deleted after ${out.GUEST_DAYS} days unused` : "kept";
397
+ }
398
+ // The signing keys: made once, never replaced here (a new one signs everyone out); `direct-auth keys --add` rotates.
399
+ const newKey = !env.DIRECT_AUTH_SIGNING_KEYS;
400
+ if (newKey)
401
+ out.DIRECT_AUTH_SIGNING_KEYS = JSON.stringify([await generateSigningKey()]);
402
+ io.summary?.(set, (steps ?? []).filter((p) => !set.includes(p)), details);
403
+ io.say("");
404
+ if (newKey)
405
+ io.say("DIRECT_AUTH_SIGNING_KEYS: a new signing key (it signs the access tokens).", "ok");
406
+ // What changed: an answer the same as the file's isn't a change.
407
+ for (const [k, v] of Object.entries(out))
408
+ if (env[k] === v || (v === "" && !env[k]))
409
+ delete out[k];
410
+ if (Object.keys(out).length === 0)
411
+ io.say("Nothing to change.");
412
+ else {
413
+ writeEnvFile(o.envFile, out);
414
+ io.say(`Written to ${o.envFile}:`, "ok");
415
+ for (const line of columns(Object.keys(out), 3))
416
+ io.say(` ${line}`, "dim");
417
+ if (!gitignored(o.envFile))
418
+ io.say(`Keep ${o.envFile} out of the repository (.gitignore): it holds the keys.`, "note");
419
+ }
420
+ const after = readEnvFile(o.envFile);
421
+ io.say("");
422
+ await deliver(io, where, { envFile: o.envFile, cwd, system: sys });
423
+ if (where === "workers" && after.MAIL_SENDER === "smtp")
424
+ io.say("Workers can't open SMTP connections: pick an HTTP sender (Resend, Postmark, Mailgun, SendGrid, SES) there.", "note");
425
+ // The sign-in at its own address: asked for its issuer, the way an app will.
426
+ if (own && o.check) {
427
+ io.say("");
428
+ const spin = spinner(io, `Asking ${after.DIRECT_AUTH_ISSUER}/.well-known/openid-configuration`);
429
+ const problem = await issuerProblem(after.DIRECT_AUTH_ISSUER, f).catch((e) => (e instanceof Error ? e.message : String(e)));
430
+ if (!problem)
431
+ spin.done(`✓ ${host} answers as ${after.DIRECT_AUTH_ISSUER}.`, "ok");
432
+ else {
433
+ spin.done(`Not yet: ${problem}.`, "note");
434
+ io.say(` Once the server is up there: npx direct-auth issuer ${after.DIRECT_AUTH_ISSUER}`, "dim");
435
+ }
436
+ }
437
+ if (where === "supabase") {
438
+ const ref = /^https:\/\/([a-z0-9]{20})\.supabase\.co\//.exec(fnUrl ?? after.DIRECT_AUTH_ISSUER ?? "")?.[1] ?? "<project-ref>";
439
+ io.say([
440
+ "",
441
+ "Supabase trusts direct-auth's tokens as a Third-Party Auth issuer (auth.uid() is the user's id):",
442
+ ` npx direct-auth supabase-trust --project ${ref} --issuer ${after.DIRECT_AUTH_ISSUER}`,
443
+ " It needs SUPABASE_ACCESS_TOKEN (Account, Access Tokens), and asks before changing anything.",
444
+ "Moving users from Supabase Auth: npx direct-auth migrate (a dry run first; no user moves until you say so).",
445
+ ].join("\n"));
446
+ }
447
+ io.say([
448
+ "",
449
+ "In each app's folder: npx direct-auth app",
450
+ ` It adds the client, with the server at ${after.DIRECT_AUTH_ISSUER}.`,
451
+ "A web app on another origin: list it in DIRECT_AUTH_ORIGINS (comma separated) for CORS.",
452
+ ].join("\n"));
453
+ await offerSkill(io, { cwd });
454
+ return 0;
455
+ }
456
+ /** `direct-auth keys --add FILE`: a new key at the front of the file's list, the others kept after it. */
457
+ export async function addSigningKey(envFile) {
458
+ const text = readEnvFile(envFile).DIRECT_AUTH_SIGNING_KEYS;
459
+ let keys = [];
460
+ if (text) {
461
+ try {
462
+ const trimmed = text.trim();
463
+ keys = JSON.parse(trimmed.startsWith("[") ? trimmed : fromUtf8(fromBase64(trimmed)));
464
+ }
465
+ catch {
466
+ keys = [];
467
+ }
468
+ if (!Array.isArray(keys) || !keys.length || !keys.every((k) => k && typeof k === "object" && typeof k.kid === "string")) {
469
+ throw new Error(`DIRECT_AUTH_SIGNING_KEYS in ${envFile} is not a JSON array of keys (nor base64 of one): fix it or take the line out.`);
470
+ }
471
+ }
472
+ const all = [await generateSigningKey(), ...keys];
473
+ writeEnvFile(envFile, { DIRECT_AUTH_SIGNING_KEYS: JSON.stringify(all) });
474
+ return { count: all.length };
475
+ }
476
+ const list = (v) => (v ?? "").split(",").map((s) => s.trim()).filter(Boolean);
477
+ function issuerOk(v) {
478
+ try {
479
+ const u = new URL(v);
480
+ return u.protocol === "https:" || (u.protocol === "http:" && ["localhost", "127.0.0.1"].includes(u.hostname));
481
+ }
482
+ catch {
483
+ return false;
484
+ }
485
+ }
486
+ /** A linked Supabase project's issuer, from the CLI's own note of the project's ref. */
487
+ function supabaseIssuer(cwd) {
488
+ const file = join(cwd, "supabase", ".temp", "project-ref");
489
+ const ref = existsSync(file) ? readFileSync(file, "utf8").trim() : "";
490
+ return /^[a-z0-9]{20}$/.test(ref) ? `https://${ref}.supabase.co/functions/v1/auth` : undefined;
491
+ }
492
+ /** The site's domain, from the server's: api.example.com is example.com; a supabase.co or workers.dev one says nothing. */
493
+ function siteDomain(host) {
494
+ if (/(^|\.)(supabase\.co|workers\.dev|localhost)$/.test(host) || /^[\d.]+$/.test(host))
495
+ return undefined;
496
+ const parts = host.split(".");
497
+ return parts.length > 2 ? parts.slice(1).join(".") : host;
498
+ }
499
+ /** A first guess at the app's name: the site's domain without its ending, capitalised (example.com: Example). */
500
+ function appName(host) {
501
+ const name = siteDomain(host)?.split(".")[0];
502
+ return name ? name[0].toUpperCase() + name.slice(1) : undefined;
503
+ }
504
+ /** The PEM on one line: the header, the base64 and the footer with no line breaks in between. */
505
+ export function oneLinePem(pem) {
506
+ return pem.replace(/\\n/g, "\n").split(/\r?\n/).map((l) => l.trim()).join("");
507
+ }
508
+ /** Whether the key loads as an ES256 private key, as Apple's client secret is signed with. */
509
+ async function loads(pem) {
510
+ try {
511
+ const body = pem.replace(/-----[^-]+-----/g, "").replace(/\s+/g, "");
512
+ await crypto.subtle.importKey("pkcs8", fromBase64(body), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
513
+ return true;
514
+ }
515
+ catch {
516
+ return false;
517
+ }
518
+ }
519
+ /** Apple asked once per client ID with a code that can't be one: `invalid_grant` means it took the key. */
520
+ async function appleTakes(io, key, ids) {
521
+ const revoker = appleRevoker(key);
522
+ for (const id of ids) {
523
+ const r = await revoker.check(id);
524
+ if (r.ok) {
525
+ io.say(` Apple took the key for ${id}.`, "ok");
526
+ continue;
527
+ }
528
+ if (r.reason === "apple_network" || /^apple_http_5/.test(r.reason)) {
529
+ io.say(` Apple couldn't be asked (${r.reason}); the key is kept unchecked.`, "note");
530
+ return true;
531
+ }
532
+ const hint = r.reason === "apple_invalid_client"
533
+ ? `Check the Key ID, the Team ID, that the key has Sign in with Apple on, and that ${id} is this team's with Sign in with Apple on.`
534
+ : "Check the Key ID and the Team ID.";
535
+ io.say(` Apple refused it for ${id}: ${r.reason.replace(/^apple_/, "")}. ${hint}`, "bad");
536
+ return false;
537
+ }
538
+ return true;
539
+ }
540
+ /** The dev sender: written with the switch it needs, and said for what it is. */
541
+ function devNote(io, out) {
542
+ out.DIRECT_AUTH_DEV = "1";
543
+ io.say(" Codes go to the server's log, not to anyone: only with DIRECT_AUTH_DEV=1 and outside production. Pick a real sender before going live.", "note");
544
+ }
545
+ /** The sender the settings make, or undefined after saying what is missing (the names, never a value). */
546
+ function senderOf(io, make) {
547
+ try {
548
+ return make();
549
+ }
550
+ catch (error) {
551
+ io.say(` The sender can't be made: ${error instanceof Error ? error.message : String(error)}.`, "bad");
552
+ return undefined;
553
+ }
554
+ }
555
+ /** One code sent as the server would send it; the answer's reason with the settings' values blanked. */
556
+ async function testSend(io, send, channel, to, app, secrets) {
557
+ const code = randomCode(6);
558
+ const m = renderCode({ channel, code, app, minutes: 10 });
559
+ const r = await send({ channel, to, code, subject: m.subject, text: m.text, html: m.html, locale: "en" });
560
+ if (r.ok)
561
+ io.say(` Sent: ${to} should have a code from ${app} now.`, "ok");
562
+ else
563
+ io.say(` Not sent: ${gist(r.reason, secrets)}`, "bad");
564
+ }
565
+ /**
566
+ * The issuer an answer stands for: a URL as it is (its last slash dropped), or a name of your own with `/auth` after
567
+ * it, the same path on every host (an Edge Function's proxy, a VPS), so moving keeps it. Undefined when it's neither.
568
+ */
569
+ export function issuerOf(answer) {
570
+ const v = answer.trim();
571
+ if (v.includes("://"))
572
+ return issuerOk(v) ? v.replace(/\/+$/, "") : undefined;
573
+ const name = v.replace(/\/+$/, "").toLowerCase();
574
+ if (/^localhost(:\d+)?$/.test(name))
575
+ return `http://${name}/auth`;
576
+ return /^([a-z0-9]([a-z0-9-]*[a-z0-9])?\.)+[a-z]{2,}$/.test(name) ? `https://${name}/auth` : undefined;
577
+ }
578
+ /** The host when it is a name of your own: not Supabase's, a workers.dev one, localhost or an IP. */
579
+ function ownName(host) {
580
+ return /(^|\.)(supabase\.co|workers\.dev|localhost)$/.test(host) || /^[\d.]+$|:/.test(host) ? undefined : host;
581
+ }
582
+ /** Words in columns, as many to a line as `n`, each column as wide as its longest. */
583
+ export function columns(words, n) {
584
+ const rows = [];
585
+ for (let i = 0; i < words.length; i += n)
586
+ rows.push(words.slice(i, i + n));
587
+ const widths = Array.from({ length: n }, (_, c) => Math.max(0, ...rows.map((r) => r[c]?.length ?? 0)));
588
+ return rows.map((r) => r.map((w, c) => (c === r.length - 1 ? w : w.padEnd(widths[c] + 2))).join(""));
589
+ }
590
+ /** A spinner where the terminal has one, a line where it doesn't. */
591
+ function spinner(io, text) {
592
+ if (io.spin)
593
+ return io.spin(text);
594
+ io.say(` ${text}…`, "dim");
595
+ return { update: () => { }, done: (line, tone) => io.say(` ${line}`, tone) };
596
+ }
597
+ /**
598
+ * DNS records the setup needs: shown to copy, aligned; with checks on, asked about over DNS-over-HTTPS, offered to be
599
+ * made at Cloudflare when the domain is there (with a token the person gives, never shown, kept only where they
600
+ * say), and waited for with a spinner, saying what is still missing.
601
+ */
602
+ async function dnsRecords(io, what, rs, o) {
603
+ if (!rs.length)
604
+ return;
605
+ io.say("");
606
+ io.say(`DNS records for ${what}, to copy:`);
607
+ recordLines(rs).forEach((line, i) => io.say(` ${line}`, i === 0 || i % 2 === 0 ? "dim" : undefined));
608
+ if (!o.check)
609
+ return;
610
+ let left = await missing(rs, o.f);
611
+ if (!left.length) {
612
+ io.say(` ✓ ${rs.length === 1 ? "It answers" : `All ${rs.length} answer`} already.`, "ok");
613
+ return;
614
+ }
615
+ if (await onCloudflare(o.zoneName, o.f)) {
616
+ io.say(` ${o.zoneName}'s DNS is at Cloudflare: they can be made from here, with an API token (Zone, DNS, Edit).`);
617
+ if (await yes(io, " Make them at Cloudflare?", false))
618
+ await atCloudflare(io, left, o);
619
+ left = await missing(left, o.f);
620
+ }
621
+ if (!left.length) {
622
+ io.say(" ✓ They all answer.", "ok");
623
+ return;
624
+ }
625
+ io.say(` Not there yet: ${left.map((r) => `${r.type} ${r.name}`).join(", ")}.`, "note");
626
+ if (!(await yes(io, " Wait for them to answer (up to 10 minutes)?", false))) {
627
+ io.say(" Check again later: they're asked about once more at the end of the next npx direct-auth init.", "dim");
628
+ return;
629
+ }
630
+ const spin = spinner(io, `Waiting for ${left.length}: ${left.map((r) => r.name).join(", ")}`);
631
+ left = await waitFor(left, { f: o.f, timeoutMs: 10 * 60_000, tick: (l) => spin.update(`Waiting for ${l.length}: ${l.map((r) => `${r.type} ${r.name}`).join(", ")}`) });
632
+ if (!left.length)
633
+ spin.done("✓ They all answer.", "ok");
634
+ else
635
+ spin.done(`Still missing after 10 minutes: ${left.map((r) => `${r.type} ${r.name}`).join(", ")}. Check the values at your DNS host.`, "bad");
636
+ }
637
+ /** The records made (or fixed) at Cloudflare: the plan shown, done after a yes. The token is never printed. */
638
+ async function atCloudflare(io, rs, o) {
639
+ const given = process.env.CLOUDFLARE_API_TOKEN || o.env.CLOUDFLARE_API_TOKEN;
640
+ if (given)
641
+ io.say(" With the CLOUDFLARE_API_TOKEN you have.", "dim");
642
+ else
643
+ io.say(" dash.cloudflare.com › My Profile › API Tokens › Create Token › Edit zone DNS, for this zone only.", "dim");
644
+ const token = given || (await answer({ ...io, ask: io.askSecret ?? io.ask }, "Cloudflare API token", {}));
645
+ const cf = cloudflare(token, o.f);
646
+ try {
647
+ const zone = await cf.zoneOf(o.zoneName);
648
+ if (!zone) {
649
+ io.say(` The token can't see ${o.zoneName}'s zone: give it Zone, DNS, Edit on that zone.`, "bad");
650
+ return;
651
+ }
652
+ const plan = await planCloudflare(cf, zone.id, rs);
653
+ const mark = { create: "+", update: "~", keep: "=" };
654
+ for (const p of plan)
655
+ io.say(` ${mark[p.action]} ${p.action.padEnd(7)}${p.record.type.padEnd(7)}${p.record.name}`, p.action === "keep" ? "dim" : undefined);
656
+ const todo = plan.filter((p) => p.action !== "keep");
657
+ if (todo.length && (await yes(io, ` ${todo.length === 1 ? "Do it" : `Do these ${todo.length}`}?`, true))) {
658
+ for (const p of todo) {
659
+ if (p.action === "create")
660
+ await cf.create(zone.id, p.record);
661
+ else
662
+ await cf.update(zone.id, p.id, p.record);
663
+ }
664
+ io.say(` ✓ Done at Cloudflare.`, "ok");
665
+ }
666
+ }
667
+ catch (error) {
668
+ io.say(` Cloudflare said: ${gist(error instanceof Error ? error.message : String(error), [token])}`, "bad");
669
+ return;
670
+ }
671
+ if (!given) {
672
+ const keep = await answer(io, "Keep the token in an env file, for next time (a path; empty: don't keep it)", { optional: true });
673
+ if (keep) {
674
+ writeEnvFile(keep, { CLOUDFLARE_API_TOKEN: token });
675
+ io.say(` Kept in ${keep} as CLOUDFLARE_API_TOKEN.`, "dim");
676
+ }
677
+ }
678
+ }
679
+ /**
680
+ * The sign-in at an address of your own while the server is an Edge Function: a Cloudflare Worker on that address
681
+ * passing `/auth/…` on (`auth-proxy/`), deployed with wrangler when it is there and signed in; it makes its DNS record
682
+ * and certificate itself. The secret it shares with the server, for the callers' IPs, goes in the env file.
683
+ */
684
+ async function supabaseProxy(io, o) {
685
+ let target = o.fnUrl;
686
+ if (!target) {
687
+ const ref = await answer(io, "Your Supabase project's ref (the 20 letters in its URL)", { wrong: (v) => (/^[a-z0-9]{20}$/.test(v) ? undefined : "20 lowercase letters and digits") });
688
+ target = `https://${ref}.supabase.co/functions/v1/auth`;
689
+ }
690
+ o.out.DIRECT_AUTH_PROXY_SECRET = o.env.DIRECT_AUTH_PROXY_SECRET ?? b64url(crypto.getRandomValues(new Uint8Array(32)));
691
+ const dir = join(o.cwd, "auth-proxy");
692
+ for (const [name, text] of Object.entries(proxyFiles({ domain: o.host, target }))) {
693
+ mkdirSync(dirname(join(dir, name)), { recursive: true });
694
+ writeFileSync(join(dir, name), text);
695
+ }
696
+ io.say(` ${o.host} goes to the Edge Function through a small Cloudflare Worker: written to auth-proxy/.`);
697
+ io.say(` ${o.issuer}/... > ${target}/...`, "dim");
698
+ if (!(await onCloudflare(o.host, o.f).catch(() => false))) {
699
+ io.say(` A Worker answers on a name whose DNS is at Cloudflare: move ${o.host.split(".").slice(-2).join(".")}'s DNS there (free), or run the server on a VPS.`, "note");
700
+ }
701
+ const loggedIn = (await o.sys.run("npx", ["--no-install", "wrangler", "whoami"], dir)).code === 0;
702
+ if (!loggedIn) {
703
+ io.say(" Deploy it with wrangler (npx wrangler login first), from auth-proxy/:", "note");
704
+ io.say(" npx wrangler deploy", "code");
705
+ io.say(" npx wrangler secret put DIRECT_AUTH_PROXY_SECRET (the value in your env file)", "code");
706
+ return;
707
+ }
708
+ if (!(await yes(io, " wrangler is signed in. Deploy the proxy now?", true)))
709
+ return;
710
+ const spin = spinner(io, "Deploying auth-proxy");
711
+ const deployed = await o.sys.run("npx", ["wrangler", "deploy"], dir);
712
+ if (deployed.code !== 0) {
713
+ spin.done(`It failed: ${gist(deployed.output, [o.out.DIRECT_AUTH_PROXY_SECRET])}`, "bad");
714
+ return;
715
+ }
716
+ const file = join(dir, ".secret.json");
717
+ writeFileSync(file, JSON.stringify({ DIRECT_AUTH_PROXY_SECRET: o.out.DIRECT_AUTH_PROXY_SECRET }), { mode: 0o600 });
718
+ try {
719
+ const secret = await o.sys.run("npx", ["wrangler", "secret", "bulk", ".secret.json"], dir);
720
+ if (secret.code === 0)
721
+ spin.done(`✓ The proxy is up at ${o.host}, with its secret.`, "ok");
722
+ else
723
+ spin.done(`Deployed, but its secret wasn't set: ${gist(secret.output, [o.out.DIRECT_AUTH_PROXY_SECRET])}`, "bad");
724
+ }
725
+ finally {
726
+ rmSync(file, { force: true });
727
+ }
728
+ }
729
+ /** The values to keep out of anything printed: the keys, tokens, secrets and passwords. */
730
+ const secretsOf = (env) => Object.entries(env)
731
+ .filter(([k, v]) => /KEY|TOKEN|SECRET|PASS|SID/.test(k) && typeof v === "string" && v.length >= 6)
732
+ .map(([, v]) => v);
733
+ /** One of a few, by number; Enter takes what the file has, or the first. */
734
+ async function pickOne(io, title, options, current) {
735
+ const fallback = Math.max(0, options.findIndex((x) => x.id === current)) + 1;
736
+ io.say(` ${title}`);
737
+ options.forEach((x, i) => io.say(` ${i + 1} ${x.label}`));
738
+ for (;;) {
739
+ const a = (await io.ask(` Number [${fallback}]: `)).trim();
740
+ const n = a === "" ? fallback : Number(a);
741
+ if (Number.isInteger(n) && n >= 1 && n <= options.length)
742
+ return options[n - 1];
743
+ }
744
+ }
745
+ /** A sender's setting, asked and put in `out`: a secret the file has is kept with Enter, and never shown. */
746
+ async function ask(base, field, env, out) {
747
+ const io = field.secret && base.askSecret ? { ...base, ask: base.askSecret } : base;
748
+ const had = out[field.name] ?? env[field.name];
749
+ if (field.secret && had) {
750
+ const v = await answer(io, field.question, { optional: true, hint: "Enter keeps the one you have", wrong: field.wrong });
751
+ out[field.name] = v || had;
752
+ return;
753
+ }
754
+ const v = await answer(io, field.question, { fallback: had ?? field.fallback, optional: field.optional, wrong: field.wrong });
755
+ if (v || had)
756
+ out[field.name] = v;
757
+ }
758
+ /** Where the server runs, as this folder suggests: a Supabase project, a Worker. */
759
+ export function hostHere(cwd) {
760
+ if (existsSync(join(cwd, "supabase", "config.toml")))
761
+ return "supabase";
762
+ if (WRANGLER.some((f) => existsSync(join(cwd, f))))
763
+ return "workers";
764
+ return undefined;
765
+ }
766
+ const WRANGLER = ["wrangler.toml", "wrangler.jsonc", "wrangler.json"];
767
+ /** The wizard's screen, or a numbered question; Enter takes what the folder suggests, or Later. */
768
+ async function whereRuns(io, here) {
769
+ if (io.host)
770
+ return io.host(here);
771
+ io.say("");
772
+ const h = await pickOne(io, "Where does your server run?", HOSTS, here ?? "later");
773
+ return h.id;
774
+ }
775
+ /**
776
+ * The env file taken to where the server runs: said how for a server of one's own; for Supabase and Workers, the
777
+ * command shown, and run when its CLI and project are there and the person says yes. What the command prints is
778
+ * never shown whole (it could echo a value): only whether it worked, and a line of why not, with the values blanked.
779
+ */
780
+ export async function deliver(io, host, o) {
781
+ const file = o.envFile;
782
+ if (host === "server") {
783
+ io.say([
784
+ "Your own server reads " + file + "; nothing to upload.",
785
+ ` Copy ${file} next to the server and start it with node --env-file=${file} server.js`,
786
+ ` (deno run --env-file=${file} …, bun --env-file=${file} …). Keep it out of git.`,
787
+ ].join("\n"));
788
+ return;
789
+ }
790
+ if (host === "later") {
791
+ io.say([
792
+ "Then, where the server runs:",
793
+ ` Node, Deno or Bun on your own machine it reads ${file} (node --env-file=${file}, deno --env-file=${file})`,
794
+ ` Supabase supabase secrets set --env-file ${file}`,
795
+ ` Cloudflare Workers npx wrangler secret bulk ${file}`,
796
+ ].join("\n"));
797
+ return;
798
+ }
799
+ const [command, ...args] = host === "supabase" ? ["supabase", "secrets", "set", "--env-file", file] : ["npx", "wrangler", "secret", "bulk", file];
800
+ const line = [command, ...args].join(" ");
801
+ const name = host === "supabase" ? "Supabase" : "Cloudflare";
802
+ let missing;
803
+ if (host === "supabase") {
804
+ if (!o.system.has("supabase"))
805
+ missing = "the Supabase CLI isn't installed (supabase.com/docs/guides/cli)";
806
+ else if (!existsSync(join(o.cwd, "supabase", "config.toml")) && (await o.system.run("supabase", ["projects", "list"], o.cwd)).code !== 0) {
807
+ missing = "this folder isn't a Supabase project (supabase init, supabase link) and the CLI isn't signed in";
808
+ }
809
+ }
810
+ else if (!WRANGLER.some((f) => existsSync(join(o.cwd, f))))
811
+ missing = "there is no wrangler.toml here: run it in the Worker's folder";
812
+ io.say(`${name}: ${line}`);
813
+ if (missing) {
814
+ io.say(` Not run: ${missing}. Run it once it is.`, "note");
815
+ return;
816
+ }
817
+ io.say(` It sends every line of ${file} as a secret (the values aren't shown).`);
818
+ if (!(await yes(io, " Run it now?", true))) {
819
+ io.say(" Not run: it's above, for when you want it.");
820
+ return;
821
+ }
822
+ const r = await o.system.run(command, args, o.cwd);
823
+ if (r.code === 0)
824
+ io.say(` Done: ${name} has the secrets.`, "ok");
825
+ else
826
+ io.say(` It failed${r.code === null ? "" : ` (exit ${r.code})`}: ${gist(r.output, Object.values(readEnvFile(file)))}`, "bad");
827
+ }
828
+ /**
829
+ * One line of what a command (or a provider) said, for a failure: the one that says error, or the last; the values
830
+ * in the env file, and anything that looks like a key, blanked; cut short.
831
+ */
832
+ export function gist(output, values) {
833
+ const lines = plainText(output).split(/\r?\n/).map((l) => l.trim()).filter(Boolean);
834
+ let line = lines.find((l) => /error|failed|not|invalid|unauthori[sz]ed/i.test(l)) ?? lines.at(-1) ?? "no output";
835
+ for (const v of values)
836
+ if (v.length >= 6)
837
+ line = line.split(v).join("…");
838
+ line = line.replace(/[A-Za-z0-9+/_=-]{32,}/g, "…");
839
+ return line.length > 200 ? `${line.slice(0, 199)}…` : line;
840
+ }
841
+ const plainText = (text) => text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
842
+ /** After settings that didn't work: try others, or leave this provider out (nothing of it is written). */
843
+ const again = (io, name) => yes(io, ` Enter them again? (no leaves ${name} out)`, true);
844
+ export async function yes(io, question, fallback) {
845
+ for (;;) {
846
+ const a = (await io.ask(`${question} ${fallback ? "[Y/n]" : "[y/N]"} `)).trim().toLowerCase();
847
+ if (a === "")
848
+ return fallback;
849
+ if (["y", "yes", "s", "si", "sí"].includes(a))
850
+ return true;
851
+ if (["n", "no"].includes(a))
852
+ return false;
853
+ }
854
+ }
855
+ /**
856
+ * Asked until it is right; `fallback` for an empty answer, shown in brackets (`hint` instead, for what isn't to be
857
+ * shown). Optional: empty is "". A file's path may come with quotes (a drag and drop), and ~ for the home folder.
858
+ */
859
+ async function answer(io, question, o = {}) {
860
+ const shown = o.hint ?? o.fallback ?? (o.optional ? "optional" : undefined);
861
+ for (;;) {
862
+ const raw = (await io.ask(` ${question}${shown ? ` [${shown}]` : ""}: `))
863
+ .trim()
864
+ .replace(/^(['"])(.*)\1$/, "$2")
865
+ .replace(/^~(?=\/|$)/, homedir());
866
+ const v = raw || o.fallback || "";
867
+ if (!v && o.optional)
868
+ return "";
869
+ const why = v ? o.wrong?.(v) : "required";
870
+ if (!why)
871
+ return v;
872
+ io.say(` ${why}.`, "bad");
873
+ }
874
+ }
875
+ /** KEY=value lines, enough to tell what is set and keep what is. */
876
+ export function readEnvFile(path) {
877
+ if (!existsSync(path))
878
+ return {};
879
+ const env = {};
880
+ for (const m of readFileSync(path, "utf8").matchAll(/^[ \t]*(?:export[ \t]+)?([\w.-]+)[ \t]*=[ \t]*(?:"([^"\n]*)"[ \t]*$|'([^'\n]*)'|([^\n#]*))/gm)) {
881
+ const value = (m[2] ?? m[3] ?? m[4] ?? "").trim();
882
+ if (value)
883
+ env[m[1]] = value;
884
+ }
885
+ return env;
886
+ }
887
+ /** Replaces the lines of the names given and appends the rest; every other line stays as it was. */
888
+ export function writeEnvFile(path, vars) {
889
+ const lines = existsSync(path) ? readFileSync(path, "utf8").replace(/\n$/, "").split("\n") : [];
890
+ const left = new Map(Object.entries(vars));
891
+ const kept = lines.map((line) => {
892
+ const name = /^[ \t]*(?:export[ \t]+)?([\w.-]+)[ \t]*=/.exec(line)?.[1];
893
+ if (!name || !left.has(name))
894
+ return line;
895
+ const value = left.get(name);
896
+ left.delete(name);
897
+ return `${name}=${value}`;
898
+ });
899
+ for (const [name, value] of left)
900
+ kept.push(`${name}=${value}`);
901
+ writeFileSync(path, `${kept.join("\n")}\n`, { mode: 0o600 });
902
+ // `mode` only applies to a new file: one that was there, readable by others, holds keys now.
903
+ chmodSync(path, 0o600);
904
+ }
905
+ /** Whether git leaves the file out; outside a repository there is nothing to leave it out of. */
906
+ function gitignored(path) {
907
+ const r = spawnSync("git", ["check-ignore", "-q", path], { stdio: "ignore" });
908
+ if (r.error)
909
+ return true;
910
+ // 0: ignored. 1: not ignored. 128: not a repository.
911
+ return r.status !== 1;
912
+ }