@soroi/auth 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/AGENTS.md +154 -0
- package/LICENSE +21 -0
- package/README.md +26 -2
- package/dist/account.d.ts +52 -0
- package/dist/account.js +177 -0
- package/dist/adapters/next.d.ts +6 -0
- package/dist/adapters/next.js +35 -0
- package/dist/adapters/tanstack.d.ts +12 -0
- package/dist/adapters/tanstack.js +40 -0
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +76 -0
- package/dist/core.d.ts +122 -0
- package/dist/core.js +351 -0
- package/dist/crypto.d.ts +12 -0
- package/dist/crypto.js +69 -0
- package/dist/db.d.ts +29 -0
- package/dist/db.js +55 -0
- package/dist/email.d.ts +9 -0
- package/dist/email.js +64 -0
- package/dist/errors.d.ts +24 -0
- package/dist/errors.js +88 -0
- package/dist/index.d.ts +202 -0
- package/dist/index.js +255 -0
- package/dist/methods.d.ts +16 -0
- package/dist/methods.js +21 -0
- package/dist/migrations.d.ts +5 -0
- package/dist/migrations.js +147 -0
- package/dist/modules/oauth-server.d.ts +110 -0
- package/dist/modules/oauth-server.js +568 -0
- package/dist/modules/tokens.d.ts +31 -0
- package/dist/modules/tokens.js +107 -0
- package/dist/modules/two-factor.d.ts +41 -0
- package/dist/modules/two-factor.js +169 -0
- package/dist/modules/workspaces.d.ts +138 -0
- package/dist/modules/workspaces.js +295 -0
- package/dist/oauth/flow.d.ts +5 -0
- package/dist/oauth/flow.js +161 -0
- package/dist/oauth/providers.d.ts +29 -0
- package/dist/oauth/providers.js +124 -0
- package/dist/password-hash.d.ts +8 -0
- package/dist/password-hash.js +68 -0
- package/dist/password.d.ts +49 -0
- package/dist/password.js +181 -0
- package/dist/routes.d.ts +5 -0
- package/dist/routes.js +77 -0
- package/dist/sessions.d.ts +51 -0
- package/dist/sessions.js +184 -0
- package/dist/testing.d.ts +15 -0
- package/dist/testing.js +32 -0
- package/dist/types.d.ts +184 -0
- package/dist/types.js +1 -0
- package/package.json +75 -4
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import * as nodeCrypto from "node:crypto";
|
|
2
|
+
import { AuthConfigError } from "./errors.js";
|
|
3
|
+
// OWASP minimum for argon2id: 19 MiB memory, 2 passes, 1 lane.
|
|
4
|
+
const MEMORY_KIB = 19456;
|
|
5
|
+
const PASSES = 2;
|
|
6
|
+
const PARALLELISM = 1;
|
|
7
|
+
const TAG_LENGTH = 32;
|
|
8
|
+
const bun = globalThis.Bun;
|
|
9
|
+
const nodeArgon2 = nodeCrypto.argon2;
|
|
10
|
+
export const hashRuntime = bun?.password ? "bun" : nodeArgon2 ? "node" : null;
|
|
11
|
+
export function assertHashRuntime() {
|
|
12
|
+
if (!hashRuntime) {
|
|
13
|
+
throw new AuthConfigError(`password hashing needs Bun or Node 24.7+ (argon2id is built in there). This is Node ${process.versions.node}.`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
function nodeArgon2Raw(password, salt, memory, passes, parallelism, tagLength) {
|
|
17
|
+
return new Promise((resolve, reject) => nodeArgon2("argon2id", { message: password, nonce: salt, parallelism, tagLength, memory, passes }, (error, key) => (error ? reject(error) : resolve(key))));
|
|
18
|
+
}
|
|
19
|
+
const b64 = (buffer) => buffer.toString("base64").replace(/=+$/, "");
|
|
20
|
+
export async function hashPassword(password) {
|
|
21
|
+
assertHashRuntime();
|
|
22
|
+
if (hashRuntime === "bun") {
|
|
23
|
+
return bun.password.hash(password, { algorithm: "argon2id", memoryCost: MEMORY_KIB, timeCost: PASSES });
|
|
24
|
+
}
|
|
25
|
+
const salt = nodeCrypto.randomBytes(16);
|
|
26
|
+
const key = await nodeArgon2Raw(password, salt, MEMORY_KIB, PASSES, PARALLELISM, TAG_LENGTH);
|
|
27
|
+
return `$argon2id$v=19$m=${MEMORY_KIB},t=${PASSES},p=${PARALLELISM}$${b64(salt)}$${b64(key)}`;
|
|
28
|
+
}
|
|
29
|
+
function parsePhc(hash) {
|
|
30
|
+
const match = /^\$argon2id\$v=19\$m=(\d+),t=(\d+),p=(\d+)\$([A-Za-z0-9+/]+)\$([A-Za-z0-9+/]+)$/.exec(hash);
|
|
31
|
+
if (!match)
|
|
32
|
+
return null;
|
|
33
|
+
return {
|
|
34
|
+
memory: Number(match[1]),
|
|
35
|
+
passes: Number(match[2]),
|
|
36
|
+
parallelism: Number(match[3]),
|
|
37
|
+
salt: Buffer.from(match[4], "base64"),
|
|
38
|
+
key: Buffer.from(match[5], "base64"),
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
export async function verifyPassword(hash, password) {
|
|
42
|
+
if (!hash.startsWith("$argon2"))
|
|
43
|
+
return false;
|
|
44
|
+
assertHashRuntime();
|
|
45
|
+
if (hashRuntime === "bun") {
|
|
46
|
+
try {
|
|
47
|
+
return await bun.password.verify(password, hash);
|
|
48
|
+
}
|
|
49
|
+
catch {
|
|
50
|
+
return false;
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const phc = parsePhc(hash);
|
|
54
|
+
if (!phc)
|
|
55
|
+
return false;
|
|
56
|
+
const key = await nodeArgon2Raw(password, phc.salt, phc.memory, phc.passes, phc.parallelism, phc.key.length);
|
|
57
|
+
return key.length === phc.key.length && nodeCrypto.timingSafeEqual(key, phc.key);
|
|
58
|
+
}
|
|
59
|
+
export function needsRehash(hash) {
|
|
60
|
+
const phc = parsePhc(hash);
|
|
61
|
+
return !phc || phc.memory < MEMORY_KIB || phc.passes < PASSES;
|
|
62
|
+
}
|
|
63
|
+
let dummyHash = null;
|
|
64
|
+
/** Runs a full verify for unknown e-mails, so the response time does not show whether an account exists. */
|
|
65
|
+
export async function burnVerifyTime(password) {
|
|
66
|
+
dummyHash ??= hashPassword("not-a-real-password");
|
|
67
|
+
await verifyPassword(await dummyHash, password);
|
|
68
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type Core, type RequestContext } from "./core.js";
|
|
2
|
+
import type { PasswordMethod } from "./types.js";
|
|
3
|
+
export declare function passwordMethod(core: Core): PasswordMethod;
|
|
4
|
+
export declare function checkPassword(core: Core, password: unknown): string;
|
|
5
|
+
declare function checkEmail(email: unknown): string;
|
|
6
|
+
export declare const verifyLink: (core: Core, token: string) => string;
|
|
7
|
+
/** The hash stored with a verification link. Only the browser holding the cookie gets signed in by that link. */
|
|
8
|
+
export declare const browserHash: (core: Core, value: string) => string;
|
|
9
|
+
export type SignUpInput = {
|
|
10
|
+
email: string;
|
|
11
|
+
password: string;
|
|
12
|
+
name?: string;
|
|
13
|
+
};
|
|
14
|
+
export declare function signUp(core: Core, ctx: RequestContext, input: SignUpInput): Promise<{
|
|
15
|
+
ok: true;
|
|
16
|
+
next: "verify_email";
|
|
17
|
+
} | {
|
|
18
|
+
ok: true;
|
|
19
|
+
next: "signed_in";
|
|
20
|
+
}>;
|
|
21
|
+
export type SignInInput = {
|
|
22
|
+
email: string;
|
|
23
|
+
password: string;
|
|
24
|
+
next?: string;
|
|
25
|
+
};
|
|
26
|
+
export declare function signIn(core: Core, ctx: RequestContext, input: SignInInput): Promise<{
|
|
27
|
+
ok: true;
|
|
28
|
+
next: "signed_in" | "two_factor";
|
|
29
|
+
redirectTo: string;
|
|
30
|
+
}>;
|
|
31
|
+
/** Always answers ok, and in the same time, so it does not show which e-mails have accounts. */
|
|
32
|
+
export declare function requestReset(core: Core, ctx: RequestContext, input: {
|
|
33
|
+
email: string;
|
|
34
|
+
}): Promise<{
|
|
35
|
+
ok: true;
|
|
36
|
+
}>;
|
|
37
|
+
/** Sets the new password and ends every session, API token and pending e-mail change. The user signs in again. */
|
|
38
|
+
export declare function resetPassword(core: Core, ctx: RequestContext, input: {
|
|
39
|
+
token: string;
|
|
40
|
+
password: string;
|
|
41
|
+
}): Promise<{
|
|
42
|
+
ok: true;
|
|
43
|
+
}>;
|
|
44
|
+
export declare function resendVerification(core: Core, ctx: RequestContext, input: {
|
|
45
|
+
email: string;
|
|
46
|
+
}): Promise<{
|
|
47
|
+
ok: true;
|
|
48
|
+
}>;
|
|
49
|
+
export { checkEmail };
|
package/dist/password.js
ADDED
|
@@ -0,0 +1,181 @@
|
|
|
1
|
+
import { assertSameOrigin, canSignIn, canSignUp, consumeEmailToken, hit, issueEmailToken, limit, limitIp, link, normalizeEmail, over, requireEmail, validEmail, } from "./core.js";
|
|
2
|
+
import { hmac, randomToken } from "./crypto.js";
|
|
3
|
+
import { AuthException } from "./errors.js";
|
|
4
|
+
import { burnVerifyTime, hashPassword, needsRehash, verifyPassword } from "./password-hash.js";
|
|
5
|
+
import { finishSignIn, getUser, insertUser, revokeAccess } from "./sessions.js";
|
|
6
|
+
const MAX_PASSWORD = 256;
|
|
7
|
+
const VERIFY_SECONDS = 24 * 3600;
|
|
8
|
+
const RESET_SECONDS = 3600;
|
|
9
|
+
const SIGNIN_FAILURES = 10;
|
|
10
|
+
const SIGNIN_WINDOW = 900;
|
|
11
|
+
export function passwordMethod(core) {
|
|
12
|
+
if (!core.password)
|
|
13
|
+
throw new AuthException("method_disabled");
|
|
14
|
+
return core.password;
|
|
15
|
+
}
|
|
16
|
+
export function checkPassword(core, password) {
|
|
17
|
+
const method = passwordMethod(core);
|
|
18
|
+
if (typeof password !== "string")
|
|
19
|
+
throw new AuthException("invalid_input");
|
|
20
|
+
if (password.length > MAX_PASSWORD)
|
|
21
|
+
throw new AuthException("password_too_long");
|
|
22
|
+
if (password.length < method.minLength)
|
|
23
|
+
throw new AuthException("weak_password");
|
|
24
|
+
return password;
|
|
25
|
+
}
|
|
26
|
+
function checkEmail(email) {
|
|
27
|
+
if (typeof email !== "string")
|
|
28
|
+
throw new AuthException("invalid_input");
|
|
29
|
+
const normalized = normalizeEmail(email);
|
|
30
|
+
if (!validEmail(normalized))
|
|
31
|
+
throw new AuthException("invalid_email");
|
|
32
|
+
return normalized;
|
|
33
|
+
}
|
|
34
|
+
export const verifyLink = (core, token) => link(core, `${core.basePath}/verify`, { token });
|
|
35
|
+
/** The hash stored with a verification link. Only the browser holding the cookie gets signed in by that link. */
|
|
36
|
+
export const browserHash = (core, value) => hmac(core.keys.browser, value);
|
|
37
|
+
function pendingBrowser(core, ctx) {
|
|
38
|
+
const value = ctx.cookie(core.cookies.pending) ?? randomToken();
|
|
39
|
+
ctx.setCookie(core.cookies.pending, value, VERIFY_SECONDS);
|
|
40
|
+
return browserHash(core, value);
|
|
41
|
+
}
|
|
42
|
+
/** Issues the link now and sends it in the background, so the answer time does not depend on the e-mail provider. */
|
|
43
|
+
async function sendVerification(core, user, browser) {
|
|
44
|
+
const token = await issueEmailToken(core, core.db, "verify_email", user.id, user.email, VERIFY_SECONDS, { browser });
|
|
45
|
+
core.background(() => core.sendEmail("verifyEmail", user.email, { appName: core.appName, url: verifyLink(core, token), email: user.email, name: user.name }));
|
|
46
|
+
}
|
|
47
|
+
export async function signUp(core, ctx, input) {
|
|
48
|
+
assertSameOrigin(core, ctx);
|
|
49
|
+
const method = passwordMethod(core);
|
|
50
|
+
if (method.verifyEmail)
|
|
51
|
+
requireEmail(core);
|
|
52
|
+
const email = checkEmail(input?.email);
|
|
53
|
+
const password = checkPassword(core, input?.password);
|
|
54
|
+
const name = typeof input?.name === "string" ? input.name.trim().slice(0, 200) || null : null;
|
|
55
|
+
await limitIp(core, ctx, "signup", 10, 3600);
|
|
56
|
+
if (!(await canSignUp(core, email)))
|
|
57
|
+
throw new AuthException("signup_closed");
|
|
58
|
+
const existing = await getUser(core, core.db, "email", email);
|
|
59
|
+
if (existing) {
|
|
60
|
+
if (!method.verifyEmail)
|
|
61
|
+
throw new AuthException("email_taken");
|
|
62
|
+
// With e-mail verification on, the answer looks the same for new and existing e-mails, and takes as long:
|
|
63
|
+
// the owner gets a note instead, and the hash runs anyway.
|
|
64
|
+
await hashPassword(password);
|
|
65
|
+
pendingBrowser(core, ctx);
|
|
66
|
+
if (await hit(core, `account-exists:${email}`, 3, 3600)) {
|
|
67
|
+
core.background(() => core.sendEmail("accountExists", email, { appName: core.appName, url: link(core, core.pages.signIn), email, name: existing.name }));
|
|
68
|
+
}
|
|
69
|
+
return { ok: true, next: "verify_email" };
|
|
70
|
+
}
|
|
71
|
+
const user = await insertUser(core, { email, name, passwordHash: await hashPassword(password), verified: false });
|
|
72
|
+
if (method.verifyEmail) {
|
|
73
|
+
await sendVerification(core, user, pendingBrowser(core, ctx));
|
|
74
|
+
return { ok: true, next: "verify_email" };
|
|
75
|
+
}
|
|
76
|
+
await finishSignIn(core, ctx, user.id, "password");
|
|
77
|
+
return { ok: true, next: "signed_in" };
|
|
78
|
+
}
|
|
79
|
+
export async function signIn(core, ctx, input) {
|
|
80
|
+
assertSameOrigin(core, ctx);
|
|
81
|
+
const method = passwordMethod(core);
|
|
82
|
+
const email = checkEmail(input?.email);
|
|
83
|
+
if (typeof input?.password !== "string" || input.password.length > MAX_PASSWORD) {
|
|
84
|
+
throw new AuthException("invalid_credentials");
|
|
85
|
+
}
|
|
86
|
+
await limitIp(core, ctx, "signin", 50, SIGNIN_WINDOW);
|
|
87
|
+
// Only failures count per e-mail, so the owner can still sign in while someone else guesses.
|
|
88
|
+
const failureKey = `signin-failures:${email}`;
|
|
89
|
+
if (await over(core, failureKey, SIGNIN_FAILURES, SIGNIN_WINDOW))
|
|
90
|
+
throw new AuthException("rate_limited");
|
|
91
|
+
const user = await getUser(core, core.db, "email", email);
|
|
92
|
+
let valid = false;
|
|
93
|
+
if (user?.passwordHash) {
|
|
94
|
+
valid = await verifyPassword(user.passwordHash, input.password);
|
|
95
|
+
if (!valid && method.legacyVerify && !user.passwordHash.startsWith("$argon2")) {
|
|
96
|
+
valid = await method.legacyVerify(user.passwordHash, input.password);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
else {
|
|
100
|
+
await burnVerifyTime(input.password);
|
|
101
|
+
}
|
|
102
|
+
if (!user || !valid) {
|
|
103
|
+
await hit(core, failureKey, SIGNIN_FAILURES, SIGNIN_WINDOW);
|
|
104
|
+
throw new AuthException("invalid_credentials");
|
|
105
|
+
}
|
|
106
|
+
if (needsRehash(user.passwordHash)) {
|
|
107
|
+
await core.db.query(`update ${core.s}.users set password_hash = $2, updated_at = now() where id = $1::uuid`, [
|
|
108
|
+
user.id,
|
|
109
|
+
await hashPassword(input.password),
|
|
110
|
+
]);
|
|
111
|
+
}
|
|
112
|
+
if (!(await canSignIn(core, email)))
|
|
113
|
+
throw new AuthException("access_denied");
|
|
114
|
+
if (method.verifyEmail && !user.emailVerified) {
|
|
115
|
+
requireEmail(core);
|
|
116
|
+
const browser = pendingBrowser(core, ctx);
|
|
117
|
+
if (await hit(core, `verify-resend:${email}`, 3, 3600))
|
|
118
|
+
await sendVerification(core, user, browser);
|
|
119
|
+
throw new AuthException("email_not_verified");
|
|
120
|
+
}
|
|
121
|
+
const step = await finishSignIn(core, ctx, user.id, "password", input.next);
|
|
122
|
+
return { ok: true, next: step.next, redirectTo: step.redirectTo };
|
|
123
|
+
}
|
|
124
|
+
/** Always answers ok, and in the same time, so it does not show which e-mails have accounts. */
|
|
125
|
+
export async function requestReset(core, ctx, input) {
|
|
126
|
+
assertSameOrigin(core, ctx);
|
|
127
|
+
passwordMethod(core);
|
|
128
|
+
requireEmail(core);
|
|
129
|
+
const email = checkEmail(input?.email);
|
|
130
|
+
await limitIp(core, ctx, "reset", 20, 3600);
|
|
131
|
+
core.background(async () => {
|
|
132
|
+
const user = await getUser(core, core.db, "email", email);
|
|
133
|
+
if (!user || !(await hit(core, `reset:email:${email}`, 3, 3600)))
|
|
134
|
+
return;
|
|
135
|
+
// Older links stay valid, so a stranger who asks for resets cannot cancel the owner's link.
|
|
136
|
+
const token = await issueEmailToken(core, core.db, "reset_password", user.id, email, RESET_SECONDS, { replace: false });
|
|
137
|
+
await core.sendEmail("resetPassword", email, {
|
|
138
|
+
appName: core.appName,
|
|
139
|
+
url: link(core, core.pages.resetPassword, { token }),
|
|
140
|
+
email,
|
|
141
|
+
name: user.name,
|
|
142
|
+
});
|
|
143
|
+
});
|
|
144
|
+
return { ok: true };
|
|
145
|
+
}
|
|
146
|
+
/** Sets the new password and ends every session, API token and pending e-mail change. The user signs in again. */
|
|
147
|
+
export async function resetPassword(core, ctx, input) {
|
|
148
|
+
assertSameOrigin(core, ctx);
|
|
149
|
+
const password = checkPassword(core, input?.password);
|
|
150
|
+
await limitIp(core, ctx, "reset-use", 20, 3600);
|
|
151
|
+
const hash = await hashPassword(password);
|
|
152
|
+
await core.db.transaction(async (tx) => {
|
|
153
|
+
const token = await consumeEmailToken(core, tx, ["reset_password"], String(input?.token ?? ""));
|
|
154
|
+
if (typeof token === "string")
|
|
155
|
+
throw new AuthException(token);
|
|
156
|
+
// The link reached this inbox, so the e-mail is proven too.
|
|
157
|
+
await tx.query(`update ${core.s}.users set password_hash = $2, email_verified_at = coalesce(email_verified_at, now()), updated_at = now()
|
|
158
|
+
where id = $1::uuid`, [token.userId, hash]);
|
|
159
|
+
await tx.query(`delete from ${core.s}.email_tokens where user_id = $1::uuid and kind = 'reset_password'`, [token.userId]);
|
|
160
|
+
await revokeAccess(core, tx, token.userId);
|
|
161
|
+
});
|
|
162
|
+
return { ok: true };
|
|
163
|
+
}
|
|
164
|
+
export async function resendVerification(core, ctx, input) {
|
|
165
|
+
assertSameOrigin(core, ctx);
|
|
166
|
+
passwordMethod(core);
|
|
167
|
+
requireEmail(core);
|
|
168
|
+
const email = checkEmail(input?.email);
|
|
169
|
+
await limitIp(core, ctx, "verify-resend", 20, 3600);
|
|
170
|
+
const browser = pendingBrowser(core, ctx);
|
|
171
|
+
core.background(async () => {
|
|
172
|
+
const user = await getUser(core, core.db, "email", email);
|
|
173
|
+
if (user && !user.emailVerified && (await hit(core, `verify-resend:${email}`, 3, 3600))) {
|
|
174
|
+
// Without the password, only the browser that signed up keeps its password through the link.
|
|
175
|
+
const [pending] = await core.db.query(`select browser from ${core.s}.email_tokens where user_id = $1::uuid and kind = 'verify_email'`, [user.id]);
|
|
176
|
+
await sendVerification(core, user, pending?.browser === browser ? browser : null);
|
|
177
|
+
}
|
|
178
|
+
});
|
|
179
|
+
return { ok: true };
|
|
180
|
+
}
|
|
181
|
+
export { checkEmail };
|
package/dist/routes.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type Core } from "./core.js";
|
|
2
|
+
/** Dev login works only outside production and only on local hosts, so a leaked env var cannot open production. */
|
|
3
|
+
export declare function devLoginAllowed(core: Core): boolean;
|
|
4
|
+
/** Serves `<basePath>/*`: OAuth start and callback, e-mail links, sign-out and dev login. */
|
|
5
|
+
export declare function handle(core: Core, request: Request): Promise<Response>;
|
package/dist/routes.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
import { verifyEmailLink } from "./account.js";
|
|
2
|
+
import { assertSameOrigin, createContext, link, normalizeEmail, safeNext, serializeCookie } from "./core.js";
|
|
3
|
+
import { AuthException } from "./errors.js";
|
|
4
|
+
import { oauthCallback, startOAuth } from "./oauth/flow.js";
|
|
5
|
+
import { createSession, getUser, insertUser, signOut } from "./sessions.js";
|
|
6
|
+
const redirect = (to) => new Response(null, { status: 302, headers: { location: to } });
|
|
7
|
+
const notFound = () => new Response("Not found", { status: 404 });
|
|
8
|
+
/** Dev login works only outside production and only on local hosts, so a leaked env var cannot open production. */
|
|
9
|
+
export function devLoginAllowed(core) {
|
|
10
|
+
if (!core.config.devLogin || process.env.NODE_ENV === "production")
|
|
11
|
+
return false;
|
|
12
|
+
const host = core.url.hostname;
|
|
13
|
+
return ["localhost", "127.0.0.1", "[::1]"].includes(host) || host.endsWith(".localhost") || host.endsWith(".test");
|
|
14
|
+
}
|
|
15
|
+
async function devLogin(core, ctx) {
|
|
16
|
+
if (!devLoginAllowed(core))
|
|
17
|
+
return notFound();
|
|
18
|
+
const email = normalizeEmail(core.config.devLogin);
|
|
19
|
+
const user = (await getUser(core, core.db, "email", email)) ?? (await insertUser(core, { email, verified: true }));
|
|
20
|
+
await createSession(core, ctx, user.id, "dev");
|
|
21
|
+
return redirect(safeNext(core, ctx.url.searchParams.get("next"), core.pages.afterSignIn));
|
|
22
|
+
}
|
|
23
|
+
async function route(core, ctx) {
|
|
24
|
+
const path = ctx.url.pathname;
|
|
25
|
+
if (!path.startsWith(`${core.basePath}/`))
|
|
26
|
+
return notFound();
|
|
27
|
+
const [first, second, ...rest] = path.slice(core.basePath.length + 1).split("/");
|
|
28
|
+
if (rest.length)
|
|
29
|
+
return notFound();
|
|
30
|
+
const method = ctx.request.method.toUpperCase();
|
|
31
|
+
if (method === "GET" && (first === "google" || first === "github")) {
|
|
32
|
+
const provider = first;
|
|
33
|
+
if (second === undefined)
|
|
34
|
+
return startOAuth(core, ctx, provider);
|
|
35
|
+
if (second === "callback")
|
|
36
|
+
return oauthCallback(core, ctx, provider);
|
|
37
|
+
return notFound();
|
|
38
|
+
}
|
|
39
|
+
if (second !== undefined)
|
|
40
|
+
return notFound();
|
|
41
|
+
if (method === "GET" && first === "verify") {
|
|
42
|
+
return redirect(await verifyEmailLink(core, ctx, ctx.url.searchParams.get("token") ?? ""));
|
|
43
|
+
}
|
|
44
|
+
if (method === "POST" && first === "sign-out") {
|
|
45
|
+
assertSameOrigin(core, ctx);
|
|
46
|
+
await signOut(core, ctx);
|
|
47
|
+
const wantsJson = ctx.request.headers.get("accept")?.includes("application/json");
|
|
48
|
+
return wantsJson ? new Response(null, { status: 204 }) : new Response(null, { status: 303, headers: { location: core.pages.afterSignOut } });
|
|
49
|
+
}
|
|
50
|
+
if (method === "GET" && first === "dev")
|
|
51
|
+
return devLogin(core, ctx);
|
|
52
|
+
return notFound();
|
|
53
|
+
}
|
|
54
|
+
/** Serves `<basePath>/*`: OAuth start and callback, e-mail links, sign-out and dev login. */
|
|
55
|
+
export async function handle(core, request) {
|
|
56
|
+
const cookies = [];
|
|
57
|
+
const ctx = createContext(core, request, (name, value, options) => {
|
|
58
|
+
cookies.push(serializeCookie(name, value, options));
|
|
59
|
+
});
|
|
60
|
+
let response;
|
|
61
|
+
try {
|
|
62
|
+
response = await route(core, ctx);
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
if (!(error instanceof AuthException))
|
|
66
|
+
throw error;
|
|
67
|
+
response =
|
|
68
|
+
error.code === "forbidden_origin"
|
|
69
|
+
? new Response("Forbidden", { status: 403 })
|
|
70
|
+
: redirect(link(core, core.pages.error, { error: error.code }));
|
|
71
|
+
}
|
|
72
|
+
const headers = new Headers(response.headers);
|
|
73
|
+
for (const cookie of cookies)
|
|
74
|
+
headers.append("set-cookie", cookie);
|
|
75
|
+
headers.set("cache-control", "no-store");
|
|
76
|
+
return new Response(response.body, { status: response.status, headers });
|
|
77
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import { type Core, type RequestContext, type SessionWithUser } from "./core.js";
|
|
2
|
+
import type { Db, Row } from "./db.js";
|
|
3
|
+
import type { Session, SignInMethod, User } from "./types.js";
|
|
4
|
+
export declare const userColumns: (a: string) => string;
|
|
5
|
+
export declare const toUser: (row: Row) => User;
|
|
6
|
+
export declare const toSession: (row: Row) => Session;
|
|
7
|
+
export declare function getUser(core: Core, db: Db, where: "id" | "email", value: string): Promise<(User & {
|
|
8
|
+
passwordHash: string | null;
|
|
9
|
+
}) | null>;
|
|
10
|
+
export declare function insertUser(core: Core, data: {
|
|
11
|
+
email: string;
|
|
12
|
+
name?: string | null;
|
|
13
|
+
image?: string | null;
|
|
14
|
+
passwordHash?: string | null;
|
|
15
|
+
verified: boolean;
|
|
16
|
+
}, then?: (user: User, tx: Db) => Promise<void>): Promise<User>;
|
|
17
|
+
export declare function createSession(core: Core, ctx: RequestContext, userId: string, method: SignInMethod, providerEmail?: string | null): Promise<string>;
|
|
18
|
+
export declare function readSession(core: Core, ctx: RequestContext): Promise<SessionWithUser | null>;
|
|
19
|
+
/** `browser: true` refuses API tokens, for account changes that only the person may make. */
|
|
20
|
+
export declare function requireSession(core: Core, ctx: RequestContext, options?: {
|
|
21
|
+
browser?: boolean;
|
|
22
|
+
}): Promise<SessionWithUser>;
|
|
23
|
+
export declare function signOut(core: Core, ctx: RequestContext): Promise<void>;
|
|
24
|
+
export declare function deleteUserSessions(core: Core, db: Db, userId: string, exceptId?: string): Promise<void>;
|
|
25
|
+
/**
|
|
26
|
+
* Ends every way back in that a stolen session could have left: other sessions, API tokens, OAuth connections,
|
|
27
|
+
* pending e-mail changes and two-factor steps. Used after a password reset or an admin password change.
|
|
28
|
+
*/
|
|
29
|
+
export declare function revokeAccess(core: Core, db: Db, userId: string, exceptSessionId?: string): Promise<void>;
|
|
30
|
+
/** How long a sign-in or re-authentication counts as recent. */
|
|
31
|
+
export declare const RECENT_MS: number;
|
|
32
|
+
export declare function renewRecent(core: Core, current: SessionWithUser): Promise<void>;
|
|
33
|
+
/**
|
|
34
|
+
* Sensitive changes need a recent sign-in, so a stolen session cookie alone cannot add a way back in.
|
|
35
|
+
* A user with a password can pass it instead. That also renews the window, unless two-factor is on:
|
|
36
|
+
* then only a code does, so a stolen password does not open every other sensitive change.
|
|
37
|
+
*/
|
|
38
|
+
export declare function requireRecent(core: Core, current: SessionWithUser, password?: unknown): Promise<void>;
|
|
39
|
+
export declare function twoFactorEnabled(core: Core, userId: string): Promise<boolean>;
|
|
40
|
+
export type SignInStep = {
|
|
41
|
+
next: "signed_in";
|
|
42
|
+
redirectTo: string;
|
|
43
|
+
} | {
|
|
44
|
+
next: "two_factor";
|
|
45
|
+
redirectTo: string;
|
|
46
|
+
};
|
|
47
|
+
/** Creates the session, or a two-factor challenge when the user has 2FA on. */
|
|
48
|
+
export declare function finishSignIn(core: Core, ctx: RequestContext, userId: string, method: SignInMethod, next?: string | null, providerEmail?: string | null): Promise<SignInStep>;
|
|
49
|
+
export declare function listSessions(core: Core, ctx: RequestContext): Promise<(Session & {
|
|
50
|
+
current: boolean;
|
|
51
|
+
})[]>;
|
package/dist/sessions.js
ADDED
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { hit, safeNext } from "./core.js";
|
|
2
|
+
import { verifyPassword } from "./password-hash.js";
|
|
3
|
+
import { randomToken, sha256 } from "./crypto.js";
|
|
4
|
+
import { AuthException } from "./errors.js";
|
|
5
|
+
const DAY = 86_400;
|
|
6
|
+
const CHALLENGE_SECONDS = 600;
|
|
7
|
+
export const userColumns = (a) => `${a}.id::text as u_id, ${a}.email as u_email, ${a}.email_verified_at is not null as u_verified,
|
|
8
|
+
${a}.name as u_name, ${a}.image as u_image, ${a}.password_hash is not null as u_has_password,
|
|
9
|
+
${a}.created_at as u_created_at`;
|
|
10
|
+
export const toUser = (row) => ({
|
|
11
|
+
id: String(row.u_id),
|
|
12
|
+
email: String(row.u_email),
|
|
13
|
+
emailVerified: Boolean(row.u_verified),
|
|
14
|
+
name: row.u_name ?? null,
|
|
15
|
+
image: row.u_image ?? null,
|
|
16
|
+
hasPassword: Boolean(row.u_has_password),
|
|
17
|
+
createdAt: new Date(row.u_created_at),
|
|
18
|
+
});
|
|
19
|
+
const sessionColumns = (a) => `${a}.id as s_id, ${a}.user_id::text as s_user_id, ${a}.method as s_method, ${a}.workspace_id::text as s_workspace_id,
|
|
20
|
+
${a}.ip as s_ip, ${a}.user_agent as s_user_agent, ${a}.created_at as s_created_at,
|
|
21
|
+
${a}.last_seen_at as s_last_seen_at, ${a}.expires_at as s_expires_at, ${a}.provider_email as s_provider_email`;
|
|
22
|
+
export const toSession = (row) => ({
|
|
23
|
+
id: String(row.s_id),
|
|
24
|
+
userId: String(row.s_user_id),
|
|
25
|
+
method: row.s_method,
|
|
26
|
+
workspaceId: row.s_workspace_id ?? null,
|
|
27
|
+
ip: row.s_ip ?? null,
|
|
28
|
+
userAgent: row.s_user_agent ?? null,
|
|
29
|
+
createdAt: new Date(row.s_created_at),
|
|
30
|
+
lastSeenAt: new Date(row.s_last_seen_at),
|
|
31
|
+
expiresAt: new Date(row.s_expires_at),
|
|
32
|
+
providerEmail: row.s_provider_email ?? null,
|
|
33
|
+
});
|
|
34
|
+
export async function getUser(core, db, where, value) {
|
|
35
|
+
const [row] = await db.query(`select ${userColumns("u")}, u.password_hash from ${core.s}.users u where ${where === "id" ? "u.id = $1::uuid" : "u.email = $1"}`, [value]);
|
|
36
|
+
return row ? { ...toUser(row), passwordHash: row.password_hash ?? null } : null;
|
|
37
|
+
}
|
|
38
|
+
export async function insertUser(core, data, then) {
|
|
39
|
+
return core.db.transaction(async (tx) => {
|
|
40
|
+
const [row] = await tx.query(`insert into ${core.s}.users as u (email, name, image, password_hash, email_verified_at)
|
|
41
|
+
values ($1, $2, $3, $4, case when $5::boolean then now() end)
|
|
42
|
+
returning ${userColumns("u")}`, [data.email, data.name ?? null, data.image ?? null, data.passwordHash ?? null, data.verified]);
|
|
43
|
+
const user = toUser(row);
|
|
44
|
+
await then?.(user, tx);
|
|
45
|
+
await core.config.onUserCreated?.(user, tx);
|
|
46
|
+
return user;
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
export async function createSession(core, ctx, userId, method, providerEmail = null) {
|
|
50
|
+
const token = randomToken();
|
|
51
|
+
await core.db.query(`insert into ${core.s}.sessions (id, user_id, method, workspace_id, ip, user_agent, expires_at, provider_email)
|
|
52
|
+
values ($1, $2::uuid, $3,
|
|
53
|
+
(select workspace_id from ${core.s}.members where user_id = $2::uuid order by created_at limit 1),
|
|
54
|
+
$4, $5, now() + make_interval(days => $6::int), $7)`, [sha256(token), userId, method, ctx.ip, ctx.userAgent?.slice(0, 500) ?? null, core.sessionDays, providerEmail]);
|
|
55
|
+
ctx.setCookie(core.cookies.session, token, core.sessionDays * DAY);
|
|
56
|
+
ctx.cache.session = undefined;
|
|
57
|
+
return token;
|
|
58
|
+
}
|
|
59
|
+
async function loadCookieSession(core, ctx) {
|
|
60
|
+
const token = ctx.cookie(core.cookies.session);
|
|
61
|
+
if (!token || token.length > 200)
|
|
62
|
+
return null;
|
|
63
|
+
const [row] = await core.db.query(`select ${sessionColumns("se")}, se.reauth_at as s_reauth_at, ${userColumns("u")}
|
|
64
|
+
from ${core.s}.sessions se join ${core.s}.users u on u.id = se.user_id
|
|
65
|
+
where se.id = $1 and se.expires_at > now()`, [sha256(token)]);
|
|
66
|
+
if (!row) {
|
|
67
|
+
ctx.clearCookie(core.cookies.session);
|
|
68
|
+
return null;
|
|
69
|
+
}
|
|
70
|
+
const session = toSession(row);
|
|
71
|
+
const user = toUser(row);
|
|
72
|
+
const now = Date.now();
|
|
73
|
+
// Sliding expiry: a session used on a new day gets a full new period, so only a long
|
|
74
|
+
// absence signs a person out. It writes at most once a day per session.
|
|
75
|
+
// The database moves only when the cookie moves too; where cookies cannot be set
|
|
76
|
+
// (a Next.js server component), the next action or route handler does the refresh.
|
|
77
|
+
// `withRequest` cannot know this: its caller must send `headers` with the response.
|
|
78
|
+
const periodMs = core.sessionDays * DAY * 1000;
|
|
79
|
+
const refreshAfterMs = Math.min(DAY * 1000, periodMs / 2);
|
|
80
|
+
let refreshed = false;
|
|
81
|
+
if (session.expiresAt.getTime() - now < periodMs - refreshAfterMs) {
|
|
82
|
+
if (await ctx.setCookie(core.cookies.session, token, core.sessionDays * DAY)) {
|
|
83
|
+
const [updated] = await core.db.query(`update ${core.s}.sessions set expires_at = now() + make_interval(days => $2::int), last_seen_at = now()
|
|
84
|
+
where id = $1 returning expires_at, last_seen_at`, [session.id, core.sessionDays]);
|
|
85
|
+
if (updated) {
|
|
86
|
+
session.expiresAt = new Date(updated.expires_at);
|
|
87
|
+
session.lastSeenAt = new Date(updated.last_seen_at);
|
|
88
|
+
}
|
|
89
|
+
refreshed = true;
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (!refreshed && now - session.lastSeenAt.getTime() > 5 * 60_000) {
|
|
93
|
+
await core.db.query(`update ${core.s}.sessions set last_seen_at = now() where id = $1`, [session.id]);
|
|
94
|
+
}
|
|
95
|
+
return { user, session, reauthAt: new Date(row.s_reauth_at) };
|
|
96
|
+
}
|
|
97
|
+
export function readSession(core, ctx) {
|
|
98
|
+
ctx.cache.session ??= (async () => (await loadCookieSession(core, ctx)) ?? (await core.bearer?.(core, ctx)) ?? null)();
|
|
99
|
+
return ctx.cache.session;
|
|
100
|
+
}
|
|
101
|
+
/** `browser: true` refuses API tokens, for account changes that only the person may make. */
|
|
102
|
+
export async function requireSession(core, ctx, options = {}) {
|
|
103
|
+
const current = await readSession(core, ctx);
|
|
104
|
+
if (!current)
|
|
105
|
+
throw new AuthException("not_signed_in");
|
|
106
|
+
if (options.browser && current.session.method === "token")
|
|
107
|
+
throw new AuthException("forbidden");
|
|
108
|
+
return current;
|
|
109
|
+
}
|
|
110
|
+
export async function signOut(core, ctx) {
|
|
111
|
+
const token = ctx.cookie(core.cookies.session);
|
|
112
|
+
if (token)
|
|
113
|
+
await core.db.query(`delete from ${core.s}.sessions where id = $1`, [sha256(token)]);
|
|
114
|
+
ctx.clearCookie(core.cookies.session);
|
|
115
|
+
ctx.cache.session = Promise.resolve(null);
|
|
116
|
+
}
|
|
117
|
+
export async function deleteUserSessions(core, db, userId, exceptId) {
|
|
118
|
+
await db.query(`delete from ${core.s}.sessions where user_id = $1::uuid and id <> $2`, [userId, exceptId ?? ""]);
|
|
119
|
+
}
|
|
120
|
+
/**
|
|
121
|
+
* Ends every way back in that a stolen session could have left: other sessions, API tokens, OAuth connections,
|
|
122
|
+
* pending e-mail changes and two-factor steps. Used after a password reset or an admin password change.
|
|
123
|
+
*/
|
|
124
|
+
export async function revokeAccess(core, db, userId, exceptSessionId) {
|
|
125
|
+
await deleteUserSessions(core, db, userId, exceptSessionId);
|
|
126
|
+
await db.query(`delete from ${core.s}.api_tokens where user_id = $1::uuid`, [userId]);
|
|
127
|
+
await db.query(`delete from ${core.s}.oauth_token where user_id = $1`, [userId]);
|
|
128
|
+
await db.query(`delete from ${core.s}.oauth_authorization where user_id = $1`, [userId]);
|
|
129
|
+
await db.query(`delete from ${core.s}.email_tokens where user_id = $1::uuid and kind = 'change_email'`, [userId]);
|
|
130
|
+
await db.query(`delete from ${core.s}.challenges where user_id = $1::uuid`, [userId]);
|
|
131
|
+
}
|
|
132
|
+
/** How long a sign-in or re-authentication counts as recent. */
|
|
133
|
+
export const RECENT_MS = 15 * 60_000;
|
|
134
|
+
export async function renewRecent(core, current) {
|
|
135
|
+
await core.db.query(`update ${core.s}.sessions set reauth_at = now() where id = $1`, [current.session.id]);
|
|
136
|
+
current.reauthAt = new Date();
|
|
137
|
+
}
|
|
138
|
+
/**
|
|
139
|
+
* Sensitive changes need a recent sign-in, so a stolen session cookie alone cannot add a way back in.
|
|
140
|
+
* A user with a password can pass it instead. That also renews the window, unless two-factor is on:
|
|
141
|
+
* then only a code does, so a stolen password does not open every other sensitive change.
|
|
142
|
+
*/
|
|
143
|
+
export async function requireRecent(core, current, password) {
|
|
144
|
+
if (current.session.method === "token")
|
|
145
|
+
throw new AuthException("forbidden");
|
|
146
|
+
const user = await getUser(core, core.db, "id", current.user.id);
|
|
147
|
+
if (user?.passwordHash && typeof password === "string") {
|
|
148
|
+
if (!(await hit(core, `confirm-password:${user.id}`, 10, 900)))
|
|
149
|
+
throw new AuthException("rate_limited");
|
|
150
|
+
if (!(await verifyPassword(user.passwordHash, password)))
|
|
151
|
+
throw new AuthException("invalid_credentials");
|
|
152
|
+
if (!(await twoFactorEnabled(core, user.id)))
|
|
153
|
+
await renewRecent(core, current);
|
|
154
|
+
return;
|
|
155
|
+
}
|
|
156
|
+
const at = current.reauthAt?.getTime() ?? 0;
|
|
157
|
+
if (Date.now() - at > RECENT_MS)
|
|
158
|
+
throw new AuthException("reauth_required");
|
|
159
|
+
}
|
|
160
|
+
export async function twoFactorEnabled(core, userId) {
|
|
161
|
+
if (!core.modules.twoFactor)
|
|
162
|
+
return false;
|
|
163
|
+
const [row] = await core.db.query(`select 1 from ${core.s}.two_factor where user_id = $1::uuid and enabled_at is not null`, [userId]);
|
|
164
|
+
return !!row;
|
|
165
|
+
}
|
|
166
|
+
/** Creates the session, or a two-factor challenge when the user has 2FA on. */
|
|
167
|
+
export async function finishSignIn(core, ctx, userId, method, next, providerEmail = null) {
|
|
168
|
+
const target = safeNext(core, next, core.pages.afterSignIn);
|
|
169
|
+
if (await twoFactorEnabled(core, userId)) {
|
|
170
|
+
const challenge = randomToken();
|
|
171
|
+
await core.db.query(`insert into ${core.s}.challenges (id, user_id, method, next, expires_at, provider_email)
|
|
172
|
+
values ($1, $2::uuid, $3, $4, now() + make_interval(secs => $5::int), $6)`, [sha256(challenge), userId, method, target, CHALLENGE_SECONDS, providerEmail]);
|
|
173
|
+
ctx.setCookie(core.cookies.challenge, challenge, CHALLENGE_SECONDS);
|
|
174
|
+
return { next: "two_factor", redirectTo: core.pages.twoFactor };
|
|
175
|
+
}
|
|
176
|
+
await createSession(core, ctx, userId, method, providerEmail);
|
|
177
|
+
return { next: "signed_in", redirectTo: target };
|
|
178
|
+
}
|
|
179
|
+
export async function listSessions(core, ctx) {
|
|
180
|
+
const { session, user } = await requireSession(core, ctx, { browser: true });
|
|
181
|
+
const rows = await core.db.query(`select ${sessionColumns("se")} from ${core.s}.sessions se
|
|
182
|
+
where se.user_id = $1::uuid and se.expires_at > now() order by se.last_seen_at desc`, [user.id]);
|
|
183
|
+
return rows.map((row) => ({ ...toSession(row), current: row.s_id === session.id }));
|
|
184
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import { type Auth } from "./index.js";
|
|
2
|
+
import type { User } from "./types.js";
|
|
3
|
+
/**
|
|
4
|
+
* Signs in as a user in tests, without a password or provider. Creates the user when the e-mail is new.
|
|
5
|
+
* Returns a `cookie` header value and a `request()` helper that sends it.
|
|
6
|
+
*/
|
|
7
|
+
export declare function signInAs(auth: Auth<any>, email: string, options?: {
|
|
8
|
+
name?: string;
|
|
9
|
+
verified?: boolean;
|
|
10
|
+
}): Promise<{
|
|
11
|
+
user: User;
|
|
12
|
+
cookie: string;
|
|
13
|
+
/** A Request to the app with the session cookie and a same-origin Origin header. */
|
|
14
|
+
request(path?: string, init?: RequestInit): Request;
|
|
15
|
+
}>;
|
package/dist/testing.js
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import { CORE } from "./index.js";
|
|
2
|
+
import { createContext, normalizeEmail } from "./core.js";
|
|
3
|
+
import { createSession, getUser, insertUser } from "./sessions.js";
|
|
4
|
+
/**
|
|
5
|
+
* Signs in as a user in tests, without a password or provider. Creates the user when the e-mail is new.
|
|
6
|
+
* Returns a `cookie` header value and a `request()` helper that sends it.
|
|
7
|
+
*/
|
|
8
|
+
export async function signInAs(auth, email, options = {}) {
|
|
9
|
+
const core = auth[CORE];
|
|
10
|
+
const normalized = normalizeEmail(email);
|
|
11
|
+
const existing = await getUser(core, core.db, "email", normalized);
|
|
12
|
+
const user = existing ?? (await insertUser(core, { email: normalized, name: options.name ?? null, verified: options.verified ?? true }));
|
|
13
|
+
let token = "";
|
|
14
|
+
const ctx = createContext(core, new Request(core.url), (name, value) => {
|
|
15
|
+
if (name === core.cookies.session)
|
|
16
|
+
token = value;
|
|
17
|
+
});
|
|
18
|
+
await createSession(core, ctx, user.id, "dev");
|
|
19
|
+
const cookie = `${core.cookies.session}=${encodeURIComponent(token)}`;
|
|
20
|
+
return {
|
|
21
|
+
user,
|
|
22
|
+
cookie,
|
|
23
|
+
/** A Request to the app with the session cookie and a same-origin Origin header. */
|
|
24
|
+
request(path = "/", init = {}) {
|
|
25
|
+
const headers = new Headers(init.headers);
|
|
26
|
+
headers.set("cookie", [headers.get("cookie"), cookie].filter(Boolean).join("; "));
|
|
27
|
+
if (init.method && init.method !== "GET" && !headers.has("origin"))
|
|
28
|
+
headers.set("origin", core.origin);
|
|
29
|
+
return new Request(new URL(path, core.url), { ...init, headers });
|
|
30
|
+
},
|
|
31
|
+
};
|
|
32
|
+
}
|