@soroi/auth 0.0.0-stage → 0.1.1

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 (52) hide show
  1. package/AGENTS.md +154 -0
  2. package/LICENSE +21 -0
  3. package/README.md +26 -2
  4. package/dist/account.d.ts +52 -0
  5. package/dist/account.js +177 -0
  6. package/dist/adapters/next.d.ts +6 -0
  7. package/dist/adapters/next.js +35 -0
  8. package/dist/adapters/tanstack.d.ts +12 -0
  9. package/dist/adapters/tanstack.js +40 -0
  10. package/dist/cli.d.ts +2 -0
  11. package/dist/cli.js +76 -0
  12. package/dist/core.d.ts +122 -0
  13. package/dist/core.js +351 -0
  14. package/dist/crypto.d.ts +12 -0
  15. package/dist/crypto.js +69 -0
  16. package/dist/db.d.ts +29 -0
  17. package/dist/db.js +55 -0
  18. package/dist/email.d.ts +9 -0
  19. package/dist/email.js +64 -0
  20. package/dist/errors.d.ts +24 -0
  21. package/dist/errors.js +88 -0
  22. package/dist/index.d.ts +202 -0
  23. package/dist/index.js +255 -0
  24. package/dist/methods.d.ts +16 -0
  25. package/dist/methods.js +21 -0
  26. package/dist/migrations.d.ts +5 -0
  27. package/dist/migrations.js +154 -0
  28. package/dist/modules/oauth-server.d.ts +110 -0
  29. package/dist/modules/oauth-server.js +568 -0
  30. package/dist/modules/tokens.d.ts +31 -0
  31. package/dist/modules/tokens.js +107 -0
  32. package/dist/modules/two-factor.d.ts +41 -0
  33. package/dist/modules/two-factor.js +169 -0
  34. package/dist/modules/workspaces.d.ts +140 -0
  35. package/dist/modules/workspaces.js +297 -0
  36. package/dist/oauth/flow.d.ts +5 -0
  37. package/dist/oauth/flow.js +161 -0
  38. package/dist/oauth/providers.d.ts +29 -0
  39. package/dist/oauth/providers.js +124 -0
  40. package/dist/password-hash.d.ts +8 -0
  41. package/dist/password-hash.js +68 -0
  42. package/dist/password.d.ts +49 -0
  43. package/dist/password.js +181 -0
  44. package/dist/routes.d.ts +5 -0
  45. package/dist/routes.js +77 -0
  46. package/dist/sessions.d.ts +51 -0
  47. package/dist/sessions.js +184 -0
  48. package/dist/testing.d.ts +15 -0
  49. package/dist/testing.js +32 -0
  50. package/dist/types.d.ts +184 -0
  51. package/dist/types.js +1 -0
  52. package/package.json +75 -4
