@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,179 @@
|
|
|
1
|
+
// Pages ready to mount with one line: `export { LoginPage as default } from "@softure-ai/auth/next"`.
|
|
2
|
+
// Server components: they read the config and the session, and render the forms from `../ui`.
|
|
3
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
4
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
5
|
+
import { Card } from "@softure-ai/ui";
|
|
6
|
+
import { notFound, redirect } from "next/navigation";
|
|
7
|
+
import type { ReactNode } from "react";
|
|
8
|
+
import { resolveRedirectTarget } from "../redirect-target.js";
|
|
9
|
+
import { toSafeNextPath } from "../safe-next-path.js";
|
|
10
|
+
import { getAuthOptions, getAuthRoutes } from "../server/options.js";
|
|
11
|
+
import { findPasswordResetUser, isPasswordResetEnabled, RESET_TOKEN_PARAM } from "../server/password-reset.js";
|
|
12
|
+
import { isRegistrationClosed } from "../server/switches.js";
|
|
13
|
+
import { ChangePasswordForm, ForgotPasswordForm, LoginForm, RegisterForm, ResetPasswordForm } from "../ui/auth-forms.js";
|
|
14
|
+
import { changePasswordAction, forgotPasswordAction, loginAction, registerAction, resetPasswordAction } from "./actions.js";
|
|
15
|
+
import { getAuthContext } from "./context.js";
|
|
16
|
+
import { getCurrentUser, requireUser } from "./current-user.js";
|
|
17
|
+
import { getAuthMessages } from "./messages.js";
|
|
18
|
+
import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
|
|
19
|
+
import { toUrlSearchParams } from "./search-params.js";
|
|
20
|
+
|
|
21
|
+
type SearchParams = Promise<Record<string, string | string[] | undefined>>;
|
|
22
|
+
|
|
23
|
+
export interface AuthPageProps {
|
|
24
|
+
readonly searchParams?: SearchParams;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const LAYOUT_CLASS = "sft:mx-auto sft:box-border sft:w-full sft:sm:max-w-md sft:px-4 sft:py-4";
|
|
28
|
+
const FOOTER_CLASS = "sft:m-0 sft:text-sm sft:text-muted";
|
|
29
|
+
const LINK_CLASS = "sft:font-medium sft:text-accent";
|
|
30
|
+
|
|
31
|
+
function AuthLayout({ title, lead, children }: { title: string; lead: string; children: ReactNode }) {
|
|
32
|
+
return (
|
|
33
|
+
<main className={LAYOUT_CLASS}>
|
|
34
|
+
<Card title={title} subtitle={lead}>
|
|
35
|
+
{children}
|
|
36
|
+
</Card>
|
|
37
|
+
</main>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function readParam(searchParams: SearchParams | undefined, name: string): Promise<string | undefined> {
|
|
42
|
+
const value = (await searchParams)?.[name];
|
|
43
|
+
return Array.isArray(value) ? value[0] : value;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
async function readNext(searchParams: SearchParams | undefined, fallback: string): Promise<string> {
|
|
47
|
+
return toSafeNextPath(await readParam(searchParams, "next"), fallback);
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** Sends a signed-in visitor on from the login or register page, through the app's redirect rewrite. */
|
|
51
|
+
async function redirectSignedIn(config: SoftureConfig, next: string, searchParams: SearchParams | undefined): Promise<never> {
|
|
52
|
+
redirect(await resolveRedirectTarget(config, next, toUrlSearchParams(await searchParams)));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export async function LoginPage({ searchParams }: AuthPageProps) {
|
|
56
|
+
const config = getSoftureConfig();
|
|
57
|
+
const routes = getAuthRoutes(config);
|
|
58
|
+
const next = await readNext(searchParams, routes.afterLogin);
|
|
59
|
+
if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
|
|
60
|
+
const messages = getAuthMessages(config);
|
|
61
|
+
const isClosed = await isRegistrationClosed(await getAuthContext(config));
|
|
62
|
+
return (
|
|
63
|
+
<AuthLayout title={messages.login.title} lead={messages.login.lead}>
|
|
64
|
+
<LoginForm
|
|
65
|
+
action={loginAction}
|
|
66
|
+
messages={messages}
|
|
67
|
+
locale={config.locale}
|
|
68
|
+
next={next}
|
|
69
|
+
registerHref={isClosed ? undefined : routes.register}
|
|
70
|
+
forgotPasswordHref={isPasswordResetEnabled(config) ? routes.forgotPassword : undefined}
|
|
71
|
+
notice={(await readParam(searchParams, PASSWORD_RESET_DONE_PARAM)) === "1" ? messages.resetPassword.success : undefined}
|
|
72
|
+
/>
|
|
73
|
+
</AuthLayout>
|
|
74
|
+
);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export async function RegisterPage({ searchParams }: AuthPageProps) {
|
|
78
|
+
const config = getSoftureConfig();
|
|
79
|
+
const routes = getAuthRoutes(config);
|
|
80
|
+
const next = await readNext(searchParams, routes.afterLogin);
|
|
81
|
+
if ((await getCurrentUser()) !== null) await redirectSignedIn(config, next, searchParams);
|
|
82
|
+
const messages = getAuthMessages(config);
|
|
83
|
+
if (await isRegistrationClosed(await getAuthContext(config))) {
|
|
84
|
+
return (
|
|
85
|
+
<AuthLayout title={messages.register.closedTitle} lead={messages.register.closedBody}>
|
|
86
|
+
{null}
|
|
87
|
+
</AuthLayout>
|
|
88
|
+
);
|
|
89
|
+
}
|
|
90
|
+
const options = getAuthOptions(config);
|
|
91
|
+
return (
|
|
92
|
+
<AuthLayout title={messages.register.title} lead={messages.register.lead}>
|
|
93
|
+
<RegisterForm
|
|
94
|
+
action={registerAction}
|
|
95
|
+
messages={messages}
|
|
96
|
+
locale={config.locale}
|
|
97
|
+
next={next}
|
|
98
|
+
loginHref={routes.login}
|
|
99
|
+
requireConsent={options.requireConsent}
|
|
100
|
+
minPasswordLength={options.password.minLength}
|
|
101
|
+
/>
|
|
102
|
+
</AuthLayout>
|
|
103
|
+
);
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export async function ChangePasswordPage() {
|
|
107
|
+
const config = getSoftureConfig();
|
|
108
|
+
const routes = getAuthRoutes(config);
|
|
109
|
+
await requireUser({ next: routes.changePassword });
|
|
110
|
+
const messages = getAuthMessages(config);
|
|
111
|
+
return (
|
|
112
|
+
<AuthLayout title={messages.changePassword.title} lead={messages.changePassword.lead}>
|
|
113
|
+
<ChangePasswordForm
|
|
114
|
+
action={changePasswordAction}
|
|
115
|
+
messages={messages}
|
|
116
|
+
locale={config.locale}
|
|
117
|
+
minPasswordLength={getAuthOptions(config).password.minLength}
|
|
118
|
+
/>
|
|
119
|
+
</AuthLayout>
|
|
120
|
+
);
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** Asks for a reset link. Not found when the app configured no sender. */
|
|
124
|
+
export function ForgotPasswordPage() {
|
|
125
|
+
const config = getSoftureConfig();
|
|
126
|
+
if (!isPasswordResetEnabled(config)) notFound();
|
|
127
|
+
const messages = getAuthMessages(config);
|
|
128
|
+
return (
|
|
129
|
+
<AuthLayout title={messages.forgotPassword.title} lead={messages.forgotPassword.lead}>
|
|
130
|
+
<ForgotPasswordForm
|
|
131
|
+
action={forgotPasswordAction}
|
|
132
|
+
messages={messages}
|
|
133
|
+
locale={config.locale}
|
|
134
|
+
ttlMinutes={getAuthOptions(config).passwordReset.ttlMinutes}
|
|
135
|
+
loginHref={getAuthRoutes(config).login}
|
|
136
|
+
/>
|
|
137
|
+
</AuthLayout>
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/**
|
|
142
|
+
* The page a reset link opens. It only checks the token (mail scanners open links too); the form
|
|
143
|
+
* submission consumes it. Its referrer policy is `same-origin`: the token in its URL never goes to
|
|
144
|
+
* another site, and the form still sends the Origin header Next checks on server actions
|
|
145
|
+
* (`no-referrer` would turn it into `null`, and Next would refuse the plain HTML form).
|
|
146
|
+
*/
|
|
147
|
+
export async function ResetPasswordPage({ searchParams }: AuthPageProps) {
|
|
148
|
+
const config = getSoftureConfig();
|
|
149
|
+
if (!isPasswordResetEnabled(config)) notFound();
|
|
150
|
+
const routes = getAuthRoutes(config);
|
|
151
|
+
const messages = getAuthMessages(config);
|
|
152
|
+
const token = (await readParam(searchParams, RESET_TOKEN_PARAM)) ?? "";
|
|
153
|
+
const user = token === "" ? null : await findPasswordResetUser(await getAuthContext(config), token);
|
|
154
|
+
const referrerPolicy = <meta name="referrer" content="same-origin" />;
|
|
155
|
+
if (user === null) {
|
|
156
|
+
return (
|
|
157
|
+
<AuthLayout title={messages.resetPassword.invalidTitle} lead={messages.resetPassword.invalidBody}>
|
|
158
|
+
{referrerPolicy}
|
|
159
|
+
<p className={FOOTER_CLASS}>
|
|
160
|
+
<a href={routes.forgotPassword} className={LINK_CLASS}>
|
|
161
|
+
{messages.resetPassword.requestNew}
|
|
162
|
+
</a>
|
|
163
|
+
</p>
|
|
164
|
+
</AuthLayout>
|
|
165
|
+
);
|
|
166
|
+
}
|
|
167
|
+
return (
|
|
168
|
+
<AuthLayout title={messages.resetPassword.title} lead={messages.resetPassword.lead}>
|
|
169
|
+
{referrerPolicy}
|
|
170
|
+
<ResetPasswordForm
|
|
171
|
+
action={resetPasswordAction}
|
|
172
|
+
messages={messages}
|
|
173
|
+
locale={config.locale}
|
|
174
|
+
token={token}
|
|
175
|
+
minPasswordLength={getAuthOptions(config).password.minLength}
|
|
176
|
+
/>
|
|
177
|
+
</AuthLayout>
|
|
178
|
+
);
|
|
179
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// Route handlers. Mount with a rename, so later handlers of the module fit next to it:
|
|
2
|
+
// `export { getSessionRoute as GET } from "@softure-ai/auth/next"` in app/api/auth/session/route.ts.
|
|
3
|
+
import { errorLogLabel, safeError } from "@softure-ai/core";
|
|
4
|
+
import { getCurrentUser } from "./current-user.js";
|
|
5
|
+
|
|
6
|
+
const NO_STORE = { "cache-control": "no-store" };
|
|
7
|
+
|
|
8
|
+
/** `{ user: { id, email } | null }` for the request's session. Never cached. */
|
|
9
|
+
export async function getSessionRoute(): Promise<Response> {
|
|
10
|
+
try {
|
|
11
|
+
const user = await getCurrentUser();
|
|
12
|
+
return Response.json({ user: user === null ? null : { id: user.id, email: user.email } }, { headers: NO_STORE });
|
|
13
|
+
} catch (error) {
|
|
14
|
+
console.error(`@softure-ai/auth: session lookup failed: ${errorLogLabel(error)}`);
|
|
15
|
+
return Response.json({ error: safeError(error).error }, { status: 500, headers: NO_STORE });
|
|
16
|
+
}
|
|
17
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// A page's search params in the one shape auth's redirect rewrite takes.
|
|
2
|
+
|
|
3
|
+
/** A page's awaited `searchParams`, or any `URLSearchParams`. */
|
|
4
|
+
export type PageSearchParams = URLSearchParams | Readonly<Record<string, string | readonly string[] | undefined>>;
|
|
5
|
+
|
|
6
|
+
/** `searchParams` as `URLSearchParams`, every value of a repeated name kept. */
|
|
7
|
+
export function toUrlSearchParams(searchParams: PageSearchParams | undefined): URLSearchParams {
|
|
8
|
+
if (searchParams instanceof URLSearchParams) return searchParams;
|
|
9
|
+
const query = new URLSearchParams();
|
|
10
|
+
for (const [name, value] of Object.entries(searchParams ?? {})) {
|
|
11
|
+
for (const item of typeof value === "string" ? [value] : (value ?? [])) query.append(name, item);
|
|
12
|
+
}
|
|
13
|
+
return query;
|
|
14
|
+
}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
// Reading and writing the session cookie through Next's request scope.
|
|
2
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
3
|
+
import { cookies } from "next/headers";
|
|
4
|
+
import type { NewSession } from "../contract.js";
|
|
5
|
+
import { getSessionCookie } from "../session-cookie.js";
|
|
6
|
+
|
|
7
|
+
export async function readSessionToken(config: SoftureConfig): Promise<string | null> {
|
|
8
|
+
const store = await cookies();
|
|
9
|
+
const value = store.get(getSessionCookie(config).name)?.value;
|
|
10
|
+
return value === undefined || value === "" ? null : value;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** Only in a server action or a route handler: pages cannot set cookies. */
|
|
14
|
+
export async function writeSessionCookie(config: SoftureConfig, session: NewSession): Promise<void> {
|
|
15
|
+
const cookie = getSessionCookie(config);
|
|
16
|
+
const store = await cookies();
|
|
17
|
+
store.set(cookie.name, session.token, {
|
|
18
|
+
httpOnly: cookie.httpOnly,
|
|
19
|
+
secure: cookie.secure,
|
|
20
|
+
sameSite: cookie.sameSite,
|
|
21
|
+
path: cookie.path,
|
|
22
|
+
domain: cookie.domain,
|
|
23
|
+
maxAge: cookie.maxAgeSeconds,
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Removes the cookie with the attributes it was set with, so the browser drops that one. */
|
|
28
|
+
export async function clearSessionCookie(config: SoftureConfig): Promise<void> {
|
|
29
|
+
const cookie = getSessionCookie(config);
|
|
30
|
+
const store = await cookies();
|
|
31
|
+
store.set(cookie.name, "", {
|
|
32
|
+
httpOnly: cookie.httpOnly,
|
|
33
|
+
secure: cookie.secure,
|
|
34
|
+
sameSite: cookie.sameSite,
|
|
35
|
+
path: cookie.path,
|
|
36
|
+
domain: cookie.domain,
|
|
37
|
+
maxAge: 0,
|
|
38
|
+
});
|
|
39
|
+
}
|
package/src/options.ts
ADDED
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// The options an app passes to `auth({ ... })` in softure.config.ts, parsed at startup.
|
|
2
|
+
import type { ModuleContext, SoftureConfig } from "@softure-ai/core";
|
|
3
|
+
import type { Queryable } from "@softure-ai/db";
|
|
4
|
+
import { z } from "zod";
|
|
5
|
+
import type { RegisteredEvent } from "./contract.js";
|
|
6
|
+
import type { PasswordResetSender } from "./password-reset-sender.js";
|
|
7
|
+
import { ROLE_NAME_PATTERN } from "./roles.js";
|
|
8
|
+
|
|
9
|
+
/** OWASP's scrypt cost for passwords: N = 2^17, r = 8, p = 1 (about 128 MiB per hash). */
|
|
10
|
+
export const DEFAULT_SCRYPT_COST = 2 ** 17;
|
|
11
|
+
|
|
12
|
+
const MAX_EMAIL_LENGTH = 254;
|
|
13
|
+
const COOKIE_NAME = /^[A-Za-z0-9_-]{1,64}$/;
|
|
14
|
+
const DOMAIN = /^(?=.{1,253}$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)+$/;
|
|
15
|
+
|
|
16
|
+
/** Runs inside the registration transaction; a thrown error rolls the registration back. */
|
|
17
|
+
export type OnRegisteredHook = (event: RegisteredEvent, ctx: ModuleContext<Queryable>) => Promise<void>;
|
|
18
|
+
|
|
19
|
+
/** What a redirect rewrite gets besides the path. */
|
|
20
|
+
export interface RewriteRedirectContext {
|
|
21
|
+
readonly config: SoftureConfig;
|
|
22
|
+
/**
|
|
23
|
+
* The page's own search params, when a page redirects while it renders (the login and register
|
|
24
|
+
* pages send a signed-in visitor on); absent for an action's redirect. A render's `Referer` is the
|
|
25
|
+
* page before, not this one.
|
|
26
|
+
*/
|
|
27
|
+
readonly searchParams?: URLSearchParams;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* Rewrites the path auth redirects to (after login, sign-up, a password reset and logout, and the
|
|
32
|
+
* login and register pages' redirect of a signed-in visitor), e.g. analytics' `tagRedirect`, which
|
|
33
|
+
* keeps the channel tag. A result that is not a path on this app, or a failure, leaves auth's own path.
|
|
34
|
+
*/
|
|
35
|
+
export type RewriteRedirect = (path: string, ctx: RewriteRedirectContext) => Promise<string> | string;
|
|
36
|
+
|
|
37
|
+
function isPowerOfTwo(value: number): boolean {
|
|
38
|
+
return Number.isInteger(Math.log2(value));
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
const scryptSchema = z.strictObject({
|
|
42
|
+
/** N: CPU and memory cost, a power of two. */
|
|
43
|
+
cost: z
|
|
44
|
+
.number()
|
|
45
|
+
.int()
|
|
46
|
+
.min(2 ** 10)
|
|
47
|
+
.max(2 ** 20)
|
|
48
|
+
.refine(isPowerOfTwo, "must be a power of two")
|
|
49
|
+
.default(DEFAULT_SCRYPT_COST),
|
|
50
|
+
/** r: block size. */
|
|
51
|
+
blockSize: z.number().int().min(1).max(32).default(8),
|
|
52
|
+
/** p: parallelization. */
|
|
53
|
+
parallelization: z.number().int().min(1).max(16).default(1),
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
export const authOptionsSchema = z.strictObject({
|
|
57
|
+
password: z
|
|
58
|
+
.strictObject({
|
|
59
|
+
/** Shortest password a user may set (characters). */
|
|
60
|
+
minLength: z.number().int().min(8).max(128).default(10),
|
|
61
|
+
/** Hash cost. Raising it rehashes each password at its owner's next login. */
|
|
62
|
+
scrypt: scryptSchema.prefault({}),
|
|
63
|
+
})
|
|
64
|
+
.prefault({}),
|
|
65
|
+
session: z
|
|
66
|
+
.strictObject({
|
|
67
|
+
/** How long a session lasts from login; it is not extended by use. */
|
|
68
|
+
ttlDays: z.number().int().min(1).max(365).default(30),
|
|
69
|
+
})
|
|
70
|
+
.prefault({}),
|
|
71
|
+
cookie: z
|
|
72
|
+
.strictObject({
|
|
73
|
+
/** Base name; `__Host-` or `__Secure-` is added when the cookie is secure. */
|
|
74
|
+
name: z.string().regex(COOKIE_NAME, "must be 1-64 letters, digits, _ or -").default("softure_session"),
|
|
75
|
+
/** Share the session with subdomains, e.g. `example.com` for the apex and `app.example.com`. */
|
|
76
|
+
domain: z.string().regex(DOMAIN, "must be a lowercase host name such as example.com").optional(),
|
|
77
|
+
/** Defaults to whether `appOrigin` is https. */
|
|
78
|
+
secure: z.boolean().optional(),
|
|
79
|
+
})
|
|
80
|
+
.prefault({}),
|
|
81
|
+
/** Registration needs a ticked consent checkbox. */
|
|
82
|
+
requireConsent: z.boolean().default(true),
|
|
83
|
+
/** Declared default of the `auth.registration_closed` switch. */
|
|
84
|
+
registrationClosed: z.boolean().default(false),
|
|
85
|
+
/** Role names the app checks besides `admin`, which is always declared. */
|
|
86
|
+
roles: z.array(z.string().regex(ROLE_NAME_PATTERN, "must be a role name such as editor (a-z, 0-9, _ or -, at most 32)")).default([]),
|
|
87
|
+
/**
|
|
88
|
+
* Initial admin list: while an email is listed, the account with that email holds `admin`.
|
|
89
|
+
* Auth does not verify emails, so create these accounts before deploying the list.
|
|
90
|
+
*/
|
|
91
|
+
adminEmails: z.array(z.string().trim().toLowerCase().max(MAX_EMAIL_LENGTH).pipe(z.email("must be an email address"))).default([]),
|
|
92
|
+
passwordReset: z
|
|
93
|
+
.strictObject({
|
|
94
|
+
/** Delivers reset links. Without it password reset is off: no link, and its pages are not found. */
|
|
95
|
+
send: z.custom<PasswordResetSender>((value) => typeof value === "function", "must be a function").optional(),
|
|
96
|
+
/** How long a reset link works. */
|
|
97
|
+
ttlMinutes: z.number().int().min(5).max(1440).default(60),
|
|
98
|
+
})
|
|
99
|
+
.prefault({}),
|
|
100
|
+
/** Called after an account is created, in the same transaction (e.g. to store the consent). */
|
|
101
|
+
onRegistered: z.custom<OnRegisteredHook>((value) => typeof value === "function", "must be a function").optional(),
|
|
102
|
+
/** Rewrites the path of every auth redirect (e.g. `tagRedirect` from `@softure-ai/analytics/next`). */
|
|
103
|
+
rewriteRedirect: z.custom<RewriteRedirect>((value) => typeof value === "function", "must be a function").optional(),
|
|
104
|
+
});
|
|
105
|
+
|
|
106
|
+
export type AuthOptionsInput = z.input<typeof authOptionsSchema>;
|
|
107
|
+
export type AuthOptions = z.output<typeof authOptionsSchema>;
|
|
108
|
+
export type ScryptParams = z.output<typeof scryptSchema>;
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
// The hook through which auth hands a password reset link to the app, which delivers it (a mail,
|
|
2
|
+
// e.g. through `mailingResetSender()` of `@softure-ai/auth/mailing`). Auth never sends anything itself.
|
|
3
|
+
import type { Locale } from "@softure-ai/core";
|
|
4
|
+
import type { AuthUser } from "./contract.js";
|
|
5
|
+
|
|
6
|
+
export interface PasswordResetDetails {
|
|
7
|
+
/** When the link stops working. */
|
|
8
|
+
readonly expiresAt: Date;
|
|
9
|
+
/** The app's locale, for the copy of the message. */
|
|
10
|
+
readonly locale: Locale;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* Delivers a reset link to `user`. The link is built on `appOrigin` (never on the request's Host);
|
|
15
|
+
* a multi-host app keeps its path and query and swaps the origin. It runs after the response is
|
|
16
|
+
* sent, so a slow or failing sender never shows on the request page. A thrown error is logged
|
|
17
|
+
* without the link.
|
|
18
|
+
*/
|
|
19
|
+
export type PasswordResetSender = (link: string, user: AuthUser, details: PasswordResetDetails) => Promise<void>;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* A development sender that prints the link to the server console. It refuses to run in
|
|
23
|
+
* production, where a reset link in the logs would be a live credential in the logs.
|
|
24
|
+
*/
|
|
25
|
+
export const consolePasswordResetSender: PasswordResetSender = (link, user, details) => {
|
|
26
|
+
if (process.env.NODE_ENV === "production") {
|
|
27
|
+
return Promise.reject(
|
|
28
|
+
new Error("@softure-ai/auth: consolePasswordResetSender is for development only; pass a real sender to auth({ passwordReset: { send } })"),
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
console.info(`@softure-ai/auth: password reset link for ${user.email}, valid until ${details.expiresAt.toISOString()}: ${link}`);
|
|
32
|
+
return Promise.resolve();
|
|
33
|
+
};
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// The route guard for the app's `proxy.ts` (roadmap ID-3, unknown 1). It uses only Web `Request`
|
|
2
|
+
// and `Response`, imports nothing from Next and no React, so it chains with other proxy pieces:
|
|
3
|
+
// `return channels.carry(request, guard(request)) ?? channels.tag(request) ?? NextResponse.next()`
|
|
4
|
+
// (the channel piece of @softure-ai/analytics/proxy).
|
|
5
|
+
//
|
|
6
|
+
// It checks that the session cookie is present, nothing more: an optimistic check that keeps
|
|
7
|
+
// anonymous visitors off private pages without a database round trip in the proxy. Pages and
|
|
8
|
+
// actions still call `requireUser`, which reads the session row.
|
|
9
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
10
|
+
import { getAuthRoutes } from "../server/options.js";
|
|
11
|
+
import { getSessionCookie, readSessionToken } from "../session-cookie.js";
|
|
12
|
+
|
|
13
|
+
export interface AuthGuardOptions {
|
|
14
|
+
/** Path prefixes that need a session; each matches whole segments (`/account` → `/account/…`). */
|
|
15
|
+
readonly protect: readonly string[];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export type AuthGuard = (request: Request) => Response | null;
|
|
19
|
+
|
|
20
|
+
/** A guard that redirects to the login page (with `?next=`) for protected paths without a session cookie. */
|
|
21
|
+
export function createAuthGuard(config: SoftureConfig, options: AuthGuardOptions): AuthGuard {
|
|
22
|
+
const routes = getAuthRoutes(config);
|
|
23
|
+
const cookieName = getSessionCookie(config).name;
|
|
24
|
+
const prefixes = [...options.protect, routes.changePassword].map(normalizePrefix);
|
|
25
|
+
|
|
26
|
+
return (request) => {
|
|
27
|
+
const url = new URL(request.url);
|
|
28
|
+
// Compared decoded and lowercased, so `/%61ccount` or `/ACCOUNT` (which a case-insensitive
|
|
29
|
+
// front proxy may route to /account) is guarded too. Undecodable paths are guarded.
|
|
30
|
+
const path = decodePath(url.pathname);
|
|
31
|
+
if (path !== null && !prefixes.some((prefix) => isUnder(path, prefix))) return null;
|
|
32
|
+
if (readSessionToken(request.headers.get("cookie"), cookieName) !== null) return null;
|
|
33
|
+
// Built on appOrigin: behind a proxy the request URL may carry an internal host.
|
|
34
|
+
const login = new URL(routes.login, config.appOrigin);
|
|
35
|
+
login.searchParams.set("next", `${url.pathname}${url.search}`);
|
|
36
|
+
return Response.redirect(login, 307);
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
function normalizePrefix(prefix: string): string {
|
|
41
|
+
if (!prefix.startsWith("/")) {
|
|
42
|
+
throw new Error(`createAuthGuard: protected path "${prefix}" must start with /`);
|
|
43
|
+
}
|
|
44
|
+
const trimmed = prefix.length > 1 && prefix.endsWith("/") ? prefix.slice(0, -1) : prefix;
|
|
45
|
+
return trimmed.toLowerCase();
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function decodePath(pathname: string): string | null {
|
|
49
|
+
try {
|
|
50
|
+
return decodeURIComponent(pathname).toLowerCase();
|
|
51
|
+
} catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function isUnder(pathname: string, prefix: string): boolean {
|
|
57
|
+
return prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`);
|
|
58
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Where auth redirects, from an action or from a page's render. The app's `rewriteRedirect` option
|
|
2
|
+
// may change auth's path (e.g. analytics' `tagRedirect` keeps the channel tag), but its result must
|
|
3
|
+
// still be a path on this app, and a rewrite that fails never blocks the redirect: auth's own path
|
|
4
|
+
// is used instead.
|
|
5
|
+
import { errorLogLabel, type SoftureConfig } from "@softure-ai/core";
|
|
6
|
+
import type { RewriteRedirectContext } from "./options.js";
|
|
7
|
+
import { toSafeNextPath } from "./safe-next-path.js";
|
|
8
|
+
import { getAuthOptions } from "./server/options.js";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* `path` as the app's `rewriteRedirect` returns it, or `path` itself without one or on failure.
|
|
12
|
+
* A page passes its own `searchParams`; an action passes none.
|
|
13
|
+
*/
|
|
14
|
+
export async function resolveRedirectTarget(config: SoftureConfig, path: string, searchParams?: URLSearchParams): Promise<string> {
|
|
15
|
+
const { rewriteRedirect } = getAuthOptions(config);
|
|
16
|
+
if (rewriteRedirect === undefined) return path;
|
|
17
|
+
const ctx: RewriteRedirectContext = searchParams === undefined ? { config } : { config, searchParams };
|
|
18
|
+
try {
|
|
19
|
+
return toSafeNextPath(await rewriteRedirect(path, ctx), path);
|
|
20
|
+
} catch (error) {
|
|
21
|
+
console.error(`@softure-ai/auth: rewriting the redirect to ${path} failed: ${errorLogLabel(error)}`);
|
|
22
|
+
return path;
|
|
23
|
+
}
|
|
24
|
+
}
|
package/src/roles.ts
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// Role names shared by the options, the server functions and the migration's CHECK constraint.
|
|
2
|
+
|
|
3
|
+
/** The role every app has: admin-only surfaces ask for it. */
|
|
4
|
+
export const ADMIN_ROLE = "admin";
|
|
5
|
+
|
|
6
|
+
/** What a role name looks like; `migrations/0002_create_user_roles.sql` enforces the same shape. */
|
|
7
|
+
export const ROLE_NAME_PATTERN = /^[a-z][a-z0-9_-]{0,31}$/;
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
// Where to go after login. `next` comes from the query string, so anyone can craft it: only a path
|
|
2
|
+
// on this app is accepted, never another origin (`//evil.example`, `/\evil.example`, `https://…`).
|
|
3
|
+
const BASE = "http://softure.invalid";
|
|
4
|
+
const MAX_LENGTH = 2048;
|
|
5
|
+
|
|
6
|
+
/** `candidate` when it is a same-origin path, else `fallback`. */
|
|
7
|
+
export function toSafeNextPath(candidate: unknown, fallback: string): string {
|
|
8
|
+
if (typeof candidate !== "string" || candidate.length > MAX_LENGTH) return fallback;
|
|
9
|
+
if (!candidate.startsWith("/") || candidate.startsWith("//") || candidate.startsWith("/\\")) return fallback;
|
|
10
|
+
// eslint-disable-next-line no-control-regex -- control characters are exactly what is refused
|
|
11
|
+
if (/[\u0000-\u001f\u007f\\]/.test(candidate)) return fallback;
|
|
12
|
+
const url = new URL(candidate, BASE);
|
|
13
|
+
if (url.origin !== BASE) return fallback;
|
|
14
|
+
return `${url.pathname}${url.search}${url.hash}`;
|
|
15
|
+
}
|
package/src/schema.ts
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
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 and the users.created_at index of
|
|
3
|
+
// 0004_index_users_created_at.sql). The migrations are the source of truth; this file only types
|
|
4
|
+
// the queries. App tables may reference `users.id`.
|
|
5
|
+
import { pgSchema, primaryKey, text, timestamp, uuid } from "drizzle-orm/pg-core";
|
|
6
|
+
|
|
7
|
+
export const authSchema = pgSchema("auth");
|
|
8
|
+
|
|
9
|
+
export const users = authSchema.table("users", {
|
|
10
|
+
id: uuid("id").primaryKey().defaultRandom(),
|
|
11
|
+
email: text("email").notNull().unique("users_email_key"),
|
|
12
|
+
passwordHash: text("password_hash").notNull(),
|
|
13
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
14
|
+
passwordChangedAt: timestamp("password_changed_at", { withTimezone: true }).notNull(),
|
|
15
|
+
});
|
|
16
|
+
|
|
17
|
+
export const sessions = authSchema.table("sessions", {
|
|
18
|
+
tokenHash: text("token_hash").primaryKey(),
|
|
19
|
+
userId: uuid("user_id")
|
|
20
|
+
.notNull()
|
|
21
|
+
.references(() => users.id, { onDelete: "cascade" }),
|
|
22
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
23
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export const userRoles = authSchema.table(
|
|
27
|
+
"user_roles",
|
|
28
|
+
{
|
|
29
|
+
userId: uuid("user_id")
|
|
30
|
+
.notNull()
|
|
31
|
+
.references(() => users.id, { onDelete: "cascade" }),
|
|
32
|
+
role: text("role").notNull(),
|
|
33
|
+
grantedAt: timestamp("granted_at", { withTimezone: true }).notNull(),
|
|
34
|
+
},
|
|
35
|
+
(table) => [primaryKey({ columns: [table.userId, table.role] })],
|
|
36
|
+
);
|
|
37
|
+
|
|
38
|
+
export const passwordResets = authSchema.table("password_resets", {
|
|
39
|
+
userId: uuid("user_id")
|
|
40
|
+
.primaryKey()
|
|
41
|
+
.references(() => users.id, { onDelete: "cascade" }),
|
|
42
|
+
tokenHash: text("token_hash").notNull().unique("password_resets_token_hash_key"),
|
|
43
|
+
createdAt: timestamp("created_at", { withTimezone: true }).notNull(),
|
|
44
|
+
expiresAt: timestamp("expires_at", { withTimezone: true }).notNull(),
|
|
45
|
+
});
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// The operator's way to grant and revoke roles: safe ops scripts (`@softure-ai/ops/scripts`), dry
|
|
2
|
+
// run by default, `--commit` writes. The app bundles them like its migrate step and runs them with
|
|
3
|
+
// its database URL. Reports carry the user id and roles, never the email.
|
|
4
|
+
import { ok, systemClock, type Clock, type SoftureConfig } from "@softure-ai/core";
|
|
5
|
+
import type { Queryable } from "@softure-ai/db";
|
|
6
|
+
import { defineOpsScript, refuseOpsScript, type OpsScript } from "@softure-ai/ops/scripts";
|
|
7
|
+
import { eq } from "drizzle-orm";
|
|
8
|
+
import { z } from "zod";
|
|
9
|
+
import { ADMIN_ROLE } from "../roles.js";
|
|
10
|
+
import { users } from "../schema.js";
|
|
11
|
+
import { getDeclaredRoles, findUserRoles, grantRole, isConfiguredAdmin, isDeclaredRole, revokeRole } from "../server/roles.js";
|
|
12
|
+
import type { AuthContext } from "../server/sessions.js";
|
|
13
|
+
import { normalizeEmail } from "../server/validation.js";
|
|
14
|
+
|
|
15
|
+
export interface RoleScriptArgs {
|
|
16
|
+
readonly email: string;
|
|
17
|
+
readonly role: string;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export interface RoleScriptOptions {
|
|
21
|
+
/** The time stored as `granted_at`; the system clock by default. */
|
|
22
|
+
readonly clock?: Clock;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const roleScriptArgs = z.strictObject({
|
|
26
|
+
email: z.string().min(1, "--email=<account email> is required"),
|
|
27
|
+
role: z.string().min(1, "--role=<role> is required"),
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
const USAGE = ["--email=<account email>", "--role=<declared role, e.g. admin>"];
|
|
31
|
+
|
|
32
|
+
interface Account {
|
|
33
|
+
readonly id: string;
|
|
34
|
+
readonly email: string;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
async function findAccount(db: Queryable, email: string): Promise<Account | undefined> {
|
|
38
|
+
const [row] = await db.select({ id: users.id, email: users.email }).from(users).where(eq(users.email, normalizeEmail(email))).limit(1);
|
|
39
|
+
return row;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function describeRoles(ctx: AuthContext, account: Account): Promise<{ userId: string; roles: string[] }> {
|
|
43
|
+
return { userId: account.id, roles: [...(await findUserRoles(ctx, account))].sort() };
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function describeDeclared(config: SoftureConfig): string {
|
|
47
|
+
return [...getDeclaredRoles(config)].join(", ");
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** `grant-role --email=… --role=…`: stores a declared role for one account. */
|
|
51
|
+
export function createGrantRoleScript(config: SoftureConfig, options: RoleScriptOptions = {}): OpsScript<RoleScriptArgs> {
|
|
52
|
+
const clock = options.clock ?? systemClock;
|
|
53
|
+
return defineOpsScript({
|
|
54
|
+
name: "grant-role",
|
|
55
|
+
description: "Grants a declared role to the account with the given email.",
|
|
56
|
+
usage: USAGE,
|
|
57
|
+
args: roleScriptArgs,
|
|
58
|
+
run: async (tx, args) => {
|
|
59
|
+
const ctx: AuthContext = { db: tx, clock, config };
|
|
60
|
+
if (!isDeclaredRole(config, args.role)) {
|
|
61
|
+
return refuseOpsScript(`role "${args.role}" is not declared (declared: ${describeDeclared(config)})`);
|
|
62
|
+
}
|
|
63
|
+
const account = await findAccount(tx, args.email);
|
|
64
|
+
if (account === undefined) return refuseOpsScript("no account has this email");
|
|
65
|
+
const before = await describeRoles(ctx, account);
|
|
66
|
+
const granted = await grantRole(ctx, { userId: account.id, role: args.role });
|
|
67
|
+
if (!granted.ok) return refuseOpsScript(`the account already has role "${args.role}"`);
|
|
68
|
+
return ok({ before, after: await describeRoles(ctx, account) });
|
|
69
|
+
},
|
|
70
|
+
});
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** `revoke-role --email=… --role=…`: deletes a stored role of one account. */
|
|
74
|
+
export function createRevokeRoleScript(config: SoftureConfig, options: RoleScriptOptions = {}): OpsScript<RoleScriptArgs> {
|
|
75
|
+
const clock = options.clock ?? systemClock;
|
|
76
|
+
return defineOpsScript({
|
|
77
|
+
name: "revoke-role",
|
|
78
|
+
description: "Revokes a stored role from the account with the given email.",
|
|
79
|
+
usage: USAGE,
|
|
80
|
+
args: roleScriptArgs,
|
|
81
|
+
run: async (tx, args) => {
|
|
82
|
+
const ctx: AuthContext = { db: tx, clock, config };
|
|
83
|
+
const account = await findAccount(tx, args.email);
|
|
84
|
+
if (account === undefined) return refuseOpsScript("no account has this email");
|
|
85
|
+
const before = await describeRoles(ctx, account);
|
|
86
|
+
const revoked = await revokeRole(ctx, { userId: account.id, role: args.role });
|
|
87
|
+
if (!revoked.ok) {
|
|
88
|
+
const isFromConfig = args.role === ADMIN_ROLE && isConfiguredAdmin(config, account);
|
|
89
|
+
return refuseOpsScript(
|
|
90
|
+
isFromConfig
|
|
91
|
+
? "admin comes from auth({ adminEmails }) in softure.config.ts; remove the email there"
|
|
92
|
+
: `the account has no stored role "${args.role}"`,
|
|
93
|
+
);
|
|
94
|
+
}
|
|
95
|
+
return ok({ before, after: await describeRoles(ctx, account) });
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
}
|