@softure-ai/auth 0.0.0-stage → 0.1.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +381 -2
- package/dist/contract.d.ts +44 -0
- package/dist/contract.d.ts.map +1 -0
- package/dist/contract.js +2 -0
- package/dist/contract.js.map +1 -0
- package/dist/index.d.ts +188 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +84 -0
- package/dist/index.js.map +1 -0
- package/dist/mailing/index.d.ts +2 -0
- package/dist/mailing/index.d.ts.map +1 -0
- package/dist/mailing/index.js +4 -0
- package/dist/mailing/index.js.map +1 -0
- package/dist/mailing/reset-mail.d.ts +27 -0
- package/dist/mailing/reset-mail.d.ts.map +1 -0
- package/dist/mailing/reset-mail.js +55 -0
- package/dist/mailing/reset-mail.js.map +1 -0
- package/dist/messages/en.d.ts +97 -0
- package/dist/messages/en.d.ts.map +1 -0
- package/dist/messages/en.js +92 -0
- package/dist/messages/en.js.map +1 -0
- package/dist/messages/index.d.ts +199 -0
- package/dist/messages/index.d.ts.map +1 -0
- package/dist/messages/index.js +11 -0
- package/dist/messages/index.js.map +1 -0
- package/dist/messages/pl.d.ts +3 -0
- package/dist/messages/pl.d.ts.map +1 -0
- package/dist/messages/pl.js +91 -0
- package/dist/messages/pl.js.map +1 -0
- package/dist/next/actions.d.ts +19 -0
- package/dist/next/actions.d.ts.map +1 -0
- package/dist/next/actions.js +210 -0
- package/dist/next/actions.js.map +1 -0
- package/dist/next/context.d.ts +4 -0
- package/dist/next/context.d.ts.map +1 -0
- package/dist/next/context.js +13 -0
- package/dist/next/context.js.map +1 -0
- package/dist/next/current-user.d.ts +34 -0
- package/dist/next/current-user.d.ts.map +1 -0
- package/dist/next/current-user.js +77 -0
- package/dist/next/current-user.js.map +1 -0
- package/dist/next/index.d.ts +8 -0
- package/dist/next/index.d.ts.map +1 -0
- package/dist/next/index.js +9 -0
- package/dist/next/index.js.map +1 -0
- package/dist/next/logout-button.d.ts +7 -0
- package/dist/next/logout-button.d.ts.map +1 -0
- package/dist/next/logout-button.js +12 -0
- package/dist/next/logout-button.js.map +1 -0
- package/dist/next/messages.d.ts +5 -0
- package/dist/next/messages.d.ts.map +1 -0
- package/dist/next/messages.js +7 -0
- package/dist/next/messages.js.map +1 -0
- package/dist/next/pages.d.ts +18 -0
- package/dist/next/pages.d.ts.map +1 -0
- package/dist/next/pages.js +92 -0
- package/dist/next/pages.js.map +1 -0
- package/dist/next/params.d.ts +3 -0
- package/dist/next/params.d.ts.map +1 -0
- package/dist/next/params.js +4 -0
- package/dist/next/params.js.map +1 -0
- package/dist/next/route.d.ts +3 -0
- package/dist/next/route.d.ts.map +1 -0
- package/dist/next/route.js +17 -0
- package/dist/next/route.js.map +1 -0
- package/dist/next/search-params.d.ts +5 -0
- package/dist/next/search-params.d.ts.map +1 -0
- package/dist/next/search-params.js +13 -0
- package/dist/next/search-params.js.map +1 -0
- package/dist/next/session-cookie.d.ts +8 -0
- package/dist/next/session-cookie.d.ts.map +1 -0
- package/dist/next/session-cookie.js +34 -0
- package/dist/next/session-cookie.js.map +1 -0
- package/dist/options.d.ts +63 -0
- package/dist/options.d.ts.map +1 -0
- package/dist/options.js +74 -0
- package/dist/options.js.map +1 -0
- package/dist/password-reset-sender.d.ts +21 -0
- package/dist/password-reset-sender.d.ts.map +1 -0
- package/dist/password-reset-sender.js +12 -0
- package/dist/password-reset-sender.js.map +1 -0
- package/dist/proxy/index.d.ts +9 -0
- package/dist/proxy/index.d.ts.map +1 -0
- package/dist/proxy/index.js +41 -0
- package/dist/proxy/index.js.map +1 -0
- package/dist/redirect-target.d.ts +7 -0
- package/dist/redirect-target.d.ts.map +1 -0
- package/dist/redirect-target.js +25 -0
- package/dist/redirect-target.js.map +1 -0
- package/dist/roles.d.ts +5 -0
- package/dist/roles.d.ts.map +1 -0
- package/dist/roles.js +6 -0
- package/dist/roles.js.map +1 -0
- package/dist/safe-next-path.d.ts +3 -0
- package/dist/safe-next-path.d.ts.map +1 -0
- package/dist/safe-next-path.js +19 -0
- package/dist/safe-next-path.js.map +1 -0
- package/dist/schema.d.ts +302 -0
- package/dist/schema.d.ts.map +1 -0
- package/dist/schema.js +37 -0
- package/dist/schema.js.map +1 -0
- package/dist/scripts/index.d.ts +2 -0
- package/dist/scripts/index.d.ts.map +1 -0
- package/dist/scripts/index.js +3 -0
- package/dist/scripts/index.js.map +1 -0
- package/dist/scripts/role-scripts.d.ts +15 -0
- package/dist/scripts/role-scripts.d.ts.map +1 -0
- package/dist/scripts/role-scripts.js +76 -0
- package/dist/scripts/role-scripts.js.map +1 -0
- package/dist/server/change-password.d.ts +14 -0
- package/dist/server/change-password.d.ts.map +1 -0
- package/dist/server/change-password.js +47 -0
- package/dist/server/change-password.js.map +1 -0
- package/dist/server/health.d.ts +3 -0
- package/dist/server/health.d.ts.map +1 -0
- package/dist/server/health.js +15 -0
- package/dist/server/health.js.map +1 -0
- package/dist/server/index.d.ts +12 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +14 -0
- package/dist/server/index.js.map +1 -0
- package/dist/server/login.d.ts +14 -0
- package/dist/server/login.d.ts.map +1 -0
- package/dist/server/login.js +49 -0
- package/dist/server/login.js.map +1 -0
- package/dist/server/options.d.ts +17 -0
- package/dist/server/options.d.ts.map +1 -0
- package/dist/server/options.js +36 -0
- package/dist/server/options.js.map +1 -0
- package/dist/server/password-reset.d.ts +54 -0
- package/dist/server/password-reset.d.ts.map +1 -0
- package/dist/server/password-reset.js +134 -0
- package/dist/server/password-reset.js.map +1 -0
- package/dist/server/password.d.ts +18 -0
- package/dist/server/password.d.ts.map +1 -0
- package/dist/server/password.js +77 -0
- package/dist/server/password.js.map +1 -0
- package/dist/server/privacy.d.ts +33 -0
- package/dist/server/privacy.d.ts.map +1 -0
- package/dist/server/privacy.js +52 -0
- package/dist/server/privacy.js.map +1 -0
- package/dist/server/rate-limits.d.ts +21 -0
- package/dist/server/rate-limits.d.ts.map +1 -0
- package/dist/server/rate-limits.js +39 -0
- package/dist/server/rate-limits.js.map +1 -0
- package/dist/server/reauthenticate.d.ts +7 -0
- package/dist/server/reauthenticate.d.ts.map +1 -0
- package/dist/server/reauthenticate.js +16 -0
- package/dist/server/reauthenticate.js.map +1 -0
- package/dist/server/register.d.ts +21 -0
- package/dist/server/register.d.ts.map +1 -0
- package/dist/server/register.js +52 -0
- package/dist/server/register.js.map +1 -0
- package/dist/server/roles.d.ts +25 -0
- package/dist/server/roles.d.ts.map +1 -0
- package/dist/server/roles.js +56 -0
- package/dist/server/roles.js.map +1 -0
- package/dist/server/session-token.d.ts +8 -0
- package/dist/server/session-token.d.ts.map +1 -0
- package/dist/server/session-token.js +18 -0
- package/dist/server/session-token.js.map +1 -0
- package/dist/server/sessions.d.ts +15 -0
- package/dist/server/sessions.d.ts.map +1 -0
- package/dist/server/sessions.js +41 -0
- package/dist/server/sessions.js.map +1 -0
- package/dist/server/switches.d.ts +9 -0
- package/dist/server/switches.d.ts.map +1 -0
- package/dist/server/switches.js +34 -0
- package/dist/server/switches.js.map +1 -0
- package/dist/server/validation.d.ts +10 -0
- package/dist/server/validation.d.ts.map +1 -0
- package/dist/server/validation.js +32 -0
- package/dist/server/validation.js.map +1 -0
- package/dist/session-cookie.d.ts +14 -0
- package/dist/session-cookie.d.ts.map +1 -0
- package/dist/session-cookie.js +31 -0
- package/dist/session-cookie.js.map +1 -0
- package/dist/ui/auth-forms.d.ts +57 -0
- package/dist/ui/auth-forms.d.ts.map +1 -0
- package/dist/ui/auth-forms.js +65 -0
- package/dist/ui/auth-forms.js.map +1 -0
- package/dist/ui/index.d.ts +2 -0
- package/dist/ui/index.d.ts.map +1 -0
- package/dist/ui/index.js +4 -0
- package/dist/ui/index.js.map +1 -0
- package/migrations/0001_create_users_and_sessions.sql +25 -0
- package/migrations/0002_create_user_roles.sql +10 -0
- package/migrations/0003_create_password_resets.sql +15 -0
- package/migrations/0004_index_users_created_at.sql +5 -0
- package/module.json +34 -0
- package/package.json +85 -4
- package/src/contract.ts +64 -0
- package/src/index.ts +100 -0
- package/src/mailing/index.ts +3 -0
- package/src/mailing/reset-mail.ts +73 -0
- package/src/messages/en.ts +91 -0
- package/src/messages/index.ts +15 -0
- package/src/messages/pl.ts +92 -0
- package/src/next/actions.ts +216 -0
- package/src/next/context.ts +14 -0
- package/src/next/current-user.ts +90 -0
- package/src/next/index.ts +24 -0
- package/src/next/logout-button.tsx +22 -0
- package/src/next/messages.ts +9 -0
- package/src/next/next-modules.d.ts +16 -0
- package/src/next/pages.tsx +179 -0
- package/src/next/params.ts +4 -0
- package/src/next/route.ts +17 -0
- package/src/next/search-params.ts +14 -0
- package/src/next/session-cookie.ts +39 -0
- package/src/options.ts +108 -0
- package/src/password-reset-sender.ts +33 -0
- package/src/proxy/index.ts +58 -0
- package/src/redirect-target.ts +24 -0
- package/src/roles.ts +7 -0
- package/src/safe-next-path.ts +15 -0
- package/src/schema.ts +45 -0
- package/src/scripts/index.ts +2 -0
- package/src/scripts/role-scripts.ts +98 -0
- package/src/server/change-password.ts +61 -0
- package/src/server/health.ts +16 -0
- package/src/server/index.ts +38 -0
- package/src/server/login.ts +61 -0
- package/src/server/options.ts +49 -0
- package/src/server/password-reset.ts +164 -0
- package/src/server/password.ts +90 -0
- package/src/server/privacy.ts +70 -0
- package/src/server/rate-limits.ts +44 -0
- package/src/server/reauthenticate.ts +16 -0
- package/src/server/register.ts +72 -0
- package/src/server/roles.ts +72 -0
- package/src/server/session-token.ts +21 -0
- package/src/server/sessions.ts +50 -0
- package/src/server/switches.ts +31 -0
- package/src/server/validation.ts +37 -0
- package/src/session-cookie.ts +47 -0
- package/src/ui/auth-forms.tsx +364 -0
- package/src/ui/index.ts +16 -0
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Password change for a signed-in user. The new hash, the end of every other session of the user
|
|
2
|
+
// and of a pending reset link happen in one transaction; the session that made the change stays signed in.
|
|
3
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
4
|
+
import type { RateLimitRejection } from "@softure-ai/security";
|
|
5
|
+
import { consumeRateLimit } from "@softure-ai/security/server";
|
|
6
|
+
import { and, eq, ne } from "drizzle-orm";
|
|
7
|
+
import { passwordResets, sessions, users } from "../schema.js";
|
|
8
|
+
import { getAuthOptions } from "./options.js";
|
|
9
|
+
import { hashPassword, verifyPassword } from "./password.js";
|
|
10
|
+
import { assertAuthBuckets, BUCKETS, userSubjectKey } from "./rate-limits.js";
|
|
11
|
+
import { findSessionUser, type AuthContext } from "./sessions.js";
|
|
12
|
+
import { hashSessionToken } from "./session-token.js";
|
|
13
|
+
import { checkNewPassword } from "./validation.js";
|
|
14
|
+
|
|
15
|
+
export interface ChangePasswordInput {
|
|
16
|
+
/** The token of the session making the change; it stays valid. */
|
|
17
|
+
readonly sessionToken: string;
|
|
18
|
+
readonly currentPassword: string;
|
|
19
|
+
readonly newPassword: string;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
export type ChangePasswordErrorCode =
|
|
23
|
+
| "auth.unauthenticated"
|
|
24
|
+
| "auth.current_password_invalid"
|
|
25
|
+
| "auth.password_too_short"
|
|
26
|
+
| "auth.password_too_long";
|
|
27
|
+
|
|
28
|
+
export type ChangePasswordResult = Ok<undefined> | Err<ChangePasswordErrorCode> | RateLimitRejection;
|
|
29
|
+
|
|
30
|
+
/** Changes the password of the session's user and ends their other sessions. Database errors propagate. */
|
|
31
|
+
export async function changePassword(ctx: AuthContext, input: ChangePasswordInput): Promise<ChangePasswordResult> {
|
|
32
|
+
const options = getAuthOptions(ctx.config);
|
|
33
|
+
assertAuthBuckets(ctx.config);
|
|
34
|
+
const user = await findSessionUser(ctx, input.sessionToken);
|
|
35
|
+
if (user === null) return err("auth.unauthenticated");
|
|
36
|
+
|
|
37
|
+
const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.changePassword, key: userSubjectKey(user.id) });
|
|
38
|
+
if (!limit.ok) return limit;
|
|
39
|
+
|
|
40
|
+
const policy = checkNewPassword(input.newPassword, options.password.minLength);
|
|
41
|
+
if (!policy.ok) return policy;
|
|
42
|
+
|
|
43
|
+
const [stored] = await ctx.db.select({ passwordHash: users.passwordHash }).from(users).where(eq(users.id, user.id)).limit(1);
|
|
44
|
+
if (stored === undefined) return err("auth.unauthenticated");
|
|
45
|
+
if (!(await verifyPassword(input.currentPassword, stored.passwordHash))) return err("auth.current_password_invalid");
|
|
46
|
+
|
|
47
|
+
const passwordHash = await hashPassword(input.newPassword, options.password.scrypt);
|
|
48
|
+
return ctx.db.transaction(async (tx): Promise<ChangePasswordResult> => {
|
|
49
|
+
// Conditional on the hash just verified: two parallel changes cannot both win.
|
|
50
|
+
const updated = await tx
|
|
51
|
+
.update(users)
|
|
52
|
+
.set({ passwordHash, passwordChangedAt: ctx.clock.now() })
|
|
53
|
+
.where(and(eq(users.id, user.id), eq(users.passwordHash, stored.passwordHash)))
|
|
54
|
+
.returning();
|
|
55
|
+
if (updated.length === 0) return err("auth.current_password_invalid");
|
|
56
|
+
await tx.delete(sessions).where(and(eq(sessions.userId, user.id), ne(sessions.tokenHash, hashSessionToken(input.sessionToken))));
|
|
57
|
+
// A reset link requested before the change must not outlive it.
|
|
58
|
+
await tx.delete(passwordResets).where(eq(passwordResets.userId, user.id));
|
|
59
|
+
return ok();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// auth's readiness probe for `GET /api/health` of `@softure-ai/ops` (core's `defineModule({ health })`):
|
|
2
|
+
// auth can serve only when all of its tables exist and answer, i.e. after `softure migrate`. It
|
|
3
|
+
// reads no rows, so it stays cheap and runs as the row-limited app role.
|
|
4
|
+
import { ok, type HealthCheck } from "@softure-ai/core";
|
|
5
|
+
import type { Queryable } from "@softure-ai/db";
|
|
6
|
+
import { sql } from "drizzle-orm";
|
|
7
|
+
|
|
8
|
+
export const checkAuthTables: HealthCheck = async (context) => {
|
|
9
|
+
// Core types `db` as unknown; the health route passes the @softure-ai/db handle.
|
|
10
|
+
const db = context.db as Queryable;
|
|
11
|
+
await db.execute(sql`select 1 from auth.users limit 0`);
|
|
12
|
+
await db.execute(sql`select 1 from auth.sessions limit 0`);
|
|
13
|
+
await db.execute(sql`select 1 from auth.user_roles limit 0`);
|
|
14
|
+
await db.execute(sql`select 1 from auth.password_resets limit 0`);
|
|
15
|
+
return ok();
|
|
16
|
+
};
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Server-only API of @softure-ai/auth. Every function receives the module context
|
|
2
|
+
// (`{ db, clock, config }`) and never reads request scope; tokens and client keys come in as values.
|
|
3
|
+
export { changePassword, type ChangePasswordErrorCode, type ChangePasswordInput, type ChangePasswordResult } from "./change-password.js";
|
|
4
|
+
export { loginUser, type LoginInput, type LoginResult } from "./login.js";
|
|
5
|
+
export { getAuthOptions, getAuthRoutes, type AuthRoutes } from "./options.js";
|
|
6
|
+
export { hashPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyPassword } from "./password.js";
|
|
7
|
+
export {
|
|
8
|
+
deliverPasswordReset,
|
|
9
|
+
findPasswordResetUser,
|
|
10
|
+
getPasswordResetLink,
|
|
11
|
+
isPasswordResetEnabled,
|
|
12
|
+
issuePasswordReset,
|
|
13
|
+
prunePasswordResets,
|
|
14
|
+
requestPasswordReset,
|
|
15
|
+
resetPassword,
|
|
16
|
+
RESET_TOKEN_PARAM,
|
|
17
|
+
type PasswordResetRequestInput,
|
|
18
|
+
type PasswordResetRequestResult,
|
|
19
|
+
type ResetPasswordErrorCode,
|
|
20
|
+
type ResetPasswordInput,
|
|
21
|
+
type ResetPasswordResult,
|
|
22
|
+
} from "./password-reset.js";
|
|
23
|
+
export {
|
|
24
|
+
assertDeclaredRole,
|
|
25
|
+
findUserRoles,
|
|
26
|
+
getDeclaredRoles,
|
|
27
|
+
grantRole,
|
|
28
|
+
isConfiguredAdmin,
|
|
29
|
+
isDeclaredRole,
|
|
30
|
+
revokeRole,
|
|
31
|
+
type RoleChange,
|
|
32
|
+
type RoleErrorCode,
|
|
33
|
+
} from "./roles.js";
|
|
34
|
+
export { authPrivacyContributor, deleteAuthUserData, exportAuthUserData, type AuthUserData } from "./privacy.js";
|
|
35
|
+
export { isCurrentPassword } from "./reauthenticate.js";
|
|
36
|
+
export { registerUser, type RegisterErrorCode, type RegisterInput, type RegisterResult } from "./register.js";
|
|
37
|
+
export { createSession, findSessionUser, logoutSession, pruneSessions, type AuthContext } from "./sessions.js";
|
|
38
|
+
export { isRegistrationClosed } from "./switches.js";
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
// Login. Both buckets are counted before anything else: `login` per client address stops a flood,
|
|
2
|
+
// `login-account` per email stops a distributed attack on one account. An unknown email takes as
|
|
3
|
+
// long as a wrong password (a dummy verification) and fails with the same code.
|
|
4
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
5
|
+
import type { RateLimitRejection } from "@softure-ai/security";
|
|
6
|
+
import { consumeRateLimit, resetRateLimit } from "@softure-ai/security/server";
|
|
7
|
+
import { and, eq } from "drizzle-orm";
|
|
8
|
+
import type { SignedIn } from "../contract.js";
|
|
9
|
+
import { users } from "../schema.js";
|
|
10
|
+
import { getAuthOptions } from "./options.js";
|
|
11
|
+
import { hashPassword, MAX_PASSWORD_LENGTH, needsRehash, verifyDummyPassword, verifyPassword } from "./password.js";
|
|
12
|
+
import { assertAuthBuckets, BUCKETS, emailSubjectKey } from "./rate-limits.js";
|
|
13
|
+
import { createSession, deleteExpiredSessions, type AuthContext } from "./sessions.js";
|
|
14
|
+
import { getPasswordLength, normalizeEmail } from "./validation.js";
|
|
15
|
+
|
|
16
|
+
export interface LoginInput {
|
|
17
|
+
readonly email: string;
|
|
18
|
+
readonly password: string;
|
|
19
|
+
/** The client's rate limit key (`identifyClient`). */
|
|
20
|
+
readonly clientKey: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export type LoginResult = Ok<SignedIn> | Err<"auth.invalid_credentials"> | RateLimitRejection;
|
|
24
|
+
|
|
25
|
+
/** Checks the credentials and opens a session. Database errors propagate. */
|
|
26
|
+
export async function loginUser(ctx: AuthContext, input: LoginInput): Promise<LoginResult> {
|
|
27
|
+
const options = getAuthOptions(ctx.config);
|
|
28
|
+
assertAuthBuckets(ctx.config);
|
|
29
|
+
const byClient = await consumeRateLimit(ctx, { bucket: BUCKETS.login, key: input.clientKey });
|
|
30
|
+
if (!byClient.ok) return byClient;
|
|
31
|
+
|
|
32
|
+
const email = normalizeEmail(input.email);
|
|
33
|
+
if (email === "" || input.password === "" || getPasswordLength(input.password) > MAX_PASSWORD_LENGTH) {
|
|
34
|
+
return err("auth.invalid_credentials");
|
|
35
|
+
}
|
|
36
|
+
const accountKey = emailSubjectKey(email);
|
|
37
|
+
const byAccount = await consumeRateLimit(ctx, { bucket: BUCKETS.loginAccount, key: accountKey });
|
|
38
|
+
if (!byAccount.ok) return byAccount;
|
|
39
|
+
|
|
40
|
+
const [user] = await ctx.db.select().from(users).where(eq(users.email, email)).limit(1);
|
|
41
|
+
if (user === undefined) {
|
|
42
|
+
await verifyDummyPassword(input.password, options.password.scrypt);
|
|
43
|
+
return err("auth.invalid_credentials");
|
|
44
|
+
}
|
|
45
|
+
if (!(await verifyPassword(input.password, user.passwordHash))) {
|
|
46
|
+
return err("auth.invalid_credentials");
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
await resetRateLimit(ctx, { bucket: BUCKETS.loginAccount, key: accountKey });
|
|
50
|
+
await deleteExpiredSessions(ctx, user.id);
|
|
51
|
+
if (needsRehash(user.passwordHash, options.password.scrypt)) {
|
|
52
|
+
const passwordHash = await hashPassword(input.password, options.password.scrypt);
|
|
53
|
+
// Conditional: a password changed meanwhile is not overwritten with the old one.
|
|
54
|
+
await ctx.db
|
|
55
|
+
.update(users)
|
|
56
|
+
.set({ passwordHash })
|
|
57
|
+
.where(and(eq(users.id, user.id), eq(users.passwordHash, user.passwordHash)));
|
|
58
|
+
}
|
|
59
|
+
const session = await createSession(ctx, user.id);
|
|
60
|
+
return ok({ user: { id: user.id, email: user.email, createdAt: user.createdAt }, session });
|
|
61
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
// The auth options of the running app, read from the configuration in the module context.
|
|
2
|
+
import { getModule, type SoftureConfig } from "@softure-ai/core";
|
|
3
|
+
import type { AuthOptions } from "../options.js";
|
|
4
|
+
|
|
5
|
+
const MODULE_ID = "auth";
|
|
6
|
+
|
|
7
|
+
/** The enabled auth module. Throws when the app did not enable it: calling its functions then is a bug. */
|
|
8
|
+
export function getAuthModule(config: SoftureConfig) {
|
|
9
|
+
const module = getModule(config, MODULE_ID);
|
|
10
|
+
if (module === undefined) {
|
|
11
|
+
throw new Error("@softure-ai/auth: the module is not enabled; add auth({ ... }) to modules in softure.config.ts");
|
|
12
|
+
}
|
|
13
|
+
return module;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function getAuthOptions(config: SoftureConfig): AuthOptions {
|
|
17
|
+
// The module factory parsed these options with authOptionsSchema.
|
|
18
|
+
return getAuthModule(config).options as AuthOptions;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The module's routes with the app's overrides applied. */
|
|
22
|
+
export function getAuthRoutes(config: SoftureConfig): AuthRoutes {
|
|
23
|
+
const routes = getAuthModule(config).routes;
|
|
24
|
+
const read = (name: keyof AuthRoutes): string => {
|
|
25
|
+
const path = routes[name];
|
|
26
|
+
// The manifest declares every route, so a missing one means a broken module definition.
|
|
27
|
+
if (path === undefined) throw new Error(`@softure-ai/auth: route "${name}" is missing from the module manifest`);
|
|
28
|
+
return path;
|
|
29
|
+
};
|
|
30
|
+
return {
|
|
31
|
+
login: read("login"),
|
|
32
|
+
register: read("register"),
|
|
33
|
+
changePassword: read("changePassword"),
|
|
34
|
+
forgotPassword: read("forgotPassword"),
|
|
35
|
+
resetPassword: read("resetPassword"),
|
|
36
|
+
afterLogin: read("afterLogin"),
|
|
37
|
+
afterLogout: read("afterLogout"),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export interface AuthRoutes {
|
|
42
|
+
readonly login: string;
|
|
43
|
+
readonly register: string;
|
|
44
|
+
readonly changePassword: string;
|
|
45
|
+
readonly forgotPassword: string;
|
|
46
|
+
readonly resetPassword: string;
|
|
47
|
+
readonly afterLogin: string;
|
|
48
|
+
readonly afterLogout: string;
|
|
49
|
+
}
|
|
@@ -0,0 +1,164 @@
|
|
|
1
|
+
// Password reset by token. A request counts its buckets and answers the same for every email;
|
|
2
|
+
// `deliverPasswordReset` then issues the token and calls the app's sender (the Next adapter runs it
|
|
3
|
+
// after the response, so neither its timing nor its failures reveal an account). A reset link
|
|
4
|
+
// carries 32 random bytes; only their sha256 is stored, one pending link per account, and the reset
|
|
5
|
+
// deletes the row in the transaction that sets the new password and ends every session.
|
|
6
|
+
import { err, ok, type Err, type Ok, type SoftureConfig } from "@softure-ai/core";
|
|
7
|
+
import type { RateLimitRejection } from "@softure-ai/security";
|
|
8
|
+
import { consumeRateLimit } from "@softure-ai/security/server";
|
|
9
|
+
import { and, eq, gt, lte } from "drizzle-orm";
|
|
10
|
+
import type { AuthUser } from "../contract.js";
|
|
11
|
+
import { passwordResets, sessions, users } from "../schema.js";
|
|
12
|
+
import { getAuthOptions, getAuthRoutes } from "./options.js";
|
|
13
|
+
import { hashPassword } from "./password.js";
|
|
14
|
+
import { assertAuthBuckets, BUCKETS, emailSubjectKey } from "./rate-limits.js";
|
|
15
|
+
import type { AuthContext } from "./sessions.js";
|
|
16
|
+
// Reset tokens have the shape of session tokens: the same generator, hash and shape check.
|
|
17
|
+
import { createSessionToken, hashSessionToken, isSessionTokenShape } from "./session-token.js";
|
|
18
|
+
import { checkNewPassword, parseEmail } from "./validation.js";
|
|
19
|
+
|
|
20
|
+
const MINUTE_MS = 60 * 1000;
|
|
21
|
+
/** The query parameter of the reset link that carries the token. */
|
|
22
|
+
export const RESET_TOKEN_PARAM = "token";
|
|
23
|
+
|
|
24
|
+
/** Whether the app passed a sender, i.e. whether password reset is offered at all. */
|
|
25
|
+
export function isPasswordResetEnabled(config: SoftureConfig): boolean {
|
|
26
|
+
return getAuthOptions(config).passwordReset.send !== undefined;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export interface PasswordResetRequestInput {
|
|
30
|
+
readonly email: string;
|
|
31
|
+
/** The client's rate limit key (`identifyClient`). */
|
|
32
|
+
readonly clientKey: string;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
export type PasswordResetRequestResult =
|
|
36
|
+
| Ok<{ readonly email: string }>
|
|
37
|
+
| Err<"auth.password_reset_unavailable" | "auth.email_invalid">
|
|
38
|
+
| RateLimitRejection;
|
|
39
|
+
|
|
40
|
+
/**
|
|
41
|
+
* Accepts a reset request: counts `password-reset` per client, checks the email's shape and counts
|
|
42
|
+
* `password-reset-account` per email. It never looks the account up, so its answer is the same for
|
|
43
|
+
* every email; pass the returned email to `deliverPasswordReset`. Database errors propagate.
|
|
44
|
+
*/
|
|
45
|
+
export async function requestPasswordReset(ctx: AuthContext, input: PasswordResetRequestInput): Promise<PasswordResetRequestResult> {
|
|
46
|
+
assertAuthBuckets(ctx.config);
|
|
47
|
+
if (!isPasswordResetEnabled(ctx.config)) return err("auth.password_reset_unavailable");
|
|
48
|
+
const byClient = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordReset, key: input.clientKey });
|
|
49
|
+
if (!byClient.ok) return byClient;
|
|
50
|
+
|
|
51
|
+
const email = parseEmail(input.email);
|
|
52
|
+
if (!email.ok) return email;
|
|
53
|
+
const byAccount = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordResetAccount, key: emailSubjectKey(email.value) });
|
|
54
|
+
if (!byAccount.ok) return byAccount;
|
|
55
|
+
return ok({ email: email.value });
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* Issues a reset link for the account with `email` (replacing a pending one) and hands it to the
|
|
60
|
+
* app's sender. `no_account` when no account has that email. Sender and database errors propagate.
|
|
61
|
+
*/
|
|
62
|
+
export async function deliverPasswordReset(ctx: AuthContext, email: string): Promise<"sent" | "no_account"> {
|
|
63
|
+
const send = getAuthOptions(ctx.config).passwordReset.send;
|
|
64
|
+
if (send === undefined) {
|
|
65
|
+
throw new Error("@softure-ai/auth: deliverPasswordReset needs auth({ passwordReset: { send } })");
|
|
66
|
+
}
|
|
67
|
+
const [user] = await ctx.db
|
|
68
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt })
|
|
69
|
+
.from(users)
|
|
70
|
+
.where(eq(users.email, email))
|
|
71
|
+
.limit(1);
|
|
72
|
+
if (user === undefined) return "no_account";
|
|
73
|
+
|
|
74
|
+
const { token, expiresAt } = await issuePasswordReset(ctx, user.id);
|
|
75
|
+
await send(getPasswordResetLink(ctx.config, token), user, { expiresAt, locale: ctx.config.locale });
|
|
76
|
+
return "sent";
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Stores a new reset token for `userId`, replacing a pending one, and returns the token. */
|
|
80
|
+
export async function issuePasswordReset(ctx: AuthContext, userId: string): Promise<{ readonly token: string; readonly expiresAt: Date }> {
|
|
81
|
+
const now = ctx.clock.now();
|
|
82
|
+
const expiresAt = new Date(now.getTime() + getAuthOptions(ctx.config).passwordReset.ttlMinutes * MINUTE_MS);
|
|
83
|
+
const { token, tokenHash } = createSessionToken();
|
|
84
|
+
await ctx.db
|
|
85
|
+
.insert(passwordResets)
|
|
86
|
+
.values({ userId, tokenHash, createdAt: now, expiresAt })
|
|
87
|
+
.onConflictDoUpdate({ target: passwordResets.userId, set: { tokenHash, createdAt: now, expiresAt } });
|
|
88
|
+
return { token, expiresAt };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** The link the sender delivers: the reset route on `appOrigin`, with the token in the query. */
|
|
92
|
+
export function getPasswordResetLink(config: SoftureConfig, token: string): string {
|
|
93
|
+
const link = new URL(getAuthRoutes(config).resetPassword, config.appOrigin);
|
|
94
|
+
link.searchParams.set(RESET_TOKEN_PARAM, token);
|
|
95
|
+
return link.href;
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
/** The account a live reset token belongs to, or null for an unknown, malformed, used or expired one. Reads only. */
|
|
99
|
+
export async function findPasswordResetUser(ctx: AuthContext, token: string): Promise<AuthUser | null> {
|
|
100
|
+
if (!isSessionTokenShape(token)) return null;
|
|
101
|
+
const [row] = await ctx.db
|
|
102
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt })
|
|
103
|
+
.from(passwordResets)
|
|
104
|
+
.innerJoin(users, eq(users.id, passwordResets.userId))
|
|
105
|
+
.where(and(eq(passwordResets.tokenHash, hashSessionToken(token)), gt(passwordResets.expiresAt, ctx.clock.now())))
|
|
106
|
+
.limit(1);
|
|
107
|
+
return row ?? null;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
export interface ResetPasswordInput {
|
|
111
|
+
readonly token: string;
|
|
112
|
+
readonly newPassword: string;
|
|
113
|
+
/** The client's rate limit key (`identifyClient`). */
|
|
114
|
+
readonly clientKey: string;
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
export type ResetPasswordErrorCode =
|
|
118
|
+
| "auth.password_reset_unavailable"
|
|
119
|
+
| "auth.reset_token_invalid"
|
|
120
|
+
| "auth.password_too_short"
|
|
121
|
+
| "auth.password_too_long";
|
|
122
|
+
|
|
123
|
+
export type ResetPasswordResult = Ok<undefined> | Err<ResetPasswordErrorCode> | RateLimitRejection;
|
|
124
|
+
|
|
125
|
+
/**
|
|
126
|
+
* Sets a new password with a reset token. Counts `password-reset-confirm` per client first. The
|
|
127
|
+
* token is consumed by a conditional delete in the transaction that stores the new hash and ends
|
|
128
|
+
* every session of the account, so it works once even when two submissions race. Database errors
|
|
129
|
+
* propagate.
|
|
130
|
+
*/
|
|
131
|
+
export async function resetPassword(ctx: AuthContext, input: ResetPasswordInput): Promise<ResetPasswordResult> {
|
|
132
|
+
const options = getAuthOptions(ctx.config);
|
|
133
|
+
assertAuthBuckets(ctx.config);
|
|
134
|
+
if (!isPasswordResetEnabled(ctx.config)) return err("auth.password_reset_unavailable");
|
|
135
|
+
const limit = await consumeRateLimit(ctx, { bucket: BUCKETS.passwordResetConfirm, key: input.clientKey });
|
|
136
|
+
if (!limit.ok) return limit;
|
|
137
|
+
|
|
138
|
+
const user = await findPasswordResetUser(ctx, input.token);
|
|
139
|
+
if (user === null) return err("auth.reset_token_invalid");
|
|
140
|
+
const policy = checkNewPassword(input.newPassword, options.password.minLength);
|
|
141
|
+
// A fresh error, not the check's own result: CodeQL treats that result as password data
|
|
142
|
+
// (js/insufficient-password-hash), as in registerUser.
|
|
143
|
+
if (!policy.ok) return err(policy.error);
|
|
144
|
+
|
|
145
|
+
const passwordHash = await hashPassword(input.newPassword, options.password.scrypt);
|
|
146
|
+
const tokenHash = hashSessionToken(input.token);
|
|
147
|
+
return ctx.db.transaction(async (tx): Promise<ResetPasswordResult> => {
|
|
148
|
+
const now = ctx.clock.now();
|
|
149
|
+
const [consumed] = await tx
|
|
150
|
+
.delete(passwordResets)
|
|
151
|
+
.where(and(eq(passwordResets.tokenHash, tokenHash), gt(passwordResets.expiresAt, now)))
|
|
152
|
+
.returning();
|
|
153
|
+
if (consumed === undefined) return err("auth.reset_token_invalid");
|
|
154
|
+
await tx.update(users).set({ passwordHash, passwordChangedAt: now }).where(eq(users.id, consumed.userId));
|
|
155
|
+
await tx.delete(sessions).where(eq(sessions.userId, consumed.userId));
|
|
156
|
+
return ok();
|
|
157
|
+
});
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/** Deletes every expired reset; for a scheduled job. Returns how many were deleted. */
|
|
161
|
+
export async function prunePasswordResets(ctx: AuthContext): Promise<number> {
|
|
162
|
+
const deleted = await ctx.db.delete(passwordResets).where(lte(passwordResets.expiresAt, ctx.clock.now())).returning();
|
|
163
|
+
return deleted.length;
|
|
164
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// Password hashing with scrypt from node:crypto. A hash describes its own parameters
|
|
2
|
+
// (`scrypt$<N>$<r>$<p>$<salt>$<key>`, base64url), so the cost can be raised later: a login with an
|
|
3
|
+
// older cost rehashes (`needsRehash`). Keys are compared with `timingSafeEqual`.
|
|
4
|
+
import { randomBytes, scrypt, timingSafeEqual, type ScryptOptions } from "node:crypto";
|
|
5
|
+
import type { ScryptParams } from "../options.js";
|
|
6
|
+
|
|
7
|
+
const SALT_BYTES = 16;
|
|
8
|
+
const KEY_BYTES = 64;
|
|
9
|
+
/** Longest password accepted anywhere, so a request cannot make the server hash megabytes. */
|
|
10
|
+
export const MAX_PASSWORD_LENGTH = 1024;
|
|
11
|
+
|
|
12
|
+
interface ParsedHash {
|
|
13
|
+
readonly params: ScryptParams;
|
|
14
|
+
readonly salt: Buffer;
|
|
15
|
+
readonly key: Buffer;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
/** A new salted hash of `password`. */
|
|
19
|
+
export async function hashPassword(password: string, params: ScryptParams): Promise<string> {
|
|
20
|
+
const salt = randomBytes(SALT_BYTES);
|
|
21
|
+
const key = await deriveKey(password, salt, params);
|
|
22
|
+
return ["scrypt", params.cost, params.blockSize, params.parallelization, salt.toString("base64url"), key.toString("base64url")].join("$");
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Whether `password` matches `storedHash`. Throws on a hash this module did not write: that is
|
|
27
|
+
* damaged data, not a wrong password.
|
|
28
|
+
*/
|
|
29
|
+
export async function verifyPassword(password: string, storedHash: string): Promise<boolean> {
|
|
30
|
+
const parsed = parseHash(storedHash);
|
|
31
|
+
const key = await deriveKey(password, parsed.salt, parsed.params);
|
|
32
|
+
return key.length === parsed.key.length && timingSafeEqual(key, parsed.key);
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** Whether `storedHash` was made with other parameters than `params`. */
|
|
36
|
+
export function needsRehash(storedHash: string, params: ScryptParams): boolean {
|
|
37
|
+
const current = parseHash(storedHash).params;
|
|
38
|
+
return current.cost !== params.cost || current.blockSize !== params.blockSize || current.parallelization !== params.parallelization;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const dummyHashes = new Map<string, Promise<string>>();
|
|
42
|
+
|
|
43
|
+
/**
|
|
44
|
+
* Spends the time of one verification without an account, so a login for an unknown email takes
|
|
45
|
+
* as long as one with a wrong password. The dummy hash is made once per parameter set.
|
|
46
|
+
*/
|
|
47
|
+
export async function verifyDummyPassword(password: string, params: ScryptParams): Promise<void> {
|
|
48
|
+
const cacheKey = `${String(params.cost)}:${String(params.blockSize)}:${String(params.parallelization)}`;
|
|
49
|
+
let dummy = dummyHashes.get(cacheKey);
|
|
50
|
+
if (dummy === undefined) {
|
|
51
|
+
dummy = hashPassword(randomBytes(SALT_BYTES).toString("base64url"), params);
|
|
52
|
+
dummyHashes.set(cacheKey, dummy);
|
|
53
|
+
dummy.catch(() => dummyHashes.delete(cacheKey));
|
|
54
|
+
}
|
|
55
|
+
await verifyPassword(password, await dummy);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function deriveKey(password: string, salt: Buffer, params: ScryptParams): Promise<Buffer> {
|
|
59
|
+
const options: ScryptOptions = {
|
|
60
|
+
N: params.cost,
|
|
61
|
+
r: params.blockSize,
|
|
62
|
+
p: params.parallelization,
|
|
63
|
+
// Node refuses above 32 MiB by default; scrypt needs 128 * N * r bytes, so leave room for it.
|
|
64
|
+
maxmem: 256 * params.cost * params.blockSize,
|
|
65
|
+
};
|
|
66
|
+
return new Promise((resolve, reject) => {
|
|
67
|
+
scrypt(password.normalize("NFC"), salt, KEY_BYTES, options, (error, key) => {
|
|
68
|
+
if (error === null) resolve(key);
|
|
69
|
+
else reject(error);
|
|
70
|
+
});
|
|
71
|
+
});
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
function parseHash(storedHash: string): ParsedHash {
|
|
75
|
+
const [scheme, cost, blockSize, parallelization, salt, key, ...rest] = storedHash.split("$");
|
|
76
|
+
const params = { cost: Number(cost), blockSize: Number(blockSize), parallelization: Number(parallelization) };
|
|
77
|
+
const isValid =
|
|
78
|
+
scheme === "scrypt" &&
|
|
79
|
+
rest.length === 0 &&
|
|
80
|
+
Object.values(params).every((value) => Number.isSafeInteger(value) && value > 0) &&
|
|
81
|
+
salt !== undefined &&
|
|
82
|
+
salt !== "" &&
|
|
83
|
+
key !== undefined &&
|
|
84
|
+
key !== "";
|
|
85
|
+
if (!isValid) {
|
|
86
|
+
// The hash itself stays out of the message: it is secret-derived data.
|
|
87
|
+
throw new Error("@softure-ai/auth: a stored password hash is not in the scrypt$N$r$p$salt$key format");
|
|
88
|
+
}
|
|
89
|
+
return { params, salt: Buffer.from(salt, "base64url"), key: Buffer.from(key, "base64url") };
|
|
90
|
+
}
|
|
@@ -0,0 +1,70 @@
|
|
|
1
|
+
// The auth part of a GDPR export and deletion (`@softure-ai/privacy`): the account, its roles, its
|
|
2
|
+
// sessions and a pending reset link. Secrets never leave: no password hash and no token hash.
|
|
3
|
+
import { ok, type ModuleContext, type Ok, type PrivacyContributor } from "@softure-ai/core";
|
|
4
|
+
import type { Queryable } from "@softure-ai/db";
|
|
5
|
+
import { asc, eq } from "drizzle-orm";
|
|
6
|
+
import { passwordResets, sessions, userRoles, users } from "../schema.js";
|
|
7
|
+
|
|
8
|
+
/** What auth holds about one user, as it appears in their export. */
|
|
9
|
+
export interface AuthUserData {
|
|
10
|
+
/** Null when no account has this id. */
|
|
11
|
+
readonly account: {
|
|
12
|
+
readonly id: string;
|
|
13
|
+
readonly email: string;
|
|
14
|
+
readonly createdAt: Date;
|
|
15
|
+
readonly passwordChangedAt: Date;
|
|
16
|
+
} | null;
|
|
17
|
+
/** Stored roles; a role held through `adminEmails` is configuration, not stored data. */
|
|
18
|
+
readonly roles: readonly { readonly role: string; readonly grantedAt: Date }[];
|
|
19
|
+
readonly sessions: readonly { readonly createdAt: Date; readonly expiresAt: Date }[];
|
|
20
|
+
readonly passwordReset: { readonly createdAt: Date; readonly expiresAt: Date } | null;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
24
|
+
|
|
25
|
+
const NO_DATA: AuthUserData = { account: null, roles: [], sessions: [], passwordReset: null };
|
|
26
|
+
|
|
27
|
+
/** The user's auth data. An id that is not a UUID cannot be an account, so it has none. */
|
|
28
|
+
export async function exportAuthUserData(context: ModuleContext, userId: string): Promise<Ok<AuthUserData>> {
|
|
29
|
+
if (!UUID.test(userId)) return ok(NO_DATA);
|
|
30
|
+
// Core types `db` as unknown; privacy passes the @softure-ai/db handle or its transaction.
|
|
31
|
+
const db = context.db as Queryable;
|
|
32
|
+
const [account] = await db
|
|
33
|
+
.select({ id: users.id, email: users.email, createdAt: users.createdAt, passwordChangedAt: users.passwordChangedAt })
|
|
34
|
+
.from(users)
|
|
35
|
+
.where(eq(users.id, userId));
|
|
36
|
+
const roles = await db
|
|
37
|
+
.select({ role: userRoles.role, grantedAt: userRoles.grantedAt })
|
|
38
|
+
.from(userRoles)
|
|
39
|
+
.where(eq(userRoles.userId, userId))
|
|
40
|
+
.orderBy(asc(userRoles.role));
|
|
41
|
+
const userSessions = await db
|
|
42
|
+
.select({ createdAt: sessions.createdAt, expiresAt: sessions.expiresAt })
|
|
43
|
+
.from(sessions)
|
|
44
|
+
.where(eq(sessions.userId, userId))
|
|
45
|
+
.orderBy(asc(sessions.createdAt));
|
|
46
|
+
const [passwordReset] = await db
|
|
47
|
+
.select({ createdAt: passwordResets.createdAt, expiresAt: passwordResets.expiresAt })
|
|
48
|
+
.from(passwordResets)
|
|
49
|
+
.where(eq(passwordResets.userId, userId));
|
|
50
|
+
return ok({ account: account ?? null, roles, sessions: userSessions, passwordReset: passwordReset ?? null });
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/**
|
|
54
|
+
* Deletes the account and everything auth keeps for it. The child rows go first, by name, so the
|
|
55
|
+
* deletion does not depend on the cascades alone; every session ends with them.
|
|
56
|
+
*/
|
|
57
|
+
export async function deleteAuthUserData(context: ModuleContext, userId: string): Promise<Ok<undefined>> {
|
|
58
|
+
if (!UUID.test(userId)) return ok();
|
|
59
|
+
const db = context.db as Queryable;
|
|
60
|
+
await db.delete(sessions).where(eq(sessions.userId, userId));
|
|
61
|
+
await db.delete(passwordResets).where(eq(passwordResets.userId, userId));
|
|
62
|
+
await db.delete(userRoles).where(eq(userRoles.userId, userId));
|
|
63
|
+
await db.delete(users).where(eq(users.id, userId));
|
|
64
|
+
return ok();
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export const authPrivacyContributor: PrivacyContributor = {
|
|
68
|
+
exportUserData: exportAuthUserData,
|
|
69
|
+
deleteUserData: deleteAuthUserData,
|
|
70
|
+
};
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
// The rate limit buckets auth consumes (AUTH_RATE_LIMIT_BUCKETS). Each attempt is counted before the
|
|
2
|
+
// work it guards, hashing included, so a flood is stopped before it costs anything.
|
|
3
|
+
import { getModule, type SoftureConfig } from "@softure-ai/core";
|
|
4
|
+
import { subjectKey } from "@softure-ai/security/server";
|
|
5
|
+
|
|
6
|
+
export const BUCKETS = {
|
|
7
|
+
register: "register",
|
|
8
|
+
login: "login",
|
|
9
|
+
loginAccount: "login-account",
|
|
10
|
+
changePassword: "change-password",
|
|
11
|
+
passwordReset: "password-reset",
|
|
12
|
+
passwordResetAccount: "password-reset-account",
|
|
13
|
+
passwordResetConfirm: "password-reset-confirm",
|
|
14
|
+
} as const;
|
|
15
|
+
|
|
16
|
+
/** The subject key of an account's email for `login-account` and `password-reset-account`. */
|
|
17
|
+
export function emailSubjectKey(normalizedEmail: string): string {
|
|
18
|
+
return subjectKey(`email:${normalizedEmail}`);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** The subject key of a user for `change-password`. */
|
|
22
|
+
export function userSubjectKey(userId: string): string {
|
|
23
|
+
return subjectKey(`user:${userId}`);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
const checkedConfigs = new WeakSet<SoftureConfig>();
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Throws, naming every missing bucket, when the app's `security({ buckets })` lacks one auth
|
|
30
|
+
* counts in. Checked once per config, before the first attempt is counted, so a setup mistake is
|
|
31
|
+
* one clear error instead of a generic failure on every login.
|
|
32
|
+
*/
|
|
33
|
+
export function assertAuthBuckets(config: SoftureConfig): void {
|
|
34
|
+
if (checkedConfigs.has(config)) return;
|
|
35
|
+
const options = getModule(config, "security")?.options as { buckets?: Readonly<Record<string, unknown>> } | undefined;
|
|
36
|
+
const configured = options?.buckets ?? {};
|
|
37
|
+
const missing = Object.values(BUCKETS).filter((name) => !Object.hasOwn(configured, name));
|
|
38
|
+
if (missing.length > 0) {
|
|
39
|
+
throw new Error(
|
|
40
|
+
`@softure-ai/auth: security({ buckets }) lacks ${missing.map((name) => `"${name}"`).join(", ")}; spread AUTH_RATE_LIMIT_BUCKETS into it`,
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
checkedConfigs.add(config);
|
|
44
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Re-authentication before an action that cannot be undone, such as deleting the account: the
|
|
2
|
+
// signed-in user types their password again, so a session cookie alone is not enough.
|
|
3
|
+
import { eq } from "drizzle-orm";
|
|
4
|
+
import { users } from "../schema.js";
|
|
5
|
+
import { verifyPassword } from "./password.js";
|
|
6
|
+
import type { AuthContext } from "./sessions.js";
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Whether `password` is the current password of the account. False for an unknown account. The
|
|
10
|
+
* caller counts the attempt in a rate limit bucket first: this is a password check like a login.
|
|
11
|
+
*/
|
|
12
|
+
export async function isCurrentPassword(ctx: AuthContext, userId: string, password: string): Promise<boolean> {
|
|
13
|
+
const [stored] = await ctx.db.select({ passwordHash: users.passwordHash }).from(users).where(eq(users.id, userId)).limit(1);
|
|
14
|
+
if (stored === undefined) return false;
|
|
15
|
+
return verifyPassword(password, stored.passwordHash);
|
|
16
|
+
}
|