@softure-ai/auth 0.2.5 → 0.2.7
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/CHANGELOG.md +59 -0
- package/README.md +113 -15
- package/dist/contract.d.ts +11 -1
- package/dist/contract.d.ts.map +1 -1
- package/dist/contract.js.map +1 -1
- package/dist/index.d.ts +72 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +9 -4
- package/dist/index.js.map +1 -1
- package/dist/messages/en.d.ts +10 -0
- package/dist/messages/en.d.ts.map +1 -1
- package/dist/messages/en.js +10 -0
- package/dist/messages/en.js.map +1 -1
- package/dist/messages/index.d.ts +28 -2
- package/dist/messages/index.d.ts.map +1 -1
- package/dist/messages/index.js +13 -3
- package/dist/messages/index.js.map +1 -1
- package/dist/next/actions.d.ts +5 -0
- package/dist/next/actions.d.ts.map +1 -1
- package/dist/next/actions.js +26 -15
- package/dist/next/actions.js.map +1 -1
- package/dist/next/index.d.ts +2 -1
- package/dist/next/index.d.ts.map +1 -1
- package/dist/next/index.js +2 -1
- package/dist/next/index.js.map +1 -1
- package/dist/next/oidc-cookie.d.ts +7 -0
- package/dist/next/oidc-cookie.d.ts.map +1 -0
- package/dist/next/oidc-cookie.js +25 -0
- package/dist/next/oidc-cookie.js.map +1 -0
- package/dist/next/oidc-login-url.d.ts +4 -0
- package/dist/next/oidc-login-url.d.ts.map +1 -0
- package/dist/next/oidc-login-url.js +13 -0
- package/dist/next/oidc-login-url.js.map +1 -0
- package/dist/next/oidc-route.d.ts +7 -0
- package/dist/next/oidc-route.d.ts.map +1 -0
- package/dist/next/oidc-route.js +48 -0
- package/dist/next/oidc-route.js.map +1 -0
- package/dist/next/pages.d.ts +5 -0
- package/dist/next/pages.d.ts.map +1 -1
- package/dist/next/pages.js +19 -4
- package/dist/next/pages.js.map +1 -1
- package/dist/next/params.d.ts +2 -0
- package/dist/next/params.d.ts.map +1 -1
- package/dist/next/params.js +2 -0
- package/dist/next/params.js.map +1 -1
- package/dist/next/previous-session.d.ts +6 -0
- package/dist/next/previous-session.d.ts.map +1 -0
- package/dist/next/previous-session.js +23 -0
- package/dist/next/previous-session.js.map +1 -0
- package/dist/options.d.ts +99 -1
- package/dist/options.d.ts.map +1 -1
- package/dist/options.js +80 -0
- package/dist/options.js.map +1 -1
- package/dist/proxy/index.d.ts.map +1 -1
- package/dist/proxy/index.js +3 -1
- package/dist/proxy/index.js.map +1 -1
- package/dist/schema.d.ts +323 -0
- package/dist/schema.d.ts.map +1 -1
- package/dist/schema.js +26 -3
- package/dist/schema.js.map +1 -1
- package/dist/server/change-password.d.ts +1 -1
- package/dist/server/change-password.d.ts.map +1 -1
- package/dist/server/change-password.js +3 -0
- package/dist/server/change-password.js.map +1 -1
- package/dist/server/health.d.ts.map +1 -1
- package/dist/server/health.js +2 -0
- package/dist/server/health.js.map +1 -1
- package/dist/server/index.d.ts +1 -0
- package/dist/server/index.d.ts.map +1 -1
- package/dist/server/index.js +1 -0
- package/dist/server/index.js.map +1 -1
- package/dist/server/login.d.ts +1 -1
- package/dist/server/login.d.ts.map +1 -1
- package/dist/server/login.js +4 -2
- package/dist/server/login.js.map +1 -1
- package/dist/server/oidc/accounts.d.ts +14 -0
- package/dist/server/oidc/accounts.d.ts.map +1 -0
- package/dist/server/oidc/accounts.js +79 -0
- package/dist/server/oidc/accounts.js.map +1 -0
- package/dist/server/oidc/context.d.ts +37 -0
- package/dist/server/oidc/context.d.ts.map +1 -0
- package/dist/server/oidc/context.js +34 -0
- package/dist/server/oidc/context.js.map +1 -0
- package/dist/server/oidc/discovery.d.ts +24 -0
- package/dist/server/oidc/discovery.d.ts.map +1 -0
- package/dist/server/oidc/discovery.js +109 -0
- package/dist/server/oidc/discovery.js.map +1 -0
- package/dist/server/oidc/flow.d.ts +49 -0
- package/dist/server/oidc/flow.d.ts.map +1 -0
- package/dist/server/oidc/flow.js +168 -0
- package/dist/server/oidc/flow.js.map +1 -0
- package/dist/server/oidc/id-token.d.ts +45 -0
- package/dist/server/oidc/id-token.d.ts.map +1 -0
- package/dist/server/oidc/id-token.js +122 -0
- package/dist/server/oidc/id-token.js.map +1 -0
- package/dist/server/oidc/index.d.ts +4 -0
- package/dist/server/oidc/index.d.ts.map +1 -0
- package/dist/server/oidc/index.js +4 -0
- package/dist/server/oidc/index.js.map +1 -0
- package/dist/server/oidc/token-request.d.ts +13 -0
- package/dist/server/oidc/token-request.d.ts.map +1 -0
- package/dist/server/oidc/token-request.js +49 -0
- package/dist/server/oidc/token-request.js.map +1 -0
- package/dist/server/password-reset.d.ts +1 -1
- package/dist/server/password-reset.d.ts.map +1 -1
- package/dist/server/password-reset.js +7 -7
- package/dist/server/password-reset.js.map +1 -1
- package/dist/server/privacy.d.ts +10 -0
- package/dist/server/privacy.d.ts.map +1 -1
- package/dist/server/privacy.js +18 -6
- package/dist/server/privacy.js.map +1 -1
- package/dist/server/rate-limits.d.ts +4 -1
- package/dist/server/rate-limits.d.ts.map +1 -1
- package/dist/server/rate-limits.js +10 -3
- package/dist/server/rate-limits.js.map +1 -1
- package/dist/server/register.js +2 -2
- package/dist/server/register.js.map +1 -1
- package/dist/server/sessions.js +2 -2
- package/dist/server/sessions.js.map +1 -1
- package/dist/server/switches.d.ts +1 -1
- package/dist/server/switches.d.ts.map +1 -1
- package/dist/server/switches.js +3 -1
- package/dist/server/switches.js.map +1 -1
- package/dist/testing/account.js +2 -2
- package/dist/testing/account.js.map +1 -1
- package/dist/testing/index.d.ts +1 -0
- package/dist/testing/index.d.ts.map +1 -1
- package/dist/testing/index.js +3 -1
- package/dist/testing/index.js.map +1 -1
- package/dist/testing/oidc-provider.d.ts +68 -0
- package/dist/testing/oidc-provider.d.ts.map +1 -0
- package/dist/testing/oidc-provider.js +185 -0
- package/dist/testing/oidc-provider.js.map +1 -0
- package/dist/ui/index.d.ts +1 -0
- package/dist/ui/index.d.ts.map +1 -1
- package/dist/ui/index.js +1 -0
- package/dist/ui/index.js.map +1 -1
- package/dist/ui/oidc-sign-in.d.ts +25 -0
- package/dist/ui/oidc-sign-in.d.ts.map +1 -0
- package/dist/ui/oidc-sign-in.js +19 -0
- package/dist/ui/oidc-sign-in.js.map +1 -0
- package/migrations/0005_create_identities_and_oidc_states.sql +34 -0
- package/migrations/0006_add_users_display_name.sql +8 -0
- package/module.json +3 -2
- package/package.json +2 -2
- package/src/contract.ts +16 -1
- package/src/index.ts +20 -5
- package/src/messages/en.ts +10 -0
- package/src/messages/index.ts +29 -4
- package/src/next/actions.ts +23 -14
- package/src/next/index.ts +2 -0
- package/src/next/oidc-cookie.ts +31 -0
- package/src/next/oidc-login-url.ts +14 -0
- package/src/next/oidc-route.ts +48 -0
- package/src/next/pages.tsx +38 -11
- package/src/next/params.ts +3 -0
- package/src/next/previous-session.ts +23 -0
- package/src/options.ts +86 -1
- package/src/proxy/index.ts +3 -1
- package/src/schema.ts +33 -3
- package/src/server/change-password.ts +3 -0
- package/src/server/health.ts +2 -0
- package/src/server/index.ts +17 -0
- package/src/server/login.ts +3 -2
- package/src/server/oidc/accounts.ts +92 -0
- package/src/server/oidc/context.ts +56 -0
- package/src/server/oidc/discovery.ts +133 -0
- package/src/server/oidc/flow.ts +196 -0
- package/src/server/oidc/id-token.ts +143 -0
- package/src/server/oidc/index.ts +14 -0
- package/src/server/oidc/token-request.ts +59 -0
- package/src/server/password-reset.ts +7 -7
- package/src/server/privacy.ts +28 -6
- package/src/server/rate-limits.ts +11 -3
- package/src/server/register.ts +2 -2
- package/src/server/sessions.ts +2 -2
- package/src/server/switches.ts +2 -1
- package/src/testing/account.ts +2 -2
- package/src/testing/index.ts +10 -1
- package/src/testing/oidc-provider.ts +254 -0
- package/src/ui/index.ts +1 -0
- package/src/ui/oidc-sign-in.tsx +61 -0
package/src/index.ts
CHANGED
|
@@ -23,7 +23,8 @@ export const REGISTRATION_CLOSED_ENV = "SOFTURE_SWITCH_AUTH_REGISTRATION_CLOSED"
|
|
|
23
23
|
* Rate limit buckets auth consumes, with defaults to spread into `security({ buckets })`:
|
|
24
24
|
* `register` and `login` per client address, `login-account` per email, `change-password` per user,
|
|
25
25
|
* `password-reset` (link requests) and `password-reset-confirm` (new passwords) per client address,
|
|
26
|
-
*
|
|
26
|
+
* `password-reset-account` per email, which bounds the mails one address can receive, and `oidc-start` and
|
|
27
|
+
* `oidc-callback` (OpenID Connect sign-ins started and completed) per client address.
|
|
27
28
|
*/
|
|
28
29
|
export const AUTH_RATE_LIMIT_BUCKETS = {
|
|
29
30
|
register: { limit: 5, windowMinutes: 15, key: "ip" },
|
|
@@ -33,6 +34,8 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
|
|
|
33
34
|
"password-reset": { limit: 10, windowMinutes: 15, key: "ip" },
|
|
34
35
|
"password-reset-account": { limit: 3, windowMinutes: 15, key: "account" },
|
|
35
36
|
"password-reset-confirm": { limit: 10, windowMinutes: 15, key: "ip" },
|
|
37
|
+
"oidc-start": { limit: 20, windowMinutes: 15, key: "ip" },
|
|
38
|
+
"oidc-callback": { limit: 20, windowMinutes: 15, key: "ip" },
|
|
36
39
|
} as const satisfies Readonly<Record<string, RateLimitBucketInput>>;
|
|
37
40
|
|
|
38
41
|
/**
|
|
@@ -42,10 +45,10 @@ export const AUTH_RATE_LIMIT_BUCKETS = {
|
|
|
42
45
|
export const auth = defineModule({
|
|
43
46
|
manifest: {
|
|
44
47
|
id: MODULE_ID,
|
|
45
|
-
version: "0.2.
|
|
48
|
+
version: "0.2.7",
|
|
46
49
|
dependsOn: { security: "^0.2.0", mailing: "^0.2.0?", ops: "^0.2.0?", jobs: "^0.1.1?" },
|
|
47
50
|
dbSchema: "auth",
|
|
48
|
-
tables: ["users", "sessions", "user_roles", "password_resets"],
|
|
51
|
+
tables: ["users", "sessions", "user_roles", "password_resets", "identities", "oidc_states"],
|
|
49
52
|
env: [
|
|
50
53
|
{
|
|
51
54
|
name: REGISTRATION_CLOSED_ENV,
|
|
@@ -70,6 +73,7 @@ export const auth = defineModule({
|
|
|
70
73
|
{ kind: "page", path: "app/forgot-password/page.tsx", export: "ForgotPasswordPage" },
|
|
71
74
|
{ kind: "page", path: "app/reset-password/page.tsx", export: "ResetPasswordPage" },
|
|
72
75
|
{ kind: "route-handler", path: "app/api/auth/session/route.ts", export: "getSessionRoute" },
|
|
76
|
+
{ kind: "route-handler", path: "app/api/auth/oidc/[provider]/callback/route.ts", export: "oidcCallbackRoute" },
|
|
73
77
|
{ kind: "middleware", path: "proxy.ts", export: "createAuthGuard" },
|
|
74
78
|
],
|
|
75
79
|
privacy: { exports: true, deletes: true },
|
|
@@ -89,11 +93,22 @@ export type {
|
|
|
89
93
|
AuthFormState,
|
|
90
94
|
AuthUser,
|
|
91
95
|
NewSession,
|
|
96
|
+
OidcSignInErrorCode,
|
|
92
97
|
RegisteredEvent,
|
|
93
98
|
SignedIn,
|
|
94
99
|
} from "./contract.js";
|
|
95
100
|
export { authMessages, getAuthErrorMessage, type AuthMessages } from "./messages/index.js";
|
|
96
|
-
export
|
|
101
|
+
export {
|
|
102
|
+
OIDC_PROVIDER_ID_PATTERN,
|
|
103
|
+
type AuthOptions,
|
|
104
|
+
type AuthOptionsInput,
|
|
105
|
+
type OidcProvider,
|
|
106
|
+
type OidcProviderInput,
|
|
107
|
+
type OnRegisteredHook,
|
|
108
|
+
type RewriteRedirect,
|
|
109
|
+
type RewriteRedirectContext,
|
|
110
|
+
type ScryptParams,
|
|
111
|
+
} from "./options.js";
|
|
97
112
|
export {
|
|
98
113
|
consolePasswordResetSender,
|
|
99
114
|
type PasswordResetDetails,
|
|
@@ -103,4 +118,4 @@ export {
|
|
|
103
118
|
export { getSessionCookie, type SessionCookie } from "./session-cookie.js";
|
|
104
119
|
export { toSafeNextPath } from "./safe-next-path.js";
|
|
105
120
|
export { ADMIN_ROLE, ROLE_NAME_PATTERN } from "./roles.js";
|
|
106
|
-
export { passwordResets, sessions, userRoles, users } from "./schema.js";
|
|
121
|
+
export { identities, oidcStates, passwordResets, sessions, userRoles, users } from "./schema.js";
|
package/src/messages/en.ts
CHANGED
|
@@ -64,6 +64,12 @@ export const en = {
|
|
|
64
64
|
logout: {
|
|
65
65
|
submit: "Log out",
|
|
66
66
|
},
|
|
67
|
+
oidc: {
|
|
68
|
+
/** The button of an OpenID Connect provider; `{provider}` is its `name` (e.g. Google). */
|
|
69
|
+
signInWith: "Sign in with {provider}",
|
|
70
|
+
/** Between the provider buttons and the password form. */
|
|
71
|
+
divider: "or",
|
|
72
|
+
},
|
|
67
73
|
errors: {
|
|
68
74
|
auth: {
|
|
69
75
|
invalid_credentials: "The email or password is incorrect.",
|
|
@@ -79,6 +85,10 @@ export const en = {
|
|
|
79
85
|
forbidden: "You do not have access to this.",
|
|
80
86
|
reset_token_invalid: "This link has expired or has already been used. Ask for a new one.",
|
|
81
87
|
password_reset_unavailable: "Password reset is not available.",
|
|
88
|
+
oidc_failed: "Signing in did not work. Try again.",
|
|
89
|
+
oidc_cancelled: "Signing in was cancelled.",
|
|
90
|
+
oidc_not_allowed: "This account may not sign in here.",
|
|
91
|
+
oidc_no_account: "There is no account for this sign-in. Ask for access.",
|
|
82
92
|
},
|
|
83
93
|
security: {
|
|
84
94
|
rate_limited: "Too many attempts. Wait a few minutes and try again.",
|
package/src/messages/index.ts
CHANGED
|
@@ -4,11 +4,36 @@ import { en } from "./en.js";
|
|
|
4
4
|
/** The built-in English dictionary; an app passes partial overrides or its own translation per locale. */
|
|
5
5
|
export const authMessages = { en };
|
|
6
6
|
|
|
7
|
-
|
|
7
|
+
type EnglishMessages = typeof en;
|
|
8
|
+
type AuthErrorCopy = EnglishMessages["errors"]["auth"];
|
|
9
|
+
type OidcErrorName = "oidc_failed" | "oidc_cancelled" | "oidc_not_allowed" | "oidc_no_account";
|
|
8
10
|
|
|
9
|
-
/**
|
|
11
|
+
/**
|
|
12
|
+
* One locale's copy. The OpenID Connect keys (`oidc`, `errors.auth.oidc_*`) are optional, so a dictionary written
|
|
13
|
+
* before them still compiles; a missing one reads the English copy.
|
|
14
|
+
*/
|
|
15
|
+
export type AuthMessages = Omit<EnglishMessages, "oidc" | "errors"> & {
|
|
16
|
+
readonly oidc?: EnglishMessages["oidc"];
|
|
17
|
+
readonly errors: Omit<EnglishMessages["errors"], "auth"> & {
|
|
18
|
+
readonly auth: Omit<AuthErrorCopy, OidcErrorName> & Partial<Pick<AuthErrorCopy, OidcErrorName>>;
|
|
19
|
+
};
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** The OpenID Connect copy of `messages`, or the English one when the dictionary has none. */
|
|
23
|
+
export function getOidcMessages(messages: AuthMessages): EnglishMessages["oidc"] {
|
|
24
|
+
return messages.oidc ?? en.oidc;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* The copy for an error code: the dictionary's, else the English one (a key the dictionary predates); an unknown code
|
|
29
|
+
* gets the dictionary's generic failure.
|
|
30
|
+
*/
|
|
10
31
|
export function getAuthErrorMessage(messages: AuthMessages, code: AuthFormErrorCode): string {
|
|
32
|
+
return findErrorCopy(messages.errors, code) ?? findErrorCopy(en.errors, code) ?? messages.errors.core.unexpected;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
function findErrorCopy(errors: AuthMessages["errors"], code: string): string | undefined {
|
|
11
36
|
const [namespace, name] = code.split(".", 2) as [string, string];
|
|
12
|
-
const group: Readonly<Record<string, string>> | undefined = (
|
|
13
|
-
return
|
|
37
|
+
const group: Readonly<Record<string, string | undefined>> | undefined = (errors as Readonly<Record<string, Readonly<Record<string, string | undefined>>>>)[namespace];
|
|
38
|
+
return group !== undefined && Object.hasOwn(group, name) ? group[name] : undefined;
|
|
14
39
|
}
|
package/src/next/actions.ts
CHANGED
|
@@ -21,10 +21,14 @@ import { loginUser } from "../server/login.js";
|
|
|
21
21
|
import { getAuthRoutes } from "../server/options.js";
|
|
22
22
|
import { deliverPasswordReset, requestPasswordReset, resetPassword } from "../server/password-reset.js";
|
|
23
23
|
import { registerUser } from "../server/register.js";
|
|
24
|
+
import { startOidcSignIn } from "../server/oidc/flow.js";
|
|
24
25
|
import { logoutSession } from "../server/sessions.js";
|
|
25
26
|
import { getAuthContext } from "./context.js";
|
|
27
|
+
import { writeOidcStateCookie } from "./oidc-cookie.js";
|
|
28
|
+
import { getOidcErrorLoginPath } from "./oidc-login-url.js";
|
|
26
29
|
import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
|
|
27
|
-
import {
|
|
30
|
+
import { endPreviousSession, readHeldTokens } from "./previous-session.js";
|
|
31
|
+
import { clearSessionCookie, readSessionToken, writeSessionCookie } from "./session-cookie.js";
|
|
28
32
|
|
|
29
33
|
/** Longer values are cut: the server functions refuse them anyway, and nothing huge is echoed back. */
|
|
30
34
|
const MAX_FIELD_LENGTH = 4096;
|
|
@@ -44,6 +48,7 @@ const registerInput = z.object({ email: text, password: text, next: nextPath, co
|
|
|
44
48
|
const changePasswordInput = z.object({ currentPassword: text, newPassword: text });
|
|
45
49
|
const forgotPasswordInput = z.object({ email: text });
|
|
46
50
|
const resetPasswordInput = z.object({ token: text, newPassword: text });
|
|
51
|
+
const oidcSignInInput = z.object({ provider: text, next: nextPath });
|
|
47
52
|
|
|
48
53
|
const FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
|
|
49
54
|
"auth.email_invalid": "email",
|
|
@@ -208,21 +213,25 @@ export async function resetPasswordAction(_previous: AuthFormState, formData: Fo
|
|
|
208
213
|
redirect(await resolveRedirectTarget(config, `${getAuthRoutes(config).login}?${PASSWORD_RESET_DONE_PARAM}=1`));
|
|
209
214
|
}
|
|
210
215
|
|
|
211
|
-
/**
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
+
/**
|
|
217
|
+
* Starts an OpenID Connect sign-in: the provider button's form posts `provider` and `next`. The state goes into a
|
|
218
|
+
* short-lived cookie and the browser to the provider; a failure goes back to the login page, which shows its code.
|
|
219
|
+
*/
|
|
220
|
+
export async function oidcSignInAction(formData: FormData): Promise<void> {
|
|
221
|
+
const config = getSoftureConfig();
|
|
222
|
+
const input = readForm(oidcSignInInput, formData);
|
|
223
|
+
const client = identifyClient({ config }, await headers());
|
|
224
|
+
if (!client.ok) redirect(getOidcErrorLoginPath(config, client.error, input.next));
|
|
216
225
|
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
} catch (error) {
|
|
223
|
-
reportFailure("ending the previous session", error);
|
|
224
|
-
}
|
|
226
|
+
let result;
|
|
227
|
+
try {
|
|
228
|
+
result = await startOidcSignIn(await getAuthContext(config), { provider: input.provider, next: input.next, clientKey: client.value });
|
|
229
|
+
} catch (error) {
|
|
230
|
+
result = { ok: false as const, error: reportFailure("starting an OpenID Connect sign-in", error) };
|
|
225
231
|
}
|
|
232
|
+
if (!result.ok) redirect(getOidcErrorLoginPath(config, result.error, input.next));
|
|
233
|
+
await writeOidcStateCookie(config, result.value.state, result.value.maxAgeSeconds);
|
|
234
|
+
redirect(result.value.url);
|
|
226
235
|
}
|
|
227
236
|
|
|
228
237
|
/** Where to go after logout: a path on this app, checked like login's `next`. */
|
package/src/next/index.ts
CHANGED
|
@@ -6,6 +6,7 @@ export {
|
|
|
6
6
|
loginAction,
|
|
7
7
|
logoutAction,
|
|
8
8
|
type LogoutInput,
|
|
9
|
+
oidcSignInAction,
|
|
9
10
|
registerAction,
|
|
10
11
|
resetPasswordAction,
|
|
11
12
|
} from "./actions.js";
|
|
@@ -30,5 +31,6 @@ export {
|
|
|
30
31
|
type RegisterPageOptions,
|
|
31
32
|
ResetPasswordPage,
|
|
32
33
|
} from "./pages.js";
|
|
34
|
+
export { oidcCallbackRoute } from "./oidc-route.js";
|
|
33
35
|
export { getSessionRoute } from "./route.js";
|
|
34
36
|
export type { PageSearchParams } from "./search-params.js";
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// The cookie that ties an OpenID Connect sign-in to the browser that started it: it holds the state until the
|
|
2
|
+
// provider sends the browser back. Host-only, httpOnly, `SameSite=Lax` (the callback is a top-level GET from the
|
|
3
|
+
// provider's site, which Lax lets through) and as short-lived as the sign-in itself.
|
|
4
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
5
|
+
import { cookies } from "next/headers";
|
|
6
|
+
import { getSessionCookie } from "../session-cookie.js";
|
|
7
|
+
import { getAuthOptions } from "../server/options.js";
|
|
8
|
+
|
|
9
|
+
function getOidcCookie(config: SoftureConfig) {
|
|
10
|
+
const { secure } = getSessionCookie(config);
|
|
11
|
+
const name = `${secure ? "__Host-" : ""}${getAuthOptions(config).cookie.name}_oidc`;
|
|
12
|
+
return { name, secure, httpOnly: true, sameSite: "lax" as const, path: "/" };
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
export async function writeOidcStateCookie(config: SoftureConfig, state: string, maxAgeSeconds: number): Promise<void> {
|
|
16
|
+
const { name, ...attributes } = getOidcCookie(config);
|
|
17
|
+
(await cookies()).set(name, state, { ...attributes, maxAge: maxAgeSeconds });
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** The state of the sign-in this browser started, or null. */
|
|
21
|
+
export async function readOidcStateCookie(config: SoftureConfig): Promise<string | null> {
|
|
22
|
+
const value = (await cookies()).get(getOidcCookie(config).name)?.value;
|
|
23
|
+
return value === undefined || value === "" ? null : value;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** Removes the cookie: a state is used once, whatever the callback came to. */
|
|
27
|
+
export async function clearOidcStateCookie(config: SoftureConfig): Promise<void> {
|
|
28
|
+
const { name, ...attributes } = getOidcCookie(config);
|
|
29
|
+
const store = await cookies();
|
|
30
|
+
if (store.get(name) !== undefined) store.set(name, "", { ...attributes, maxAge: 0 });
|
|
31
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// The login page a failed OpenID Connect sign-in goes back to, with the error code it shows.
|
|
2
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
3
|
+
import { toSafeNextPath } from "../safe-next-path.js";
|
|
4
|
+
import { getAuthRoutes } from "../server/options.js";
|
|
5
|
+
import { OIDC_ERROR_PARAM } from "./params.js";
|
|
6
|
+
|
|
7
|
+
/** `<login>?oidc_error=<code>[&next=…]`, a path on this app. */
|
|
8
|
+
export function getOidcErrorLoginPath(config: SoftureConfig, code: string, next?: string): string {
|
|
9
|
+
const routes = getAuthRoutes(config);
|
|
10
|
+
const query = new URLSearchParams({ [OIDC_ERROR_PARAM]: code });
|
|
11
|
+
const target = toSafeNextPath(next, routes.afterLogin);
|
|
12
|
+
if (target !== routes.afterLogin) query.set("next", target);
|
|
13
|
+
return `${routes.login}?${query.toString()}`;
|
|
14
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
// The OpenID Connect callback, mounted with one line:
|
|
2
|
+
// `app/api/auth/oidc/[provider]/callback/route.ts → export { oidcCallbackRoute as GET } from "@softure-ai/auth/next";`
|
|
3
|
+
// The provider sends the browser here with `code` and `state` (or `error`). The answer is always a `303`: to the
|
|
4
|
+
// sign-in's `next` with a new session cookie, or to the login page with `?oidc_error=<code>`. The state cookie is
|
|
5
|
+
// cleared either way, and the URL (it carries the code) is never sent on as a referrer.
|
|
6
|
+
import { errorLogLabel, safeError, type SoftureConfig } from "@softure-ai/core";
|
|
7
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
8
|
+
import { identifyClient } from "@softure-ai/security/server";
|
|
9
|
+
import { resolveRedirectTarget } from "../redirect-target.js";
|
|
10
|
+
import { completeOidcSignIn } from "../server/oidc/flow.js";
|
|
11
|
+
import { getAuthContext } from "./context.js";
|
|
12
|
+
import { clearOidcStateCookie, readOidcStateCookie } from "./oidc-cookie.js";
|
|
13
|
+
import { getOidcErrorLoginPath } from "./oidc-login-url.js";
|
|
14
|
+
import { endPreviousSession } from "./previous-session.js";
|
|
15
|
+
import { writeSessionCookie } from "./session-cookie.js";
|
|
16
|
+
|
|
17
|
+
const NO_STORE = { "cache-control": "no-store", "referrer-policy": "no-referrer" };
|
|
18
|
+
|
|
19
|
+
function seeOther(config: SoftureConfig, path: string): Response {
|
|
20
|
+
return new Response(null, { status: 303, headers: { ...NO_STORE, location: new URL(path, config.appOrigin).toString() } });
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `GET /api/auth/oidc/<provider>/callback`. */
|
|
24
|
+
export async function oidcCallbackRoute(request: Request, route: { readonly params: Promise<{ readonly provider: string }> }): Promise<Response> {
|
|
25
|
+
const config = getSoftureConfig();
|
|
26
|
+
const { provider } = await route.params;
|
|
27
|
+
const query = new URL(request.url).searchParams;
|
|
28
|
+
const browserState = await readOidcStateCookie(config);
|
|
29
|
+
await clearOidcStateCookie(config);
|
|
30
|
+
const client = identifyClient({ config }, request.headers);
|
|
31
|
+
if (!client.ok) return seeOther(config, getOidcErrorLoginPath(config, client.error));
|
|
32
|
+
|
|
33
|
+
try {
|
|
34
|
+
const result = await completeOidcSignIn(await getAuthContext(config), {
|
|
35
|
+
provider,
|
|
36
|
+
params: { state: query.get("state"), code: query.get("code"), error: query.get("error") },
|
|
37
|
+
browserState,
|
|
38
|
+
clientKey: client.value,
|
|
39
|
+
});
|
|
40
|
+
if (!result.ok) return seeOther(config, getOidcErrorLoginPath(config, result.error));
|
|
41
|
+
await endPreviousSession(config);
|
|
42
|
+
await writeSessionCookie(config, result.value.session);
|
|
43
|
+
return seeOther(config, await resolveRedirectTarget(config, result.value.next));
|
|
44
|
+
} catch (error) {
|
|
45
|
+
console.error(`@softure-ai/auth: completing an OpenID Connect sign-in failed: ${errorLogLabel(error)}`);
|
|
46
|
+
return seeOther(config, getOidcErrorLoginPath(config, safeError(error).error));
|
|
47
|
+
}
|
|
48
|
+
}
|
package/src/next/pages.tsx
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
// Pages ready to mount with one line: `export { LoginPage as default } from "@softure-ai/auth/next"`.
|
|
2
2
|
// Server components: they read the config and the session, and render the forms from `../ui`.
|
|
3
3
|
import type { SoftureConfig } from "@softure-ai/core";
|
|
4
|
+
import type { AuthFormErrorCode } from "../contract.js";
|
|
4
5
|
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
5
6
|
import { Card } from "@softure-ai/ui";
|
|
6
7
|
import { notFound, redirect } from "next/navigation";
|
|
@@ -10,12 +11,15 @@ import { toSafeNextPath } from "../safe-next-path.js";
|
|
|
10
11
|
import { getAuthOptions, getAuthRoutes } from "../server/options.js";
|
|
11
12
|
import { findPasswordResetUser, isPasswordResetEnabled, RESET_TOKEN_PARAM } from "../server/password-reset.js";
|
|
12
13
|
import { isRegistrationClosed } from "../server/switches.js";
|
|
14
|
+
import { getAuthErrorMessage } from "../messages/index.js";
|
|
15
|
+
import { getOidcProviders } from "../server/oidc/context.js";
|
|
13
16
|
import { ChangePasswordForm, ForgotPasswordForm, LoginForm, RegisterForm, ResetPasswordForm } from "../ui/auth-forms.js";
|
|
14
|
-
import {
|
|
17
|
+
import { OidcSignIn } from "../ui/oidc-sign-in.js";
|
|
18
|
+
import { changePasswordAction, forgotPasswordAction, loginAction, oidcSignInAction, registerAction, resetPasswordAction } from "./actions.js";
|
|
15
19
|
import { getAuthContext } from "./context.js";
|
|
16
20
|
import { getCurrentUser, requireUser } from "./current-user.js";
|
|
17
21
|
import { getAuthMessages } from "./messages.js";
|
|
18
|
-
import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
|
|
22
|
+
import { OIDC_ERROR_PARAM, PASSWORD_RESET_DONE_PARAM } from "./params.js";
|
|
19
23
|
import { toUrlSearchParams } from "./search-params.js";
|
|
20
24
|
|
|
21
25
|
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
|
|
@@ -27,6 +31,8 @@ export interface AuthPageProps {
|
|
|
27
31
|
const LAYOUT_CLASS = "sft:mx-auto sft:box-border sft:w-full sft:sm:max-w-md sft:px-4 sft:py-4";
|
|
28
32
|
const FOOTER_CLASS = "sft:m-0 sft:text-sm sft:text-muted";
|
|
29
33
|
const LINK_CLASS = "sft:font-medium sft:text-accent";
|
|
34
|
+
/** An error code as auth writes it into `?oidc_error=`; anything else in the URL is not shown. */
|
|
35
|
+
const ERROR_CODE = /^[a-z]+\.[a-z_]{1,64}$/;
|
|
30
36
|
/** The server keeps 512 characters of a registration field; nothing longer is echoed into the page. */
|
|
31
37
|
const MAX_CARRIED_LENGTH = 512;
|
|
32
38
|
|
|
@@ -54,24 +60,43 @@ async function redirectSignedIn(config: SoftureConfig, next: string, searchParam
|
|
|
54
60
|
redirect(await resolveRedirectTarget(config, next, toUrlSearchParams(await searchParams)));
|
|
55
61
|
}
|
|
56
62
|
|
|
63
|
+
/**
|
|
64
|
+
* The login page: the OpenID Connect buttons when the app configured providers, then the password form unless
|
|
65
|
+
* `password.enabled` is false. A failed provider sign-in comes back here with `?oidc_error=`, shown above the buttons.
|
|
66
|
+
*/
|
|
57
67
|
export async function LoginPage({ searchParams }: AuthPageProps) {
|
|
58
68
|
const config = getSoftureConfig();
|
|
59
69
|
const routes = getAuthRoutes(config);
|
|
60
70
|
const next = await readNext(searchParams, routes.afterLogin);
|
|
61
71
|
if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
|
|
62
72
|
const messages = getAuthMessages(config);
|
|
73
|
+
const isPasswordOn = getAuthOptions(config).password.enabled;
|
|
74
|
+
const providers = getOidcProviders(config).map((provider) => ({ id: provider.id, name: provider.name }));
|
|
75
|
+
const oidcError = await readParam(searchParams, OIDC_ERROR_PARAM);
|
|
63
76
|
const isClosed = await isRegistrationClosed(await getAuthContext(config));
|
|
64
77
|
return (
|
|
65
78
|
<AuthLayout title={messages.login.title} lead={messages.login.lead}>
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
79
|
+
{providers.length === 0 ? null : (
|
|
80
|
+
<OidcSignIn
|
|
81
|
+
action={oidcSignInAction}
|
|
82
|
+
providers={providers}
|
|
83
|
+
messages={messages}
|
|
84
|
+
next={next}
|
|
85
|
+
error={oidcError !== undefined && ERROR_CODE.test(oidcError) ? getAuthErrorMessage(messages, oidcError as AuthFormErrorCode) : undefined}
|
|
86
|
+
hasDivider={isPasswordOn}
|
|
87
|
+
/>
|
|
88
|
+
)}
|
|
89
|
+
{!isPasswordOn ? null : (
|
|
90
|
+
<LoginForm
|
|
91
|
+
action={loginAction}
|
|
92
|
+
messages={messages}
|
|
93
|
+
locale={config.locale}
|
|
94
|
+
next={next}
|
|
95
|
+
registerHref={isClosed ? undefined : routes.register}
|
|
96
|
+
forgotPasswordHref={isPasswordResetEnabled(config) ? routes.forgotPassword : undefined}
|
|
97
|
+
notice={(await readParam(searchParams, PASSWORD_RESET_DONE_PARAM)) === "1" ? messages.resetPassword.success : undefined}
|
|
98
|
+
/>
|
|
99
|
+
)}
|
|
75
100
|
</AuthLayout>
|
|
76
101
|
);
|
|
77
102
|
}
|
|
@@ -147,8 +172,10 @@ async function readCarriedFields(searchParams: SearchParams | undefined, declare
|
|
|
147
172
|
return carried;
|
|
148
173
|
}
|
|
149
174
|
|
|
175
|
+
/** Not found when `password.enabled` is false: there is no password to change. */
|
|
150
176
|
export async function ChangePasswordPage() {
|
|
151
177
|
const config = getSoftureConfig();
|
|
178
|
+
if (!getAuthOptions(config).password.enabled) notFound();
|
|
152
179
|
const routes = getAuthRoutes(config);
|
|
153
180
|
await requireUser({ next: routes.changePassword });
|
|
154
181
|
const messages = getAuthMessages(config);
|
package/src/next/params.ts
CHANGED
|
@@ -2,3 +2,6 @@
|
|
|
2
2
|
|
|
3
3
|
/** Set on the login page after a password reset, so it confirms the change. */
|
|
4
4
|
export const PASSWORD_RESET_DONE_PARAM = "reset";
|
|
5
|
+
|
|
6
|
+
/** Set on the login page after a failed OpenID Connect sign-in: the error code it shows. */
|
|
7
|
+
export const OIDC_ERROR_PARAM = "oidc_error";
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
// The sessions a browser already holds when it signs in again, ended before the new cookie is written, so they
|
|
2
|
+
// cannot be reused. Shared by the login and register actions and the OpenID Connect callback.
|
|
3
|
+
import { errorLogLabel, type SoftureConfig } from "@softure-ai/core";
|
|
4
|
+
import { logoutSession } from "../server/sessions.js";
|
|
5
|
+
import { getAuthContext } from "./context.js";
|
|
6
|
+
import { readLegacySessionToken, readSessionToken } from "./session-cookie.js";
|
|
7
|
+
|
|
8
|
+
/** Every session token the browser holds: the current cookie's and a legacy session's. */
|
|
9
|
+
export async function readHeldTokens(config: SoftureConfig): Promise<string[]> {
|
|
10
|
+
const tokens = [await readSessionToken(config), await readLegacySessionToken(config)];
|
|
11
|
+
return [...new Set(tokens.filter((token) => token !== null))];
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** Ends the sessions the browser held before a sign-in. A failure is logged: the new session still opens. */
|
|
15
|
+
export async function endPreviousSession(config: SoftureConfig): Promise<void> {
|
|
16
|
+
for (const previous of await readHeldTokens(config)) {
|
|
17
|
+
try {
|
|
18
|
+
await logoutSession(await getAuthContext(config), previous);
|
|
19
|
+
} catch (error) {
|
|
20
|
+
console.error(`@softure-ai/auth: ending the previous session failed: ${errorLogLabel(error)}`);
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
package/src/options.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// The options an app passes to `auth({ ... })` in softure.config.ts, parsed at startup.
|
|
2
|
-
import type { ModuleContext, SoftureConfig } from "@softure-ai/core";
|
|
2
|
+
import type { FetchFunction, ModuleContext, SoftureConfig } from "@softure-ai/core";
|
|
3
3
|
import type { Queryable } from "@softure-ai/db";
|
|
4
4
|
import { z } from "zod";
|
|
5
5
|
import type { RegisteredEvent } from "./contract.js";
|
|
@@ -86,9 +86,76 @@ function parseAdminEmailList(raw: string): string[] {
|
|
|
86
86
|
return emails;
|
|
87
87
|
}
|
|
88
88
|
|
|
89
|
+
/** A provider id: the path segment of its callback (`/api/auth/oidc/<id>/callback`) and the key of its identities. */
|
|
90
|
+
export const OIDC_PROVIDER_ID_PATTERN = /^[a-z][a-z0-9-]{0,31}$/;
|
|
91
|
+
const GOOGLE_ISSUER = "https://accounts.google.com";
|
|
92
|
+
const ENV_NAME = /^[A-Z][A-Z0-9_]{0,127}$/;
|
|
93
|
+
const LOCAL_HOSTS: ReadonlySet<string> = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
94
|
+
|
|
95
|
+
/** An https URL, or http on the local machine (a development identity provider). */
|
|
96
|
+
export function isSecureEndpoint(value: string): boolean {
|
|
97
|
+
let url: URL;
|
|
98
|
+
try {
|
|
99
|
+
url = new URL(value);
|
|
100
|
+
} catch {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (url.username !== "" || url.password !== "" || url.hash !== "") return false;
|
|
104
|
+
return url.protocol === "https:" || (url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname));
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
const domainSchema = z.string().trim().toLowerCase().regex(DOMAIN, "must be a lowercase host name such as example.com");
|
|
108
|
+
|
|
109
|
+
const oidcProviderSchema = z
|
|
110
|
+
.strictObject({
|
|
111
|
+
/** The provider's id in URLs and in `auth.identities`, e.g. `google`. */
|
|
112
|
+
id: z.string().regex(OIDC_PROVIDER_ID_PATTERN, "must be an id such as google (a-z first, then a-z, 0-9 or -, at most 32)"),
|
|
113
|
+
/** The provider's name as the button shows it (`messages.oidc.signInWith`), e.g. `Google`. */
|
|
114
|
+
name: z.string().trim().min(1).max(64),
|
|
115
|
+
/** The issuer; its discovery document is `<issuer>/.well-known/openid-configuration`. */
|
|
116
|
+
issuer: z
|
|
117
|
+
.string()
|
|
118
|
+
.refine(isSecureEndpoint, "must be an https URL (http only on localhost)")
|
|
119
|
+
.transform((issuer) => issuer.replace(/\/+$/, "")),
|
|
120
|
+
/** The environment variable that holds the client id. */
|
|
121
|
+
clientIdEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_ID"),
|
|
122
|
+
/** The environment variable that holds the client secret; absent for a public client. */
|
|
123
|
+
clientSecretEnv: z.string().regex(ENV_NAME, "must be an environment variable name such as GOOGLE_AUTH_CLIENT_SECRET").optional(),
|
|
124
|
+
/** How the client authenticates at the token endpoint: form fields (`client_secret_post`) or HTTP Basic. */
|
|
125
|
+
clientAuth: z.enum(["body", "basic"]).default("body"),
|
|
126
|
+
/** Requested scopes; `openid` and `email` are always sent. */
|
|
127
|
+
scopes: z.array(z.string().regex(/^[\x21\x23-\x5b\x5d-\x7e]{1,128}$/, "must be a scope token")).default([]),
|
|
128
|
+
/** Extra parameters of the authorize URL, e.g. `{ prompt: "select_account", hd: "example.com" }`. */
|
|
129
|
+
authorizeParams: z.record(z.string().regex(/^[a-z_]{1,64}$/), z.string().max(512)).default({}),
|
|
130
|
+
/** Who may sign in: a verified email in one of these domains. */
|
|
131
|
+
allowedDomains: z.array(domainSchema).default([]),
|
|
132
|
+
/** Who may sign in: one of these verified emails. */
|
|
133
|
+
allowedEmails: z.array(adminEmailSchema).default([]),
|
|
134
|
+
/**
|
|
135
|
+
* A domain match also needs the token's `hd` claim to name that domain (a Google Workspace account). Defaults to
|
|
136
|
+
* true for Google, whose consumer accounts can carry a verified address of any domain.
|
|
137
|
+
*/
|
|
138
|
+
requireHostedDomain: z.boolean().optional(),
|
|
139
|
+
/** A first sign-in of an allowed identity without an account creates one (no password); false only links. */
|
|
140
|
+
createAccounts: z.boolean().default(true),
|
|
141
|
+
})
|
|
142
|
+
.transform((provider) => ({ ...provider, requireHostedDomain: provider.requireHostedDomain ?? provider.issuer === GOOGLE_ISSUER }))
|
|
143
|
+
.refine((provider) => provider.allowedDomains.length + provider.allowedEmails.length > 0, {
|
|
144
|
+
message: "needs allowedDomains or allowedEmails: an OpenID Connect sign-in is limited to them",
|
|
145
|
+
path: ["allowedDomains"],
|
|
146
|
+
});
|
|
147
|
+
|
|
148
|
+
export type OidcProviderInput = z.input<typeof oidcProviderSchema>;
|
|
149
|
+
export type OidcProvider = z.output<typeof oidcProviderSchema>;
|
|
150
|
+
|
|
89
151
|
export const authOptionsSchema = z.strictObject({
|
|
90
152
|
password: z
|
|
91
153
|
.strictObject({
|
|
154
|
+
/**
|
|
155
|
+
* The password form and routes (login, register, change, reset). False leaves OpenID Connect as the only way in:
|
|
156
|
+
* the pages are not found and the server functions refuse.
|
|
157
|
+
*/
|
|
158
|
+
enabled: z.boolean().default(true),
|
|
92
159
|
/** Shortest password a user may set (characters). */
|
|
93
160
|
minLength: z.number().int().min(8).max(128).default(10),
|
|
94
161
|
/** Hash cost; memory per hash is 128 * cost * blockSize bytes. Raising it rehashes each password at its owner's next login. */
|
|
@@ -167,6 +234,21 @@ export const authOptionsSchema = z.strictObject({
|
|
|
167
234
|
ttlMinutes: z.number().int().min(5).max(1440).default(60),
|
|
168
235
|
})
|
|
169
236
|
.prefault({}),
|
|
237
|
+
/** Sign-in with OpenID Connect providers (e.g. Google), limited to allowed domains or emails. Off without providers. */
|
|
238
|
+
oidc: z
|
|
239
|
+
.strictObject({
|
|
240
|
+
providers: z
|
|
241
|
+
.array(oidcProviderSchema)
|
|
242
|
+
.refine((providers) => new Set(providers.map((provider) => provider.id)).size === providers.length, "must not repeat a provider id")
|
|
243
|
+
.default([]),
|
|
244
|
+
/** How long a started sign-in may take at the provider. */
|
|
245
|
+
stateTtlMinutes: z.number().int().min(1).max(60).default(10),
|
|
246
|
+
/** Timeout of each call to a provider (discovery, keys, token). */
|
|
247
|
+
httpTimeoutMs: z.number().int().min(1000).max(60_000).default(10_000),
|
|
248
|
+
/** The `fetch` the provider calls go through; tests pass a fake provider's. */
|
|
249
|
+
fetch: z.custom<FetchFunction>((value) => typeof value === "function", "must be a function").optional(),
|
|
250
|
+
})
|
|
251
|
+
.prefault({}),
|
|
170
252
|
/** Called after an account is created, in the same transaction (e.g. to store the consent). */
|
|
171
253
|
onRegistered: z.custom<OnRegisteredHook>((value) => typeof value === "function", "must be a function").optional(),
|
|
172
254
|
/** Rewrites the path of every auth redirect (e.g. `tagRedirect` from `@softure-ai/analytics/next`). */
|
|
@@ -175,6 +257,9 @@ export const authOptionsSchema = z.strictObject({
|
|
|
175
257
|
if (options.passwordReset.enqueue !== undefined && options.passwordReset.send === undefined) {
|
|
176
258
|
context.addIssue({ code: "custom", path: ["passwordReset", "enqueue"], message: "needs passwordReset.send, which the job calls" });
|
|
177
259
|
}
|
|
260
|
+
if (!options.password.enabled && options.oidc.providers.length === 0) {
|
|
261
|
+
context.addIssue({ code: "custom", path: ["password", "enabled"], message: "needs an oidc provider: without passwords nobody could sign in" });
|
|
262
|
+
}
|
|
178
263
|
const legacy = options.legacySession?.cookieName;
|
|
179
264
|
const base = options.cookie.name;
|
|
180
265
|
if (legacy !== undefined && [base, `__Host-${base}`, `__Secure-${base}`].includes(legacy)) {
|
package/src/proxy/index.ts
CHANGED
|
@@ -43,6 +43,8 @@ export interface AuthGuardOptions {
|
|
|
43
43
|
|
|
44
44
|
/** Mounted at a fixed path by the module (manifest `mount`); it answers `{ user: null }` without a session. */
|
|
45
45
|
const SESSION_ROUTE = "/api/auth/session";
|
|
46
|
+
/** The OpenID Connect callbacks (`/api/auth/oidc/<provider>/callback`): a visitor arrives there without a session. */
|
|
47
|
+
const OIDC_ROUTES = "/api/auth/oidc";
|
|
46
48
|
|
|
47
49
|
export type AuthGuard = (request: Request) => Response | null;
|
|
48
50
|
|
|
@@ -53,7 +55,7 @@ export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions
|
|
|
53
55
|
const prefixes = options.protect.map((prefix) => normalizePrefix(prefix, "protected"));
|
|
54
56
|
const changePassword = normalizePrefix(routes.changePassword, "protected");
|
|
55
57
|
// Auth's own public pages: guarding them would send a visitor from the login page to itself.
|
|
56
|
-
const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE].map((path) =>
|
|
58
|
+
const publicPaths = [routes.login, routes.register, routes.forgotPassword, routes.resetPassword, SESSION_ROUTE, OIDC_ROUTES].map((path) =>
|
|
57
59
|
normalizePrefix(path, "excluded"),
|
|
58
60
|
);
|
|
59
61
|
const excluded = (options.exclude ?? []).map((prefix) => normalizePrefix(prefix, "excluded"));
|
package/src/schema.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
// Drizzle view of the module's tables (migrations/0001_create_users_and_sessions.sql,
|
|
2
|
-
// 0002_create_user_roles.sql, 0003_create_password_resets.sql
|
|
3
|
-
// 0004_index_users_created_at.sql
|
|
2
|
+
// 0002_create_user_roles.sql, 0003_create_password_resets.sql, the users.created_at index of
|
|
3
|
+
// 0004_index_users_created_at.sql, 0005_create_identities_and_oidc_states.sql and
|
|
4
|
+
// 0006_add_users_display_name.sql). The migrations are the source of truth; this file only types
|
|
4
5
|
// the queries. App tables may reference `users.id`.
|
|
5
|
-
import { pgSchema, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
|
6
|
+
import { pgSchema, primaryKey, text, timestamp, unique, uuid } from "drizzle-orm/pg-core";
|
|
6
7
|
|
|
7
8
|
export const authSchema = pgSchema("auth");
|
|
8
9
|
|
|
@@ -12,8 +13,12 @@ export const users = authSchema.table("users", {
|
|
|
12
13
|
passwordHash: text("password_hash").notNull(),
|
|
13
14
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
14
15
|
passwordChangedAt: timestamp("password_changed_at", { withTimezone: true }).notNull(),
|
|
16
|
+
displayName: text("display_name"),
|
|
15
17
|
});
|
|
16
18
|
|
|
19
|
+
/** The columns of an `AuthUser`: every query that returns one selects these. */
|
|
20
|
+
export const AUTH_USER_COLUMNS = { id: users.id, email: users.email, createdAt: users.createdAt, displayName: users.displayName };
|
|
21
|
+
|
|
17
22
|
export const sessions = authSchema.table("sessions", {
|
|
18
23
|
tokenHash: text("token_hash").primaryKey(),
|
|
19
24
|
userId: uuid("user_id")
|
|
@@ -43,3 +48,28 @@ export const passwordResets = authSchema.table("password_resets", {
|
|
|
43
48
|
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
44
49
|
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
45
50
|
});
|
|
51
|
+
|
|
52
|
+
export const identities = authSchema.table(
|
|
53
|
+
"identities",
|
|
54
|
+
{
|
|
55
|
+
provider: text("provider").notNull(),
|
|
56
|
+
subject: text("subject").notNull(),
|
|
57
|
+
userId: uuid("user_id")
|
|
58
|
+
.notNull()
|
|
59
|
+
.references(() => users.id, { onDelete: "cascade" }),
|
|
60
|
+
email: text("email").notNull(),
|
|
61
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
62
|
+
lastLoginAt: timestamp("last_login_at", { withTimezone: true }).notNull(),
|
|
63
|
+
},
|
|
64
|
+
(table) => [primaryKey({ columns: [table.provider, table.subject] }), unique("identities_user_provider_key").on(table.userId, table.provider)],
|
|
65
|
+
);
|
|
66
|
+
|
|
67
|
+
export const oidcStates = authSchema.table("oidc_states", {
|
|
68
|
+
stateHash: text("state_hash").primaryKey(),
|
|
69
|
+
provider: text("provider").notNull(),
|
|
70
|
+
nonce: text("nonce").notNull(),
|
|
71
|
+
codeVerifier: text("code_verifier").notNull(),
|
|
72
|
+
nextPath: text("next_path").notNull(),
|
|
73
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
74
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
75
|
+
});
|