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.
- package/LICENSE +21 -0
- package/README.md +486 -2
- package/dist/accounts.d.ts +118 -0
- package/dist/accounts.js +314 -0
- package/dist/apps.d.ts +85 -0
- package/dist/apps.js +449 -0
- package/dist/auth.d.ts +396 -0
- package/dist/auth.js +699 -0
- package/dist/base64.d.ts +20 -0
- package/dist/base64.js +45 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +463 -0
- package/dist/client.d.ts +170 -0
- package/dist/client.js +438 -0
- package/dist/codes.d.ts +81 -0
- package/dist/codes.js +91 -0
- package/dist/crypto.d.ts +11 -0
- package/dist/crypto.js +37 -0
- package/dist/d1.d.ts +2 -0
- package/dist/d1.js +2 -0
- package/dist/db/limits.d.ts +16 -0
- package/dist/db/limits.js +23 -0
- package/dist/db/schema.d.ts +25 -0
- package/dist/db/schema.js +136 -0
- package/dist/db/sql.d.ts +52 -0
- package/dist/db/sql.js +121 -0
- package/dist/dns.d.ts +48 -0
- package/dist/dns.js +133 -0
- package/dist/env.d.ts +39 -0
- package/dist/env.js +169 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.js +14 -0
- package/dist/init.d.ts +134 -0
- package/dist/init.js +912 -0
- package/dist/jwks.d.ts +18 -0
- package/dist/jwks.js +63 -0
- package/dist/jwt.d.ts +90 -0
- package/dist/jwt.js +99 -0
- package/dist/keys.d.ts +33 -0
- package/dist/keys.js +54 -0
- package/dist/messages.d.ts +26 -0
- package/dist/messages.js +57 -0
- package/dist/migrate-cli.d.ts +82 -0
- package/dist/migrate-cli.js +564 -0
- package/dist/migrate.d.ts +99 -0
- package/dist/migrate.js +396 -0
- package/dist/node.d.ts +16 -0
- package/dist/node.js +63 -0
- package/dist/passkeys.d.ts +126 -0
- package/dist/passkeys.js +383 -0
- package/dist/passwords.d.ts +53 -0
- package/dist/passwords.js +326 -0
- package/dist/pgwire.d.ts +86 -0
- package/dist/pgwire.js +445 -0
- package/dist/phone.d.ts +11 -0
- package/dist/phone.js +18 -0
- package/dist/postgres.d.ts +2 -0
- package/dist/postgres.js +2 -0
- package/dist/providers/apple-revoke.d.ts +55 -0
- package/dist/providers/apple-revoke.js +113 -0
- package/dist/providers/apple.d.ts +28 -0
- package/dist/providers/apple.js +51 -0
- package/dist/providers/github.d.ts +28 -0
- package/dist/providers/github.js +67 -0
- package/dist/providers/google.d.ts +23 -0
- package/dist/providers/google.js +47 -0
- package/dist/providers/identity.d.ts +24 -0
- package/dist/providers/identity.js +3 -0
- package/dist/proxy.d.ts +19 -0
- package/dist/proxy.js +43 -0
- package/dist/records.d.ts +91 -0
- package/dist/records.js +264 -0
- package/dist/scrypt.d.ts +26 -0
- package/dist/scrypt.js +179 -0
- package/dist/senders/aws.d.ts +13 -0
- package/dist/senders/aws.js +47 -0
- package/dist/senders/dev.d.ts +6 -0
- package/dist/senders/dev.js +13 -0
- package/dist/senders/index.d.ts +5 -0
- package/dist/senders/index.js +4 -0
- package/dist/senders/mail.d.ts +26 -0
- package/dist/senders/mail.js +66 -0
- package/dist/senders/sms.d.ts +34 -0
- package/dist/senders/sms.js +69 -0
- package/dist/senders/smtp.d.ts +32 -0
- package/dist/senders/smtp.js +145 -0
- package/dist/senders/types.d.ts +31 -0
- package/dist/senders/types.js +25 -0
- package/dist/server.d.ts +67 -0
- package/dist/server.js +494 -0
- package/dist/sessions.d.ts +74 -0
- package/dist/sessions.js +146 -0
- package/dist/skill.d.ts +25 -0
- package/dist/skill.js +66 -0
- package/dist/sources.d.ts +138 -0
- package/dist/sources.js +931 -0
- package/dist/sqlite.d.ts +2 -0
- package/dist/sqlite.js +2 -0
- package/dist/stores/d1.d.ts +22 -0
- package/dist/stores/d1.js +23 -0
- package/dist/stores/postgres.d.ts +33 -0
- package/dist/stores/postgres.js +71 -0
- package/dist/stores/sqlite.d.ts +27 -0
- package/dist/stores/sqlite.js +55 -0
- package/dist/supabase.d.ts +71 -0
- package/dist/supabase.js +283 -0
- package/dist/tui.d.ts +178 -0
- package/dist/tui.js +537 -0
- package/package.json +90 -4
- package/skills/direct-auth/SKILL.md +101 -0
package/dist/codes.d.ts
ADDED
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time codes by email or SMS: six digits, ten minutes, five tries, kept as an HMAC (never the code), the newest
|
|
3
|
+
* one the only one that works. Asking for one is limited per address or number, per IP, and for SMS per calling
|
|
4
|
+
* code and per day, with the counters in the database so they hold across instances.
|
|
5
|
+
*/
|
|
6
|
+
import { type Limit } from "./db/limits.ts";
|
|
7
|
+
import { type Sql } from "./db/sql.ts";
|
|
8
|
+
export interface CodeLimits {
|
|
9
|
+
/** Codes one address or number may ask for (5 an hour). */
|
|
10
|
+
perTarget: Limit;
|
|
11
|
+
/** Codes one IP may ask for, any channel (20 an hour). */
|
|
12
|
+
perIp: Limit;
|
|
13
|
+
/** Seconds between two codes to the same target (30). */
|
|
14
|
+
resendAfter: number;
|
|
15
|
+
/** SMS per calling code (50 an hour). */
|
|
16
|
+
perPrefix: Limit;
|
|
17
|
+
/** SMS in all (500 a day). */
|
|
18
|
+
smsPerDay: Limit;
|
|
19
|
+
/** Codes one IP may try, right or wrong, any address (60 an hour): guessing across many addresses. */
|
|
20
|
+
verifyPerIp: Limit;
|
|
21
|
+
/** Password sign-ins one IP may try (30 an hour). */
|
|
22
|
+
passwordPerIp: Limit;
|
|
23
|
+
/** Password sign-ins one IP may try on one address (10 an hour). */
|
|
24
|
+
passwordPerIpAccount: Limit;
|
|
25
|
+
/**
|
|
26
|
+
* Password sign-ins one address may be tried with from anywhere (100 a day): loose enough that someone else can't
|
|
27
|
+
* easily lock the owner out, tight enough against guessing from many IPs. A code still gets the owner in.
|
|
28
|
+
*/
|
|
29
|
+
passwordPerAccount: Limit;
|
|
30
|
+
/** Passwords one signed-in user may set (10 an hour): each is a long hash to make. */
|
|
31
|
+
passwordSetPerUser: Limit;
|
|
32
|
+
/** Guests one IP may make (30 an hour). */
|
|
33
|
+
guestPerIp: Limit;
|
|
34
|
+
/** GitHub sign-ins per IP (each is three calls to GitHub). */
|
|
35
|
+
githubPerIp: Limit;
|
|
36
|
+
/** Guests made in all when the caller's IP isn't known (300 an hour). */
|
|
37
|
+
guestWithoutIp: Limit;
|
|
38
|
+
/** Refreshes one IP may make (1,000 an hour: many apps can share one address). */
|
|
39
|
+
refreshPerIp: Limit;
|
|
40
|
+
}
|
|
41
|
+
export declare const DEFAULT_LIMITS: CodeLimits;
|
|
42
|
+
export interface CodeOptions {
|
|
43
|
+
digits?: number;
|
|
44
|
+
/** Minutes a code lasts (10). */
|
|
45
|
+
minutes?: number;
|
|
46
|
+
/** Wrong tries before a code stops working (5). */
|
|
47
|
+
attempts?: number;
|
|
48
|
+
}
|
|
49
|
+
export type StartFailure = "rate_limited" | "too_soon";
|
|
50
|
+
export declare function createCode(sql: Sql, key: CryptoKey, a: {
|
|
51
|
+
channel: "email" | "sms";
|
|
52
|
+
target: string;
|
|
53
|
+
ip?: string;
|
|
54
|
+
prefix?: string;
|
|
55
|
+
limits: CodeLimits;
|
|
56
|
+
options: CodeOptions;
|
|
57
|
+
now?: number;
|
|
58
|
+
}): Promise<{
|
|
59
|
+
ok: true;
|
|
60
|
+
code: string;
|
|
61
|
+
minutes: number;
|
|
62
|
+
} | {
|
|
63
|
+
ok: false;
|
|
64
|
+
reason: StartFailure;
|
|
65
|
+
}>;
|
|
66
|
+
export type CheckFailure = "invalid_code" | "expired" | "too_many_attempts";
|
|
67
|
+
export declare function checkCode(sql: Sql, key: CryptoKey, a: {
|
|
68
|
+
channel: "email" | "sms";
|
|
69
|
+
target: string;
|
|
70
|
+
code: string;
|
|
71
|
+
options: CodeOptions;
|
|
72
|
+
ip?: string;
|
|
73
|
+
limits?: CodeLimits;
|
|
74
|
+
now?: number;
|
|
75
|
+
}): Promise<{
|
|
76
|
+
ok: true;
|
|
77
|
+
} | {
|
|
78
|
+
ok: false;
|
|
79
|
+
reason: CheckFailure | "rate_limited";
|
|
80
|
+
}>;
|
|
81
|
+
export declare function pruneCodes(sql: Sql, now?: number): Promise<void>;
|
package/dist/codes.js
ADDED
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* One-time codes by email or SMS: six digits, ten minutes, five tries, kept as an HMAC (never the code), the newest
|
|
3
|
+
* one the only one that works. Asking for one is limited per address or number, per IP, and for SMS per calling
|
|
4
|
+
* code and per day, with the counters in the database so they hold across instances.
|
|
5
|
+
*/
|
|
6
|
+
import { hmac, randomCode, same } from "./crypto.js";
|
|
7
|
+
import { count, hit } from "./db/limits.js";
|
|
8
|
+
import { num } from "./db/sql.js";
|
|
9
|
+
const MINUTE = 60_000;
|
|
10
|
+
const HOUR = 60 * MINUTE;
|
|
11
|
+
const DAY = 24 * HOUR;
|
|
12
|
+
export const DEFAULT_LIMITS = {
|
|
13
|
+
perTarget: { max: 5, window: HOUR },
|
|
14
|
+
perIp: { max: 20, window: HOUR },
|
|
15
|
+
resendAfter: 30,
|
|
16
|
+
perPrefix: { max: 50, window: HOUR },
|
|
17
|
+
smsPerDay: { max: 500, window: DAY },
|
|
18
|
+
verifyPerIp: { max: 60, window: HOUR },
|
|
19
|
+
passwordPerIp: { max: 30, window: HOUR },
|
|
20
|
+
passwordPerIpAccount: { max: 10, window: HOUR },
|
|
21
|
+
passwordPerAccount: { max: 100, window: DAY },
|
|
22
|
+
passwordSetPerUser: { max: 10, window: HOUR },
|
|
23
|
+
guestPerIp: { max: 30, window: HOUR },
|
|
24
|
+
githubPerIp: { max: 60, window: HOUR },
|
|
25
|
+
guestWithoutIp: { max: 300, window: HOUR },
|
|
26
|
+
refreshPerIp: { max: 1000, window: HOUR },
|
|
27
|
+
};
|
|
28
|
+
export async function createCode(sql, key, a) {
|
|
29
|
+
const now = a.now ?? Date.now();
|
|
30
|
+
const [last] = await sql.all(`select created_at from {codes} where channel = ? and target = ? order by created_at desc limit 1`, [a.channel, a.target]);
|
|
31
|
+
if (last && now - num(last.created_at) < a.limits.resendAfter * 1000)
|
|
32
|
+
return { ok: false, reason: "too_soon" };
|
|
33
|
+
// The IP first, and nothing counted unless every limit has room: a request refused by one limit doesn't use up
|
|
34
|
+
// another (the victim's address, the day's SMS).
|
|
35
|
+
const checks = [];
|
|
36
|
+
if (a.ip)
|
|
37
|
+
checks.push([`code-ip:${a.ip}`, a.limits.perIp]);
|
|
38
|
+
checks.push([`code:${a.channel}:${a.target}`, a.limits.perTarget]);
|
|
39
|
+
if (a.channel === "sms") {
|
|
40
|
+
if (a.prefix)
|
|
41
|
+
checks.push([`sms-prefix:${a.prefix}`, a.limits.perPrefix]);
|
|
42
|
+
checks.push(["sms-day", a.limits.smsPerDay]);
|
|
43
|
+
}
|
|
44
|
+
for (const [k, limit] of checks) {
|
|
45
|
+
if ((await count(sql, k, limit, now)) >= limit.max)
|
|
46
|
+
return { ok: false, reason: "rate_limited" };
|
|
47
|
+
}
|
|
48
|
+
for (const [k, limit] of checks) {
|
|
49
|
+
if (!(await hit(sql, k, limit, now)))
|
|
50
|
+
return { ok: false, reason: "rate_limited" };
|
|
51
|
+
}
|
|
52
|
+
const minutes = a.options.minutes ?? 10;
|
|
53
|
+
const code = randomCode(a.options.digits ?? 6);
|
|
54
|
+
const id = crypto.randomUUID();
|
|
55
|
+
await sql.batch([
|
|
56
|
+
// Only the newest code works: the ones before it are spent.
|
|
57
|
+
[`update {codes} set used_at = ? where channel = ? and target = ? and used_at is null`, [now, a.channel, a.target]],
|
|
58
|
+
[
|
|
59
|
+
`insert into {codes} (id, channel, target, hash, attempts, created_at, expires_at) values (?, ?, ?, ?, 0, ?, ?)`,
|
|
60
|
+
[id, a.channel, a.target, await hmac(key, `${id}:${a.channel}:${a.target}:${code}`), now, now + minutes * MINUTE],
|
|
61
|
+
],
|
|
62
|
+
]);
|
|
63
|
+
return { ok: true, code, minutes };
|
|
64
|
+
}
|
|
65
|
+
export async function checkCode(sql, key, a) {
|
|
66
|
+
const now = a.now ?? Date.now();
|
|
67
|
+
if (a.ip && a.limits && !(await hit(sql, `verify-ip:${a.ip}`, a.limits.verifyPerIp, now)))
|
|
68
|
+
return { ok: false, reason: "rate_limited" };
|
|
69
|
+
const [row] = await sql.all(`select id, hash, attempts, expires_at from {codes}
|
|
70
|
+
where channel = ? and target = ? and used_at is null order by created_at desc limit 1`, [a.channel, a.target]);
|
|
71
|
+
if (!row)
|
|
72
|
+
return { ok: false, reason: "invalid_code" };
|
|
73
|
+
if (num(row.expires_at) < now)
|
|
74
|
+
return { ok: false, reason: "expired" };
|
|
75
|
+
const max = a.options.attempts ?? 5;
|
|
76
|
+
// A try is taken before the code is compared, in one statement: many guesses at once can't all get in under the
|
|
77
|
+
// limit, since only `max` of them find a try left.
|
|
78
|
+
const { changes: reserved } = await sql.run(`update {codes} set attempts = attempts + 1 where id = ? and used_at is null and attempts < ? and expires_at >= ?`, [row.id, max, now]);
|
|
79
|
+
if (!reserved)
|
|
80
|
+
return { ok: false, reason: num(row.attempts) >= max ? "too_many_attempts" : "invalid_code" };
|
|
81
|
+
const code = a.code.replace(/\D/g, "");
|
|
82
|
+
const good = same(await hmac(key, `${row.id}:${a.channel}:${a.target}:${code}`), row.hash);
|
|
83
|
+
if (!good)
|
|
84
|
+
return { ok: false, reason: num(row.attempts) + 1 >= max ? "too_many_attempts" : "invalid_code" };
|
|
85
|
+
// Spent once: two requests with the same code can't both sign in.
|
|
86
|
+
const { changes } = await sql.run(`update {codes} set used_at = ? where id = ? and used_at is null`, [now, row.id]);
|
|
87
|
+
return changes ? { ok: true } : { ok: false, reason: "invalid_code" };
|
|
88
|
+
}
|
|
89
|
+
export async function pruneCodes(sql, now = Date.now()) {
|
|
90
|
+
await sql.run(`delete from {codes} where expires_at < ?`, [now - DAY]);
|
|
91
|
+
}
|
package/dist/crypto.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/** Random tokens, codes and hashes, with WebCrypto alone. */
|
|
2
|
+
/** `bytes` random bytes as base64url: 32 make a refresh token nobody guesses. */
|
|
3
|
+
export declare function randomToken(bytes?: number): string;
|
|
4
|
+
/** A code of `digits` digits, uniform (no modulo bias): six by default. */
|
|
5
|
+
export declare function randomCode(digits?: number): string;
|
|
6
|
+
export declare function sha256(text: string): Promise<string>;
|
|
7
|
+
/** An HMAC-SHA256 of `text` under `key`, base64url. */
|
|
8
|
+
export declare function hmac(key: CryptoKey, text: string): Promise<string>;
|
|
9
|
+
export declare function hmacKey(secret: string | Uint8Array): Promise<CryptoKey>;
|
|
10
|
+
/** Two strings compared in time that doesn't depend on where they differ. */
|
|
11
|
+
export declare function same(a: string, b: string): boolean;
|
package/dist/crypto.js
ADDED
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
/** Random tokens, codes and hashes, with WebCrypto alone. */
|
|
2
|
+
import { b64url, utf8 } from "./base64.js";
|
|
3
|
+
/** `bytes` random bytes as base64url: 32 make a refresh token nobody guesses. */
|
|
4
|
+
export function randomToken(bytes = 32) {
|
|
5
|
+
return b64url(crypto.getRandomValues(new Uint8Array(bytes)));
|
|
6
|
+
}
|
|
7
|
+
/** A code of `digits` digits, uniform (no modulo bias): six by default. */
|
|
8
|
+
export function randomCode(digits = 6) {
|
|
9
|
+
const max = 10 ** digits;
|
|
10
|
+
const limit = Math.floor(0x1_0000_0000 / max) * max;
|
|
11
|
+
const buf = new Uint32Array(1);
|
|
12
|
+
for (;;) {
|
|
13
|
+
crypto.getRandomValues(buf);
|
|
14
|
+
if (buf[0] < limit)
|
|
15
|
+
return String(buf[0] % max).padStart(digits, "0");
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
export async function sha256(text) {
|
|
19
|
+
return b64url(new Uint8Array(await crypto.subtle.digest("SHA-256", utf8(text))));
|
|
20
|
+
}
|
|
21
|
+
/** An HMAC-SHA256 of `text` under `key`, base64url. */
|
|
22
|
+
export async function hmac(key, text) {
|
|
23
|
+
return b64url(new Uint8Array(await crypto.subtle.sign("HMAC", key, utf8(text))));
|
|
24
|
+
}
|
|
25
|
+
export function hmacKey(secret) {
|
|
26
|
+
const raw = typeof secret === "string" ? utf8(secret) : secret;
|
|
27
|
+
return crypto.subtle.importKey("raw", raw, { name: "HMAC", hash: "SHA-256" }, false, ["sign"]);
|
|
28
|
+
}
|
|
29
|
+
/** Two strings compared in time that doesn't depend on where they differ. */
|
|
30
|
+
export function same(a, b) {
|
|
31
|
+
if (a.length !== b.length)
|
|
32
|
+
return false;
|
|
33
|
+
let diff = 0;
|
|
34
|
+
for (let i = 0; i < a.length; i += 1)
|
|
35
|
+
diff |= a.charCodeAt(i) ^ b.charCodeAt(i);
|
|
36
|
+
return diff === 0;
|
|
37
|
+
}
|
package/dist/d1.d.ts
ADDED
package/dist/d1.js
ADDED
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixed-window counters in the database, so the limits hold across instances (several Workers, several Node
|
|
3
|
+
* processes): one row per key and window, gone once the window is.
|
|
4
|
+
*/
|
|
5
|
+
import { type Sql } from "./sql.ts";
|
|
6
|
+
export interface Limit {
|
|
7
|
+
/** How many in one window. */
|
|
8
|
+
max: number;
|
|
9
|
+
/** The window, in milliseconds. */
|
|
10
|
+
window: number;
|
|
11
|
+
}
|
|
12
|
+
/** Counts one more for `key`; true while the window's count is within `limit.max`. */
|
|
13
|
+
export declare function hit(sql: Sql, key: string, limit: Limit, now?: number): Promise<boolean>;
|
|
14
|
+
/** How many `key` has had in this window, without counting one more. */
|
|
15
|
+
export declare function count(sql: Sql, key: string, limit: Limit, now?: number): Promise<number>;
|
|
16
|
+
export declare function pruneLimits(sql: Sql, now?: number): Promise<void>;
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Fixed-window counters in the database, so the limits hold across instances (several Workers, several Node
|
|
3
|
+
* processes): one row per key and window, gone once the window is.
|
|
4
|
+
*/
|
|
5
|
+
import { num } from "./sql.js";
|
|
6
|
+
/** Counts one more for `key`; true while the window's count is within `limit.max`. */
|
|
7
|
+
export async function hit(sql, key, limit, now = Date.now()) {
|
|
8
|
+
const start = Math.floor(now / limit.window) * limit.window;
|
|
9
|
+
const id = `${key}@${start}`;
|
|
10
|
+
await sql.run(`insert into {limits} (key, count, expires_at) values (?, 1, ?)
|
|
11
|
+
on conflict (key) do update set count = {limits}.count + 1`, [id, start + limit.window]);
|
|
12
|
+
const [row] = await sql.all(`select count from {limits} where key = ?`, [id]);
|
|
13
|
+
return num(row?.count) <= limit.max;
|
|
14
|
+
}
|
|
15
|
+
/** How many `key` has had in this window, without counting one more. */
|
|
16
|
+
export async function count(sql, key, limit, now = Date.now()) {
|
|
17
|
+
const start = Math.floor(now / limit.window) * limit.window;
|
|
18
|
+
const [row] = await sql.all(`select count from {limits} where key = ?`, [`${key}@${start}`]);
|
|
19
|
+
return num(row?.count);
|
|
20
|
+
}
|
|
21
|
+
export async function pruneLimits(sql, now = Date.now()) {
|
|
22
|
+
await sql.run(`delete from {limits} where expires_at < ?`, [now]);
|
|
23
|
+
}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema, as a list that only grows: each entry runs once, in order, and the count of those that ran is kept in
|
|
3
|
+
* `{meta}`. A change to a table is a new entry, never an edit to one that shipped, and each entry is safe to run twice.
|
|
4
|
+
*
|
|
5
|
+
* Portable on purpose: ids are text (`crypto.randomUUID()`), times are integer milliseconds (`bigint`), flags are
|
|
6
|
+
* integers. A user's id is `uuid` on Postgres (`{uuid}`), so an app's tables that pointed at Supabase's
|
|
7
|
+
* `auth.users(id)` can point at `{users}(id)` with the same ids. Nothing a database needs that SQLite, D1 and Postgres don't all have.
|
|
8
|
+
*
|
|
9
|
+
* `{users}` is one row per person, with the email and phone they signed in with once checked, whether they are a
|
|
10
|
+
* guest (no way to sign in yet), and their password's hash when they have one. `{identities}` is each
|
|
11
|
+
* way they sign in (an Apple or Google account, an address, a number, a passkey): one user, many identities.
|
|
12
|
+
* `{sessions}` is each signed-in device; `{refresh}` the refresh tokens a session has had, hashed, so a stolen one
|
|
13
|
+
* used twice ends the session. `{codes}` the email and SMS codes, hashed. `{limits}` the counters the rate limits keep. `{passkeys}` the
|
|
14
|
+
* passkeys' public keys; `{challenges}` the WebAuthn challenges waiting for an answer; `{guest_claims}` the guests
|
|
15
|
+
* moved from Supabase Auth, by their old refresh token's hash. A user moved from another service keeps its old id in
|
|
16
|
+
* `{users}.source_id`.
|
|
17
|
+
*/
|
|
18
|
+
import type { Sql } from "./sql.ts";
|
|
19
|
+
export type Migration = string | {
|
|
20
|
+
readonly sqlite?: string;
|
|
21
|
+
readonly postgres?: string;
|
|
22
|
+
};
|
|
23
|
+
export declare const MIGRATIONS: readonly Migration[];
|
|
24
|
+
/** Brings a database up to the last entry of `MIGRATIONS`. Safe to call on every start. */
|
|
25
|
+
export declare function migrate(sql: Sql): Promise<void>;
|
|
@@ -0,0 +1,136 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The schema, as a list that only grows: each entry runs once, in order, and the count of those that ran is kept in
|
|
3
|
+
* `{meta}`. A change to a table is a new entry, never an edit to one that shipped, and each entry is safe to run twice.
|
|
4
|
+
*
|
|
5
|
+
* Portable on purpose: ids are text (`crypto.randomUUID()`), times are integer milliseconds (`bigint`), flags are
|
|
6
|
+
* integers. A user's id is `uuid` on Postgres (`{uuid}`), so an app's tables that pointed at Supabase's
|
|
7
|
+
* `auth.users(id)` can point at `{users}(id)` with the same ids. Nothing a database needs that SQLite, D1 and Postgres don't all have.
|
|
8
|
+
*
|
|
9
|
+
* `{users}` is one row per person, with the email and phone they signed in with once checked, whether they are a
|
|
10
|
+
* guest (no way to sign in yet), and their password's hash when they have one. `{identities}` is each
|
|
11
|
+
* way they sign in (an Apple or Google account, an address, a number, a passkey): one user, many identities.
|
|
12
|
+
* `{sessions}` is each signed-in device; `{refresh}` the refresh tokens a session has had, hashed, so a stolen one
|
|
13
|
+
* used twice ends the session. `{codes}` the email and SMS codes, hashed. `{limits}` the counters the rate limits keep. `{passkeys}` the
|
|
14
|
+
* passkeys' public keys; `{challenges}` the WebAuthn challenges waiting for an answer; `{guest_claims}` the guests
|
|
15
|
+
* moved from Supabase Auth, by their old refresh token's hash. A user moved from another service keeps its old id in
|
|
16
|
+
* `{users}.source_id`.
|
|
17
|
+
*/
|
|
18
|
+
export const MIGRATIONS = [
|
|
19
|
+
`create table if not exists {users} (
|
|
20
|
+
id {uuid} primary key,
|
|
21
|
+
email text unique,
|
|
22
|
+
phone text unique,
|
|
23
|
+
name text,
|
|
24
|
+
picture text,
|
|
25
|
+
created_at bigint not null,
|
|
26
|
+
updated_at bigint not null,
|
|
27
|
+
last_sign_in_at bigint
|
|
28
|
+
)`,
|
|
29
|
+
`create table if not exists {identities} (
|
|
30
|
+
id text primary key,
|
|
31
|
+
user_id {uuid} not null references {users} (id) on delete cascade,
|
|
32
|
+
provider text not null,
|
|
33
|
+
subject text not null,
|
|
34
|
+
email text,
|
|
35
|
+
data text,
|
|
36
|
+
created_at bigint not null,
|
|
37
|
+
last_used_at bigint not null,
|
|
38
|
+
unique (provider, subject)
|
|
39
|
+
)`,
|
|
40
|
+
`create index if not exists {identities}_user on {identities} (user_id)`,
|
|
41
|
+
`create table if not exists {sessions} (
|
|
42
|
+
id text primary key,
|
|
43
|
+
user_id {uuid} not null references {users} (id) on delete cascade,
|
|
44
|
+
created_at bigint not null,
|
|
45
|
+
refreshed_at bigint not null,
|
|
46
|
+
expires_at bigint not null,
|
|
47
|
+
revoked_at bigint,
|
|
48
|
+
user_agent text
|
|
49
|
+
)`,
|
|
50
|
+
`create index if not exists {sessions}_user on {sessions} (user_id)`,
|
|
51
|
+
`create table if not exists {refresh} (
|
|
52
|
+
hash text primary key,
|
|
53
|
+
session_id text not null references {sessions} (id) on delete cascade,
|
|
54
|
+
created_at bigint not null,
|
|
55
|
+
used_at bigint,
|
|
56
|
+
uses integer not null default 0
|
|
57
|
+
)`,
|
|
58
|
+
`create index if not exists {refresh}_session on {refresh} (session_id)`,
|
|
59
|
+
`create table if not exists {codes} (
|
|
60
|
+
id text primary key,
|
|
61
|
+
channel text not null check (channel in ('email', 'sms')),
|
|
62
|
+
target text not null,
|
|
63
|
+
hash text not null,
|
|
64
|
+
attempts integer not null default 0,
|
|
65
|
+
created_at bigint not null,
|
|
66
|
+
expires_at bigint not null,
|
|
67
|
+
used_at bigint
|
|
68
|
+
)`,
|
|
69
|
+
`create index if not exists {codes}_target on {codes} (channel, target, created_at)`,
|
|
70
|
+
`create table if not exists {limits} (
|
|
71
|
+
key text primary key,
|
|
72
|
+
count integer not null,
|
|
73
|
+
expires_at bigint not null
|
|
74
|
+
)`,
|
|
75
|
+
`create table if not exists {passkeys} (
|
|
76
|
+
id text primary key,
|
|
77
|
+
user_id {uuid} not null references {users} (id) on delete cascade,
|
|
78
|
+
public_key text not null,
|
|
79
|
+
alg integer not null,
|
|
80
|
+
sign_count bigint not null default 0,
|
|
81
|
+
transports text,
|
|
82
|
+
name text,
|
|
83
|
+
created_at bigint not null,
|
|
84
|
+
last_used_at bigint
|
|
85
|
+
)`,
|
|
86
|
+
`create index if not exists {passkeys}_user on {passkeys} (user_id)`,
|
|
87
|
+
`create table if not exists {challenges} (
|
|
88
|
+
id text primary key,
|
|
89
|
+
kind text not null,
|
|
90
|
+
user_id {uuid},
|
|
91
|
+
challenge text not null,
|
|
92
|
+
expires_at bigint not null
|
|
93
|
+
)`,
|
|
94
|
+
// On Supabase every table in `public` is reachable through its Data API with the anon key. Row level security with
|
|
95
|
+
// no policies shuts that door: only the server's own connection reads and writes them.
|
|
96
|
+
{ postgres: `alter table {users} enable row level security` },
|
|
97
|
+
{ postgres: `alter table {identities} enable row level security` },
|
|
98
|
+
{ postgres: `alter table {sessions} enable row level security` },
|
|
99
|
+
{ postgres: `alter table {refresh} enable row level security` },
|
|
100
|
+
{ postgres: `alter table {codes} enable row level security` },
|
|
101
|
+
{ postgres: `alter table {limits} enable row level security` },
|
|
102
|
+
{ postgres: `alter table {passkeys} enable row level security` },
|
|
103
|
+
{ postgres: `alter table {challenges} enable row level security` },
|
|
104
|
+
{ postgres: `alter table {meta} enable row level security` },
|
|
105
|
+
// Guests (an account made with nothing to sign in with yet) and passwords.
|
|
106
|
+
{ sqlite: `alter table {users} add column is_guest integer not null default 0`, postgres: `alter table {users} add column if not exists is_guest integer not null default 0` },
|
|
107
|
+
{ sqlite: `alter table {users} add column password_hash text`, postgres: `alter table {users} add column if not exists password_hash text` },
|
|
108
|
+
`create index if not exists {users}_guest on {users} (is_guest, last_sign_in_at)`,
|
|
109
|
+
// Guests moved from Supabase Auth: the hashes of their Supabase refresh tokens, each good once to get back in.
|
|
110
|
+
`create table if not exists {guest_claims} (
|
|
111
|
+
hash text primary key,
|
|
112
|
+
user_id {uuid} not null references {users} (id) on delete cascade,
|
|
113
|
+
expires_at bigint not null
|
|
114
|
+
)`,
|
|
115
|
+
`create index if not exists {guest_claims}_user on {guest_claims} (user_id)`,
|
|
116
|
+
{ postgres: `alter table {guest_claims} enable row level security` },
|
|
117
|
+
// Users moved from a service whose ids aren't UUIDs (Firebase, Clerk, Auth0, Auth.js, Better Auth): the old id,
|
|
118
|
+
// for the app's own tables to be mapped with (`select id, source_id from {users}`).
|
|
119
|
+
{ sqlite: `alter table {users} add column source_id text`, postgres: `alter table {users} add column if not exists source_id text` },
|
|
120
|
+
`create unique index if not exists {users}_source on {users} (source_id)`,
|
|
121
|
+
];
|
|
122
|
+
/** Brings a database up to the last entry of `MIGRATIONS`. Safe to call on every start. */
|
|
123
|
+
export async function migrate(sql) {
|
|
124
|
+
await sql.run(`create table if not exists {meta} (key text primary key, value text not null)`);
|
|
125
|
+
const [row] = await sql.all(`select value from {meta} where key = 'schema'`);
|
|
126
|
+
const done = row ? Number(row.value) : 0;
|
|
127
|
+
for (let i = done; i < MIGRATIONS.length; i += 1) {
|
|
128
|
+
const m = MIGRATIONS[i];
|
|
129
|
+
const statement = (typeof m === "string" ? m : m[sql.dialect])?.replace(/\{uuid\}/g, sql.dialect === "postgres" ? "uuid" : "text");
|
|
130
|
+
const count = [
|
|
131
|
+
`insert into {meta} (key, value) values ('schema', ?) on conflict (key) do update set value = excluded.value`,
|
|
132
|
+
[String(i + 1)],
|
|
133
|
+
];
|
|
134
|
+
await sql.batch(statement ? [[statement, []], count] : [count]);
|
|
135
|
+
}
|
|
136
|
+
}
|
package/dist/db/sql.d.ts
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* What a database has to give the server: run a statement, read rows, and run
|
|
3
|
+
* several at once. That is all, so any database a backend has will do:
|
|
4
|
+
*
|
|
5
|
+
* SQLite `sqliteSql(db)` over node:sqlite, better-sqlite3 or bun:sqlite
|
|
6
|
+
* (`direct-auth/sqlite`), a file on a server or a laptop.
|
|
7
|
+
* D1 `d1Sql(env.DB)`, Cloudflare's (`direct-auth/d1`).
|
|
8
|
+
* Postgres `pgSql(client)` over node-postgres, Neon, Vercel Postgres, RDS,
|
|
9
|
+
* PGlite (`direct-auth/postgres`), or `postgresJsSql(sql)` over
|
|
10
|
+
* postgres.js, which is what Supabase's Edge Functions use.
|
|
11
|
+
*
|
|
12
|
+
* Queries are written once, with `?` for each value and `{name}` for each table:
|
|
13
|
+
* the store turns `?` into `$1, $2…` on Postgres, and the server turns `{name}`
|
|
14
|
+
* into the table's name with its prefix (`auth_` unless told otherwise), so the
|
|
15
|
+
* tables sit beside an app's own without a clash.
|
|
16
|
+
*
|
|
17
|
+
* Every value is bound, never written into the text. Both rewrites skip what is
|
|
18
|
+
* quoted (strings, quoted names, comments, Postgres' dollar quotes), so a `?` or a
|
|
19
|
+
* `{word}` inside a literal stays what it is.
|
|
20
|
+
*/
|
|
21
|
+
export interface Sql {
|
|
22
|
+
readonly dialect: "sqlite" | "postgres";
|
|
23
|
+
all<T>(sql: string, params?: readonly unknown[]): Promise<T[]>;
|
|
24
|
+
run(sql: string, params?: readonly unknown[]): Promise<{
|
|
25
|
+
changes: number;
|
|
26
|
+
}>;
|
|
27
|
+
/** Several statements, all or none. */
|
|
28
|
+
batch(statements: readonly (readonly [string, readonly unknown[]])[]): Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
/**
|
|
31
|
+
* Runs `edit` on the parts of a statement that are SQL, and leaves alone what is quoted: `'strings'` (with `''`
|
|
32
|
+
* inside), `"names"`, `-- comments`, `/* comments *\/` and Postgres' `$$dollar quotes$$` / `$tag$…$tag$`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function outsideQuotes(sql: string, edit: (code: string) => string): string;
|
|
35
|
+
/** The same database with `{name}` written as the prefixed table's name in every statement. */
|
|
36
|
+
export declare function withTables(sql: Sql, prefix: string): Sql;
|
|
37
|
+
/**
|
|
38
|
+
* A number as any driver answers it: Postgres drivers give a `bigint` as text (node-postgres, postgres.js) or as a
|
|
39
|
+
* BigInt, SQLite as a number. Times here are milliseconds, well inside what a double holds exactly.
|
|
40
|
+
*/
|
|
41
|
+
export declare function num(v: unknown): number;
|
|
42
|
+
export declare function numOrNull(v: unknown): number | null;
|
|
43
|
+
/** JSON kept as text, read back; anything that isn't an object reads as null. */
|
|
44
|
+
export declare function object<T extends object>(v: unknown): T | null;
|
|
45
|
+
/**
|
|
46
|
+
* Lists in pieces small enough to bind: D1 takes at most 100 values in one statement, so a statement with a list
|
|
47
|
+
* binds 80 of them and keeps room for the rest.
|
|
48
|
+
*/
|
|
49
|
+
export declare const CHUNK = 80;
|
|
50
|
+
export declare function chunks<T>(list: readonly T[], size?: number): T[][];
|
|
51
|
+
/** `?, ?, ?` for a list of `n` values. */
|
|
52
|
+
export declare const marks: (n: number) => string;
|
package/dist/db/sql.js
ADDED
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Runs `edit` on the parts of a statement that are SQL, and leaves alone what is quoted: `'strings'` (with `''`
|
|
3
|
+
* inside), `"names"`, `-- comments`, `/* comments *\/` and Postgres' `$$dollar quotes$$` / `$tag$…$tag$`.
|
|
4
|
+
*/
|
|
5
|
+
export function outsideQuotes(sql, edit) {
|
|
6
|
+
let out = "";
|
|
7
|
+
let from = 0;
|
|
8
|
+
let i = 0;
|
|
9
|
+
const code = (to) => {
|
|
10
|
+
out += edit(sql.slice(from, to));
|
|
11
|
+
};
|
|
12
|
+
const keep = (to) => {
|
|
13
|
+
out += sql.slice(i, to);
|
|
14
|
+
i = from = to;
|
|
15
|
+
};
|
|
16
|
+
while (i < sql.length) {
|
|
17
|
+
const c = sql[i];
|
|
18
|
+
if (c === "'" || c === '"') {
|
|
19
|
+
code(i);
|
|
20
|
+
let j = i + 1;
|
|
21
|
+
for (;;) {
|
|
22
|
+
const k = sql.indexOf(c, j);
|
|
23
|
+
if (k === -1) {
|
|
24
|
+
j = sql.length;
|
|
25
|
+
break;
|
|
26
|
+
}
|
|
27
|
+
// A doubled quote is the quote itself, inside.
|
|
28
|
+
if (sql[k + 1] === c) {
|
|
29
|
+
j = k + 2;
|
|
30
|
+
continue;
|
|
31
|
+
}
|
|
32
|
+
j = k + 1;
|
|
33
|
+
break;
|
|
34
|
+
}
|
|
35
|
+
keep(j);
|
|
36
|
+
}
|
|
37
|
+
else if (c === "-" && sql[i + 1] === "-") {
|
|
38
|
+
code(i);
|
|
39
|
+
const k = sql.indexOf("\n", i);
|
|
40
|
+
keep(k === -1 ? sql.length : k);
|
|
41
|
+
}
|
|
42
|
+
else if (c === "/" && sql[i + 1] === "*") {
|
|
43
|
+
code(i);
|
|
44
|
+
const k = sql.indexOf("*/", i + 2);
|
|
45
|
+
keep(k === -1 ? sql.length : k + 2);
|
|
46
|
+
}
|
|
47
|
+
else if (c === "$") {
|
|
48
|
+
// `$1` is a placeholder; `$$` and `$tag$` open a dollar quote, closed by the same tag.
|
|
49
|
+
const tag = /^\$(?:[A-Za-z_][A-Za-z0-9_]*)?\$/.exec(sql.slice(i))?.[0];
|
|
50
|
+
if (tag) {
|
|
51
|
+
code(i);
|
|
52
|
+
const k = sql.indexOf(tag, i + tag.length);
|
|
53
|
+
keep(k === -1 ? sql.length : k + tag.length);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
i += 1;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
else {
|
|
60
|
+
i += 1;
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
code(sql.length);
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
/** A table prefix: letters, digits and underscores, short enough for Postgres' 63-byte names with an index's suffix. */
|
|
67
|
+
const PREFIX = /^[a-z_][a-z0-9_]{0,39}$/i;
|
|
68
|
+
/** The same database with `{name}` written as the prefixed table's name in every statement. */
|
|
69
|
+
export function withTables(sql, prefix) {
|
|
70
|
+
if (!PREFIX.test(prefix))
|
|
71
|
+
throw new Error(`a table prefix is up to 40 letters, digits and underscores: ${prefix}`);
|
|
72
|
+
const name = (s) => outsideQuotes(s, (code) => code.replace(/\{([a-z_]+)\}/g, (_, t) => `${prefix}${t}`));
|
|
73
|
+
return {
|
|
74
|
+
dialect: sql.dialect,
|
|
75
|
+
all: (s, p) => sql.all(name(s), p),
|
|
76
|
+
run: (s, p) => sql.run(name(s), p),
|
|
77
|
+
batch: (list) => sql.batch(list.map(([s, p]) => [name(s), p])),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
// MARK: Reading rows
|
|
81
|
+
/**
|
|
82
|
+
* A number as any driver answers it: Postgres drivers give a `bigint` as text (node-postgres, postgres.js) or as a
|
|
83
|
+
* BigInt, SQLite as a number. Times here are milliseconds, well inside what a double holds exactly.
|
|
84
|
+
*/
|
|
85
|
+
export function num(v) {
|
|
86
|
+
if (typeof v === "number")
|
|
87
|
+
return v;
|
|
88
|
+
if (typeof v === "bigint")
|
|
89
|
+
return Number(v);
|
|
90
|
+
if (typeof v === "string" && v !== "")
|
|
91
|
+
return Number(v);
|
|
92
|
+
return 0;
|
|
93
|
+
}
|
|
94
|
+
export function numOrNull(v) {
|
|
95
|
+
return v === null || v === undefined ? null : num(v);
|
|
96
|
+
}
|
|
97
|
+
/** JSON kept as text, read back; anything that isn't an object reads as null. */
|
|
98
|
+
export function object(v) {
|
|
99
|
+
if (typeof v !== "string" || v === "")
|
|
100
|
+
return null;
|
|
101
|
+
try {
|
|
102
|
+
const parsed = JSON.parse(v);
|
|
103
|
+
return typeof parsed === "object" && parsed !== null && !Array.isArray(parsed) ? parsed : null;
|
|
104
|
+
}
|
|
105
|
+
catch {
|
|
106
|
+
return null;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Lists in pieces small enough to bind: D1 takes at most 100 values in one statement, so a statement with a list
|
|
111
|
+
* binds 80 of them and keeps room for the rest.
|
|
112
|
+
*/
|
|
113
|
+
export const CHUNK = 80;
|
|
114
|
+
export function chunks(list, size = CHUNK) {
|
|
115
|
+
const out = [];
|
|
116
|
+
for (let i = 0; i < list.length; i += size)
|
|
117
|
+
out.push(list.slice(i, i + size));
|
|
118
|
+
return out;
|
|
119
|
+
}
|
|
120
|
+
/** `?, ?, ?` for a list of `n` values. */
|
|
121
|
+
export const marks = (n) => Array.from({ length: n }, () => "?").join(", ");
|
package/dist/dns.d.ts
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
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 declare const DOH_URL = "https://cloudflare-dns.com/dns-query";
|
|
14
|
+
export type MailService = "resend" | "postmark" | "mailgun" | "sendgrid" | "ses" | "smtp";
|
|
15
|
+
export declare const MAIL_SERVICES: readonly MailService[];
|
|
16
|
+
export interface DnsLine {
|
|
17
|
+
/** `ok`: there and right. `missing`: not there, or wrong. `info`: what can't be checked, or worth knowing. */
|
|
18
|
+
state: "ok" | "missing" | "info";
|
|
19
|
+
text: string;
|
|
20
|
+
}
|
|
21
|
+
export interface DnsReport {
|
|
22
|
+
domain: string;
|
|
23
|
+
lines: DnsLine[];
|
|
24
|
+
spf: boolean;
|
|
25
|
+
dmarc: boolean;
|
|
26
|
+
}
|
|
27
|
+
export declare class DnsError extends Error {
|
|
28
|
+
name: string;
|
|
29
|
+
}
|
|
30
|
+
declare const TYPE: {
|
|
31
|
+
readonly A: 1;
|
|
32
|
+
readonly NS: 2;
|
|
33
|
+
readonly CNAME: 5;
|
|
34
|
+
readonly MX: 15;
|
|
35
|
+
readonly TXT: 16;
|
|
36
|
+
readonly AAAA: 28;
|
|
37
|
+
};
|
|
38
|
+
/** The records of one type at a name, as their text: TXT without its quotes (its strings joined), MX and CNAME as given. */
|
|
39
|
+
export declare function lookup(name: string, type: keyof typeof TYPE, f?: typeof fetch): Promise<string[]>;
|
|
40
|
+
/** The domain of a from address: `Acme <hello@acme.com>` or `hello@acme.com`. */
|
|
41
|
+
export declare function domainOf(from: string): string | undefined;
|
|
42
|
+
export declare function checkMailDns(domain: string, o?: {
|
|
43
|
+
sender?: MailService;
|
|
44
|
+
fetch?: typeof fetch;
|
|
45
|
+
}): Promise<DnsReport>;
|
|
46
|
+
/** The report as lines to print: ✓ there, ✗ missing, i to know. */
|
|
47
|
+
export declare function dnsText(r: DnsReport): string[];
|
|
48
|
+
export {};
|