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/pgwire.js ADDED
@@ -0,0 +1,445 @@
1
+ /**
2
+ * A Postgres connection for the command line (`direct-auth migrate`), with nothing but Node: the wire protocol's
3
+ * simple queries, SCRAM-SHA-256 (or MD5) passwords, and TLS when the server offers it. Not for the server, which
4
+ * takes whatever driver the app already uses.
5
+ *
6
+ * `sslmode` in the URL as libpq reads it: `disable`, `prefer` (TLS when the server has it), `require` (TLS or
7
+ * nothing), `verify-ca` (TLS with the certificate's chain checked against `sslrootcert`), `verify-full` (the chain
8
+ * and the host's name). `sslrootcert` is a CA file, such as the one Supabase gives under Database Settings › SSL
9
+ * Configuration, or `system` for the system's CAs. With no sslmode given: `verify-full` when there is an
10
+ * `sslrootcert`, `require` for a database elsewhere (what moves is password hashes: no one on the way may turn TLS
11
+ * off), `prefer` on this machine.
12
+ *
13
+ * Who is at the other end is proven one of two ways, and nothing is sent or believed until it is:
14
+ *
15
+ * - the certificate, checked strongly: `verify-full`, or `verify-ca` against a CA file of its own (any certificate
16
+ * the system's CAs signed, for any name, would pass `verify-ca` with `system`, so that one doesn't count);
17
+ * - or SCRAM bound to the TLS channel (SCRAM-SHA-256-PLUS, tls-server-end-point): the server proves it knows the
18
+ * password for this very connection, so one in between can neither pose as the database nor pass the sign-in
19
+ * through to it. Without a strongly checked certificate this is required (`channel_binding=require`, the
20
+ * default then). Supabase's pooler doesn't offer it: give it the CA file (`sslrootcert=prod-ca-2021.crt`), or
21
+ * use the direct connection. `channel_binding=prefer` or `disable` in the URL goes without, and the connection
22
+ * says it is open to a server in between.
23
+ *
24
+ * A password sent as it is or as MD5, or none asked for, only goes to this machine's database with TLS not asked
25
+ * for, or to a strongly checked certificate. Until the server says the sign-in is done (AuthenticationOk, after
26
+ * one of those proofs), nothing else it sends is taken: a server that says it is ready without it is refused.
27
+ */
28
+ import { connect as netConnect } from "node:net";
29
+ import { connect as tlsConnect } from "node:tls";
30
+ import { readFileSync } from "node:fs";
31
+ import { createHash, createHmac, pbkdf2Sync, randomBytes } from "node:crypto";
32
+ export class PgError extends Error {
33
+ name = "PgError";
34
+ code;
35
+ constructor(message, code) {
36
+ super(message);
37
+ this.code = code;
38
+ }
39
+ }
40
+ /** The most SCRAM iterations a server may ask for: past this it is a way to keep this tool busy, not a password. */
41
+ export const MAX_SCRAM_ITERATIONS = 1_000_000;
42
+ /** The parts of a database URL, and the URL with its password hidden (for saying which database). */
43
+ export function parseDatabaseUrl(url) {
44
+ const u = new URL(url);
45
+ if (u.protocol !== "postgres:" && u.protocol !== "postgresql:")
46
+ throw new Error("not a postgres:// URL");
47
+ const host = u.hostname.replace(/^\[|\]$/g, "");
48
+ const loopback = host === "localhost" || host === "::1" || /^127\./.test(host);
49
+ const sslrootcert = u.searchParams.get("sslrootcert") ?? undefined;
50
+ const sslmode = u.searchParams.get("sslmode") ?? (sslrootcert ? "verify-full" : loopback ? "prefer" : "require");
51
+ const local = loopback && (sslmode === "disable" || sslmode === "prefer");
52
+ /** The certificate checked well enough to stand for the server: its name too, or a CA of its own. */
53
+ const strong = sslmode === "verify-full" || (sslmode === "verify-ca" && !!sslrootcert && sslrootcert !== "system");
54
+ return {
55
+ host,
56
+ /** This machine's database, with TLS not asked for: the old ways of sending a password are allowed. */
57
+ local,
58
+ strong,
59
+ sslrootcert,
60
+ /** Required unless the other end is proven some other way (this machine, a strongly checked certificate). */
61
+ channelBinding: u.searchParams.get("channel_binding") ?? (local || strong ? "prefer" : "require"),
62
+ port: Number(u.port || 5432),
63
+ user: decodeURIComponent(u.username || "postgres"),
64
+ password: decodeURIComponent(u.password),
65
+ database: decodeURIComponent(u.pathname.slice(1)) || "postgres",
66
+ sslmode,
67
+ shown: `${u.protocol}//${u.username ? `${decodeURIComponent(u.username)}${u.password ? ":•••••" : ""}@` : ""}${u.host}${u.pathname}`,
68
+ };
69
+ }
70
+ /**
71
+ * SCRAM-SHA-256's client side (RFC 5802, 7677): the final message and the server signature to expect. `gs2` is the
72
+ * header the first message began with (`n,,` none, `y,,` able but not offered, `p=tls-server-end-point,,` bound),
73
+ * and `binding` the channel's bytes when bound (RFC 5929).
74
+ */
75
+ export function scramFinal(password, clientNonce, serverFirst, user = "*", gs2 = "n,,", binding) {
76
+ const attrs = Object.fromEntries(serverFirst.split(",").map((p) => [p[0], p.slice(2)]));
77
+ const nonce = attrs.r ?? "";
78
+ if (!nonce.startsWith(clientNonce) || nonce.length <= clientNonce.length)
79
+ throw new Error("SCRAM: the server's nonce doesn't extend ours");
80
+ const iterations = Number(attrs.i);
81
+ if (!Number.isInteger(iterations) || iterations < 1 || iterations > MAX_SCRAM_ITERATIONS) {
82
+ throw new Error(`SCRAM: the server asks for ${attrs.i} iterations (at most ${MAX_SCRAM_ITERATIONS})`);
83
+ }
84
+ if (!attrs.s)
85
+ throw new Error("SCRAM: the server sent no salt");
86
+ const salted = pbkdf2Sync(password.normalize("NFKC"), Buffer.from(attrs.s, "base64"), iterations, 32, "sha256");
87
+ const clientKey = createHmac("sha256", salted).update("Client Key").digest();
88
+ const storedKey = createHash("sha256").update(clientKey).digest();
89
+ const channel = Buffer.concat([Buffer.from(gs2), binding ? Buffer.from(binding) : Buffer.alloc(0)]).toString("base64");
90
+ const withoutProof = `c=${channel},r=${nonce}`;
91
+ const authMessage = `n=${user},r=${clientNonce},${serverFirst},${withoutProof}`;
92
+ const signature = createHmac("sha256", storedKey).update(authMessage).digest();
93
+ const proof = Buffer.from(clientKey.map((b, i) => b ^ signature[i]));
94
+ const serverKey = createHmac("sha256", salted).update("Server Key").digest();
95
+ return {
96
+ message: `${withoutProof},p=${proof.toString("base64")}`,
97
+ serverSignature: createHmac("sha256", serverKey).update(authMessage).digest("base64"),
98
+ };
99
+ }
100
+ function message(type, body) {
101
+ const head = Buffer.alloc(5);
102
+ head.write(type, 0, "latin1");
103
+ head.writeInt32BE(body.length + 4, 1);
104
+ return Buffer.concat([head, body]);
105
+ }
106
+ const cstr = (s) => Buffer.concat([Buffer.from(s, "utf8"), Buffer.from([0])]);
107
+ /**
108
+ * The hash tls-server-end-point uses for a certificate (RFC 5929): its signature's, or SHA-256 for MD5 and SHA-1.
109
+ * Read from the DER: Certificate ::= SEQUENCE { tbsCertificate, signatureAlgorithm, signature }.
110
+ */
111
+ export function endPointHash(der) {
112
+ const element = (at) => {
113
+ let length = der[at + 1];
114
+ let head = 2;
115
+ if (length & 0x80) {
116
+ const n = length & 0x7f;
117
+ length = 0;
118
+ for (let i = 0; i < n; i += 1)
119
+ length = length * 256 + der[at + 2 + i];
120
+ head = 2 + n;
121
+ }
122
+ return { start: at + head, end: at + head + length };
123
+ };
124
+ try {
125
+ const certificate = element(0);
126
+ const tbs = element(certificate.start);
127
+ const algorithm = element(tbs.end);
128
+ const oid = element(algorithm.start);
129
+ const hex = Buffer.from(der.subarray(oid.start, oid.end)).toString("hex");
130
+ return ({
131
+ "2a864886f70d01010c": "sha384", // sha384WithRSAEncryption
132
+ "2a864886f70d01010d": "sha512", // sha512WithRSAEncryption
133
+ "2a8648ce3d040303": "sha384", // ecdsa-with-SHA384
134
+ "2a8648ce3d040304": "sha512", // ecdsa-with-SHA512
135
+ }[hex] ?? "sha256");
136
+ }
137
+ catch {
138
+ return "sha256";
139
+ }
140
+ }
141
+ export async function pgConnect(url, o = {}) {
142
+ const c = parseDatabaseUrl(url);
143
+ const local = o.local ?? c.local;
144
+ const timeout = o.timeoutMs ?? 15_000;
145
+ // Unless the URL says, binding is required wherever nothing else proves the server.
146
+ const channelBinding = new URL(url).searchParams.get("channel_binding") ?? (local || c.strong ? "prefer" : "require");
147
+ let tls = null;
148
+ let verified = false;
149
+ let socket = await new Promise((resolve, reject) => {
150
+ const s = netConnect({ host: c.host, port: c.port });
151
+ s.setTimeout(timeout, () => s.destroy(new Error(`no answer from ${c.host}:${c.port}`)));
152
+ s.once("connect", () => resolve(s));
153
+ s.once("error", reject);
154
+ });
155
+ if (c.sslmode !== "disable") {
156
+ const req = Buffer.alloc(8);
157
+ req.writeInt32BE(8, 0);
158
+ req.writeInt32BE(80877103, 4);
159
+ socket.write(req);
160
+ const answer = await new Promise((resolve, reject) => {
161
+ socket.once("data", (d) => resolve(d.toString("latin1", 0, 1)));
162
+ socket.once("error", reject);
163
+ });
164
+ if (answer === "S") {
165
+ verified = c.sslmode === "verify-full" || c.sslmode === "verify-ca";
166
+ const ca = c.sslrootcert && c.sslrootcert !== "system" ? readFileSync(c.sslrootcert) : undefined;
167
+ const ip = /^[\d.:]+$/.test(c.host);
168
+ tls = await new Promise((resolve, reject) => {
169
+ const t = tlsConnect({
170
+ socket,
171
+ ca,
172
+ servername: ip ? undefined : c.host,
173
+ rejectUnauthorized: verified,
174
+ // verify-ca checks the chain and not the name. (Node refuses the key given as undefined.)
175
+ ...(c.sslmode === "verify-ca" ? { checkServerIdentity: () => undefined } : {}),
176
+ }, () => resolve(t));
177
+ t.once("error", reject);
178
+ });
179
+ socket = tls;
180
+ }
181
+ else if (c.sslmode === "require" || c.sslmode.startsWith("verify")) {
182
+ socket.destroy();
183
+ throw new Error(`${c.host} doesn't offer TLS, and sslmode=${c.sslmode} asks for it`);
184
+ }
185
+ }
186
+ // Incoming messages, one at a time.
187
+ let buffer = Buffer.alloc(0);
188
+ const waiting = [];
189
+ const queued = [];
190
+ let failure = null;
191
+ const fails = [];
192
+ socket.on("data", (d) => {
193
+ buffer = Buffer.concat([buffer, d]);
194
+ while (buffer.length >= 5) {
195
+ const length = buffer.readInt32BE(1);
196
+ // The length counts itself: under 4 is no message, and reading on would never end.
197
+ if (length < 4) {
198
+ buffer = Buffer.alloc(0);
199
+ socket.destroy();
200
+ return onFail(new Error("the server sent something that isn't a Postgres message"));
201
+ }
202
+ if (buffer.length < length + 1)
203
+ break;
204
+ const m = { type: buffer.toString("latin1", 0, 1), body: buffer.subarray(5, length + 1) };
205
+ buffer = buffer.subarray(length + 1);
206
+ const w = waiting.shift();
207
+ if (w)
208
+ w(m);
209
+ else
210
+ queued.push(m);
211
+ }
212
+ });
213
+ const onFail = (e) => {
214
+ failure ??= e;
215
+ for (const f of fails.splice(0))
216
+ f(e);
217
+ };
218
+ socket.on("error", onFail);
219
+ socket.on("close", () => onFail(new Error("the connection closed")));
220
+ const next = () => new Promise((resolve, reject) => {
221
+ const q = queued.shift();
222
+ if (q)
223
+ return resolve(q);
224
+ if (failure)
225
+ return reject(failure);
226
+ waiting.push(resolve);
227
+ fails.push(reject);
228
+ });
229
+ const fields = (body) => {
230
+ const out = {};
231
+ let at = 0;
232
+ while (at < body.length && body[at] !== 0) {
233
+ const code = String.fromCharCode(body[at]);
234
+ const end = body.indexOf(0, at + 1);
235
+ out[code] = body.toString("utf8", at + 1, end);
236
+ at = end + 1;
237
+ }
238
+ return out;
239
+ };
240
+ const errorOf = (body) => {
241
+ const f = fields(body);
242
+ return new PgError(`${f.M ?? "error"}${f.D ? ` (${f.D})` : ""}${f.H ? ` hint: ${f.H}` : ""}`, f.C ?? "");
243
+ };
244
+ const startup = Buffer.concat([
245
+ Buffer.alloc(4),
246
+ cstr("user"),
247
+ cstr(c.user),
248
+ cstr("database"),
249
+ cstr(c.database),
250
+ cstr("client_encoding"),
251
+ cstr("UTF8"),
252
+ cstr("application_name"),
253
+ cstr("direct-auth"),
254
+ Buffer.from([0]),
255
+ ]);
256
+ startup.writeInt32BE(196608, 0);
257
+ const len = Buffer.alloc(4);
258
+ len.writeInt32BE(startup.length + 4, 0);
259
+ socket.write(Buffer.concat([len, startup]));
260
+ let clientNonce = "";
261
+ let expected = "";
262
+ let gs2 = "n,,";
263
+ let binding;
264
+ let scram = "none";
265
+ const refuse = (why) => {
266
+ socket.destroy();
267
+ throw new Error(why);
268
+ };
269
+ // Without a checked certificate, a server in between could pose as the database: only one that proves it knows
270
+ // the password (SCRAM's signature) is believed, and the password never goes as it is.
271
+ const trusted = () => local || (verified && c.strong);
272
+ let signedIn = false;
273
+ for (;;) {
274
+ const m = await next();
275
+ if (m.type === "E") {
276
+ socket.destroy();
277
+ throw errorOf(m.body);
278
+ }
279
+ if (m.type === "N")
280
+ continue;
281
+ if (signedIn) {
282
+ // After AuthenticationOk: its settings (S) and key (K), then ready (Z).
283
+ if (m.type === "Z")
284
+ break;
285
+ if (m.type === "S" || m.type === "K")
286
+ continue;
287
+ refuse(`the server sent '${m.type}' while starting the session`);
288
+ }
289
+ // Before it, only the sign-in itself: a server that says it's ready, or anything else, hasn't proven a thing.
290
+ if (m.type !== "R")
291
+ refuse(`${c.host} said '${m.type}' before the sign-in was done (not the database you meant?)`);
292
+ const kind = m.body.readInt32BE(0);
293
+ if (kind === 0) {
294
+ if (scram === "started")
295
+ refuse("SCRAM: the server said yes without proving it knows the password (not the database you meant?)");
296
+ if (scram === "none" && !trusted()) {
297
+ refuse(`${c.host} let us in without a password, so it proved nothing: check its certificate (sslmode=verify-full with sslrootcert) to connect to it`);
298
+ }
299
+ signedIn = true;
300
+ continue;
301
+ }
302
+ if (signedIn)
303
+ refuse("the server asked for a password after saying yes");
304
+ if (kind === 3 || kind === 5) {
305
+ if (!trusted()) {
306
+ refuse(`${c.host} asks for the password ${kind === 3 ? "as it is" : "as MD5"}, which a server in between could take: check its certificate (sslmode=verify-full with sslrootcert) to send it`);
307
+ }
308
+ }
309
+ if (kind === 3)
310
+ socket.write(message("p", cstr(c.password)));
311
+ else if (kind === 5) {
312
+ const salt = m.body.subarray(4, 8);
313
+ const inner = createHash("md5").update(c.password + c.user).digest("hex");
314
+ socket.write(message("p", cstr(`md5${createHash("md5").update(Buffer.concat([Buffer.from(inner), salt])).digest("hex")}`)));
315
+ }
316
+ else if (kind === 10) {
317
+ if (scram !== "none")
318
+ refuse("SCRAM: the server started over");
319
+ const mechanisms = m.body.toString("utf8", 4).split("\0");
320
+ const plus = !!tls && mechanisms.includes("SCRAM-SHA-256-PLUS") && channelBinding !== "disable";
321
+ if (!plus && channelBinding === "require") {
322
+ refuse(`${c.host} doesn't offer SCRAM bound to the TLS channel (SCRAM-SHA-256-PLUS), so nothing proves it is the database and not one in between. ` +
323
+ "Check its certificate: add sslrootcert=<its CA file> to the URL (Supabase: Database Settings › SSL Configuration, prod-ca-2021.crt), " +
324
+ "or use the direct connection (db.<ref>.supabase.co), which offers it. channel_binding=prefer goes without, knowingly");
325
+ }
326
+ if (!plus && !mechanisms.includes("SCRAM-SHA-256"))
327
+ refuse("the server asks for a password method this tool doesn't speak");
328
+ let mechanism = "SCRAM-SHA-256";
329
+ if (plus) {
330
+ const der = tls.getPeerCertificate(false)?.raw;
331
+ if (!der)
332
+ refuse("TLS: the server showed no certificate to bind to");
333
+ mechanism = "SCRAM-SHA-256-PLUS";
334
+ gs2 = "p=tls-server-end-point,,";
335
+ binding = createHash(endPointHash(der)).update(der).digest();
336
+ }
337
+ else
338
+ gs2 = tls && channelBinding !== "disable" ? "y,," : "n,,";
339
+ clientNonce = randomBytes(18).toString("base64");
340
+ const first = Buffer.from(`${gs2}n=*,r=${clientNonce}`);
341
+ const n = Buffer.alloc(4);
342
+ n.writeInt32BE(first.length, 0);
343
+ socket.write(message("p", Buffer.concat([cstr(mechanism), n, first])));
344
+ scram = "started";
345
+ }
346
+ else if (kind === 11) {
347
+ if (scram !== "started" || expected)
348
+ refuse("SCRAM: the server's messages came out of order");
349
+ let f;
350
+ try {
351
+ f = scramFinal(c.password, clientNonce, m.body.toString("utf8", 4), "*", gs2, binding);
352
+ }
353
+ catch (e) {
354
+ return refuse(e.message);
355
+ }
356
+ expected = f.serverSignature;
357
+ socket.write(message("p", Buffer.from(f.message)));
358
+ }
359
+ else if (kind === 12) {
360
+ if (scram !== "started" || !expected || m.body.toString("utf8", 4) !== `v=${expected}`) {
361
+ refuse("SCRAM: the server's signature is wrong (not the database you meant?)");
362
+ }
363
+ scram = "proven";
364
+ }
365
+ else
366
+ refuse(`the server asks for a password method this tool doesn't speak (${kind})`);
367
+ }
368
+ socket.setTimeout(0);
369
+ let busy = Promise.resolve();
370
+ const channelBound = gs2.startsWith("p=") && scram === "proven";
371
+ const security = {
372
+ tls: !!tls,
373
+ verified,
374
+ channelBound,
375
+ summary: !tls
376
+ ? local
377
+ ? "Without TLS (this machine's database)."
378
+ : "Without TLS, nothing proving the server is the database: a server in between could read and change what is sent."
379
+ : verified && c.strong
380
+ ? "TLS, the certificate checked."
381
+ : channelBound
382
+ ? "TLS, the sign-in bound to it (SCRAM-SHA-256-PLUS): no server in between could pass it through."
383
+ : "TLS, but nothing proving the server is the database (channel_binding off, the certificate not checked by name or its own CA): a server in between could pass the sign-in through. Add sslrootcert=<the CA file> (Supabase: Database Settings › SSL Configuration) to check it.",
384
+ };
385
+ return {
386
+ security,
387
+ query(text) {
388
+ const run = busy.then(async () => {
389
+ socket.write(message("Q", cstr(text)));
390
+ const out = { rows: [], commands: [], notices: [] };
391
+ let names = [];
392
+ let error = null;
393
+ for (;;) {
394
+ const m = await next();
395
+ if (m.type === "T") {
396
+ const n = m.body.readInt16BE(0);
397
+ names = [];
398
+ out.rows = [];
399
+ let at = 2;
400
+ for (let i = 0; i < n; i += 1) {
401
+ const end = m.body.indexOf(0, at);
402
+ names.push(m.body.toString("utf8", at, end));
403
+ at = end + 1 + 18;
404
+ }
405
+ }
406
+ else if (m.type === "D") {
407
+ const n = m.body.readInt16BE(0);
408
+ const row = {};
409
+ let at = 2;
410
+ for (let i = 0; i < n; i += 1) {
411
+ const l = m.body.readInt32BE(at);
412
+ at += 4;
413
+ row[names[i]] = l < 0 ? null : m.body.toString("utf8", at, at + l);
414
+ if (l > 0)
415
+ at += l;
416
+ }
417
+ out.rows.push(row);
418
+ }
419
+ else if (m.type === "C")
420
+ out.commands.push(m.body.toString("utf8", 0, m.body.length - 1));
421
+ else if (m.type === "N")
422
+ out.notices.push(fields(m.body).M ?? "");
423
+ else if (m.type === "E")
424
+ error = errorOf(m.body);
425
+ else if (m.type === "Z")
426
+ break;
427
+ }
428
+ if (error)
429
+ throw Object.assign(error, { notices: out.notices });
430
+ return out;
431
+ });
432
+ busy = run.then(() => undefined, () => undefined);
433
+ return run;
434
+ },
435
+ async close() {
436
+ try {
437
+ socket.write(message("X", Buffer.alloc(0)));
438
+ }
439
+ catch {
440
+ /* already gone */
441
+ }
442
+ socket.end();
443
+ },
444
+ };
445
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Phone numbers in E.164 (`+59899123456`), as SMS providers take them. What people type is cleaned (spaces, dashes,
3
+ * dots, brackets, a leading `00`), and anything that isn't then `+` and 8 to 15 digits is refused. No country's own
4
+ * rules are checked: the provider's answer says whether a number exists.
5
+ */
6
+ export declare function normalizePhone(input: string): string | null;
7
+ /**
8
+ * The calling code of `phone` among those allowed (`["+598", "+54"]`), or null when none matches. SMS only goes
9
+ * where the project said it may: sending anywhere is how SMS pumping fraud runs up a bill.
10
+ */
11
+ export declare function allowedPrefix(phone: string, prefixes: readonly string[]): string | null;
package/dist/phone.js ADDED
@@ -0,0 +1,18 @@
1
+ /**
2
+ * Phone numbers in E.164 (`+59899123456`), as SMS providers take them. What people type is cleaned (spaces, dashes,
3
+ * dots, brackets, a leading `00`), and anything that isn't then `+` and 8 to 15 digits is refused. No country's own
4
+ * rules are checked: the provider's answer says whether a number exists.
5
+ */
6
+ export function normalizePhone(input) {
7
+ let s = input.trim().replace(/[\s\-.() ]/g, "");
8
+ if (s.startsWith("00"))
9
+ s = `+${s.slice(2)}`;
10
+ return /^\+[1-9]\d{7,14}$/.test(s) ? s : null;
11
+ }
12
+ /**
13
+ * The calling code of `phone` among those allowed (`["+598", "+54"]`), or null when none matches. SMS only goes
14
+ * where the project said it may: sending anywhere is how SMS pumping fraud runs up a bill.
15
+ */
16
+ export function allowedPrefix(phone, prefixes) {
17
+ return [...prefixes].sort((a, b) => b.length - a.length).find((p) => phone.startsWith(p)) ?? null;
18
+ }
@@ -0,0 +1,2 @@
1
+ /** A Postgres store: node-postgres, Neon, Vercel Postgres, PGlite, Supabase (postgres.js). */
2
+ export { pgSql, postgresJsSql, numbered, type PgLike, type PostgresJsLike } from "./stores/postgres.ts";
@@ -0,0 +1,2 @@
1
+ /** A Postgres store: node-postgres, Neon, Vercel Postgres, PGlite, Supabase (postgres.js). */
2
+ export { pgSql, postgresJsSql, numbered } from "./stores/postgres.js";
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Revoking Sign in with Apple when an account is deleted, as App Store guideline 5.1.1(v) asks: the app's
3
+ * authorization code is exchanged at sign-in for Apple's refresh token, which is kept (encrypted) until the account
4
+ * is deleted, and then revoked. Both calls are signed with a client secret: a short ES256 JWT made with the team's
5
+ * Sign in with Apple key (a `.p8`).
6
+ *
7
+ * The refresh token is encrypted with AES-GCM under a key derived from the `.p8` itself, so there is no other secret
8
+ * to keep. A replaced `.p8` stays readable for tokens kept before it while it is listed in `previousPrivateKeys`.
9
+ */
10
+ export declare const APPLE_TOKEN_URL = "https://appleid.apple.com/auth/token";
11
+ export declare const APPLE_REVOKE_URL = "https://appleid.apple.com/auth/revoke";
12
+ export interface AppleKeyOptions {
13
+ /** The team's ID (10 characters, top right in the developer portal). */
14
+ teamId: string;
15
+ /** The Sign in with Apple key's ID. */
16
+ keyId: string;
17
+ /** The `.p8`'s text (`-----BEGIN PRIVATE KEY-----…`), as kept in a secret. */
18
+ privateKey: string;
19
+ /** Keys this one replaced, only to read tokens kept under them. */
20
+ previousPrivateKeys?: readonly string[];
21
+ fetch?: typeof fetch;
22
+ timeoutMs?: number;
23
+ }
24
+ export interface AppleRevoker {
25
+ /** Exchanges an authorization code for Apple's refresh token, encrypted for keeping; null when Apple refuses. */
26
+ exchange(code: string, clientId: string, redirectUri?: string): Promise<{
27
+ ok: true;
28
+ sealed: string;
29
+ } | {
30
+ ok: false;
31
+ reason: string;
32
+ }>;
33
+ /** Revokes a token kept by `exchange`. */
34
+ revoke(sealed: string, clientId: string): Promise<{
35
+ ok: true;
36
+ } | {
37
+ ok: false;
38
+ reason: string;
39
+ }>;
40
+ /** Exchanges a fresh code and revokes what it gives at once: for an account that has no token kept. */
41
+ revokeCode(code: string, clientId: string, redirectUri?: string): Promise<{
42
+ ok: true;
43
+ } | {
44
+ ok: false;
45
+ reason: string;
46
+ }>;
47
+ /** Whether Apple takes this key for `clientId` (a made-up code: `invalid_grant` means the key is good). */
48
+ check(clientId: string): Promise<{
49
+ ok: true;
50
+ } | {
51
+ ok: false;
52
+ reason: string;
53
+ }>;
54
+ }
55
+ export declare function appleRevoker(o: AppleKeyOptions): AppleRevoker;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Revoking Sign in with Apple when an account is deleted, as App Store guideline 5.1.1(v) asks: the app's
3
+ * authorization code is exchanged at sign-in for Apple's refresh token, which is kept (encrypted) until the account
4
+ * is deleted, and then revoked. Both calls are signed with a client secret: a short ES256 JWT made with the team's
5
+ * Sign in with Apple key (a `.p8`).
6
+ *
7
+ * The refresh token is encrypted with AES-GCM under a key derived from the `.p8` itself, so there is no other secret
8
+ * to keep. A replaced `.p8` stays readable for tokens kept before it while it is listed in `previousPrivateKeys`.
9
+ */
10
+ import { b64url, fromBase64, fromUtf8, utf8 } from "../base64.js";
11
+ import { signJwt } from "../jwt.js";
12
+ export const APPLE_TOKEN_URL = "https://appleid.apple.com/auth/token";
13
+ export const APPLE_REVOKE_URL = "https://appleid.apple.com/auth/revoke";
14
+ function pemBytes(pem) {
15
+ const body = pem.replace(/-----[^-]+-----/g, "").replace(/\\n/g, "").replace(/\s+/g, "");
16
+ if (!body)
17
+ throw new Error("apple: privateKey is empty");
18
+ return fromBase64(body);
19
+ }
20
+ async function aesKey(pem) {
21
+ const base = await crypto.subtle.importKey("raw", pemBytes(pem), "HKDF", false, ["deriveKey"]);
22
+ return crypto.subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt: utf8("direct-auth"), info: utf8("apple refresh token") }, base, { name: "AES-GCM", length: 256 }, false, ["encrypt", "decrypt"]);
23
+ }
24
+ export function appleRevoker(o) {
25
+ const fetcher = o.fetch ?? fetch;
26
+ let signing = null;
27
+ const signer = () => (signing ??= crypto.subtle.importKey("pkcs8", pemBytes(o.privateKey), { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]));
28
+ const sealKey = aesKey(o.privateKey);
29
+ const openKeys = [sealKey, ...(o.previousPrivateKeys ?? []).map(aesKey)];
30
+ const clientSecret = async (clientId) => {
31
+ const now = Math.floor(Date.now() / 1000);
32
+ return signJwt({ alg: "ES256", kid: o.keyId }, { iss: o.teamId, iat: now, exp: now + 300, aud: "https://appleid.apple.com", sub: clientId }, await signer());
33
+ };
34
+ const call = async (url, fields) => {
35
+ try {
36
+ const res = await fetcher(url, {
37
+ method: "POST",
38
+ headers: { "content-type": "application/x-www-form-urlencoded" },
39
+ body: new URLSearchParams(fields).toString(),
40
+ signal: AbortSignal.timeout(o.timeoutMs ?? 15_000),
41
+ });
42
+ const body = (await res.json().catch(() => ({})));
43
+ return { status: res.status, body };
44
+ }
45
+ catch {
46
+ return { status: 0, body: { error: "network" } };
47
+ }
48
+ };
49
+ const seal = async (token) => {
50
+ const iv = crypto.getRandomValues(new Uint8Array(12));
51
+ const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await sealKey, utf8(token)));
52
+ return `v1.${b64url(iv)}.${b64url(ct)}`;
53
+ };
54
+ const open = async (sealed) => {
55
+ const [v, iv, ct] = sealed.split(".");
56
+ if (v !== "v1" || !iv || !ct)
57
+ return null;
58
+ for (const key of openKeys) {
59
+ try {
60
+ return fromUtf8(new Uint8Array(await crypto.subtle.decrypt({ name: "AES-GCM", iv: fromBase64(iv) }, await key, fromBase64(ct))));
61
+ }
62
+ catch {
63
+ // Not this key: the next one.
64
+ }
65
+ }
66
+ return null;
67
+ };
68
+ const exchangeRaw = async (code, clientId, redirectUri) => {
69
+ const fields = {
70
+ client_id: clientId,
71
+ client_secret: await clientSecret(clientId),
72
+ code,
73
+ grant_type: "authorization_code",
74
+ };
75
+ if (redirectUri)
76
+ fields.redirect_uri = redirectUri;
77
+ const r = await call(APPLE_TOKEN_URL, fields);
78
+ if (r.status === 200 && r.body.refresh_token)
79
+ return { ok: true, token: r.body.refresh_token };
80
+ return { ok: false, reason: `apple_${r.body.error ?? `http_${r.status}`}` };
81
+ };
82
+ const revokeRaw = async (token, clientId) => {
83
+ const r = await call(APPLE_REVOKE_URL, {
84
+ client_id: clientId,
85
+ client_secret: await clientSecret(clientId),
86
+ token,
87
+ token_type_hint: "refresh_token",
88
+ });
89
+ return r.status === 200 ? { ok: true } : { ok: false, reason: `apple_${r.body.error ?? `http_${r.status}`}` };
90
+ };
91
+ return {
92
+ async exchange(code, clientId, redirectUri) {
93
+ const r = await exchangeRaw(code, clientId, redirectUri);
94
+ return r.ok ? { ok: true, sealed: await seal(r.token) } : r;
95
+ },
96
+ async revoke(sealed, clientId) {
97
+ const token = await open(sealed);
98
+ if (!token)
99
+ return { ok: false, reason: "apple_token_unreadable" };
100
+ return revokeRaw(token, clientId);
101
+ },
102
+ async revokeCode(code, clientId, redirectUri) {
103
+ const r = await exchangeRaw(code, clientId, redirectUri);
104
+ return r.ok ? revokeRaw(r.token, clientId) : r;
105
+ },
106
+ async check(clientId) {
107
+ const r = await exchangeRaw("direct-auth-check", clientId);
108
+ if (!r.ok && r.reason === "apple_invalid_grant")
109
+ return { ok: true };
110
+ return r.ok ? { ok: true } : r;
111
+ },
112
+ };
113
+ }