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/tui.js ADDED
@@ -0,0 +1,537 @@
1
+ /**
2
+ * `direct-auth init` on a terminal: a welcome, a checklist of the ways to sign in, a screen for each one chosen and
3
+ * one for what was written. Only when stdin and stderr are both a terminal; a pipe or a test gets the plain questions.
4
+ *
5
+ * The screens with keys (the welcome, the checklist, where the server runs) run in raw mode and are over before the
6
+ * line reader the questions use is made, so a key is read by one or the other, never both. Whatever happens, the
7
+ * terminal is given back as it was: raw mode off, the cursor shown.
8
+ *
9
+ * The parts that decide (`checklist`, `press`, `pick`) and draw (`welcomeScreen`, `providersScreen`, …) are pure,
10
+ * and tested as such; `Terminal` is the little that touches the terminal.
11
+ */
12
+ import { emitKeypressEvents } from "node:readline";
13
+ import { HOSTS } from "./init.js";
14
+ import { KIND_LABEL } from "./apps.js";
15
+ /**
16
+ * The terminal's own sixteen colours (cyan, green, yellow, red), so they follow its theme, light or dark; nothing at
17
+ * all when colour is off (NO_COLOR).
18
+ */
19
+ export function style(color) {
20
+ const sgr = (on, off) => (t) => (color ? `\x1b[${on}m${t}\x1b[${off}m` : t);
21
+ return {
22
+ bold: sgr("1", "22"),
23
+ dim: sgr("2", "22"),
24
+ accent: sgr("36", "39"),
25
+ ok: sgr("32", "39"),
26
+ note: sgr("33", "39"),
27
+ bad: sgr("31", "39"),
28
+ code: sgr("36", "39"),
29
+ };
30
+ }
31
+ /** Whitebear's bear, drawn from its logo in quarter blocks: the ears, the eyes running down to the cheeks, the nose, the split muzzle. */
32
+ export const BEAR = [
33
+ " ▗▄▙▄▄▄▖ ▄▄▄▄▟████▙▄▄▄▄ ▗▄▄▄▟▄▖",
34
+ " ▜████████████████████████████▛",
35
+ " ▝████████████████████████████▘",
36
+ " ████████████████████████████",
37
+ " ▐████████████████████████████▌",
38
+ " ▟████████████████████████████▙",
39
+ "▗█████▛▀ ▀▜██████████▛▀ ▀▜█████▖",
40
+ "▐████▙▄▖ ▀██████▀ ▗▄▟████▌",
41
+ "▜██████▙▄▄ ▗▟██████▙▖ ▄▄▟██████▛",
42
+ " ▝▜██████▘▗██████████▖▝██████▛▘",
43
+ " ▀███▛ ▟████████████▙ ▜███▀",
44
+ " ▀▘ ▝████▙ ▟████▘ ▝▀",
45
+ " ▝████▙▖▗▟████▘",
46
+ " ▝████▌▐████▘",
47
+ ];
48
+ /** The bear with lines of text beside it, by row. */
49
+ function besideBear(side) {
50
+ return BEAR.map((line, i) => (side[i] ? `${line.padEnd(35)}${side[i]}` : line));
51
+ }
52
+ const credit = (s) => `by ${s.bold("Guille Cura")} ${s.dim("whitebear.io")} ${s.dim("cura.is")}`;
53
+ /**
54
+ * The welcome when the answers are piped in on a terminal (`cat answers | direct-auth init`): the bear, and what
55
+ * this does beside it. The wizard has its own screen.
56
+ */
57
+ export function banner(color) {
58
+ const s = style(color);
59
+ const side = {
60
+ 3: s.bold(s.accent("direct-auth init")),
61
+ 5: "Sign-in from your own backend.",
62
+ 6: "Apple, Google, codes, passwords and passkeys, step by step.",
63
+ 8: s.dim("Nothing secret is printed: it all goes to your env file."),
64
+ 10: credit(s),
65
+ };
66
+ return ["", ...besideBear(side), "", ""].join("\n");
67
+ }
68
+ /** The wizard's first screen: what direct-auth is, what this does, the license. The bear only where there's room. */
69
+ export function welcomeScreen(color, columns = 80) {
70
+ const s = style(color);
71
+ const about = [
72
+ s.bold(s.accent("direct-auth")),
73
+ "",
74
+ "Sign-in from your own backend: Apple,",
75
+ "Google, codes, passwords, passkeys, guests.",
76
+ s.dim("Zero dependencies, self-hosted: your keys,"),
77
+ s.dim("your database, nobody in between."),
78
+ "",
79
+ "This wizard: pick the ways to sign in,",
80
+ "give it their keys, it checks them and",
81
+ "writes your env file.",
82
+ s.dim("Nothing secret is shown."),
83
+ ];
84
+ const license = [
85
+ `${s.bold("MIT")}: free to use, change and share; no warranty.`,
86
+ s.dim("github.com/guillecura/direct-auth"),
87
+ ];
88
+ const top = columns >= 78
89
+ ? besideBear(Object.fromEntries(about.map((line, i) => [i + 2, line]).filter(([, line]) => line)))
90
+ : about;
91
+ return ["", ...top, "", credit(s), ...license, "", footer(s, ["Enter to start", "q to quit"])].join("\n");
92
+ }
93
+ /** "Enter to start q to quit": each key in the accent, what it does dim. */
94
+ function footer(s, parts) {
95
+ return parts
96
+ .map((part) => {
97
+ const [key, ...rest] = part.split(" ");
98
+ return `${s.accent(key)} ${s.dim(rest.join(" "))}`;
99
+ })
100
+ .join(" ");
101
+ }
102
+ /** A list with the cursor on its first item that can be checked. */
103
+ export function checklist(items) {
104
+ return { items, cursor: Math.max(0, items.findIndex((i) => !i.disabled)) };
105
+ }
106
+ /** What a key does to the list: moves the cursor (past what is disabled, round the ends), checks, confirms, quits. */
107
+ export function press(state, key) {
108
+ const name = key.name ?? key.sequence;
109
+ if (key.ctrl && name === "c")
110
+ return { state, done: "interrupt" };
111
+ if (name === "q" || name === "escape")
112
+ return { state, done: "quit" };
113
+ if (name === "up" || name === "k" || name === "down" || name === "j") {
114
+ return { state: { ...state, cursor: move(state, name === "up" || name === "k" ? -1 : 1), hint: undefined } };
115
+ }
116
+ if (name === "space") {
117
+ const item = state.items[state.cursor];
118
+ if (!item || item.disabled)
119
+ return { state };
120
+ const items = state.items.map((it, i) => (i === state.cursor ? { ...it, checked: !it.checked } : it));
121
+ return { state: { ...state, items, hint: undefined } };
122
+ }
123
+ if (name === "return" || name === "enter") {
124
+ if (!state.allowNone && !state.items.some((i) => i.checked && !i.disabled))
125
+ return { state: { ...state, hint: "Check one with space first (q quits)." } };
126
+ return { state, done: "confirm" };
127
+ }
128
+ return { state };
129
+ }
130
+ function move(state, by) {
131
+ const n = state.items.length;
132
+ for (let step = 1; step <= n; step += 1) {
133
+ const i = (((state.cursor + by * step) % n) + n) % n;
134
+ if (!state.items[i].disabled)
135
+ return i;
136
+ }
137
+ return state.cursor;
138
+ }
139
+ export function checked(state) {
140
+ return state.items.filter((i) => i.checked && !i.disabled).map((i) => i.id);
141
+ }
142
+ /** The ways to sign in, as the checklist shows them. */
143
+ export const PROVIDERS = [
144
+ { id: "apple", label: "Sign in with Apple", detail: "iOS, macOS, the web; revoked on deletion" },
145
+ { id: "google", label: "Google", detail: "Android, iOS, the web" },
146
+ { id: "github", label: "GitHub", detail: "an OAuth app; the server trades the code" },
147
+ { id: "email", label: "Email codes", detail: "a six-digit code by email" },
148
+ { id: "passwords", label: "Passwords", detail: "email and password, the address proved by a code" },
149
+ { id: "sms", label: "SMS codes", detail: "a code by text message, to the countries you list" },
150
+ { id: "passkeys", label: "Passkeys", detail: "Face ID, Touch ID, a fingerprint, a security key" },
151
+ { id: "guests", label: "Guests", detail: "in first, a way to sign in linked later, same id" },
152
+ ];
153
+ /** The checklist to start from: nothing checked, what the env file has marked as configured. */
154
+ export function providerItems(configured) {
155
+ return PROVIDERS.map((p) => ({ ...p, note: configured.includes(p.id) ? "configured" : undefined, checked: false }));
156
+ }
157
+ export function providersScreen(state, color, envFile, columns = 80) {
158
+ const s = style(color);
159
+ const anyConfigured = state.items.some((i) => i.note === "configured");
160
+ return [
161
+ "",
162
+ s.bold(s.accent("How do people sign in?")),
163
+ s.dim(`The settings go to ${envFile}.${anyConfigured ? " Configured ones stay as they are unless checked." : ""}`),
164
+ "",
165
+ ...checklistRows(state, s, columns),
166
+ "",
167
+ state.hint ? s.note(state.hint) : "",
168
+ footer(s, ["↑/↓ move", "space check", "Enter continue", "q quit"]),
169
+ ].join("\n");
170
+ }
171
+ /** A checklist's lines: the cursor, the box, the label, the detail dim, the note; the detail cut short to fit. */
172
+ function checklistRows(state, s, columns = 80) {
173
+ const width = Math.max(...state.items.map((i) => i.label.length)) + 3;
174
+ const noteWidth = Math.max(0, ...state.items.map((i) => i.note?.length ?? 0));
175
+ const room = Math.max(10, columns - 1 - 8 - width - (noteWidth ? noteWidth + 3 : 0));
176
+ const cut = (d) => (d.length > room ? `${d.slice(0, room - 1).trimEnd()}…` : d);
177
+ const items = state.items.map((i) => ({ ...i, detail: cut(i.detail) }));
178
+ const detail = Math.max(...items.map((i) => i.detail.length)) + 3;
179
+ return items.map((item, i) => {
180
+ const here = i === state.cursor;
181
+ if (item.disabled) {
182
+ const line = ` [-] ${item.label.padEnd(width)}${item.detail.padEnd(detail)}${item.note ?? ""}`.trimEnd();
183
+ return ` ${s.dim(line)}`;
184
+ }
185
+ const cursor = here ? s.accent("›") : " ";
186
+ const box = item.checked ? s.ok("[x]") : "[ ]";
187
+ const label = here ? s.bold(item.label.padEnd(width)) : item.label.padEnd(width);
188
+ const note = item.note ? s.note(item.note) : "";
189
+ // Padded only when a note follows: a line ends at its last word.
190
+ return ` ${cursor} ${box} ${label}${s.dim(note ? item.detail.padEnd(detail) : item.detail)}${note}`;
191
+ });
192
+ }
193
+ /** The server's own questions (the issuer, the app's name), before the providers'. */
194
+ const SERVER = { label: "Your server", detail: "the address of your sign-in: where the apps sign in, and what the tokens name" };
195
+ /**
196
+ * The header of one step's questions: its name, "step 2 of 4" and a bar of the steps, done ones filled. The server's
197
+ * step is the first of them all.
198
+ */
199
+ export function stepScreen(step, n, of, color) {
200
+ const s = style(color);
201
+ const p = step === "server" ? SERVER : PROVIDERS.find((x) => x.id === step);
202
+ const total = of + 1;
203
+ const at = step === "server" ? 1 : n + 1;
204
+ const bar = Array.from({ length: total }, (_, i) => (i < at ? s.accent("━━━━") : s.dim("────"))).join(" ");
205
+ return ["", `${bar} ${s.dim(`step ${at} of ${total}`)}`, "", s.bold(s.accent(p.label)), s.dim(p.detail), "", ""].join("\n");
206
+ }
207
+ /**
208
+ * The header of the last screen: the server and each provider set up, with a word on each, in columns; those left
209
+ * out after settings that didn't work, crossed.
210
+ */
211
+ export function summaryScreen(set, left, color, details = {}) {
212
+ const s = style(color);
213
+ const label = (p) => (p === "server" ? "Your server" : PROVIDERS.find((x) => x.id === p).label);
214
+ const rows = [...(details.server ? [["server", true]] : []), ...set.map((p) => [p, true]), ...left.map((p) => [p, false])];
215
+ const width = Math.max(0, ...rows.map(([p]) => label(p).length)) + 3;
216
+ const lines = ["", s.bold(s.ok("Done")), ""];
217
+ for (const [p, ok] of rows) {
218
+ const what = ok ? (details[p] ?? "set up") : "left out, nothing of it written";
219
+ lines.push(` ${ok ? s.ok("✓") : s.bad("✗")} ${label(p).padEnd(width)}${s.dim(what)}`);
220
+ }
221
+ // The blank line after comes from what follows.
222
+ return [...lines, ""].join("\n");
223
+ }
224
+ /** The options with the cursor on the one given, or the first. */
225
+ export function choice(options, selected) {
226
+ return { options, cursor: Math.max(0, options.findIndex((o) => o.id === selected)) };
227
+ }
228
+ /** What a key does to a choice: moves (round the ends), picks by its number, confirms, quits. */
229
+ export function pick(state, key) {
230
+ const name = key.name ?? key.sequence;
231
+ const n = state.options.length;
232
+ if (key.ctrl && name === "c")
233
+ return { state, done: "interrupt" };
234
+ if (name === "q" || name === "escape")
235
+ return { state, done: "quit" };
236
+ if (name === "up" || name === "k")
237
+ return { state: { ...state, cursor: (state.cursor + n - 1) % n } };
238
+ if (name === "down" || name === "j")
239
+ return { state: { ...state, cursor: (state.cursor + 1) % n } };
240
+ if (name === "return" || name === "enter")
241
+ return { state, done: "confirm" };
242
+ const digit = Number(key.sequence);
243
+ if (/^[1-9]$/.test(key.sequence ?? "") && digit <= n)
244
+ return { state: { ...state, cursor: digit - 1 } };
245
+ return { state };
246
+ }
247
+ export function chosen(state) {
248
+ return state.options[state.cursor].id;
249
+ }
250
+ /** Where the server runs, the one this folder looks like (a supabase/ or wrangler file) marked and chosen. */
251
+ export function hostOptions(here) {
252
+ return HOSTS.map((h) => ({ ...h, note: h.id === here ? "found here" : undefined }));
253
+ }
254
+ export function hostScreen(state, color, envFile) {
255
+ const s = style(color);
256
+ const width = Math.max(...state.options.map((o) => o.label.length)) + 3;
257
+ const detail = Math.max(...state.options.map((o) => o.detail.length)) + 3;
258
+ const rows = state.options.map((o, i) => {
259
+ const here = i === state.cursor;
260
+ const cursor = here ? s.accent("›") : " ";
261
+ const label = here ? s.bold(o.label.padEnd(width)) : o.label.padEnd(width);
262
+ const note = o.note ? s.note(o.note) : "";
263
+ return ` ${cursor} ${label}${s.dim(note ? o.detail.padEnd(detail) : o.detail)}${note}`;
264
+ });
265
+ return [
266
+ "",
267
+ s.bold(s.accent("Where does your server run?")),
268
+ s.dim(`It reads the settings from ${envFile}; this is how they get there.`),
269
+ "",
270
+ ...rows,
271
+ "",
272
+ "",
273
+ footer(s, ["↑/↓ move", "Enter choose", "q quit"]),
274
+ ].join("\n");
275
+ }
276
+ // The apps found: which get the client.
277
+ /** The apps as a checklist, all checked: they were found, so most likely wanted; the folder and what told, in columns. */
278
+ export function appItems(apps) {
279
+ const path = (a) => (a.dir === "." ? "./" : `${a.dir}/`);
280
+ const width = Math.max(...apps.map((a) => path(a).length)) + 3;
281
+ return apps.map((a) => ({ id: `${a.kind}:${a.dir}`, label: KIND_LABEL[a.kind], detail: `${path(a).padEnd(width)}${a.via}`, checked: true }));
282
+ }
283
+ export function appsScreen(state, color, columns = 80) {
284
+ const s = style(color);
285
+ return [
286
+ "",
287
+ `${s.bold(s.accent("direct-auth app"))} ${s.dim("the client in your apps: iOS, macOS, Android, the web")}`,
288
+ "",
289
+ s.bold("Add it to which apps?"),
290
+ s.dim("Found under this folder. What is safe to add is added, once; the rest comes as steps."),
291
+ "",
292
+ ...checklistRows(state, s, columns),
293
+ "",
294
+ state.hint ? s.note(state.hint) : "",
295
+ footer(s, ["↑/↓ move", "space check", "Enter continue", "q quit"]),
296
+ ].join("\n");
297
+ }
298
+ /** The header of the questions after the checklist (the issuer's URL): the apps they go into. */
299
+ export function appsHeader(apps, color) {
300
+ const s = style(color);
301
+ const names = apps.map((a) => `${KIND_LABEL[a.kind]} ${s.dim(`(${a.dir === "." ? "./" : a.dir})`)}`).join(", ");
302
+ return ["", s.bold(s.accent("Your apps")), names, s.dim("They sign in at your server: its URL goes into the steps."), "", ""].join("\n");
303
+ }
304
+ /**
305
+ * A spinner on one line, redrawn in place, until `done` writes its last line; the text cut to the terminal's
306
+ * width so it never wraps. Without colour the frames still turn (they're characters, not colour).
307
+ */
308
+ export function spin(out, text, color) {
309
+ const s = style(color);
310
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
311
+ let i = 0;
312
+ let now = text;
313
+ const fit = (t) => (t.length > (out.columns ?? 80) - 6 ? `${t.slice(0, (out.columns ?? 80) - 7)}…` : t);
314
+ const draw = () => out.write(`\r\x1b[2K ${s.accent(frames[(i += 1) % frames.length])} ${fit(now)}`);
315
+ draw();
316
+ const timer = setInterval(draw, 80);
317
+ return {
318
+ update(t) {
319
+ now = t;
320
+ },
321
+ done(line, tone) {
322
+ clearInterval(timer);
323
+ out.write(`\r\x1b[2K ${tone ? s[tone](line) : line}\n`);
324
+ },
325
+ };
326
+ }
327
+ /**
328
+ * A line wrapped at words to `width`, each piece under the line's own indent (and a list's "1. " or "! " beside it).
329
+ * A word longer than the width (a URL, a command) stays whole on a line of its own.
330
+ */
331
+ export function wrap(line, width) {
332
+ if (line.length <= width || width < 20)
333
+ return [line];
334
+ let lead = /^(\s*(?:[✓✗!i+~=]\s|\d+\.\s)?)/.exec(line)[1];
335
+ // A row of aligned columns (a label, spaces, a count, spaces, a note): it goes on under its last column.
336
+ for (const m of line.matchAll(/\S( {2,})(?=\S)/g)) {
337
+ const end = m.index + m[0].length;
338
+ if (end > lead.length && end <= Math.min(44, width - 20))
339
+ lead = line.slice(0, end);
340
+ }
341
+ const indent = " ".repeat(lead.length);
342
+ const out = [];
343
+ let now = lead;
344
+ for (const word of line.slice(lead.length).split(/ +/)) {
345
+ if (now.trim() && now.length + 1 + word.length > width) {
346
+ out.push(now.trimEnd());
347
+ now = indent + word;
348
+ }
349
+ else
350
+ now = now.trim() && !now.endsWith(" ") ? `${now} ${word}` : `${now}${word}`;
351
+ }
352
+ out.push(now.trimEnd());
353
+ return out;
354
+ }
355
+ /** Escape codes and nothing else: what the screen reads as text. */
356
+ export function plain(text) {
357
+ return text.replace(/\x1b\[[0-9;?]*[A-Za-z]/g, "");
358
+ }
359
+ // The terminal itself.
360
+ const CLEAR = "\x1b[H\x1b[2J";
361
+ const HIDE_CURSOR = "\x1b[?25l";
362
+ const SHOW_CURSOR = "\x1b[?25h";
363
+ /**
364
+ * Raw mode for the screens that take keys, and the terminal given back on every way out: `restore()` when done, and
365
+ * on exit, an uncaught error, SIGINT or SIGTERM.
366
+ */
367
+ export class Terminal {
368
+ input;
369
+ output;
370
+ #raw = false;
371
+ #queue = [];
372
+ #waiting;
373
+ #redraw;
374
+ #onKey = (sequence, key) => {
375
+ const k = key ?? { sequence };
376
+ if (this.#waiting) {
377
+ const w = this.#waiting;
378
+ this.#waiting = undefined;
379
+ w(k);
380
+ }
381
+ else
382
+ this.#queue.push(k);
383
+ };
384
+ #onResize = () => this.#redraw?.();
385
+ #onExit = () => this.restore();
386
+ #onSignal = (signal) => {
387
+ this.restore();
388
+ process.exit(signal === "SIGINT" ? 130 : 143);
389
+ };
390
+ constructor(input, output) {
391
+ this.input = input;
392
+ this.output = output;
393
+ process.on("exit", this.#onExit);
394
+ process.on("SIGINT", this.#onSignal);
395
+ process.on("SIGTERM", this.#onSignal);
396
+ output.on("resize", this.#onResize);
397
+ }
398
+ get columns() {
399
+ return this.output.columns ?? 80;
400
+ }
401
+ /** Keys one at a time, in raw mode, the cursor hidden. */
402
+ keys() {
403
+ if (this.#raw)
404
+ return;
405
+ emitKeypressEvents(this.input);
406
+ this.input.setRawMode(true);
407
+ this.input.on("keypress", this.#onKey);
408
+ this.input.resume();
409
+ this.output.write(HIDE_CURSOR);
410
+ this.#raw = true;
411
+ }
412
+ key() {
413
+ const next = this.#queue.shift();
414
+ if (next)
415
+ return Promise.resolve(next);
416
+ return new Promise((resolve) => (this.#waiting = resolve));
417
+ }
418
+ /** The screen cleared and drawn anew; again with the same function when the window changes size. */
419
+ draw(screen) {
420
+ this.#redraw = () => this.output.write(CLEAR + screen());
421
+ this.#redraw();
422
+ }
423
+ /**
424
+ * Back to lines: raw mode off, the cursor shown, stdin paused until the line reader takes it. Keys typed ahead
425
+ * (with the Enter that ended the checklist, a paste) wait for `replay()`.
426
+ */
427
+ lines() {
428
+ this.#redraw = undefined;
429
+ if (!this.#raw)
430
+ return;
431
+ this.input.off("keypress", this.#onKey);
432
+ this.input.setRawMode(false);
433
+ this.input.pause();
434
+ this.output.write(SHOW_CURSOR);
435
+ this.#raw = false;
436
+ }
437
+ /** The keys typed ahead, handed to the line reader that now listens for them (readline takes keypress events). */
438
+ replay() {
439
+ const keys = this.#queue;
440
+ this.#queue = [];
441
+ for (const key of keys)
442
+ this.input.emit("keypress", key.sequence, key);
443
+ }
444
+ /** A screen's worth of text, cleared first, outside raw mode (a step's header, the summary). */
445
+ clear(text) {
446
+ this.output.write(CLEAR + text);
447
+ }
448
+ /** The terminal as it was. Safe to call more than once. */
449
+ restore() {
450
+ this.lines();
451
+ this.#queue = [];
452
+ if (this.input.isTTY && this.input.isRaw)
453
+ this.input.setRawMode(false);
454
+ this.output.write(SHOW_CURSOR);
455
+ }
456
+ /** Done with it: the terminal back, and the handlers off the process. */
457
+ close() {
458
+ this.restore();
459
+ process.off("exit", this.#onExit);
460
+ process.off("SIGINT", this.#onSignal);
461
+ process.off("SIGTERM", this.#onSignal);
462
+ this.output.off("resize", this.#onResize);
463
+ }
464
+ }
465
+ /**
466
+ * The welcome and the checklist. The providers checked, or how it was left: "quit" (q, Esc) or "interrupt" (Ctrl-C).
467
+ * Raw mode is over when it returns.
468
+ */
469
+ export async function chooseProviders(term, o) {
470
+ term.keys();
471
+ try {
472
+ term.draw(() => welcomeScreen(o.color, term.columns));
473
+ for (;;) {
474
+ const key = await term.key();
475
+ const name = key.name ?? key.sequence;
476
+ if (key.ctrl && name === "c")
477
+ return "interrupt";
478
+ if (name === "q" || name === "escape")
479
+ return "quit";
480
+ if (name === "return" || name === "enter")
481
+ break;
482
+ }
483
+ let state = checklist(providerItems(o.configured));
484
+ for (;;) {
485
+ term.draw(() => providersScreen(state, o.color, o.envFile, term.columns));
486
+ const r = press(state, await term.key());
487
+ state = r.state;
488
+ if (r.done === "confirm")
489
+ return checked(state);
490
+ if (r.done)
491
+ return r.done;
492
+ }
493
+ }
494
+ finally {
495
+ term.lines();
496
+ }
497
+ }
498
+ /** Where the server runs, on its own screen; raw mode is over when it returns. */
499
+ export async function chooseHost(term, o) {
500
+ term.keys();
501
+ try {
502
+ let state = choice(hostOptions(o.here), o.here ?? "later");
503
+ for (;;) {
504
+ term.draw(() => hostScreen(state, o.color, o.envFile));
505
+ const r = pick(state, await term.key());
506
+ state = r.state;
507
+ if (r.done === "confirm")
508
+ return chosen(state);
509
+ if (r.done)
510
+ return r.done;
511
+ }
512
+ }
513
+ finally {
514
+ term.lines();
515
+ }
516
+ }
517
+ /** The apps to add the client to, from those found; none is an answer too. Raw mode is over when it returns. */
518
+ export async function chooseApps(term, apps, o) {
519
+ term.keys();
520
+ try {
521
+ let state = { ...checklist(appItems(apps)), allowNone: true };
522
+ for (;;) {
523
+ term.draw(() => appsScreen(state, o.color, term.columns));
524
+ const r = press(state, await term.key());
525
+ state = r.state;
526
+ if (r.done === "confirm") {
527
+ const ids = checked(state);
528
+ return apps.filter((a) => ids.includes(`${a.kind}:${a.dir}`));
529
+ }
530
+ if (r.done)
531
+ return r.done;
532
+ }
533
+ }
534
+ finally {
535
+ term.lines();
536
+ }
537
+ }
package/package.json CHANGED
@@ -1,6 +1,92 @@
1
1
  {
2
2
  "name": "direct-auth",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Sign-in from your own backend: Sign in with Apple (with revocation), Google, GitHub, email and SMS codes and passkeys, checked with WebCrypto, with accounts and rotating sessions on SQLite, Postgres (Supabase, Neon) or Cloudflare D1, and an OIDC issuer Supabase's Third-Party Auth trusts. Zero dependencies; Deno, Node, Bun, Workers. Clients for iOS (Swift), Android (Kotlin) and the web.",
5
+ "keywords": [
6
+ "apple",
7
+ "auth",
8
+ "authentication",
9
+ "cloudflare-workers",
10
+ "d1",
11
+ "deno",
12
+ "google",
13
+ "jwt",
14
+ "kotlin",
15
+ "login",
16
+ "oidc",
17
+ "otp",
18
+ "passkeys",
19
+ "postgres",
20
+ "self-hosted",
21
+ "sign-in-with-apple",
22
+ "sms",
23
+ "sqlite",
24
+ "supabase",
25
+ "swift",
26
+ "webauthn"
27
+ ],
28
+ "license": "MIT",
29
+ "author": "Guille Cura",
30
+ "homepage": "https://whitebear.io/en/oss/direct-auth",
31
+ "repository": {
32
+ "type": "git",
33
+ "url": "git+https://github.com/guillecura/direct-auth.git"
34
+ },
35
+ "bugs": "https://github.com/guillecura/direct-auth/issues",
36
+ "type": "module",
37
+ "sideEffects": false,
38
+ "engines": {
39
+ "node": ">=22.18"
40
+ },
41
+ "bin": {
42
+ "direct-auth": "dist/cli.js"
43
+ },
44
+ "exports": {
45
+ ".": {
46
+ "types": "./dist/index.d.ts",
47
+ "default": "./dist/index.js"
48
+ },
49
+ "./node": {
50
+ "types": "./dist/node.d.ts",
51
+ "default": "./dist/node.js"
52
+ },
53
+ "./senders": {
54
+ "types": "./dist/senders/index.d.ts",
55
+ "default": "./dist/senders/index.js"
56
+ },
57
+ "./sqlite": {
58
+ "types": "./dist/sqlite.d.ts",
59
+ "default": "./dist/sqlite.js"
60
+ },
61
+ "./postgres": {
62
+ "types": "./dist/postgres.d.ts",
63
+ "default": "./dist/postgres.js"
64
+ },
65
+ "./d1": {
66
+ "types": "./dist/d1.d.ts",
67
+ "default": "./dist/d1.js"
68
+ },
69
+ "./client": {
70
+ "types": "./dist/client.d.ts",
71
+ "default": "./dist/client.js"
72
+ }
73
+ },
74
+ "files": [
75
+ "dist",
76
+ "README.md",
77
+ "LICENSE",
78
+ "skills"
79
+ ],
80
+ "scripts": {
81
+ "build": "rm -rf dist && tsc -p tsconfig.build.json && chmod +x dist/cli.js",
82
+ "typecheck": "tsc --noEmit",
83
+ "test": "node --test test/*.test.ts",
84
+ "prepublishOnly": "npm run typecheck && npm test && npm run build",
85
+ "prepare": "npm run build"
86
+ },
87
+ "devDependencies": {
88
+ "@electric-sql/pglite": "0.3.14",
89
+ "@types/node": "24.10.1",
90
+ "typescript": "5.9.3"
91
+ }
92
+ }