@@ -0,0 +1,297 @@
1
+ import { assertSameOrigin, limit, link, normalizeEmail, requireEmail, validEmail } from "../core.js";
2
+ import { randomToken, sha256 } from "../crypto.js";
3
+ import { AuthException } from "../errors.js";
4
+ import { requireSession } from "../sessions.js";
5
+ const INVITE_SECONDS = 7 * 24 * 3600;
6
+ const isUuid = (value) => typeof value === "string" && /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(value);
7
+ function guard(core) {
8
+ if (!core.modules.workspaces)
9
+ throw new AuthException("method_disabled");
10
+ }
11
+ const rank = (core, role) => {
12
+ const index = core.roles.indexOf(role);
13
+ return index === -1 ? Number.POSITIVE_INFINITY : index;
14
+ };
15
+ /** True when `role` is `min` or higher. Roles are listed highest first. */
16
+ export const atLeast = (core, role, min) => rank(core, role) <= rank(core, min);
17
+ function checkRole(core, role) {
18
+ if (typeof role !== "string" || !core.roles.includes(role))
19
+ throw new AuthException("invalid_input");
20
+ return role;
21
+ }
22
+ function checkName(name) {
23
+ if (typeof name !== "string" || !name.trim() || name.length > 200)
24
+ throw new AuthException("invalid_input");
25
+ return name.trim();
26
+ }
27
+ const toWorkspace = (row) => ({
28
+ id: row.id,
29
+ name: row.name,
30
+ createdAt: new Date(row.created_at),
31
+ });
32
+ async function membership(core, userId, workspaceId) {
33
+ if (!isUuid(workspaceId))
34
+ return null;
35
+ const [row] = await core.db.query(`select w.id::text, w.name, w.created_at, m.role from ${core.s}.members m
36
+ join ${core.s}.workspaces w on w.id = m.workspace_id
37
+ where m.user_id = $1::uuid and m.workspace_id = $2::uuid`, [userId, workspaceId]);
38
+ return row ? { workspace: toWorkspace(row), role: row.role } : null;
39
+ }
40
+ /**
41
+ * The workspace to act on: the given one, or the session's active one.
42
+ * `write` refuses API tokens. A token tied to a workspace cannot reach any other workspace.
43
+ */
44
+ async function resolve(core, ctx, workspaceId, min, write = false) {
45
+ guard(core);
46
+ const current = await requireSession(core, ctx, { browser: write });
47
+ const target = workspaceId ?? current.session.workspaceId;
48
+ const bound = current.session.method === "token" ? current.session.workspaceId : null;
49
+ if (bound && target !== bound)
50
+ throw new AuthException(workspaceId ? "not_found" : "forbidden");
51
+ const member = await membership(core, current.user.id, target);
52
+ if (!member)
53
+ throw new AuthException(workspaceId ? "not_found" : "forbidden");
54
+ if (min && !atLeast(core, member.role, min))
55
+ throw new AuthException("forbidden");
56
+ return { ...current, ...member };
57
+ }
58
+ export async function current(core, ctx) {
59
+ guard(core);
60
+ const { user, session } = await requireSession(core, ctx);
61
+ return membership(core, user.id, session.workspaceId);
62
+ }
63
+ /** Use in loaders and server functions. Throws `not_signed_in` or `forbidden`. */
64
+ export async function requireMember(core, ctx, options = {}) {
65
+ if (options.role)
66
+ checkRole(core, options.role);
67
+ const { user, session, workspace, role } = await resolve(core, ctx, options.workspaceId, options.role);
68
+ return { user, session, workspace, role };
69
+ }
70
+ export async function list(core, ctx) {
71
+ guard(core);
72
+ const { user, session } = await requireSession(core, ctx);
73
+ const bound = session.method === "token" ? session.workspaceId : null;
74
+ const rows = await core.db.query(`select w.id::text, w.name, w.created_at, m.role from ${core.s}.members m
75
+ join ${core.s}.workspaces w on w.id = m.workspace_id
76
+ where m.user_id = $1::uuid and ($2::uuid is null or w.id = $2::uuid) order by w.created_at`, [user.id, bound]);
77
+ return rows.map((row) => ({ workspace: toWorkspace(row), role: row.role }));
78
+ }
79
+ /** Makes the creator the owner and switches the session to the new workspace. */
80
+ export async function create(core, ctx, input) {
81
+ guard(core);
82
+ assertSameOrigin(core, ctx);
83
+ const { user, session } = await requireSession(core, ctx, { browser: true });
84
+ const name = checkName(input?.name);
85
+ await limit(core, `workspace-create:${user.id}`, 20, 3600);
86
+ const workspace = await core.db.transaction(async (tx) => {
87
+ const [row] = await tx.query(`insert into ${core.s}.workspaces (name) values ($1) returning id::text, name, created_at`, [name]);
88
+ await tx.query(`insert into ${core.s}.members (workspace_id, user_id, role) values ($1::uuid, $2::uuid, $3)`, [
89
+ row.id,
90
+ user.id,
91
+ core.roles[0],
92
+ ]);
93
+ if (session.method !== "token") {
94
+ await tx.query(`update ${core.s}.sessions set workspace_id = $2::uuid where id = $1`, [session.id, row.id]);
95
+ }
96
+ return toWorkspace(row);
97
+ });
98
+ session.workspaceId = workspace.id;
99
+ return { ok: true, workspace };
100
+ }
101
+ export async function switchTo(core, ctx, input) {
102
+ guard(core);
103
+ assertSameOrigin(core, ctx);
104
+ const { user, session } = await requireSession(core, ctx, { browser: true });
105
+ const member = await membership(core, user.id, input?.workspaceId);
106
+ if (!member)
107
+ throw new AuthException("not_found");
108
+ if (session.method === "token")
109
+ throw new AuthException("forbidden");
110
+ await core.db.query(`update ${core.s}.sessions set workspace_id = $2::uuid where id = $1`, [session.id, member.workspace.id]);
111
+ session.workspaceId = member.workspace.id;
112
+ return { ok: true, ...member };
113
+ }
114
+ export async function rename(core, ctx, input) {
115
+ assertSameOrigin(core, ctx);
116
+ const { workspace } = await resolve(core, ctx, input?.workspaceId, core.manageRole, true);
117
+ const name = checkName(input?.name);
118
+ await core.db.query(`update ${core.s}.workspaces set name = $2 where id = $1::uuid`, [workspace.id, name]);
119
+ return { ok: true, workspace: { ...workspace, name } };
120
+ }
121
+ export async function remove(core, ctx, input = {}) {
122
+ assertSameOrigin(core, ctx);
123
+ const { workspace } = await resolve(core, ctx, input?.workspaceId, core.roles[0], true);
124
+ await core.db.query(`delete from ${core.s}.workspaces where id = $1::uuid`, [workspace.id]);
125
+ return { ok: true };
126
+ }
127
+ export async function members(core, ctx, input = {}) {
128
+ const { workspace } = await resolve(core, ctx, input?.workspaceId);
129
+ // Soroi Account adds the color column. to_jsonb reads it, and gives null where it does not exist.
130
+ const rows = await core.db.query(`select u.id::text, u.email, u.name, u.image, m.role, m.created_at, to_jsonb(m)->>'color' as color from ${core.s}.members m
131
+ join ${core.s}.users u on u.id = m.user_id where m.workspace_id = $1::uuid order by m.created_at`, [workspace.id]);
132
+ return rows
133
+ .map((row) => ({
134
+ user: { id: row.id, email: row.email, name: row.name, image: row.image },
135
+ role: row.role,
136
+ joinedAt: new Date(row.created_at),
137
+ color: row.color,
138
+ }))
139
+ .sort((a, b) => rank(core, a.role) - rank(core, b.role));
140
+ }
141
+ /** Admins and up can invite. Nobody can invite someone above their own role, or as owner. */
142
+ export async function invite(core, ctx, input) {
143
+ assertSameOrigin(core, ctx);
144
+ const { user, workspace, role: myRole } = await resolve(core, ctx, input?.workspaceId, core.manageRole, true);
145
+ if (!user.emailVerified)
146
+ throw new AuthException("email_not_verified");
147
+ requireEmail(core);
148
+ const role = checkRole(core, input?.role);
149
+ if (role === core.roles[0] || !atLeast(core, myRole, role))
150
+ throw new AuthException("forbidden");
151
+ if (typeof input?.email !== "string")
152
+ throw new AuthException("invalid_input");
153
+ const email = normalizeEmail(input.email);
154
+ if (!validEmail(email))
155
+ throw new AuthException("invalid_email");
156
+ await limit(core, `invite:${user.id}`, 50, 3600);
157
+ await limit(core, `invite-workspace:${workspace.id}`, 100, 86_400);
158
+ const [already] = await core.db.query(`select 1 from ${core.s}.members m join ${core.s}.users u on u.id = m.user_id where m.workspace_id = $1::uuid and u.email = $2`, [workspace.id, email]);
159
+ if (already)
160
+ throw new AuthException("already_member");
161
+ const token = randomToken();
162
+ await core.db.query(`insert into ${core.s}.invites (id, workspace_id, email, role, invited_by, expires_at)
163
+ values ($1, $2::uuid, $3, $4, $5::uuid, now() + make_interval(secs => $6::int))
164
+ on conflict (workspace_id, email) do update set id = excluded.id, role = excluded.role,
165
+ invited_by = excluded.invited_by, expires_at = excluded.expires_at, created_at = now()`, [sha256(token), workspace.id, email, role, user.id, INVITE_SECONDS]);
166
+ await core.sendEmail("invite", email, {
167
+ appName: core.appName,
168
+ url: link(core, core.pages.acceptInvite, { token }),
169
+ email,
170
+ name: null,
171
+ workspace: workspace.name,
172
+ invitedBy: user.name ?? user.email,
173
+ role,
174
+ });
175
+ return { ok: true };
176
+ }
177
+ export async function invites(core, ctx, input = {}) {
178
+ const { workspace } = await resolve(core, ctx, input?.workspaceId, core.manageRole);
179
+ const rows = await core.db.query(`select email, role, expires_at, created_at from ${core.s}.invites
180
+ where workspace_id = $1::uuid and expires_at > now() order by created_at`, [workspace.id]);
181
+ return rows.map((row) => ({ email: row.email, role: row.role, expiresAt: new Date(row.expires_at), createdAt: new Date(row.created_at) }));
182
+ }
183
+ export async function revokeInvite(core, ctx, input) {
184
+ assertSameOrigin(core, ctx);
185
+ const { workspace } = await resolve(core, ctx, input?.workspaceId, core.manageRole, true);
186
+ await core.db.query(`delete from ${core.s}.invites where workspace_id = $1::uuid and email = $2`, [
187
+ workspace.id,
188
+ normalizeEmail(String(input?.email ?? "")),
189
+ ]);
190
+ return { ok: true };
191
+ }
192
+ /** For the invite page before sign-in: what the invite is for. Does not use it up. */
193
+ export async function inviteInfo(core, input) {
194
+ guard(core);
195
+ const [row] = await core.db.query(`select i.email, i.role, w.name as workspace, coalesce(u.name, u.email) as invited_by
196
+ from ${core.s}.invites i join ${core.s}.workspaces w on w.id = i.workspace_id
197
+ left join ${core.s}.users u on u.id = i.invited_by
198
+ where i.id = $1 and i.expires_at > now()`, [sha256(String(input?.token ?? ""))]);
199
+ if (!row)
200
+ return { ok: false, error: "link_expired" };
201
+ return { ok: true, email: row.email, role: row.role, workspace: row.workspace, invitedBy: row.invited_by };
202
+ }
203
+ /** The signed-in user's verified e-mail must match the invite. */
204
+ export async function acceptInvite(core, ctx, input) {
205
+ guard(core);
206
+ assertSameOrigin(core, ctx);
207
+ const { user, session } = await requireSession(core, ctx, { browser: true });
208
+ const result = await core.db.transaction(async (tx) => {
209
+ const [row] = await tx.query(`select workspace_id::text, email, role, expires_at < now() as expired from ${core.s}.invites where id = $1 for update`, [sha256(String(input?.token ?? ""))]);
210
+ if (!row)
211
+ throw new AuthException("invalid_token");
212
+ if (row.expired)
213
+ throw new AuthException("link_expired");
214
+ if (row.email !== user.email || !user.emailVerified)
215
+ throw new AuthException("invite_email_mismatch");
216
+ await tx.query(`insert into ${core.s}.members (workspace_id, user_id, role) values ($1::uuid, $2::uuid, $3) on conflict do nothing`, [row.workspace_id, user.id, row.role]);
217
+ await tx.query(`delete from ${core.s}.invites where id = $1`, [sha256(String(input.token))]);
218
+ await tx.query(`update ${core.s}.sessions set workspace_id = $2::uuid where id = $1`, [session.id, row.workspace_id]);
219
+ return row.workspace_id;
220
+ });
221
+ session.workspaceId = result;
222
+ const member = await membership(core, user.id, result);
223
+ return { ok: true, workspace: member.workspace, role: member.role };
224
+ }
225
+ async function targetMember(core, workspaceId, userId) {
226
+ if (!isUuid(userId))
227
+ throw new AuthException("not_found");
228
+ const [row] = await core.db.query(`select role from ${core.s}.members where workspace_id = $1::uuid and user_id = $2::uuid`, [workspaceId, userId]);
229
+ if (!row)
230
+ throw new AuthException("not_found");
231
+ return { userId, role: row.role };
232
+ }
233
+ /** Owner role changes only through `transferOwnership`. Nobody can raise someone above themselves. */
234
+ export async function setRole(core, ctx, input) {
235
+ assertSameOrigin(core, ctx);
236
+ const me = await resolve(core, ctx, input?.workspaceId, core.manageRole, true);
237
+ const role = checkRole(core, input?.role);
238
+ const target = await targetMember(core, me.workspace.id, input?.userId);
239
+ if (role === core.roles[0] || target.role === core.roles[0])
240
+ throw new AuthException("forbidden");
241
+ if (!atLeast(core, me.role, role) || !atLeast(core, me.role, target.role))
242
+ throw new AuthException("forbidden");
243
+ await core.db.query(`update ${core.s}.members set role = $3 where workspace_id = $1::uuid and user_id = $2::uuid`, [
244
+ me.workspace.id,
245
+ target.userId,
246
+ role,
247
+ ]);
248
+ return { ok: true };
249
+ }
250
+ export async function removeMember(core, ctx, input) {
251
+ assertSameOrigin(core, ctx);
252
+ const me = await resolve(core, ctx, input?.workspaceId, core.manageRole, true);
253
+ const target = await targetMember(core, me.workspace.id, input?.userId);
254
+ if (target.role === core.roles[0] || !atLeast(core, me.role, target.role))
255
+ throw new AuthException("forbidden");
256
+ await dropMember(core, me.workspace.id, target.userId);
257
+ return { ok: true };
258
+ }
259
+ async function dropMember(core, workspaceId, userId) {
260
+ await core.db.transaction(async (tx) => {
261
+ await tx.query(`delete from ${core.s}.members where workspace_id = $1::uuid and user_id = $2::uuid`, [workspaceId, userId]);
262
+ await tx.query(`update ${core.s}.sessions set workspace_id = null where user_id = $1::uuid and workspace_id = $2::uuid`, [
263
+ userId,
264
+ workspaceId,
265
+ ]);
266
+ await tx.query(`delete from ${core.s}.api_tokens where user_id = $1::uuid and workspace_id = $2::uuid`, [userId, workspaceId]);
267
+ });
268
+ }
269
+ export async function leave(core, ctx, input = {}) {
270
+ assertSameOrigin(core, ctx);
271
+ const me = await resolve(core, ctx, input?.workspaceId, undefined, true);
272
+ if (me.role === core.roles[0])
273
+ throw new AuthException("owner_cannot_leave");
274
+ await dropMember(core, me.workspace.id, me.user.id);
275
+ return { ok: true };
276
+ }
277
+ /** The new owner must be a member. The old owner gets the second role. */
278
+ export async function transferOwnership(core, ctx, input) {
279
+ assertSameOrigin(core, ctx);
280
+ const me = await resolve(core, ctx, input?.workspaceId, core.roles[0], true);
281
+ const target = await targetMember(core, me.workspace.id, input?.userId);
282
+ if (target.userId === me.user.id)
283
+ return { ok: true };
284
+ await core.db.transaction(async (tx) => {
285
+ await tx.query(`update ${core.s}.members set role = $3 where workspace_id = $1::uuid and user_id = $2::uuid`, [
286
+ me.workspace.id,
287
+ target.userId,
288
+ core.roles[0],
289
+ ]);
290
+ await tx.query(`update ${core.s}.members set role = $3 where workspace_id = $1::uuid and user_id = $2::uuid`, [
291
+ me.workspace.id,
292
+ me.user.id,
293
+ core.roles[1] ?? core.roles[0],
294
+ ]);
295
+ });
296
+ return { ok: true };
297
+ }
@@ -0,0 +1,5 @@
1
+ import { type Core, type RequestContext } from "../core.js";
2
+ import type { OAuthProviderId } from "../types.js";
3
+ export declare const redirectUri: (core: Core, provider: OAuthProviderId) => string;
4
+ export declare function startOAuth(core: Core, ctx: RequestContext, provider: OAuthProviderId): Promise<Response>;
5
+ export declare function oauthCallback(core: Core, ctx: RequestContext, provider: OAuthProviderId): Promise<Response>;
@@ -0,0 +1,161 @@
1
+ import { canSignIn, canSignUp, limit, link, normalizeEmail, safeNext } from "../core.js";
2
+ import { randomToken, safeEqual, seal, sha256Base64Url, unseal } from "../crypto.js";
3
+ import { AuthException } from "../errors.js";
4
+ import { finishSignIn, getUser, insertUser, readSession, requireRecent, revokeAccess } from "../sessions.js";
5
+ import { OAuthError, providers } from "./providers.js";
6
+ const STATE_SECONDS = 600;
7
+ export const redirectUri = (core, provider) => `${core.origin}${core.basePath}/${provider}/callback`;
8
+ const redirect = (to) => new Response(null, { status: 302, headers: { location: to } });
9
+ // A failed account link goes back to the page that started it, usually the settings page.
10
+ function errorRedirect(core, error, flow) {
11
+ return redirect(link(core, flow?.link ? flow.next : core.pages.error, { error }));
12
+ }
13
+ export async function startOAuth(core, ctx, provider) {
14
+ const method = core.oauth.get(provider);
15
+ if (!method)
16
+ return errorRedirect(core, "method_disabled");
17
+ const params = ctx.url.searchParams;
18
+ const flow = {
19
+ provider,
20
+ state: randomToken(),
21
+ verifier: randomToken(48),
22
+ nonce: randomToken(),
23
+ next: safeNext(core, params.get("next"), core.pages.afterSignIn),
24
+ link: params.get("link") === "1",
25
+ expires: Date.now() + STATE_SECONDS * 1000,
26
+ };
27
+ // The flow state lives in an encrypted cookie, so the browser that started the login must finish it.
28
+ ctx.setCookie(core.cookies.oauth, seal(core.keys.state, JSON.stringify(flow)), STATE_SECONDS);
29
+ return redirect(providers[provider].authorizeUrl(method, {
30
+ redirectUri: redirectUri(core, provider),
31
+ state: flow.state,
32
+ codeChallenge: sha256Base64Url(flow.verifier),
33
+ nonce: flow.nonce,
34
+ }));
35
+ }
36
+ function readFlow(core, ctx, provider) {
37
+ const raw = ctx.cookie(core.cookies.oauth);
38
+ ctx.clearCookie(core.cookies.oauth);
39
+ if (!raw)
40
+ return null;
41
+ const json = unseal(core.keys.state, raw);
42
+ if (!json)
43
+ return null;
44
+ try {
45
+ const flow = JSON.parse(json);
46
+ if (flow.provider !== provider || flow.expires < Date.now())
47
+ return null;
48
+ return flow;
49
+ }
50
+ catch {
51
+ return null;
52
+ }
53
+ }
54
+ export async function oauthCallback(core, ctx, provider) {
55
+ const method = core.oauth.get(provider);
56
+ if (!method)
57
+ return errorRedirect(core, "method_disabled");
58
+ const params = ctx.url.searchParams;
59
+ const flow = readFlow(core, ctx, provider);
60
+ if (!flow)
61
+ return errorRedirect(core, "oauth_failed");
62
+ if (params.get("error"))
63
+ return errorRedirect(core, "oauth_denied", flow);
64
+ const state = params.get("state") ?? "";
65
+ const code = params.get("code");
66
+ if (!code || !safeEqual(state, flow.state))
67
+ return errorRedirect(core, "oauth_failed", flow);
68
+ let profile;
69
+ try {
70
+ await limit(core, `oauth:ip:${ctx.ip}`, 30, 300);
71
+ profile = await providers[provider].exchange(method, {
72
+ code,
73
+ codeVerifier: flow.verifier,
74
+ redirectUri: redirectUri(core, provider),
75
+ nonce: flow.nonce,
76
+ });
77
+ }
78
+ catch (error) {
79
+ if (error instanceof AuthException)
80
+ return errorRedirect(core, error.code, flow);
81
+ if (!(error instanceof OAuthError))
82
+ throw error;
83
+ console.warn(`[@soroi/auth] ${provider} sign-in failed: ${error.message}`);
84
+ return errorRedirect(core, "oauth_failed", flow);
85
+ }
86
+ try {
87
+ if (flow.link) {
88
+ await linkAccount(core, ctx, profile);
89
+ return redirect(flow.next);
90
+ }
91
+ const userId = await userForProfile(core, profile);
92
+ const step = await finishSignIn(core, ctx, userId, provider, flow.next, profile.email && profile.emailVerified ? normalizeEmail(profile.email) : null);
93
+ return redirect(step.redirectTo);
94
+ }
95
+ catch (error) {
96
+ if (error instanceof AuthException)
97
+ return errorRedirect(core, error.code, flow);
98
+ throw error;
99
+ }
100
+ }
101
+ async function linkAccount(core, ctx, profile) {
102
+ const current = await readSession(core, ctx);
103
+ if (!current)
104
+ throw new AuthException("not_signed_in");
105
+ // An unverified user may not own this e-mail; a linked provider would outlive a later claim by the real owner.
106
+ if (!current.user.emailVerified)
107
+ throw new AuthException("email_not_verified");
108
+ await requireRecent(core, current);
109
+ const [existing] = await core.db.query(`select user_id::text from ${core.s}.accounts where provider = $1 and provider_user_id = $2`, [profile.provider, profile.providerUserId]);
110
+ if (existing && existing.user_id !== current.user.id)
111
+ throw new AuthException("account_linked_elsewhere");
112
+ if (!existing) {
113
+ await core.db.query(`insert into ${core.s}.accounts (provider, provider_user_id, user_id, email) values ($1, $2, $3::uuid, $4)`, [profile.provider, profile.providerUserId, current.user.id, profile.email]);
114
+ const user = current.user;
115
+ const provider = profile.provider === "google" ? "Google" : "GitHub";
116
+ core.background(() => core.sendEmail("accountLinked", user.email, { appName: core.appName, email: user.email, name: user.name, provider }));
117
+ }
118
+ }
119
+ async function userForProfile(core, profile) {
120
+ const [account] = await core.db.query(`select a.user_id::text, u.email from ${core.s}.accounts a join ${core.s}.users u on u.id = a.user_id
121
+ where a.provider = $1 and a.provider_user_id = $2`, [profile.provider, profile.providerUserId]);
122
+ if (account) {
123
+ if (!(await canSignIn(core, account.email)))
124
+ throw new AuthException("access_denied");
125
+ return account.user_id;
126
+ }
127
+ if (!profile.email || !profile.emailVerified)
128
+ throw new AuthException("oauth_email_unverified");
129
+ const email = normalizeEmail(profile.email);
130
+ const existing = await getUser(core, core.db, "email", email);
131
+ if (existing) {
132
+ if (!(await canSignIn(core, email)))
133
+ throw new AuthException("access_denied");
134
+ await core.db.transaction(async (tx) => {
135
+ if (!existing.emailVerified) {
136
+ // Someone signed up with this e-mail and never confirmed it. The provider proves the real owner.
137
+ // Remove every way back in that the earlier sign-up could have set up.
138
+ await tx.query(`update ${core.s}.users set email_verified_at = now(), password_hash = null, updated_at = now() where id = $1::uuid`, [existing.id]);
139
+ await revokeAccess(core, tx, existing.id);
140
+ await tx.query(`delete from ${core.s}.email_tokens where user_id = $1::uuid`, [existing.id]);
141
+ await tx.query(`delete from ${core.s}.accounts where user_id = $1::uuid`, [existing.id]);
142
+ await tx.query(`delete from ${core.s}.two_factor where user_id = $1::uuid`, [existing.id]);
143
+ await tx.query(`delete from ${core.s}.recovery_codes where user_id = $1::uuid`, [existing.id]);
144
+ }
145
+ await tx.query(`insert into ${core.s}.accounts (provider, provider_user_id, user_id, email) values ($1, $2, $3::uuid, $4)
146
+ on conflict do nothing`, [profile.provider, profile.providerUserId, existing.id, profile.email]);
147
+ });
148
+ return existing.id;
149
+ }
150
+ if (!(await canSignUp(core, email)))
151
+ throw new AuthException("signup_closed");
152
+ const user = await insertUser(core, { email, name: profile.name, image: profile.image, verified: true }, (created, tx) => tx
153
+ .query(`insert into ${core.s}.accounts (provider, provider_user_id, user_id, email) values ($1, $2, $3::uuid, $4)`, [
154
+ profile.provider,
155
+ profile.providerUserId,
156
+ created.id,
157
+ profile.email,
158
+ ])
159
+ .then(() => undefined));
160
+ return user.id;
161
+ }
@@ -0,0 +1,29 @@
1
+ import type { OAuthMethod, OAuthProviderId } from "../types.js";
2
+ export type Profile = {
3
+ provider: OAuthProviderId;
4
+ providerUserId: string;
5
+ email: string | null;
6
+ emailVerified: boolean;
7
+ name: string | null;
8
+ image: string | null;
9
+ };
10
+ type AuthorizeInput = {
11
+ redirectUri: string;
12
+ state: string;
13
+ codeChallenge: string;
14
+ nonce: string;
15
+ };
16
+ type ExchangeInput = {
17
+ code: string;
18
+ codeVerifier: string;
19
+ redirectUri: string;
20
+ nonce: string;
21
+ };
22
+ export type Provider = {
23
+ authorizeUrl(method: OAuthMethod, input: AuthorizeInput): string;
24
+ exchange(method: OAuthMethod, input: ExchangeInput): Promise<Profile>;
25
+ };
26
+ export declare class OAuthError extends Error {
27
+ }
28
+ export declare const providers: Record<OAuthProviderId, Provider>;
29
+ export {};
@@ -0,0 +1,124 @@
1
+ export class OAuthError extends Error {
2
+ }
3
+ const GOOGLE_ISSUERS = new Set(["https://accounts.google.com", "accounts.google.com"]);
4
+ function decodeJwtPayload(jwt) {
5
+ const part = jwt.split(".")[1];
6
+ if (!part)
7
+ throw new OAuthError("id_token is not a JWT");
8
+ return JSON.parse(Buffer.from(part, "base64url").toString("utf8"));
9
+ }
10
+ async function postForm(url, body) {
11
+ const response = await fetch(url, {
12
+ method: "POST",
13
+ headers: { "content-type": "application/x-www-form-urlencoded", accept: "application/json" },
14
+ body: new URLSearchParams(body),
15
+ });
16
+ const data = (await response.json().catch(() => ({})));
17
+ if (!response.ok || data.error)
18
+ throw new OAuthError(`token endpoint: ${String(data.error ?? response.status)}`);
19
+ return data;
20
+ }
21
+ const google = {
22
+ authorizeUrl(method, { redirectUri, state, codeChallenge, nonce }) {
23
+ const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
24
+ url.search = new URLSearchParams({
25
+ client_id: method.clientId,
26
+ redirect_uri: redirectUri,
27
+ response_type: "code",
28
+ scope: ["openid", "email", "profile", ...(method.scopes ?? [])].join(" "),
29
+ state,
30
+ nonce,
31
+ code_challenge: codeChallenge,
32
+ code_challenge_method: "S256",
33
+ prompt: method.prompt ?? "select_account",
34
+ }).toString();
35
+ return url.toString();
36
+ },
37
+ async exchange(method, { code, codeVerifier, redirectUri, nonce }) {
38
+ const tokens = await postForm("https://oauth2.googleapis.com/token", {
39
+ client_id: method.clientId,
40
+ client_secret: method.clientSecret,
41
+ code,
42
+ code_verifier: codeVerifier,
43
+ grant_type: "authorization_code",
44
+ redirect_uri: redirectUri,
45
+ });
46
+ if (typeof tokens.id_token !== "string")
47
+ throw new OAuthError("no id_token");
48
+ // The token came straight from Google's token endpoint over TLS, with our client secret.
49
+ // OIDC Core 3.1.3.7 allows TLS server validation in place of the signature check here.
50
+ // The claims still need checks: they tie the token to this client and this login attempt.
51
+ const claims = decodeJwtPayload(tokens.id_token);
52
+ if (!GOOGLE_ISSUERS.has(String(claims.iss)))
53
+ throw new OAuthError("wrong issuer");
54
+ const audience = Array.isArray(claims.aud) ? claims.aud : [claims.aud];
55
+ if (!audience.includes(method.clientId))
56
+ throw new OAuthError("wrong audience");
57
+ if (typeof claims.exp !== "number" || claims.exp * 1000 < Date.now())
58
+ throw new OAuthError("expired id_token");
59
+ if (claims.nonce !== nonce)
60
+ throw new OAuthError("wrong nonce");
61
+ if (typeof claims.sub !== "string" || !claims.sub)
62
+ throw new OAuthError("no subject");
63
+ return {
64
+ provider: "google",
65
+ providerUserId: claims.sub,
66
+ email: typeof claims.email === "string" ? claims.email : null,
67
+ emailVerified: claims.email_verified === true || claims.email_verified === "true",
68
+ name: typeof claims.name === "string" ? claims.name : null,
69
+ image: typeof claims.picture === "string" ? claims.picture : null,
70
+ };
71
+ },
72
+ };
73
+ async function githubApi(path, accessToken) {
74
+ const response = await fetch(`https://api.github.com${path}`, {
75
+ headers: {
76
+ authorization: `Bearer ${accessToken}`,
77
+ accept: "application/vnd.github+json",
78
+ "user-agent": "soroi-auth",
79
+ "x-github-api-version": "2022-11-28",
80
+ },
81
+ });
82
+ if (!response.ok)
83
+ throw new OAuthError(`github ${path}: ${response.status}`);
84
+ return (await response.json());
85
+ }
86
+ const github = {
87
+ authorizeUrl(method, { redirectUri, state, codeChallenge }) {
88
+ const url = new URL("https://github.com/login/oauth/authorize");
89
+ url.search = new URLSearchParams({
90
+ client_id: method.clientId,
91
+ redirect_uri: redirectUri,
92
+ scope: ["read:user", "user:email", ...(method.scopes ?? [])].join(" "),
93
+ state,
94
+ code_challenge: codeChallenge,
95
+ code_challenge_method: "S256",
96
+ allow_signup: "true",
97
+ }).toString();
98
+ return url.toString();
99
+ },
100
+ async exchange(method, { code, codeVerifier, redirectUri }) {
101
+ const tokens = await postForm("https://github.com/login/oauth/access_token", {
102
+ client_id: method.clientId,
103
+ client_secret: method.clientSecret,
104
+ code,
105
+ code_verifier: codeVerifier,
106
+ redirect_uri: redirectUri,
107
+ });
108
+ if (typeof tokens.access_token !== "string")
109
+ throw new OAuthError("no access_token");
110
+ const user = await githubApi("/user", tokens.access_token);
111
+ const emails = await githubApi("/user/emails", tokens.access_token);
112
+ // Only the primary address counts, and only when GitHub verified it.
113
+ const primary = emails.find((entry) => entry.primary);
114
+ return {
115
+ provider: "github",
116
+ providerUserId: String(user.id),
117
+ email: primary?.email ?? null,
118
+ emailVerified: primary?.verified === true,
119
+ name: user.name ?? user.login,
120
+ image: user.avatar_url,
121
+ };
122
+ },
123
+ };
124
+ export const providers = { google, github };
@@ -0,0 +1,8 @@
1
+ export type HashRuntime = "bun" | "node" | null;
2
+ export declare const hashRuntime: HashRuntime;
3
+ export declare function assertHashRuntime(): void;
4
+ export declare function hashPassword(password: string): Promise<string>;
5
+ export declare function verifyPassword(hash: string, password: string): Promise<boolean>;
6
+ export declare function needsRehash(hash: string): boolean;
7
+ /** Runs a full verify for unknown e-mails, so the response time does not show whether an account exists. */
8
+ export declare function burnVerifyTime(password: string): Promise<void>;