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
@@ -0,0 +1,2 @@
1
+ /** A SQLite store: node:sqlite, better-sqlite3 or bun:sqlite. */
2
+ export { openSqlite, sqliteSql, type SqliteLike } from "./stores/sqlite.ts";
package/dist/sqlite.js ADDED
@@ -0,0 +1,2 @@
1
+ /** A SQLite store: node:sqlite, better-sqlite3 or bun:sqlite. */
2
+ export { openSqlite, sqliteSql } from "./stores/sqlite.js";
@@ -0,0 +1,22 @@
1
+ import type { Sql } from "../db/sql.ts";
2
+ /** The parts of Cloudflare's D1 binding the store uses, so this needs no types package. */
3
+ export interface D1Like {
4
+ prepare(sql: string): {
5
+ bind(...values: unknown[]): {
6
+ all<T>(): Promise<{
7
+ results: T[];
8
+ }>;
9
+ run(): Promise<{
10
+ meta: {
11
+ changes?: number;
12
+ };
13
+ }>;
14
+ };
15
+ };
16
+ batch(statements: unknown[]): Promise<unknown>;
17
+ }
18
+ /**
19
+ * A store on a D1 database (the binding from `wrangler.toml`). D1 takes at most 100
20
+ * values in one statement; the server's statements stay under it.
21
+ */
22
+ export declare function d1Sql(db: D1Like): Sql;
@@ -0,0 +1,23 @@
1
+ /** What D1 binds: numbers for booleans, null for nothing (it refuses `undefined`). */
2
+ const values = (params) => params.map((v) => (typeof v === "boolean" ? Number(v) : v === undefined ? null : v));
3
+ /**
4
+ * A store on a D1 database (the binding from `wrangler.toml`). D1 takes at most 100
5
+ * values in one statement; the server's statements stay under it.
6
+ */
7
+ export function d1Sql(db) {
8
+ return {
9
+ dialect: "sqlite",
10
+ async all(sql, params = []) {
11
+ return (await db.prepare(sql).bind(...values(params)).all()).results;
12
+ },
13
+ async run(sql, params = []) {
14
+ const { meta } = await db.prepare(sql).bind(...values(params)).run();
15
+ return { changes: meta.changes ?? 0 };
16
+ },
17
+ async batch(statements) {
18
+ // D1 runs a batch as one transaction.
19
+ if (statements.length)
20
+ await db.batch(statements.map(([sql, params]) => db.prepare(sql).bind(...values(params))));
21
+ },
22
+ };
23
+ }
@@ -0,0 +1,33 @@
1
+ import { type Sql } from "../db/sql.ts";
2
+ /**
3
+ * A Postgres client as node-postgres has it (`Pool` or `Client`), which is also
4
+ * Neon's serverless driver, `@vercel/postgres`, and PGlite: `query(text, values)`
5
+ * answering the rows and how many it touched.
6
+ */
7
+ export interface PgLike {
8
+ query(text: string, values?: unknown[]): Promise<{
9
+ rows: unknown[];
10
+ rowCount?: number | null;
11
+ affectedRows?: number;
12
+ }>;
13
+ }
14
+ /** postgres.js (`import postgres from "postgres"`), which Supabase's Edge Functions use. */
15
+ export interface PostgresJsLike {
16
+ unsafe(text: string, values?: unknown[]): Promise<unknown[] & {
17
+ count?: number;
18
+ }>;
19
+ begin<T>(fn: (tx: PostgresJsLike) => Promise<T>): Promise<T>;
20
+ }
21
+ /**
22
+ * `?, ?, ?` as Postgres writes them, `$1, $2, $3`. A `?` inside a string, a quoted name, a comment or a dollar quote
23
+ * is left alone; one in the SQL itself is always a value (so Postgres' jsonb `?` operators are written as functions,
24
+ * `jsonb_exists(…)`, in a query that goes through here).
25
+ */
26
+ export declare function numbered(sql: string): string;
27
+ /**
28
+ * A store on Postgres through a node-postgres–style client. Numbers that Postgres keeps as `bigint` come back as
29
+ * the driver gives them (text, with node-postgres); the server reads every one with `Number`.
30
+ */
31
+ export declare function pgSql(client: PgLike): Sql;
32
+ /** A store on Postgres through postgres.js. */
33
+ export declare function postgresJsSql(sql: PostgresJsLike): Sql;
@@ -0,0 +1,71 @@
1
+ import { outsideQuotes } from "../db/sql.js";
2
+ /**
3
+ * `?, ?, ?` as Postgres writes them, `$1, $2, $3`. A `?` inside a string, a quoted name, a comment or a dollar quote
4
+ * is left alone; one in the SQL itself is always a value (so Postgres' jsonb `?` operators are written as functions,
5
+ * `jsonb_exists(…)`, in a query that goes through here).
6
+ */
7
+ export function numbered(sql) {
8
+ let n = 0;
9
+ return outsideQuotes(sql, (code) => code.replace(/\?/g, () => `$${(n += 1)}`));
10
+ }
11
+ /** What every driver takes: null for nothing (postgres.js refuses `undefined`). */
12
+ const values = (params) => params.map((v) => (v === undefined ? null : v));
13
+ const isPool = (c) => typeof c.connect === "function" && typeof c.totalCount === "number";
14
+ /**
15
+ * A store on Postgres through a node-postgres–style client. Numbers that Postgres keeps as `bigint` come back as
16
+ * the driver gives them (text, with node-postgres); the server reads every one with `Number`.
17
+ */
18
+ export function pgSql(client) {
19
+ return {
20
+ dialect: "postgres",
21
+ async all(sql, params = []) {
22
+ return (await client.query(numbered(sql), values(params))).rows;
23
+ },
24
+ async run(sql, params = []) {
25
+ const r = await client.query(numbered(sql), values(params));
26
+ return { changes: Number(r.rowCount ?? r.affectedRows ?? 0) };
27
+ },
28
+ async batch(statements) {
29
+ if (!statements.length)
30
+ return;
31
+ const own = isPool(client) ? await client.connect() : null;
32
+ const db = own ?? client;
33
+ try {
34
+ await db.query("begin");
35
+ try {
36
+ for (const [sql, params] of statements)
37
+ await db.query(numbered(sql), values(params));
38
+ await db.query("commit");
39
+ }
40
+ catch (e) {
41
+ await db.query("rollback").catch(() => undefined);
42
+ throw e;
43
+ }
44
+ }
45
+ finally {
46
+ own?.release();
47
+ }
48
+ },
49
+ };
50
+ }
51
+ /** A store on Postgres through postgres.js. */
52
+ export function postgresJsSql(sql) {
53
+ return {
54
+ dialect: "postgres",
55
+ async all(text, params = []) {
56
+ return [...(await sql.unsafe(numbered(text), values(params)))];
57
+ },
58
+ async run(text, params = []) {
59
+ const r = await sql.unsafe(numbered(text), values(params));
60
+ return { changes: Number(r.count ?? 0) };
61
+ },
62
+ async batch(statements) {
63
+ if (!statements.length)
64
+ return;
65
+ await sql.begin(async (tx) => {
66
+ for (const [text, params] of statements)
67
+ await tx.unsafe(numbered(text), values(params));
68
+ });
69
+ },
70
+ };
71
+ }
@@ -0,0 +1,27 @@
1
+ import type { Sql } from "../db/sql.ts";
2
+ /**
3
+ * The shape the three synchronous SQLite drivers share: Node's own `node:sqlite`
4
+ * (`DatabaseSync`), `better-sqlite3` and Bun's `bun:sqlite`. Whichever the backend
5
+ * has, it is passed in as it is.
6
+ */
7
+ export interface SqliteLike {
8
+ prepare(sql: string): {
9
+ all(...params: never[]): unknown[];
10
+ run(...params: never[]): {
11
+ changes: number | bigint;
12
+ };
13
+ };
14
+ exec(sql: string): unknown;
15
+ }
16
+ /**
17
+ * A store on a SQLite database the caller opened. The drivers are synchronous, so a
18
+ * batch runs from `begin` to `commit` with nothing else in between.
19
+ */
20
+ export declare function sqliteSql(db: SqliteLike): Sql;
21
+ /**
22
+ * A SQLite file opened with the runtime's own driver, nothing to install: `node:sqlite` on Node and Deno,
23
+ * `bun:sqlite` on Bun. `":memory:"` keeps it in memory, which is what the tests use.
24
+ */
25
+ export declare function openSqlite(path: string): Promise<Sql & {
26
+ close(): void;
27
+ }>;
@@ -0,0 +1,55 @@
1
+ var __rewriteRelativeImportExtension = (this && this.__rewriteRelativeImportExtension) || function (path, preserveJsx) {
2
+ if (typeof path === "string" && /^\.\.?\//.test(path)) {
3
+ return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) {
4
+ return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js");
5
+ });
6
+ }
7
+ return path;
8
+ };
9
+ /** What SQLite binds: numbers for booleans, null for nothing (node:sqlite refuses both `true` and `undefined`). */
10
+ const values = (params) => params.map((v) => (typeof v === "boolean" ? Number(v) : v === undefined ? null : v));
11
+ /**
12
+ * A store on a SQLite database the caller opened. The drivers are synchronous, so a
13
+ * batch runs from `begin` to `commit` with nothing else in between.
14
+ */
15
+ export function sqliteSql(db) {
16
+ return {
17
+ dialect: "sqlite",
18
+ async all(sql, params = []) {
19
+ return db.prepare(sql).all(...values(params));
20
+ },
21
+ async run(sql, params = []) {
22
+ return { changes: Number(db.prepare(sql).run(...values(params)).changes) };
23
+ },
24
+ async batch(statements) {
25
+ if (!statements.length)
26
+ return;
27
+ db.exec("begin");
28
+ try {
29
+ for (const [sql, params] of statements)
30
+ db.prepare(sql).run(...values(params));
31
+ db.exec("commit");
32
+ }
33
+ catch (e) {
34
+ db.exec("rollback");
35
+ throw e;
36
+ }
37
+ },
38
+ };
39
+ }
40
+ /**
41
+ * A SQLite file opened with the runtime's own driver, nothing to install: `node:sqlite` on Node and Deno,
42
+ * `bun:sqlite` on Bun. `":memory:"` keeps it in memory, which is what the tests use.
43
+ */
44
+ export async function openSqlite(path) {
45
+ if ("Bun" in globalThis) {
46
+ const { Database } = await import(__rewriteRelativeImportExtension(/* bun */ "bun:sqlite"));
47
+ const db = new Database(path);
48
+ db.exec("pragma journal_mode = wal; pragma busy_timeout = 5000;");
49
+ return { ...sqliteSql(db), close: () => db.close() };
50
+ }
51
+ const { DatabaseSync } = await import("node:sqlite");
52
+ const db = new DatabaseSync(path);
53
+ db.exec("pragma journal_mode = wal; pragma busy_timeout = 5000;");
54
+ return { ...sqliteSql(db), close: () => db.close() };
55
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Moving a Supabase project's users from Supabase Auth to direct-auth, once, in the same database, with the same ids:
3
+ * one SQL script the owner reads and runs (`npx direct-auth supabase-sql > move.sql`, then the SQL editor or `psql`),
4
+ * or that `direct-auth migrate` runs. It is a hard stop: no Supabase session comes over, so everyone signs in again
5
+ * in the app's new version, and Supabase Auth's sign-ins go off.
6
+ *
7
+ * In one transaction it:
8
+ *
9
+ * 1. refuses a database moved into before (`supabase_moved` or `source_moved` in `{meta}`), and users with a second factor
10
+ * (`auth.mfa_factors`), which direct-auth doesn't check, unless `allowMfaLoss`;
11
+ * 2. makes direct-auth's tables in `public` (what the server makes on its first start);
12
+ * 3. takes every user Supabase has (not the banned, not the deleted; the anonymous ones as guests) with their
13
+ * confirmed address and number (not an SSO user's: their identity provider vouched for it, nobody here did),
14
+ * name, picture, password hash (bcrypt, only with a confirmed address; checked and made PBKDF2 at its first
15
+ * sign-in; not an address confirmed the moment it signed up, unless `keepUnprovenPasswords`), Apple and Google
16
+ * identities, passkeys (COSE, turned into a JWK at their first use), and for each guest the hashes of its
17
+ * Supabase refresh tokens, each good once to get back in (`POST /guest/claim`). An address,
18
+ * number, Apple, Google or GitHub account two accounts have stays with the older one (or the one here already);
19
+ * 4. points every foreign key on `auth.users(id)` outside Supabase's own schemas at `{users}(id)`, keeping all of
20
+ * it (`on delete`, `on update`, deferrable);
21
+ * 5. names the app's triggers on `auth.users` (a `handle_new_user`): where they belong now.
22
+ *
23
+ * `auth.uid()` keeps working in the policies once direct-auth is a Third-Party Auth issuer of the project: it reads
24
+ * the access token's `sub`, which is the same id.
25
+ */
26
+ export interface MoveOptions {
27
+ /** The tables' prefix (`auth_`). */
28
+ prefix?: string;
29
+ /** Move users who have a second factor, which direct-auth doesn't check (they sign in with the first alone). */
30
+ allowMfaLoss?: boolean;
31
+ /**
32
+ * Keep the passwords of email sign-ups whose address was confirmed within seconds of the sign-up (Confirm email
33
+ * off, or the admin API): nobody proved those addresses, so by default they move without the password, and the
34
+ * address's owner gets in with an email code.
35
+ */
36
+ keepUnprovenPasswords?: boolean;
37
+ }
38
+ /** Who moves: not deleted, not banned now. */
39
+ export declare const ELIGIBLE: (u: string) => string;
40
+ /**
41
+ * A SAML SSO user: GoTrue keeps them apart from the others (an address is unique only among users who aren't), and
42
+ * their address is whatever the tenant's identity provider asserted, marked confirmed.
43
+ */
44
+ export declare const SSO: (u: string) => string;
45
+ /** A user's confirmed address and number, as direct-auth keeps them (an SSO user's are nobody's proof). */
46
+ export declare const EMAIL_OF: (u: string) => string;
47
+ export declare const PHONE_OF: (u: string) => string;
48
+ /** A confirmed address's bcrypt hash, the only kind Supabase Auth makes. */
49
+ export declare const PASSWORD: (u: string) => string;
50
+ /**
51
+ * An email sign-up whose address was confirmed within 2 seconds of it: Confirm email was off (or the admin API made
52
+ * it), so nobody proved the address, and the password was set by whoever signed up with it.
53
+ */
54
+ export declare const CONFIRMED_AT_ONCE: (u: string) => string;
55
+ /** The password hash that moves: a confirmed address's, and not an unproven one's unless asked. */
56
+ export declare const MOVED_PASSWORD: (u: string, keepUnproven?: boolean) => string;
57
+ /** An anonymous user's Supabase refresh tokens still good: what the app on their device holds. */
58
+ export declare const GUEST_TOKENS: (u: string) => string;
59
+ /** How long a moved guest's claim waits: 180 days. */
60
+ export declare const CLAIM_DAYS = 180;
61
+ /** Bytes as base64url, in SQL. */
62
+ export declare const B64URL: (col: string) => string;
63
+ /**
64
+ * The dry run's note that Supabase Auth's users wait to be moved here: until a move clears it, direct-auth makes
65
+ * nobody (503 migration_pending), so a sign-in can't make a second, empty account for one of them. Only this note
66
+ * turns that on: auth.users' rows alone never do.
67
+ */
68
+ export declare function supabasePendingSql(o?: {
69
+ prefix?: string;
70
+ }): string;
71
+ export declare function supabaseMoveSql(o?: MoveOptions): string;
@@ -0,0 +1,283 @@
1
+ /**
2
+ * Moving a Supabase project's users from Supabase Auth to direct-auth, once, in the same database, with the same ids:
3
+ * one SQL script the owner reads and runs (`npx direct-auth supabase-sql > move.sql`, then the SQL editor or `psql`),
4
+ * or that `direct-auth migrate` runs. It is a hard stop: no Supabase session comes over, so everyone signs in again
5
+ * in the app's new version, and Supabase Auth's sign-ins go off.
6
+ *
7
+ * In one transaction it:
8
+ *
9
+ * 1. refuses a database moved into before (`supabase_moved` or `source_moved` in `{meta}`), and users with a second factor
10
+ * (`auth.mfa_factors`), which direct-auth doesn't check, unless `allowMfaLoss`;
11
+ * 2. makes direct-auth's tables in `public` (what the server makes on its first start);
12
+ * 3. takes every user Supabase has (not the banned, not the deleted; the anonymous ones as guests) with their
13
+ * confirmed address and number (not an SSO user's: their identity provider vouched for it, nobody here did),
14
+ * name, picture, password hash (bcrypt, only with a confirmed address; checked and made PBKDF2 at its first
15
+ * sign-in; not an address confirmed the moment it signed up, unless `keepUnprovenPasswords`), Apple and Google
16
+ * identities, passkeys (COSE, turned into a JWK at their first use), and for each guest the hashes of its
17
+ * Supabase refresh tokens, each good once to get back in (`POST /guest/claim`). An address,
18
+ * number, Apple, Google or GitHub account two accounts have stays with the older one (or the one here already);
19
+ * 4. points every foreign key on `auth.users(id)` outside Supabase's own schemas at `{users}(id)`, keeping all of
20
+ * it (`on delete`, `on update`, deferrable);
21
+ * 5. names the app's triggers on `auth.users` (a `handle_new_user`): where they belong now.
22
+ *
23
+ * `auth.uid()` keeps working in the policies once direct-auth is a Third-Party Auth issuer of the project: it reads
24
+ * the access token's `sub`, which is the same id.
25
+ */
26
+ import { MIGRATIONS } from "./db/schema.js";
27
+ /** Who moves: not deleted, not banned now. */
28
+ export const ELIGIBLE = (u) => `${u}.deleted_at is null and (${u}.banned_until is null or ${u}.banned_until < now())`;
29
+ /**
30
+ * A SAML SSO user: GoTrue keeps them apart from the others (an address is unique only among users who aren't), and
31
+ * their address is whatever the tenant's identity provider asserted, marked confirmed.
32
+ */
33
+ export const SSO = (u) => `coalesce(${u}.is_sso_user, false)`;
34
+ /** A user's confirmed address and number, as direct-auth keeps them (an SSO user's are nobody's proof). */
35
+ export const EMAIL_OF = (u) => `case when ${u}.email_confirmed_at is not null and coalesce(${u}.email, '') <> '' and not ${SSO(u)} then lower(${u}.email) end`;
36
+ export const PHONE_OF = (u) => `case when ${u}.phone_confirmed_at is not null and coalesce(${u}.phone, '') <> '' and not ${SSO(u)} then '+' || ltrim(${u}.phone, '+') end`;
37
+ /** A confirmed address's bcrypt hash, the only kind Supabase Auth makes. */
38
+ export const PASSWORD = (u) => `case when ${EMAIL_OF(u)} is not null and ${u}.encrypted_password like '$2%' then ${u}.encrypted_password end`;
39
+ /**
40
+ * An email sign-up whose address was confirmed within 2 seconds of it: Confirm email was off (or the admin API made
41
+ * it), so nobody proved the address, and the password was set by whoever signed up with it.
42
+ */
43
+ export const CONFIRMED_AT_ONCE = (u) => `(not ${SSO(u)} and ${u}.encrypted_password like '$2%'
44
+ and exists (select 1 from auth.identities i where i.user_id = ${u}.id and i.provider = 'email')
45
+ and not exists (select 1 from auth.identities i where i.user_id = ${u}.id and i.provider not in ('email', 'phone'))
46
+ and ${u}.email_confirmed_at <= ${u}.created_at + interval '2 seconds')`;
47
+ /** The password hash that moves: a confirmed address's, and not an unproven one's unless asked. */
48
+ export const MOVED_PASSWORD = (u, keepUnproven = false) => keepUnproven ? PASSWORD(u) : `case when not ${CONFIRMED_AT_ONCE(u)} then ${PASSWORD(u)} end`;
49
+ /** An anonymous user's Supabase refresh tokens still good: what the app on their device holds. */
50
+ export const GUEST_TOKENS = (u) => `select rt.token from auth.refresh_tokens rt where rt.user_id = ${u}.id::text and not coalesce(rt.revoked, false) and coalesce(rt.token, '') <> ''`;
51
+ /** How long a moved guest's claim waits: 180 days. */
52
+ export const CLAIM_DAYS = 180;
53
+ /** Bytes as base64url, in SQL. */
54
+ export const B64URL = (col) => `translate(rtrim(replace(encode(${col}, 'base64'), E'\\n', ''), '='), '+/', '-_')`;
55
+ const ident = (s) => {
56
+ if (!/^[a-z_][a-z0-9_]*$/.test(s))
57
+ throw new Error(`${s} is not a plain lowercase name`);
58
+ return s;
59
+ };
60
+ const ms = (col) => `(extract(epoch from ${col}) * 1000)::bigint`;
61
+ const NOW = ms("now()");
62
+ /**
63
+ * The dry run's note that Supabase Auth's users wait to be moved here: until a move clears it, direct-auth makes
64
+ * nobody (503 migration_pending), so a sign-in can't make a second, empty account for one of them. Only this note
65
+ * turns that on: auth.users' rows alone never do.
66
+ */
67
+ export function supabasePendingSql(o = {}) {
68
+ const t = (name) => `public.${ident(o.prefix ?? "auth_")}${name}`;
69
+ return `create table if not exists ${t("meta")} (key text primary key, value text not null);
70
+ alter table ${t("meta")} enable row level security;
71
+ insert into ${t("meta")} (key, value) values ('supabase_pending', ${NOW}::text) on conflict (key) do nothing;
72
+ `;
73
+ }
74
+ export function supabaseMoveSql(o = {}) {
75
+ const prefix = ident(o.prefix ?? "auth_");
76
+ const t = (name) => `public.${prefix}${name}`;
77
+ const tables = (sql) => sql.replace(/\{uuid\}/g, "uuid").replace(/\{([a-z_]+)\}/g, (_m, name) => `${t(name)}`).replace(/public\.(\w+)_(\w+) on/g, "$1_$2 on");
78
+ const schema = MIGRATIONS.map((m) => (typeof m === "string" ? m : m.postgres))
79
+ .filter((m) => !!m)
80
+ .map((m) => `${tables(m)};`)
81
+ // An index's own name takes no schema: `create index … public.auth_identities_user on …` is `auth_identities_user`.
82
+ .map((m) => m.replace(/create index if not exists public\./g, "create index if not exists "))
83
+ .join("\n\n");
84
+ // Who goes first when two have one address or number: the older account.
85
+ const older = (a, b) => `(coalesce(${a}.created_at, '-infinity'), ${a}.id) < (coalesce(${b}.created_at, '-infinity'), ${b}.id)`;
86
+ return `-- direct-auth: moving users from Supabase Auth, once (read it before running it)
87
+ begin;
88
+ set local lock_timeout = '30s';
89
+ -- Every name below says its schema; this keeps what Postgres prints (a foreign key's definition) saying it too.
90
+ set local search_path = '';
91
+
92
+ -- 1. Once per database: run the way back first to move again.
93
+ do $$
94
+ begin
95
+ if to_regclass('${t("meta")}') is not null then
96
+ if exists (select 1 from ${t("meta")} where key in ('supabase_moved', 'source_moved')) then
97
+ raise exception 'direct-auth: the users were moved here already: it runs once. To move again, run the way back first';
98
+ end if;
99
+ end if;
100
+ end $$;
101
+
102
+ -- 2. direct-auth's tables.
103
+ create table if not exists ${t("meta")} (key text primary key, value text not null);
104
+
105
+ ${schema}
106
+
107
+ insert into ${t("meta")} (key, value) values ('schema', '${MIGRATIONS.length}')
108
+ on conflict (key) do update set value = excluded.value;
109
+
110
+ ${o.allowMfaLoss ? "" : `
111
+ -- Second factors: direct-auth doesn't check one, so these users would sign in with the first alone.
112
+ do $$
113
+ declare
114
+ n bigint;
115
+ begin
116
+ if to_regclass('auth.mfa_factors') is not null then
117
+ select count(distinct f.user_id) into n from auth.mfa_factors f join auth.users u on u.id = f.user_id
118
+ where f.status::text = 'verified' and ${ELIGIBLE("u")}
119
+ and not exists (select 1 from ${t("users")} d where d.id = u.id);
120
+ if n > 0 then
121
+ raise exception 'direct-auth: % users have a second factor (auth.mfa_factors), which direct-auth does not check: they would sign in with the first alone. To go ahead anyway: migrate --without-mfa (or supabase-sql --without-mfa)', n;
122
+ end if;
123
+ end if;
124
+ end $$;
125
+ `}
126
+ -- Nothing on Supabase Auth's side changes while this reads it (its sign-ins should be off already).
127
+ do $$
128
+ declare
129
+ r text;
130
+ begin
131
+ foreach r in array array['auth.users', 'auth.identities', 'auth.webauthn_credentials', 'auth.refresh_tokens'] loop
132
+ if to_regclass(r) is not null then execute format('lock table %s in share mode', r); end if;
133
+ end loop;
134
+ end $$;
135
+
136
+ -- 3. The users, then their ways in. An address or number another account has (here already, or an older one moving)
137
+ -- stays with it; the newer account moves without it, and with no password (a password goes with an address).
138
+ create temporary table da_moving on commit drop as
139
+ select u.id, u.created_at, u.updated_at, u.last_sign_in_at, coalesce(u.is_anonymous, false) as guest,
140
+ ${EMAIL_OF("u")} as email, ${PHONE_OF("u")} as phone, ${MOVED_PASSWORD("u", o.keepUnprovenPasswords)} as password,
141
+ coalesce(u.raw_user_meta_data ->> 'full_name', u.raw_user_meta_data ->> 'name') as name,
142
+ coalesce(u.raw_user_meta_data ->> 'avatar_url', u.raw_user_meta_data ->> 'picture') as picture
143
+ from auth.users u
144
+ where ${ELIGIBLE("u")} and not exists (select 1 from ${t("users")} d where d.id = u.id);
145
+
146
+ do $$
147
+ declare
148
+ emails bigint;
149
+ phones bigint;
150
+ accounts bigint;
151
+ begin
152
+ with x as (
153
+ update pg_temp.da_moving m set email = null, password = null
154
+ where m.email is not null and (
155
+ exists (select 1 from ${t("users")} d where d.email = m.email)
156
+ or exists (select 1 from ${t("identities")} i where i.provider = 'email' and i.subject = m.email)
157
+ or exists (select 1 from pg_temp.da_moving o where o.email = m.email and ${older("o", "m")}))
158
+ returning 1)
159
+ select count(*) into emails from x;
160
+ with x as (
161
+ update pg_temp.da_moving m set phone = null
162
+ where m.phone is not null and (
163
+ exists (select 1 from ${t("users")} d where d.phone = m.phone)
164
+ or exists (select 1 from ${t("identities")} i where i.provider = 'phone' and i.subject = m.phone)
165
+ or exists (select 1 from pg_temp.da_moving o where o.phone = m.phone and ${older("o", "m")}))
166
+ returning 1)
167
+ select count(*) into phones from x;
168
+ select count(*) into accounts from auth.identities i join pg_temp.da_moving m on m.id = i.user_id
169
+ where i.provider in ('apple', 'google', 'github') and exists (select 1 from ${t("identities")} d where d.provider = i.provider and d.subject = i.provider_id);
170
+ if emails + phones + accounts > 0 then
171
+ raise notice 'shared: % addresses, % numbers, % Apple, Google or GitHub accounts another account has: they stay with it, and these move without them', emails, phones, accounts;
172
+ end if;
173
+ end $$;
174
+
175
+ insert into ${t("users")} (id, email, phone, name, picture, created_at, updated_at, last_sign_in_at, is_guest, password_hash)
176
+ select m.id, m.email, m.phone, m.name, m.picture,
177
+ ${ms("coalesce(m.created_at, now())")}, ${ms("coalesce(m.updated_at, m.created_at, now())")}, ${ms("m.last_sign_in_at")},
178
+ case when m.guest then 1 else 0 end, m.password
179
+ from pg_temp.da_moving m
180
+ order by m.created_at, m.id;
181
+
182
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
183
+ select pg_catalog.gen_random_uuid()::text, m.id, 'email', m.email, m.email, ${ms("coalesce(m.created_at, now())")}, ${ms("coalesce(m.last_sign_in_at, m.created_at, now())")}
184
+ from pg_temp.da_moving m where m.email is not null
185
+ on conflict (provider, subject) do nothing;
186
+
187
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
188
+ select pg_catalog.gen_random_uuid()::text, m.id, 'phone', m.phone, null, ${ms("coalesce(m.created_at, now())")}, ${ms("coalesce(m.last_sign_in_at, m.created_at, now())")}
189
+ from pg_temp.da_moving m where m.phone is not null
190
+ on conflict (provider, subject) do nothing;
191
+
192
+ insert into ${t("identities")} (id, user_id, provider, subject, email, created_at, last_used_at)
193
+ select pg_catalog.gen_random_uuid()::text, i.user_id, i.provider, i.provider_id, lower(i.identity_data ->> 'email'),
194
+ ${ms("coalesce(i.created_at, now())")}, ${ms("coalesce(i.last_sign_in_at, i.created_at, now())")}
195
+ from auth.identities i join pg_temp.da_moving m on m.id = i.user_id
196
+ where i.provider in ('apple', 'google', 'github') and coalesce(i.provider_id, '') <> ''
197
+ on conflict (provider, subject) do nothing;
198
+
199
+ do $$
200
+ begin
201
+ if to_regclass('auth.webauthn_credentials') is not null then
202
+ insert into ${t("passkeys")} (id, user_id, public_key, alg, sign_count, transports, name, created_at, last_used_at)
203
+ select ${B64URL("c.credential_id")}, c.user_id, 'cose:' || ${B64URL("c.public_key")}, 0, c.sign_count, c.transports::text, nullif(c.friendly_name, ''),
204
+ ${ms("coalesce(c.created_at, now())")}, ${ms("c.last_used_at")}
205
+ from auth.webauthn_credentials c join pg_temp.da_moving m on m.id = c.user_id
206
+ on conflict (id) do nothing;
207
+ end if;
208
+ end $$;
209
+
210
+ -- Guests: nothing to sign in with, so each gets back in with the Supabase refresh token their app kept, once, within
211
+ -- ${CLAIM_DAYS} days (POST /guest/claim). Only the hash is kept. Supabase Auth still trades a refresh token for a new
212
+ -- one with its sign-ins off: the claim takes an unrevoked one from auth.refresh_tokens too, while the user's claim waits.
213
+ do $$
214
+ begin
215
+ if to_regclass('auth.refresh_tokens') is not null then
216
+ insert into ${t("guest_claims")} (hash, user_id, expires_at)
217
+ select ${B64URL("pg_catalog.sha256(pg_catalog.convert_to(g.token, 'UTF8'))")}, m.id, ${NOW} + ${CLAIM_DAYS}::bigint * 86400000
218
+ from pg_temp.da_moving m cross join lateral (${GUEST_TOKENS("m")}) g
219
+ where m.guest
220
+ on conflict (hash) do nothing;
221
+ end if;
222
+ end $$;
223
+
224
+ -- 4. Foreign keys on auth.users(id) point at ${t("users")}(id) instead, with all they said (on delete, on update,
225
+ -- deferrable). Rows of users left out (banned, deleted) have no row to point at: the key is made NOT VALID, which
226
+ -- holds for every new row and keeps those, and validated when there are none. A partitioned table's key is moved on
227
+ -- the table itself (its partitions follow), and can't be NOT VALID: with such rows the move stops.
228
+ do $$
229
+ declare
230
+ r record;
231
+ def text;
232
+ orphans bigint;
233
+ begin
234
+ for r in
235
+ select c.conname, c.conrelid::regclass as tbl, a.attname as col, pg_get_constraintdef(c.oid) as def, k.relkind = 'p' as partitioned
236
+ from pg_constraint c
237
+ join pg_attribute a on a.attrelid = c.conrelid and a.attnum = c.conkey[1]
238
+ join pg_class k on k.oid = c.conrelid
239
+ join pg_namespace n on n.oid = k.relnamespace
240
+ where c.contype = 'f'
241
+ and c.confrelid = 'auth.users'::regclass
242
+ and c.conparentid = 0
243
+ and array_length(c.conkey, 1) = 1
244
+ and c.confkey = array[(select attnum from pg_attribute where attrelid = 'auth.users'::regclass and attname = 'id')]::int2[]
245
+ and n.nspname not in ('auth', 'storage', 'realtime', 'supabase_functions', 'supabase_migrations', 'extensions', 'graphql', 'graphql_public', 'vault', 'pgsodium', 'pgsodium_masks', 'net', 'cron', 'pgbouncer', '_realtime', '_analytics', 'pgmq', 'pgtle')
246
+ and n.nspname not like 'pg\\_%'
247
+ loop
248
+ def := regexp_replace(r.def, '\\s+NOT VALID$', '');
249
+ if position('REFERENCES auth.users(id)' in def) = 0 then
250
+ raise exception 'direct-auth: % on % reads %, not REFERENCES auth.users(id): move it by hand', r.conname, r.tbl, def;
251
+ end if;
252
+ def := replace(def, 'REFERENCES auth.users(id)', 'REFERENCES ${t("users")}(id)');
253
+ execute format('select count(*) from %s x where x.%I is not null and not exists (select 1 from ${t("users")} u where u.id = x.%I)', r.tbl, r.col, r.col) into orphans;
254
+ if r.partitioned and orphans > 0 then
255
+ raise exception 'direct-auth: %.% is partitioned and % rows belong to users left out (banned or deleted); its key can''t be NOT VALID: delete those rows, or move the key by hand', r.tbl, r.col, orphans;
256
+ end if;
257
+ execute format('alter table %s drop constraint %I', r.tbl, r.conname);
258
+ if orphans = 0 then
259
+ execute format('alter table %s add constraint %I %s', r.tbl, r.conname, def);
260
+ raise notice 'moved: %.% now references ${t("users")} (%)', r.tbl, r.col, def;
261
+ else
262
+ execute format('alter table %s add constraint %I %s not valid', r.tbl, r.conname, def);
263
+ raise notice 'moved: %.% now references ${t("users")} (%), not validated: % rows belong to users left out (banned or deleted)', r.tbl, r.col, def, orphans;
264
+ end if;
265
+ end loop;
266
+ end $$;
267
+
268
+ -- 5. The app's triggers on auth.users: Supabase Auth makes no users from now on.
269
+ do $$
270
+ declare
271
+ r record;
272
+ begin
273
+ for r in select tgname, tgfoid::regproc as fn from pg_trigger where tgrelid = 'auth.users'::regclass and not tgisinternal loop
274
+ raise notice 'trigger on auth.users: % runs %(): new users are made in ${t("users")} now: make it a trigger after insert there, and drop this one', r.tgname, r.fn;
275
+ end loop;
276
+ end $$;
277
+
278
+ insert into ${t("meta")} (key, value) values ('supabase_moved', ${NOW}::text);
279
+ delete from ${t("meta")} where key = 'supabase_pending';
280
+
281
+ commit;
282
+ `;
283
+ }