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/dns.js ADDED
@@ -0,0 +1,133 @@
1
+ /**
2
+ * `direct-auth dns <domain>`: whether a domain's DNS has what mail from it needs to land in the inbox rather than in
3
+ * spam, asked over DNS-over-HTTPS (Cloudflare's JSON API), so it works the same on every machine with no `dig`.
4
+ *
5
+ * SPF a TXT `v=spf1 …` on the domain: which servers may send as it
6
+ * DMARC a TXT `v=DMARC1; …` on `_dmarc.<domain>`: what receivers do with mail that fails SPF and DKIM
7
+ * DKIM the sender's public key under `<selector>._domainkey.<domain>`, where the selector is the sender's
8
+ *
9
+ * Gmail and Yahoo turn down or bin mail with no SPF or no DMARC, so those two are what make it exit 1. DKIM is
10
+ * checked where the sender's selector has a fixed name; SES's and Postmark's are random, and are said as such.
11
+ * An MX on the domain is for receiving mail: sending codes doesn't need one.
12
+ */
13
+ export const DOH_URL = "https://cloudflare-dns.com/dns-query";
14
+ export const MAIL_SERVICES = ["resend", "postmark", "mailgun", "sendgrid", "ses", "smtp"];
15
+ export class DnsError extends Error {
16
+ name = "DnsError";
17
+ }
18
+ const TYPE = { A: 1, NS: 2, CNAME: 5, MX: 15, TXT: 16, AAAA: 28 };
19
+ /** The records of one type at a name, as their text: TXT without its quotes (its strings joined), MX and CNAME as given. */
20
+ export async function lookup(name, type, f = fetch) {
21
+ let body;
22
+ try {
23
+ const res = await f(`${DOH_URL}?name=${encodeURIComponent(name)}&type=${type}`, {
24
+ headers: { accept: "application/dns-json" },
25
+ signal: AbortSignal.timeout(10_000),
26
+ });
27
+ if (!res.ok)
28
+ throw new DnsError(`DNS-over-HTTPS answered ${res.status} for ${name}`);
29
+ body = (await res.json());
30
+ }
31
+ catch (error) {
32
+ if (error instanceof DnsError)
33
+ throw error;
34
+ throw new DnsError(`couldn't ask ${new URL(DOH_URL).host} about ${name}: ${error instanceof Error ? error.message : String(error)}`);
35
+ }
36
+ // 3 is NXDOMAIN: the name isn't there, so neither is any record.
37
+ if (body.Status !== 0)
38
+ return [];
39
+ return (body.Answer ?? [])
40
+ .filter((a) => a.type === TYPE[type])
41
+ .map((a) => (type === "TXT" ? a.data.replace(/^"|"$/g, "").replace(/"\s*"/g, "") : a.data).trim());
42
+ }
43
+ const spfOf = (records) => records.filter((r) => /^v=spf1(\s|$)/i.test(r));
44
+ /** The domain of a from address: `Acme <hello@acme.com>` or `hello@acme.com`. */
45
+ export function domainOf(from) {
46
+ const address = /<([^>]+)>/.exec(from)?.[1] ?? from;
47
+ return /@([A-Za-z0-9.-]+\.[A-Za-z]{2,})\s*$/.exec(address.trim())?.[1]?.toLowerCase();
48
+ }
49
+ export async function checkMailDns(domain, o = {}) {
50
+ const f = o.fetch ?? fetch;
51
+ const d = domain.trim().toLowerCase().replace(/\.$/, "");
52
+ const lines = [];
53
+ const say = (state, text) => lines.push({ state, text });
54
+ // SPF. Resend sends with a return path on send.<domain>, and asks for the SPF there; the root's is then optional.
55
+ const rootSpf = spfOf(await lookup(d, "TXT", f));
56
+ const sendSpf = o.sender === "resend" ? spfOf(await lookup(`send.${d}`, "TXT", f)) : [];
57
+ let spf = false;
58
+ if (rootSpf.length > 1)
59
+ say("missing", `SPF ${d} has ${rootSpf.length} SPF records: only one may exist, merge them into one.`);
60
+ else if (rootSpf.length === 1) {
61
+ spf = true;
62
+ say("ok", `SPF ${d}: ${rootSpf[0]}`);
63
+ if (o.sender === "mailgun" && !/include:mailgun\.org/i.test(rootSpf[0]))
64
+ say("missing", " It doesn't include Mailgun: add include:mailgun.org before the all.");
65
+ }
66
+ if (o.sender === "resend") {
67
+ if (sendSpf.length) {
68
+ spf = rootSpf.length <= 1;
69
+ say("ok", `SPF send.${d}: ${sendSpf[0]}`);
70
+ }
71
+ else
72
+ say("missing", `SPF send.${d}: none. Add the TXT Resend shows for it.`);
73
+ }
74
+ else if (!rootSpf.length)
75
+ say("missing", `SPF ${d}: none. Add a TXT on ${d} like v=spf1 include:<your sender's> ~all (your sender's DNS page has it).`);
76
+ // DMARC.
77
+ const dmarc = (await lookup(`_dmarc.${d}`, "TXT", f)).find((r) => /^v=DMARC1\b/i.test(r));
78
+ if (dmarc)
79
+ say("ok", `DMARC _dmarc.${d}: ${dmarc}`);
80
+ else
81
+ say("missing", `DMARC _dmarc.${d}: none. Add a TXT there: v=DMARC1; p=none (quarantine later, once reports are clean).`);
82
+ // DKIM, where the sender's selector has a name to ask for.
83
+ const dkimTxt = async (selectors) => {
84
+ for (const s of selectors) {
85
+ const name = `${s}._domainkey.${d}`;
86
+ const found = (await lookup(name, "TXT", f)).find((r) => /(^|;)\s*p=/.test(r) || /^v=DKIM1/i.test(r));
87
+ if (found)
88
+ return name;
89
+ }
90
+ return undefined;
91
+ };
92
+ switch (o.sender) {
93
+ case "resend": {
94
+ const name = await dkimTxt(["resend"]);
95
+ say(name ? "ok" : "missing", name ? `DKIM ${name}` : `DKIM resend._domainkey.${d}: none. Add the TXT Resend shows.`);
96
+ const mx = await lookup(`send.${d}`, "MX", f);
97
+ say(mx.length ? "ok" : "missing", mx.length ? `MX send.${d}: ${mx[0]} (Resend's bounces)` : `MX send.${d}: none. Add the MX Resend shows for it: bounces come back there.`);
98
+ break;
99
+ }
100
+ case "mailgun": {
101
+ const name = await dkimTxt(["mx", "k1", "smtp"]);
102
+ say(name ? "ok" : "missing", name ? `DKIM ${name}` : `DKIM none at mx, k1 or smtp._domainkey.${d}. Add the TXT Mailgun shows under Sending › Domains.`);
103
+ break;
104
+ }
105
+ case "sendgrid":
106
+ for (const s of ["s1", "s2"]) {
107
+ const name = `${s}._domainkey.${d}`;
108
+ const cname = await lookup(name, "CNAME", f);
109
+ say(cname.length ? "ok" : "missing", cname.length ? `DKIM ${name} → ${cname[0]}` : `DKIM ${name}: no CNAME. Add the one SendGrid shows under Sender Authentication.`);
110
+ }
111
+ break;
112
+ case "ses":
113
+ say("info", "DKIM SES uses three CNAMEs with random selectors (<token>._domainkey): they can't be checked by name. The SES console says whether it sees them.");
114
+ break;
115
+ case "postmark":
116
+ say("info", "DKIM Postmark's selector is a timestamp (<date>pm._domainkey): it can't be checked by name. Postmark's Sender Signatures page says whether it sees it.");
117
+ break;
118
+ case "smtp":
119
+ say("info", "DKIM your mail server's own selector (<selector>._domainkey): check it with the server's DKIM setup (OpenDKIM, say).");
120
+ say("info", "PTR the server's IP needs a reverse DNS name (PTR) that matches its HELO name: set it at your VPS provider.");
121
+ say("info", "Port 25 many VPS providers block it to stop spam: use 587 to a relay, or ask them to open it.");
122
+ break;
123
+ default:
124
+ say("info", "DKIM not checked: give --sender (resend, postmark, mailgun, sendgrid, ses, smtp) to look for its selector.");
125
+ }
126
+ say("info", `MX on ${d} it is for receiving mail. Sending codes doesn't need one.`);
127
+ return { domain: d, lines, spf, dmarc: Boolean(dmarc) };
128
+ }
129
+ /** The report as lines to print: ✓ there, ✗ missing, i to know. */
130
+ export function dnsText(r) {
131
+ const mark = { ok: "✓", missing: "✗", info: "i" };
132
+ return r.lines.map((l) => `${mark[l.state]} ${l.text}`);
133
+ }
package/dist/env.d.ts ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * The server's options from environment variables, the names `npx direct-auth init` writes. Everything but the
3
+ * database comes from here, so a deployment is the env file and one line:
4
+ *
5
+ * const server = await createAuthServer({ sql, ...authFromEnv(process.env) });
6
+ *
7
+ * DIRECT_AUTH_ISSUER the server's public URL with its base path (https://api.example.com/auth)
8
+ * DIRECT_AUTH_SIGNING_KEYS the signing keys (a JSON array of private JWKs, or base64 of it)
9
+ * DIRECT_AUTH_APP_NAME the name the codes' messages say
10
+ * DIRECT_AUTH_ORIGINS browser origins allowed (comma separated)
11
+ * DIRECT_AUTH_BASE_PATH where the routes answer, when not the issuer's path (on Supabase, /functions/v1 is left out)
12
+ * DIRECT_AUTH_TABLE_PREFIX the tables' prefix (auth_), as `direct-auth migrate --prefix` made them
13
+ * DIRECT_AUTH_PROXY_SECRET the secret of the proxy in front (the Worker on your own address), when there is one
14
+ * APPLE_CLIENT_IDS bundle IDs and Services IDs (comma separated)
15
+ * APPLE_TEAM_ID APPLE_KEY_ID APPLE_PRIVATE_KEY the Sign in with Apple key, for revoking at deletion
16
+ * GOOGLE_CLIENT_IDS OAuth client IDs (comma separated)
17
+ * GITHUB_CLIENT_ID GITHUB_CLIENT_SECRET a GitHub OAuth app, for POST /github
18
+ * PASSKEY_RP_ID PASSKEY_RP_NAME PASSKEY_ORIGINS
19
+ * MAIL_SENDER resend | postmark | mailgun | sendgrid | ses | smtp | dev, with MAIL_FROM and its keys
20
+ * SMS_SENDER twilio | vonage | sns | sms-gateway | dev, with SMS_COUNTRIES and its keys
21
+ * GUESTS 1 to allow guests; GUEST_DAYS deletes those unused that long
22
+ * PASSWORDS 1 to allow email and password (needs MAIL_SENDER); PASSWORD_ITERATIONS, PASSWORD_MIN_LENGTH
23
+ */
24
+ import type { AuthServerOptions } from "./server.ts";
25
+ import type { Sender } from "./senders/types.ts";
26
+ export type Env = Record<string, string | undefined>;
27
+ export declare class EnvError extends Error {
28
+ name: string;
29
+ }
30
+ /** The mail sender `MAIL_SENDER` names, or undefined when none is set. */
31
+ export declare function mailFromEnv(env: Env, http?: {
32
+ fetch?: typeof fetch;
33
+ }): Sender | undefined;
34
+ /** The SMS sender `SMS_SENDER` names, or undefined when none is set. */
35
+ export declare function smsFromEnv(env: Env, http?: {
36
+ fetch?: typeof fetch;
37
+ }): Sender | undefined;
38
+ /** Everything `createAuthServer` takes but the database. Throws `EnvError` naming what is missing, never a value. */
39
+ export declare function authFromEnv(env: Env): Omit<AuthServerOptions, "sql">;
package/dist/env.js ADDED
@@ -0,0 +1,169 @@
1
+ /**
2
+ * The server's options from environment variables, the names `npx direct-auth init` writes. Everything but the
3
+ * database comes from here, so a deployment is the env file and one line:
4
+ *
5
+ * const server = await createAuthServer({ sql, ...authFromEnv(process.env) });
6
+ *
7
+ * DIRECT_AUTH_ISSUER the server's public URL with its base path (https://api.example.com/auth)
8
+ * DIRECT_AUTH_SIGNING_KEYS the signing keys (a JSON array of private JWKs, or base64 of it)
9
+ * DIRECT_AUTH_APP_NAME the name the codes' messages say
10
+ * DIRECT_AUTH_ORIGINS browser origins allowed (comma separated)
11
+ * DIRECT_AUTH_BASE_PATH where the routes answer, when not the issuer's path (on Supabase, /functions/v1 is left out)
12
+ * DIRECT_AUTH_TABLE_PREFIX the tables' prefix (auth_), as `direct-auth migrate --prefix` made them
13
+ * DIRECT_AUTH_PROXY_SECRET the secret of the proxy in front (the Worker on your own address), when there is one
14
+ * APPLE_CLIENT_IDS bundle IDs and Services IDs (comma separated)
15
+ * APPLE_TEAM_ID APPLE_KEY_ID APPLE_PRIVATE_KEY the Sign in with Apple key, for revoking at deletion
16
+ * GOOGLE_CLIENT_IDS OAuth client IDs (comma separated)
17
+ * GITHUB_CLIENT_ID GITHUB_CLIENT_SECRET a GitHub OAuth app, for POST /github
18
+ * PASSKEY_RP_ID PASSKEY_RP_NAME PASSKEY_ORIGINS
19
+ * MAIL_SENDER resend | postmark | mailgun | sendgrid | ses | smtp | dev, with MAIL_FROM and its keys
20
+ * SMS_SENDER twilio | vonage | sns | sms-gateway | dev, with SMS_COUNTRIES and its keys
21
+ * GUESTS 1 to allow guests; GUEST_DAYS deletes those unused that long
22
+ * PASSWORDS 1 to allow email and password (needs MAIL_SENDER); PASSWORD_ITERATIONS, PASSWORD_MIN_LENGTH
23
+ */
24
+ import { mailgun, postmark, resend, sendgrid, ses } from "./senders/mail.js";
25
+ import { smsGateway, sns, twilio, vonage } from "./senders/sms.js";
26
+ import { smtp } from "./senders/smtp.js";
27
+ import { devSender } from "./senders/dev.js";
28
+ export class EnvError extends Error {
29
+ name = "EnvError";
30
+ }
31
+ const list = (v) => (v ?? "").split(",").map((s) => s.trim()).filter(Boolean);
32
+ function need(env, ...names) {
33
+ const missing = names.filter((n) => !env[n]?.trim());
34
+ if (missing.length)
35
+ throw new EnvError(`missing ${missing.join(", ")}`);
36
+ return names.map((n) => env[n].trim());
37
+ }
38
+ /** The mail sender `MAIL_SENDER` names, or undefined when none is set. */
39
+ export function mailFromEnv(env, http = {}) {
40
+ const kind = env.MAIL_SENDER?.trim().toLowerCase();
41
+ if (!kind)
42
+ return undefined;
43
+ if (kind === "dev")
44
+ return devSender(env);
45
+ const [from] = need(env, "MAIL_FROM");
46
+ switch (kind) {
47
+ case "resend":
48
+ return resend({ ...http, from: from, apiKey: need(env, "RESEND_API_KEY")[0] });
49
+ case "postmark":
50
+ return postmark({ ...http, from: from, serverToken: need(env, "POSTMARK_SERVER_TOKEN")[0] });
51
+ case "mailgun": {
52
+ const [apiKey, domain] = need(env, "MAILGUN_API_KEY", "MAILGUN_DOMAIN");
53
+ return mailgun({ ...http, from: from, apiKey: apiKey, domain: domain, region: env.MAILGUN_REGION === "eu" ? "eu" : "us" });
54
+ }
55
+ case "sendgrid":
56
+ return sendgrid({ ...http, from: from, apiKey: need(env, "SENDGRID_API_KEY")[0] });
57
+ case "ses": {
58
+ const [region, accessKeyId, secretAccessKey] = need(env, "AWS_REGION", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY");
59
+ return ses({ ...http, from: from, region: region, accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: env.AWS_SESSION_TOKEN });
60
+ }
61
+ case "smtp": {
62
+ const [host] = need(env, "SMTP_HOST");
63
+ return smtp({ from: from, host: host, port: env.SMTP_PORT ? Number(env.SMTP_PORT) : undefined, user: env.SMTP_USER, pass: env.SMTP_PASS });
64
+ }
65
+ default:
66
+ throw new EnvError(`MAIL_SENDER: ${kind} is not one of resend, postmark, mailgun, sendgrid, ses, smtp, dev`);
67
+ }
68
+ }
69
+ /** The SMS sender `SMS_SENDER` names, or undefined when none is set. */
70
+ export function smsFromEnv(env, http = {}) {
71
+ const kind = env.SMS_SENDER?.trim().toLowerCase();
72
+ if (!kind)
73
+ return undefined;
74
+ switch (kind) {
75
+ case "dev":
76
+ return devSender(env);
77
+ case "twilio": {
78
+ const [accountSid, authToken] = need(env, "TWILIO_ACCOUNT_SID", "TWILIO_AUTH_TOKEN");
79
+ if (!env.TWILIO_FROM && !env.TWILIO_MESSAGING_SERVICE_SID)
80
+ throw new EnvError("missing TWILIO_FROM or TWILIO_MESSAGING_SERVICE_SID");
81
+ return twilio({ ...http, accountSid: accountSid, authToken: authToken, from: env.TWILIO_FROM, messagingServiceSid: env.TWILIO_MESSAGING_SERVICE_SID });
82
+ }
83
+ case "vonage": {
84
+ const [apiKey, apiSecret, from] = need(env, "VONAGE_API_KEY", "VONAGE_API_SECRET", "VONAGE_FROM");
85
+ return vonage({ ...http, apiKey: apiKey, apiSecret: apiSecret, from: from });
86
+ }
87
+ case "sns": {
88
+ const [region, accessKeyId, secretAccessKey] = need(env, "AWS_REGION", "AWS_ACCESS_KEY_ID", "AWS_SECRET_ACCESS_KEY");
89
+ return sns({ ...http, region: region, accessKeyId: accessKeyId, secretAccessKey: secretAccessKey, sessionToken: env.AWS_SESSION_TOKEN, senderId: env.SNS_SENDER_ID });
90
+ }
91
+ case "sms-gateway": {
92
+ const [url, username, password] = need(env, "SMS_GATEWAY_URL", "SMS_GATEWAY_USERNAME", "SMS_GATEWAY_PASSWORD");
93
+ return smsGateway({ ...http, url: url, username: username, password: password });
94
+ }
95
+ default:
96
+ throw new EnvError(`SMS_SENDER: ${kind} is not one of twilio, vonage, sns, sms-gateway, dev`);
97
+ }
98
+ }
99
+ function positive(env, name) {
100
+ const n = Number(env[name]);
101
+ if (!Number.isInteger(n) || n < 1)
102
+ throw new EnvError(`${name} is not a whole number above 0`);
103
+ return n;
104
+ }
105
+ /**
106
+ * Where the routes answer, from the issuer's path: an Edge Function's requests come without Supabase's
107
+ * `/functions/v1` (the function sees `/auth/…`), so it is left out; DIRECT_AUTH_BASE_PATH says it outright.
108
+ */
109
+ function basePathOf(url, given) {
110
+ if (given?.trim())
111
+ return given.trim();
112
+ const path = url.pathname.replace(/\/+$/, "") || "/";
113
+ return url.hostname.endsWith(".supabase.co") ? path.replace(/^\/functions\/v1(?=\/)/, "") : path;
114
+ }
115
+ /** Everything `createAuthServer` takes but the database. Throws `EnvError` naming what is missing, never a value. */
116
+ export function authFromEnv(env) {
117
+ const [issuer, keys] = need(env, "DIRECT_AUTH_ISSUER", "DIRECT_AUTH_SIGNING_KEYS");
118
+ const url = new URL(issuer);
119
+ const o = {
120
+ issuer: issuer,
121
+ keys,
122
+ app: env.DIRECT_AUTH_APP_NAME?.trim() || url.hostname,
123
+ basePath: basePathOf(url, env.DIRECT_AUTH_BASE_PATH),
124
+ origins: list(env.DIRECT_AUTH_ORIGINS),
125
+ proxySecret: env.DIRECT_AUTH_PROXY_SECRET?.trim() || undefined,
126
+ };
127
+ const prefix = env.DIRECT_AUTH_TABLE_PREFIX?.trim();
128
+ if (prefix) {
129
+ if (!/^[a-z_][a-z0-9_]*$/.test(prefix))
130
+ throw new EnvError("DIRECT_AUTH_TABLE_PREFIX is a plain lowercase name, like auth_");
131
+ o.tablePrefix = prefix;
132
+ }
133
+ const appleIds = list(env.APPLE_CLIENT_IDS);
134
+ if (appleIds.length) {
135
+ o.apple = { clientIds: appleIds };
136
+ if (env.APPLE_PRIVATE_KEY?.trim()) {
137
+ const [teamId, keyId, privateKey] = need(env, "APPLE_TEAM_ID", "APPLE_KEY_ID", "APPLE_PRIVATE_KEY");
138
+ o.apple.revoke = { teamId: teamId, keyId: keyId, privateKey: privateKey, previousPrivateKeys: env.APPLE_PREVIOUS_PRIVATE_KEY ? [env.APPLE_PREVIOUS_PRIVATE_KEY] : undefined };
139
+ }
140
+ }
141
+ const googleIds = list(env.GOOGLE_CLIENT_IDS);
142
+ if (googleIds.length)
143
+ o.google = { clientIds: googleIds, domains: list(env.GOOGLE_DOMAINS) };
144
+ if (env.GITHUB_CLIENT_ID?.trim() || env.GITHUB_CLIENT_SECRET?.trim()) {
145
+ const [clientId, clientSecret] = need(env, "GITHUB_CLIENT_ID", "GITHUB_CLIENT_SECRET");
146
+ o.github = { clientId: clientId.trim(), clientSecret: clientSecret.trim() };
147
+ }
148
+ if (env.PASSKEY_RP_ID?.trim()) {
149
+ o.passkeys = { rpId: env.PASSKEY_RP_ID.trim(), rpName: env.PASSKEY_RP_NAME?.trim() || o.app, origins: list(env.PASSKEY_ORIGINS) };
150
+ }
151
+ const mail = mailFromEnv(env);
152
+ if (mail)
153
+ o.email = { send: mail };
154
+ const on = (v) => /^(1|true|yes|on)$/i.test(v?.trim() ?? "");
155
+ if (on(env.GUESTS) || env.GUEST_DAYS?.trim())
156
+ o.guests = { days: env.GUEST_DAYS ? positive(env, "GUEST_DAYS") : undefined };
157
+ if (on(env.PASSWORDS)) {
158
+ if (!o.email)
159
+ throw new EnvError("PASSWORDS needs MAIL_SENDER: sign-up and reset prove the address with a code");
160
+ o.passwords = {
161
+ iterations: env.PASSWORD_ITERATIONS ? positive(env, "PASSWORD_ITERATIONS") : undefined,
162
+ minLength: env.PASSWORD_MIN_LENGTH ? positive(env, "PASSWORD_MIN_LENGTH") : undefined,
163
+ };
164
+ }
165
+ const sms = smsFromEnv(env);
166
+ if (sms)
167
+ o.sms = { send: sms, countries: list(env.SMS_COUNTRIES), domain: env.SMS_DOMAIN?.trim() || undefined };
168
+ return o;
169
+ }
@@ -0,0 +1,19 @@
1
+ export { createAuth, normalizeEmail, type Auth, type AuthOptions, type Context, type SignInResult } from "./auth.ts";
2
+ export type { User, IdentityInfo } from "./accounts.ts";
3
+ export type { Tokens, SessionInfo } from "./sessions.ts";
4
+ export { generateSigningKey, loadSigningKeys, publicHalf, thumbprint, KeyError, type PrivateJwk, type SigningKeys } from "./keys.ts";
5
+ export { verifyJwt, decodeJwt, type Claims, type JwtResult } from "./jwt.ts";
6
+ export { remoteJwks, staticJwks } from "./jwks.ts";
7
+ export { apple, APPLE_ISSUER, APPLE_JWKS } from "./providers/apple.ts";
8
+ export { google, GOOGLE_ISSUERS, GOOGLE_JWKS } from "./providers/google.ts";
9
+ export type { Identity, IdentityResult } from "./providers/identity.ts";
10
+ export { normalizePhone, allowedPrefix } from "./phone.ts";
11
+ export { renderCode, type CodeMessage } from "./messages.ts";
12
+ export { DEFAULT_LIMITS, type CodeLimits } from "./codes.ts";
13
+ export type { Sql } from "./db/sql.ts";
14
+ export type { Sender, Outgoing, SendResult } from "./senders/types.ts";
15
+ export { createAuthServer, type AuthServer, type AuthServerOptions } from "./server.ts";
16
+ export { appleRevoker, type AppleKeyOptions, type AppleRevoker } from "./providers/apple-revoke.ts";
17
+ export { passkeys, type PasskeyOptions } from "./passkeys.ts";
18
+ export { authFromEnv, mailFromEnv, smsFromEnv, EnvError, type Env } from "./env.ts";
19
+ export { supabaseMoveSql } from "./supabase.ts";
package/dist/index.js ADDED
@@ -0,0 +1,14 @@
1
+ export { createAuth, normalizeEmail } from "./auth.js";
2
+ export { generateSigningKey, loadSigningKeys, publicHalf, thumbprint, KeyError } from "./keys.js";
3
+ export { verifyJwt, decodeJwt } from "./jwt.js";
4
+ export { remoteJwks, staticJwks } from "./jwks.js";
5
+ export { apple, APPLE_ISSUER, APPLE_JWKS } from "./providers/apple.js";
6
+ export { google, GOOGLE_ISSUERS, GOOGLE_JWKS } from "./providers/google.js";
7
+ export { normalizePhone, allowedPrefix } from "./phone.js";
8
+ export { renderCode } from "./messages.js";
9
+ export { DEFAULT_LIMITS } from "./codes.js";
10
+ export { createAuthServer } from "./server.js";
11
+ export { appleRevoker } from "./providers/apple-revoke.js";
12
+ export { passkeys } from "./passkeys.js";
13
+ export { authFromEnv, mailFromEnv, smsFromEnv, EnvError } from "./env.js";
14
+ export { supabaseMoveSql } from "./supabase.js";
package/dist/init.d.ts ADDED
@@ -0,0 +1,134 @@
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
+ export type Provider = "apple" | "google" | "github" | "email" | "passwords" | "sms" | "passkeys" | "guests";
15
+ export declare const PROVIDER_IDS: readonly Provider[];
16
+ /** How a line the setup says reads: plain unless it is good news, worth a look, or a failure. */
17
+ export type Tone = "ok" | "note" | "bad" | "dim" | "code";
18
+ export interface InitIO {
19
+ /** One question; the answer as typed (empty for the default). */
20
+ ask(question: string): Promise<string>;
21
+ /** The same for a key or a password: on a terminal, what is typed shows as dots. */
22
+ askSecret?(question: string): Promise<string>;
23
+ /** A line; `tone` says whether it is good news, worth a look or a failure, for a terminal to colour. */
24
+ say(line: string, tone?: Tone): void;
25
+ /** Before a step's questions (the server's, then each provider's, the nth of so many): where a wizard clears its screen and heads it. */
26
+ section?(step: Provider | "server", n: number, of: number): void;
27
+ /** Before the end (what was written, what next): the providers set up (a word on each) and those left out. */
28
+ summary?(set: Provider[], left: Provider[], details: Partial<Record<Provider | "server", string>>): void;
29
+ /** Something that takes a while (a deploy, the DNS): a spinner on a terminal, until `done` says how it went. */
30
+ spin?(text: string): Spinner;
31
+ /** Where the server runs, on a screen of its own (`here`, what the folder looks like, chosen); without it, a numbered question. */
32
+ host?(here: Host | undefined): Promise<Host>;
33
+ }
34
+ export interface Spinner {
35
+ update(text: string): void;
36
+ done(line: string, tone?: Tone): void;
37
+ }
38
+ /** Where the server runs, which says how the env file gets to it. */
39
+ export type Host = "server" | "supabase" | "workers" | "later";
40
+ export declare const HOSTS: readonly {
41
+ id: Host;
42
+ label: string;
43
+ detail: string;
44
+ }[];
45
+ /** Thrown by a screen left with q (code 0) or Ctrl-C (130): nothing is written. */
46
+ export declare class Stopped extends Error {
47
+ readonly code: number;
48
+ constructor(code: number);
49
+ }
50
+ /** How commands are found and run; a test gives its own. */
51
+ export interface System {
52
+ /** Whether the command is installed. */
53
+ has(command: string): boolean;
54
+ /** Runs it in `cwd` with nothing on the terminal: the exit code, and what it said (for a summary, never shown whole). */
55
+ run(command: string, args: readonly string[], cwd: string): Promise<{
56
+ code: number | null;
57
+ output: string;
58
+ }>;
59
+ }
60
+ export declare const system: System;
61
+ export interface InitOptions {
62
+ envFile: string;
63
+ /** Ask Apple about the key and the DNS about the mail domain. On unless `--no-check`. */
64
+ check: boolean;
65
+ /**
66
+ * The providers to set up, chosen beforehand (a wizard's checklist): those are asked for, a configured one
67
+ * replaced, and the rest left as they are. Without it, each provider is a yes or no question.
68
+ */
69
+ providers?: Provider[];
70
+ /** The folder the server's project is in: where supabase/ or a wrangler file is looked for, and the commands run. */
71
+ cwd?: string;
72
+ system?: System;
73
+ /** For Apple, the DNS and the test sends; a test gives its own. */
74
+ fetch?: typeof fetch;
75
+ }
76
+ /** One setting a sender takes: the variable, the question, and what a right answer looks like. */
77
+ interface Field {
78
+ name: string;
79
+ question: string;
80
+ /** Typed, never shown: an existing one is kept with Enter, and isn't printed as the default. */
81
+ secret?: boolean;
82
+ optional?: boolean;
83
+ fallback?: string;
84
+ wrong?: (v: string) => string | undefined;
85
+ }
86
+ export declare const MAIL_SENDERS: readonly {
87
+ id: string;
88
+ label: string;
89
+ fields: Field[];
90
+ }[];
91
+ export declare const SMS_SENDERS: readonly {
92
+ id: string;
93
+ label: string;
94
+ fields: Field[];
95
+ }[];
96
+ /** The providers the env file has turned on. */
97
+ export declare function configured(envFile: string): Provider[];
98
+ export declare function init(io: InitIO, o: InitOptions): Promise<number>;
99
+ /** `direct-auth keys --add FILE`: a new key at the front of the file's list, the others kept after it. */
100
+ export declare function addSigningKey(envFile: string): Promise<{
101
+ count: number;
102
+ }>;
103
+ /** The PEM on one line: the header, the base64 and the footer with no line breaks in between. */
104
+ export declare function oneLinePem(pem: string): string;
105
+ /**
106
+ * The issuer an answer stands for: a URL as it is (its last slash dropped), or a name of your own with `/auth` after
107
+ * it, the same path on every host (an Edge Function's proxy, a VPS), so moving keeps it. Undefined when it's neither.
108
+ */
109
+ export declare function issuerOf(answer: string): string | undefined;
110
+ /** Words in columns, as many to a line as `n`, each column as wide as its longest. */
111
+ export declare function columns(words: readonly string[], n: number): string[];
112
+ /** Where the server runs, as this folder suggests: a Supabase project, a Worker. */
113
+ export declare function hostHere(cwd: string): Host | undefined;
114
+ /**
115
+ * The env file taken to where the server runs: said how for a server of one's own; for Supabase and Workers, the
116
+ * command shown, and run when its CLI and project are there and the person says yes. What the command prints is
117
+ * never shown whole (it could echo a value): only whether it worked, and a line of why not, with the values blanked.
118
+ */
119
+ export declare function deliver(io: InitIO, host: Host, o: {
120
+ envFile: string;
121
+ cwd: string;
122
+ system: System;
123
+ }): Promise<void>;
124
+ /**
125
+ * One line of what a command (or a provider) said, for a failure: the one that says error, or the last; the values
126
+ * in the env file, and anything that looks like a key, blanked; cut short.
127
+ */
128
+ export declare function gist(output: string, values: readonly string[]): string;
129
+ export declare function yes(io: Pick<InitIO, "ask">, question: string, fallback: boolean): Promise<boolean>;
130
+ /** KEY=value lines, enough to tell what is set and keep what is. */
131
+ export declare function readEnvFile(path: string): Record<string, string>;
132
+ /** Replaces the lines of the names given and appends the rest; every other line stays as it was. */
133
+ export declare function writeEnvFile(path: string, vars: Record<string, string>): void;
134
+ export {};