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,118 @@
1
+ /**
2
+ * From an identity to a user: the one it already belongs to; else the user with the same address or number, when
3
+ * the provider checked it (so Apple and Google with the same Gmail are one person); else a new user. A provider's
4
+ * address that nobody checked is kept on the identity, never used to join two accounts.
5
+ */
6
+ import { type Sql } from "./db/sql.ts";
7
+ import type { Identity } from "./providers/identity.ts";
8
+ /**
9
+ * Whether the user's password is one they are known to know: one set here (PBKDF2). A hash moved from Supabase
10
+ * (bcrypt) may be the random one GoTrue gives every user made without a password, so it isn't counted as a way in
11
+ * (removing everything else would leave the account with nothing anyone knows) until it has signed someone in, and
12
+ * been replaced with PBKDF2 then. It signs in all the same, and `hasPassword` says so: any stored hash is a password,
13
+ * and the user can remove it.
14
+ */
15
+ export declare const provenPassword: (hash: string | null | undefined) => boolean;
16
+ export interface User {
17
+ id: string;
18
+ email: string | null;
19
+ phone: string | null;
20
+ name: string | null;
21
+ picture: string | null;
22
+ createdAt: number;
23
+ lastSignInAt: number | null;
24
+ /** Made with nothing to sign in with yet (`POST /guest`): it becomes a full account when a way in is linked. */
25
+ isGuest: boolean;
26
+ hasPassword: boolean;
27
+ }
28
+ export declare function getUser(sql: Sql, id: string): Promise<User | null>;
29
+ /**
30
+ * Who has this address or number: an account's own sign-in with it (an email or phone identity, so a second
31
+ * address an account proved counts), then the one it goes by. One answer, the same every time.
32
+ */
33
+ export declare function ownerOf(sql: Sql, kind: "email" | "phone", value: string, except?: string): Promise<string | null>;
34
+ /** The user `identity` signs in as, made or joined as needed. `created` says whether the user is new. */
35
+ export declare function resolveUser(sql: Sql, identity: Identity, now?: number): Promise<{
36
+ user: User;
37
+ created: boolean;
38
+ }>;
39
+ export interface IdentityInfo {
40
+ id: string;
41
+ provider: string;
42
+ subject: string;
43
+ email: string | null;
44
+ createdAt: number;
45
+ lastUsedAt: number;
46
+ }
47
+ /** The identities of one provider a user has, with what is kept for each (Apple's sealed token). */
48
+ export declare function identitiesOf(sql: Sql, userId: string, provider: string): Promise<{
49
+ subject: string;
50
+ data: Record<string, string> | null;
51
+ }[]>;
52
+ export declare function userOfIdentity(sql: Sql, provider: string, subject: string): Promise<string | null>;
53
+ export declare function listIdentities(sql: Sql, userId: string): Promise<IdentityInfo[]>;
54
+ /** Everything the user had here, gone: identities, sessions and their tokens, the user. */
55
+ export declare function deleteUserRows(sql: Sql, userId: string): Promise<boolean>;
56
+ /** A guest: an account with nothing to sign in with yet, kept on the device's session until a way in is linked. */
57
+ export declare function createGuest(sql: Sql, name: string | null, now?: number): Promise<User>;
58
+ export type LinkFailure = "identity_in_use" | "not_found";
59
+ /**
60
+ * Adds `identity` to the signed-in user, keeping their id (a guest becomes a full account). An identity that
61
+ * already signs someone else in, or an address that is someone else's, answers `identity_in_use`: the app decides
62
+ * (switch to that account, or keep this one).
63
+ */
64
+ export declare function linkIdentity(sql: Sql, userId: string, identity: Identity, now?: number): Promise<{
65
+ ok: true;
66
+ user: User;
67
+ } | {
68
+ ok: false;
69
+ reason: LinkFailure;
70
+ }>;
71
+ /**
72
+ * The account's address becomes `email` (already proven by a code): the email sign-in moves with it, and a
73
+ * password keeps working with the new address.
74
+ */
75
+ export declare function changeEmail(sql: Sql, userId: string, email: string, now?: number): Promise<{
76
+ ok: true;
77
+ user: User;
78
+ } | {
79
+ ok: false;
80
+ reason: LinkFailure;
81
+ }>;
82
+ /** How many ways in a user has: identities, passkeys, and a password while they have an address to use it with. */
83
+ export declare function waysIn(sql: Sql, userId: string): Promise<{
84
+ identities: number;
85
+ passkeys: number;
86
+ password: boolean;
87
+ }>;
88
+ /** Removes a passkey of the user unless it is their last way in, in one statement after the lock. */
89
+ export declare function removePasskey(sql: Sql, userId: string, id: string): Promise<{
90
+ ok: true;
91
+ } | {
92
+ ok: false;
93
+ reason: "not_found" | "last_way_in";
94
+ }>;
95
+ /** Removes the user's password unless it is their last way in, in one statement after the lock. */
96
+ export declare function removePasswordHash(sql: Sql, userId: string, now?: number): Promise<{
97
+ ok: true;
98
+ } | {
99
+ ok: false;
100
+ reason: "not_found" | "last_way_in";
101
+ }>;
102
+ /**
103
+ * Removes one of the user's identities, unless it is their last way in. Removing the address the account goes by
104
+ * clears it (and with it the password's use, which needs an address).
105
+ */
106
+ export declare function unlinkIdentity(sql: Sql, userId: string, identityId: string): Promise<{
107
+ ok: true;
108
+ removed: {
109
+ provider: string;
110
+ subject: string;
111
+ data: Record<string, string> | null;
112
+ };
113
+ } | {
114
+ ok: false;
115
+ reason: "not_found" | "last_way_in";
116
+ }>;
117
+ /** Guests nobody has used for `days` (a moved guest whose claim still waits isn't): their ids, for deleting (oldest first, at most `limit`). */
118
+ export declare function staleGuests(sql: Sql, days: number, now?: number, limit?: number): Promise<string[]>;
@@ -0,0 +1,314 @@
1
+ /**
2
+ * From an identity to a user: the one it already belongs to; else the user with the same address or number, when
3
+ * the provider checked it (so Apple and Google with the same Gmail are one person); else a new user. A provider's
4
+ * address that nobody checked is kept on the identity, never used to join two accounts.
5
+ */
6
+ import { num } from "./db/sql.js";
7
+ /**
8
+ * Whether the user's password is one they are known to know: one set here (PBKDF2). A hash moved from Supabase
9
+ * (bcrypt) may be the random one GoTrue gives every user made without a password, so it isn't counted as a way in
10
+ * (removing everything else would leave the account with nothing anyone knows) until it has signed someone in, and
11
+ * been replaced with PBKDF2 then. It signs in all the same, and `hasPassword` says so: any stored hash is a password,
12
+ * and the user can remove it.
13
+ */
14
+ export const provenPassword = (hash) => !!hash && hash.startsWith("$pbkdf2-");
15
+ const toUser = (r) => ({
16
+ id: r.id,
17
+ email: r.email,
18
+ phone: r.phone,
19
+ name: r.name,
20
+ picture: r.picture,
21
+ createdAt: num(r.created_at),
22
+ lastSignInAt: r.last_sign_in_at === null ? null : num(r.last_sign_in_at),
23
+ isGuest: num(r.is_guest) === 1,
24
+ hasPassword: !!r.password_hash,
25
+ });
26
+ export async function getUser(sql, id) {
27
+ const [row] = await sql.all(`select * from {users} where id = ?`, [id]);
28
+ return row ? toUser(row) : null;
29
+ }
30
+ async function byIdentity(sql, i) {
31
+ const [row] = await sql.all(`select user_id from {identities} where provider = ? and subject = ?`, [i.provider, i.subject]);
32
+ return row?.user_id ?? null;
33
+ }
34
+ /**
35
+ * Who has this address or number: an account's own sign-in with it (an email or phone identity, so a second
36
+ * address an account proved counts), then the one it goes by. One answer, the same every time.
37
+ */
38
+ export async function ownerOf(sql, kind, value, except) {
39
+ const [row] = await sql.all(`select id from (
40
+ select user_id as id, 0 as rank, created_at from {identities} where provider = ? and subject = ?${except ? " and user_id <> ?" : ""}
41
+ union all select id, 1 as rank, created_at from {users} where ${kind === "email" ? "email" : "phone"} = ?${except ? " and id <> ?" : ""}
42
+ ) x order by rank, created_at, id limit 1`, except ? [kind, value, except, value, except] : [kind, value, value]);
43
+ return row?.id ?? null;
44
+ }
45
+ async function byVerified(sql, i) {
46
+ if (i.phone) {
47
+ const id = await ownerOf(sql, "phone", i.phone);
48
+ if (id)
49
+ return id;
50
+ }
51
+ if (i.email && i.emailVerified) {
52
+ const id = await ownerOf(sql, "email", i.email);
53
+ if (id)
54
+ return id;
55
+ }
56
+ return null;
57
+ }
58
+ /** The user `identity` signs in as, made or joined as needed. `created` says whether the user is new. */
59
+ export async function resolveUser(sql, identity, now = Date.now()) {
60
+ for (let attempt = 0; attempt < 2; attempt += 1) {
61
+ let userId = await byIdentity(sql, identity);
62
+ let created = false;
63
+ try {
64
+ if (!userId) {
65
+ userId = await byVerified(sql, identity);
66
+ const statements = [];
67
+ if (!userId) {
68
+ userId = crypto.randomUUID();
69
+ created = true;
70
+ statements.push([
71
+ `insert into {users} (id, email, phone, name, picture, created_at, updated_at) values (?, ?, ?, ?, ?, ?, ?)`,
72
+ [userId, identity.emailVerified ? identity.email ?? null : null, identity.phone ?? null, identity.name ?? null, identity.picture ?? null, now, now],
73
+ ]);
74
+ }
75
+ statements.push([
76
+ `insert into {identities} (id, user_id, provider, subject, email, created_at, last_used_at) values (?, ?, ?, ?, ?, ?, ?)`,
77
+ [crypto.randomUUID(), userId, identity.provider, identity.subject, identity.email ?? null, now, now],
78
+ ]);
79
+ await sql.batch(statements);
80
+ }
81
+ }
82
+ catch (e) {
83
+ // Two first sign-ins at once: the other one made the row. Read it again.
84
+ if (attempt === 0 && /unique|constraint|duplicate/i.test(String(e?.message)))
85
+ continue;
86
+ throw e;
87
+ }
88
+ // What the provider vouches for fills in what the user doesn't have yet; nothing the user has is overwritten.
89
+ await sql.batch([
90
+ [`update {identities} set last_used_at = ?, email = coalesce(?, email) where provider = ? and subject = ?`, [now, identity.email ?? null, identity.provider, identity.subject]],
91
+ [
92
+ `update {users} set last_sign_in_at = ?, updated_at = ?,
93
+ name = coalesce(name, ?), picture = coalesce(picture, ?)
94
+ where id = ?`,
95
+ [now, now, identity.name ?? null, identity.picture ?? null, userId],
96
+ ],
97
+ ]);
98
+ if (identity.emailVerified && identity.email) {
99
+ await sql.run(`update {users} set email = ? where id = ? and email is null and not exists (select 1 from {users} u where u.email = ?)`, [identity.email, userId, identity.email]);
100
+ }
101
+ if (identity.phone) {
102
+ await sql.run(`update {users} set phone = ? where id = ? and phone is null and not exists (select 1 from {users} u where u.phone = ?)`, [identity.phone, userId, identity.phone]);
103
+ }
104
+ const user = await getUser(sql, userId);
105
+ if (!user)
106
+ throw new Error("the user was deleted while signing in");
107
+ return { user, created };
108
+ }
109
+ throw new Error("could not resolve the user");
110
+ }
111
+ /** The identities of one provider a user has, with what is kept for each (Apple's sealed token). */
112
+ export async function identitiesOf(sql, userId, provider) {
113
+ const rows = await sql.all(`select subject, data from {identities} where user_id = ? and provider = ?`, [userId, provider]);
114
+ return rows.map((r) => ({ subject: r.subject, data: r.data ? JSON.parse(r.data) : null }));
115
+ }
116
+ export async function userOfIdentity(sql, provider, subject) {
117
+ const [row] = await sql.all(`select user_id from {identities} where provider = ? and subject = ?`, [provider, subject]);
118
+ return row?.user_id ?? null;
119
+ }
120
+ export async function listIdentities(sql, userId) {
121
+ const rows = await sql.all(`select id, provider, subject, email, created_at, last_used_at from {identities} where user_id = ? order by created_at`, [userId]);
122
+ return rows.map((r) => ({ id: r.id, provider: r.provider, subject: r.subject, email: r.email, createdAt: num(r.created_at), lastUsedAt: num(r.last_used_at) }));
123
+ }
124
+ /** Everything the user had here, gone: identities, sessions and their tokens, the user. */
125
+ export async function deleteUserRows(sql, userId) {
126
+ const before = await getUser(sql, userId);
127
+ if (!before)
128
+ return false;
129
+ await sql.batch([
130
+ [`delete from {refresh} where session_id in (select id from {sessions} where user_id = ?)`, [userId]],
131
+ [`delete from {sessions} where user_id = ?`, [userId]],
132
+ [`delete from {identities} where user_id = ?`, [userId]],
133
+ [`delete from {passkeys} where user_id = ?`, [userId]],
134
+ [`delete from {challenges} where user_id = ?`, [userId]],
135
+ [`delete from {codes} where target = ? or target = ?`, [before.email ?? "", before.phone ?? ""]],
136
+ [`delete from {users} where id = ?`, [userId]],
137
+ ]);
138
+ return true;
139
+ }
140
+ /** A guest: an account with nothing to sign in with yet, kept on the device's session until a way in is linked. */
141
+ export async function createGuest(sql, name, now = Date.now()) {
142
+ const id = crypto.randomUUID();
143
+ await sql.run(`insert into {users} (id, name, created_at, updated_at, last_sign_in_at, is_guest) values (?, ?, ?, ?, ?, 1)`, [id, name, now, now, now]);
144
+ return (await getUser(sql, id));
145
+ }
146
+ /**
147
+ * Adds `identity` to the signed-in user, keeping their id (a guest becomes a full account). An identity that
148
+ * already signs someone else in, or an address that is someone else's, answers `identity_in_use`: the app decides
149
+ * (switch to that account, or keep this one).
150
+ */
151
+ export async function linkIdentity(sql, userId, identity, now = Date.now()) {
152
+ const user = await getUser(sql, userId);
153
+ if (!user)
154
+ return { ok: false, reason: "not_found" };
155
+ const owner = await byIdentity(sql, identity);
156
+ if (owner && owner !== userId)
157
+ return { ok: false, reason: "identity_in_use" };
158
+ if (identity.provider === "email" || identity.provider === "phone") {
159
+ if (await ownerOf(sql, identity.provider, identity.subject, userId))
160
+ return { ok: false, reason: "identity_in_use" };
161
+ }
162
+ // An Apple or Google account whose checked address or number is another account's: the same person has that
163
+ // account already, which a sign-in with it would open. The app decides, as for an identity in use.
164
+ if (!owner && identity.email && identity.emailVerified && (await ownerOf(sql, "email", identity.email, userId)))
165
+ return { ok: false, reason: "identity_in_use" };
166
+ if (!owner && identity.phone && (await ownerOf(sql, "phone", identity.phone, userId)))
167
+ return { ok: false, reason: "identity_in_use" };
168
+ if (!owner) {
169
+ try {
170
+ await sql.run(`insert into {identities} (id, user_id, provider, subject, email, created_at, last_used_at) values (?, ?, ?, ?, ?, ?, ?)`, [crypto.randomUUID(), userId, identity.provider, identity.subject, identity.email ?? null, now, now]);
171
+ }
172
+ catch (e) {
173
+ if (/unique|constraint|duplicate/i.test(String(e?.message)))
174
+ return { ok: false, reason: "identity_in_use" };
175
+ throw e;
176
+ }
177
+ }
178
+ await sql.run(`update {users} set is_guest = 0, updated_at = ?, name = coalesce(name, ?), picture = coalesce(picture, ?) where id = ?`, [now, identity.name ?? null, identity.picture ?? null, userId]);
179
+ if (identity.emailVerified && identity.email) {
180
+ await sql.run(`update {users} set email = ? where id = ? and email is null and not exists (select 1 from {users} u where u.email = ?)`, [identity.email, userId, identity.email]);
181
+ }
182
+ if (identity.phone) {
183
+ await sql.run(`update {users} set phone = ? where id = ? and phone is null and not exists (select 1 from {users} u where u.phone = ?)`, [identity.phone, userId, identity.phone]);
184
+ }
185
+ return { ok: true, user: (await getUser(sql, userId)) };
186
+ }
187
+ /**
188
+ * The account's address becomes `email` (already proven by a code): the email sign-in moves with it, and a
189
+ * password keeps working with the new address.
190
+ */
191
+ export async function changeEmail(sql, userId, email, now = Date.now()) {
192
+ const user = await getUser(sql, userId);
193
+ if (!user)
194
+ return { ok: false, reason: "not_found" };
195
+ if (user.email === email)
196
+ return { ok: true, user };
197
+ const [taken] = await sql.all(`select id from {users} where email = ? and id <> ?
198
+ union select user_id as id from {identities} where provider = 'email' and subject = ? and user_id <> ?`, [email, userId, email, userId]);
199
+ if (taken)
200
+ return { ok: false, reason: "identity_in_use" };
201
+ const statements = [];
202
+ if (user.email)
203
+ statements.push([`delete from {identities} where user_id = ? and provider = 'email' and subject = ?`, [userId, user.email]]);
204
+ statements.push([
205
+ `insert into {identities} (id, user_id, provider, subject, email, created_at, last_used_at) values (?, ?, 'email', ?, ?, ?, ?)
206
+ on conflict (provider, subject) do nothing`,
207
+ [crypto.randomUUID(), userId, email, email, now, now],
208
+ ], [`update {users} set email = ?, is_guest = 0, updated_at = ? where id = ?`, [email, now, userId]]);
209
+ try {
210
+ await sql.batch(statements);
211
+ }
212
+ catch (e) {
213
+ if (/unique|constraint|duplicate/i.test(String(e?.message)))
214
+ return { ok: false, reason: "identity_in_use" };
215
+ throw e;
216
+ }
217
+ return { ok: true, user: (await getUser(sql, userId)) };
218
+ }
219
+ /** How many ways in a user has: identities, passkeys, and a password while they have an address to use it with. */
220
+ export async function waysIn(sql, userId) {
221
+ const [i] = await sql.all(`select count(*) as n from {identities} where user_id = ?`, [userId]);
222
+ const [p] = await sql.all(`select count(*) as n from {passkeys} where user_id = ?`, [userId]);
223
+ const [u] = await sql.all(`select email, password_hash, (select count(*) from {identities} e where e.user_id = u.id and e.provider = 'email') as addresses from {users} u where id = ?`, [userId]);
224
+ return { identities: num(i?.n), passkeys: num(p?.n), password: (!!u?.email || num(u?.addresses) > 0) && provenPassword(u?.password_hash ?? null) };
225
+ }
226
+ /**
227
+ * The statement every removal of a way in starts with: the user's row, locked until the removal commits (Postgres),
228
+ * so two removals at once take turns and the second sees what the first left. SQLite and D1 run one batch at a time.
229
+ */
230
+ const LOCK = `update {users} set updated_at = updated_at where id = ?`;
231
+ /** A password that has worked here (PBKDF2), with an address to use it with: one way in, as SQL on `u`. */
232
+ const PASSWORD_WAY = (except) => `u.password_hash like '$pbkdf2-%' and (${except} or exists (select 1 from {identities} e where e.user_id = u.id and e.provider = 'email' and e.id <> ?))`;
233
+ /** Removes a passkey of the user unless it is their last way in, in one statement after the lock. */
234
+ export async function removePasskey(sql, userId, id) {
235
+ const [mine] = await sql.all(`select id from {passkeys} where id = ? and user_id = ?`, [id, userId]);
236
+ if (!mine)
237
+ return { ok: false, reason: "not_found" };
238
+ await sql.batch([
239
+ [LOCK, [userId]],
240
+ [
241
+ `delete from {passkeys} where id = ? and user_id = ? and (
242
+ (select count(*) from {identities} i where i.user_id = ?)
243
+ + (select count(*) from {passkeys} o where o.user_id = ? and o.id <> ?)
244
+ + (select count(*) from {users} u where u.id = ? and ${PASSWORD_WAY("u.email is not null")})
245
+ ) >= 1`,
246
+ [id, userId, userId, userId, id, userId, ""],
247
+ ],
248
+ ]);
249
+ const [still] = await sql.all(`select id from {passkeys} where id = ?`, [id]);
250
+ return still ? { ok: false, reason: "last_way_in" } : { ok: true };
251
+ }
252
+ /** Removes the user's password unless it is their last way in, in one statement after the lock. */
253
+ export async function removePasswordHash(sql, userId, now = Date.now()) {
254
+ const [had] = await sql.all(`select password_hash from {users} where id = ?`, [userId]);
255
+ if (!had?.password_hash)
256
+ return { ok: false, reason: "not_found" };
257
+ await sql.batch([
258
+ [LOCK, [userId]],
259
+ [
260
+ `update {users} set password_hash = null, updated_at = ? where id = ? and password_hash is not null and (
261
+ (select count(*) from {identities} i where i.user_id = ?) + (select count(*) from {passkeys} p where p.user_id = ?)
262
+ ) >= 1`,
263
+ [now, userId, userId, userId],
264
+ ],
265
+ ]);
266
+ const [u] = await sql.all(`select password_hash from {users} where id = ?`, [userId]);
267
+ return u?.password_hash ? { ok: false, reason: "last_way_in" } : { ok: true };
268
+ }
269
+ /**
270
+ * Removes one of the user's identities, unless it is their last way in. Removing the address the account goes by
271
+ * clears it (and with it the password's use, which needs an address).
272
+ */
273
+ export async function unlinkIdentity(sql, userId, identityId) {
274
+ const [row] = await sql.all(`select provider, subject, data from {identities} where id = ? and user_id = ?`, [identityId, userId]);
275
+ if (!row)
276
+ return { ok: false, reason: "not_found" };
277
+ const now = Date.now();
278
+ // One statement decides, after the lock: what's left (the other identities, the passkeys, a password with an
279
+ // address still to use it with) must be one way in at least. Two removals at once can't both pass.
280
+ await sql.batch([
281
+ [LOCK, [userId]],
282
+ [
283
+ `delete from {identities} where id = ? and user_id = ? and (
284
+ (select count(*) from {identities} o where o.user_id = ? and o.id <> ?)
285
+ + (select count(*) from {passkeys} p where p.user_id = ?)
286
+ + (select count(*) from {users} u where u.id = ? and ${PASSWORD_WAY("(u.email is not null and not (? = 'email' and u.email = ?))")})
287
+ ) >= 1`,
288
+ [identityId, userId, userId, identityId, userId, userId, row.provider, row.subject, identityId],
289
+ ],
290
+ // The address or number the account went by goes with it.
291
+ [
292
+ `update {users} set email = null, updated_at = ? where id = ? and ? = 'email' and email = ? and not exists (select 1 from {identities} where id = ?)`,
293
+ [now, userId, row.provider, row.subject, identityId],
294
+ ],
295
+ [
296
+ `update {users} set phone = null, updated_at = ? where id = ? and ? = 'phone' and phone = ? and not exists (select 1 from {identities} where id = ?)`,
297
+ [now, userId, row.provider, row.subject, identityId],
298
+ ],
299
+ ]);
300
+ const [still] = await sql.all(`select id from {identities} where id = ?`, [identityId]);
301
+ if (still)
302
+ return { ok: false, reason: "last_way_in" };
303
+ return { ok: true, removed: { provider: row.provider, subject: row.subject, data: row.data ? JSON.parse(row.data) : null } };
304
+ }
305
+ /** Guests nobody has used for `days` (a moved guest whose claim still waits isn't): their ids, for deleting (oldest first, at most `limit`). */
306
+ export async function staleGuests(sql, days, now = Date.now(), limit = 500) {
307
+ const cutoff = now - days * 86_400_000;
308
+ const rows = await sql.all(`select u.id from {users} u
309
+ where u.is_guest = 1 and coalesce(u.last_sign_in_at, u.created_at) < ?
310
+ and not exists (select 1 from {sessions} s where s.user_id = u.id and s.refreshed_at >= ?)
311
+ and not exists (select 1 from {guest_claims} g where g.user_id = u.id and g.expires_at > ?)
312
+ order by u.created_at limit ?`, [cutoff, cutoff, now, limit]);
313
+ return rows.map((r) => r.id);
314
+ }
package/dist/apps.d.ts ADDED
@@ -0,0 +1,85 @@
1
+ /**
2
+ * `direct-auth app`: the apps under the folder it runs in, and the client added to each one checked. Its own command,
3
+ * not a step of `init`: init runs where the server is, and the apps are most often in folders (repositories) of their
4
+ * own. It needs no keys, only the server's URL (the issuer) and, for passkeys, the domain.
5
+ *
6
+ * Only what can't go wrong is done here, and only when it isn't there yet, so running it again changes nothing: the
7
+ * npm package added to a web app's package.json, JitPack and the dependency added to Gradle, the Swift package added
8
+ * to a Package.swift. The rest (the code that signs in, a pbxproj that Xcode owns, the capabilities, the files a
9
+ * domain serves for passkeys) comes out as steps to follow, with the URL and the domain already in them.
10
+ *
11
+ * The edits are text, not a parser: each finds the block it adds to, and when it can't tell where that is it leaves
12
+ * the file alone and says what to add instead.
13
+ */
14
+ import { type InitIO } from "./init.ts";
15
+ export type AppKind = "web" | "android" | "apple";
16
+ export interface App {
17
+ kind: AppKind;
18
+ /** The project's folder, relative to where it runs ("." for that one). */
19
+ dir: string;
20
+ /** What gave it away: "package.json (vite)", "settings.gradle.kts", "Package.swift", "Acme.xcodeproj". */
21
+ via: string;
22
+ }
23
+ export interface AppSetup {
24
+ /** The folder it runs in: `dir`s are relative to it, and so are the paths reported. */
25
+ root: string;
26
+ /** The clients' version: the npm range, the JitPack tag (vX.Y.Z) and the Swift package's lowest version. */
27
+ version: string;
28
+ /** The issuer (…/auth); the snippets keep a placeholder without it. */
29
+ serverUrl?: string;
30
+ /** The passkeys' domain; a placeholder without it. */
31
+ rpId?: string;
32
+ }
33
+ export interface AppResult {
34
+ changed: string[];
35
+ /** Files that already had what this adds. */
36
+ unchanged: string[];
37
+ /** What is left to do by hand, as lines to print. */
38
+ steps: string[];
39
+ }
40
+ export declare const REPO = "https://github.com/guillecura/direct-auth";
41
+ export declare const PLACEHOLDER_URL = "https://api.example.com/auth";
42
+ /**
43
+ * The clients' version: the Android client's (clients/android/gradle.properties, what the tags follow) when it is
44
+ * there, this package's otherwise. One folder up from src/ and dist/ alike.
45
+ */
46
+ export declare const VERSION: string;
47
+ /** The apps under `root`, at most three folders down: web, Android and Apple projects, by the files they all have. */
48
+ export declare function findApps(root: string, depth?: number): App[];
49
+ /** What `kind` is called on a screen. */
50
+ export declare const KIND_LABEL: Record<AppKind, string>;
51
+ /** The client added to one app: the files changed, and the steps left. */
52
+ export declare function addToApp(app: App, o: AppSetup): AppResult;
53
+ /** `direct-auth` added to package.json's dependencies, in order, the file's indent kept; as it was when it has it, undefined when it isn't JSON. */
54
+ export declare function addNpmDependency(text: string, version: string): string | undefined;
55
+ /** JitPack added to the repositories block; undefined when there is none this can find, the text as it was when it has it. */
56
+ export declare function addJitpack(text: string, kts: boolean): string | undefined;
57
+ /** The dependency added at the end of the top-level dependencies block (one made when there is none); as it was when it has it. */
58
+ export declare function addGradleDependency(text: string, notation: string): string;
59
+ /** The catalog's alias for direct-auth, when it has one. */
60
+ export declare function catalogAlias(toml: string): string | undefined;
61
+ /** `direct-auth` added to the version catalog: its version under [versions], the library under [libraries]. */
62
+ export declare function addToCatalog(toml: string, tag: string): string;
63
+ /**
64
+ * The package added to Package(…)'s own `dependencies:` (not a target's), made before `targets:` when there is none;
65
+ * as it was when it has it; undefined when Package( can't be found.
66
+ */
67
+ export declare function addSwiftPackage(text: string, version: string): string | undefined;
68
+ export interface AppIO extends Pick<InitIO, "ask" | "say"> {
69
+ /** The apps to add the client to, on a checklist; without it, a yes or no for each. */
70
+ apps?(found: App[]): Promise<App[]>;
71
+ /** Before the questions about the apps chosen: where a wizard clears its screen and heads it. */
72
+ chosen?(apps: App[]): void;
73
+ /** Before each app's changes and steps. */
74
+ section?(app: App): void;
75
+ }
76
+ export interface AppOptions {
77
+ cwd: string;
78
+ /** `--url`: the issuer; otherwise the env file's DIRECT_AUTH_ISSUER, or asked. */
79
+ url?: string;
80
+ /** Where to look for the issuer and the passkeys' domain: `.env` unless told. */
81
+ envFile?: string;
82
+ /** The clients' version; `VERSION` unless told (a test). */
83
+ version?: string;
84
+ }
85
+ export declare function app(io: AppIO, o: AppOptions): Promise<number>;