@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,15 @@
|
|
|
1
|
+
import type { AuthFormErrorCode } from "../contract.js";
|
|
2
|
+
import { en } from "./en.js";
|
|
3
|
+
import { pl } from "./pl.js";
|
|
4
|
+
|
|
5
|
+
/** Complete default dictionaries; apps pass partial overrides per locale. */
|
|
6
|
+
export const authMessages = { en, pl };
|
|
7
|
+
|
|
8
|
+
export type AuthMessages = typeof en;
|
|
9
|
+
|
|
10
|
+
/** The copy for an error code; an unknown code gets the generic failure. */
|
|
11
|
+
export function getAuthErrorMessage(messages: AuthMessages, code: AuthFormErrorCode): string {
|
|
12
|
+
const [namespace, name] = code.split(".", 2) as [string, string];
|
|
13
|
+
const group: Readonly<Record<string, string>> | undefined = (messages.errors as Readonly<Record<string, Readonly<Record<string, string>>>>)[namespace];
|
|
14
|
+
return (group !== undefined && Object.hasOwn(group, name) ? group[name] : undefined) ?? messages.errors.core.unexpected;
|
|
15
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
import type { en } from "./en.js";
|
|
2
|
+
|
|
3
|
+
export const pl: typeof en = {
|
|
4
|
+
fields: {
|
|
5
|
+
email: "E-mail",
|
|
6
|
+
password: "Hasło",
|
|
7
|
+
currentPassword: "Obecne hasło",
|
|
8
|
+
newPassword: "Nowe hasło",
|
|
9
|
+
newPasswordHint: "Co najmniej {minLength} znaków.",
|
|
10
|
+
consent: "Akceptuję regulamin i politykę prywatności.",
|
|
11
|
+
},
|
|
12
|
+
login: {
|
|
13
|
+
title: "Zaloguj się",
|
|
14
|
+
lead: "Witaj ponownie.",
|
|
15
|
+
submit: "Zaloguj się",
|
|
16
|
+
pending: "Logowanie…",
|
|
17
|
+
noAccount: "Nie masz jeszcze konta?",
|
|
18
|
+
registerLink: "Załóż je",
|
|
19
|
+
forgotPassword: "Nie pamiętasz hasła?",
|
|
20
|
+
},
|
|
21
|
+
register: {
|
|
22
|
+
title: "Załóż konto",
|
|
23
|
+
lead: "To zajmie chwilę.",
|
|
24
|
+
submit: "Załóż konto",
|
|
25
|
+
pending: "Zakładanie…",
|
|
26
|
+
hasAccount: "Masz już konto?",
|
|
27
|
+
loginLink: "Zaloguj się",
|
|
28
|
+
closedTitle: "Rejestracja jest zamknięta",
|
|
29
|
+
closedBody: "Nie można teraz założyć nowego konta. Spróbuj ponownie później.",
|
|
30
|
+
},
|
|
31
|
+
changePassword: {
|
|
32
|
+
title: "Zmień hasło",
|
|
33
|
+
lead: "Wszystkie inne urządzenia, na których jesteś zalogowany, zostaną wylogowane.",
|
|
34
|
+
submit: "Zmień hasło",
|
|
35
|
+
pending: "Zapisywanie…",
|
|
36
|
+
success: "Hasło zostało zmienione.",
|
|
37
|
+
},
|
|
38
|
+
forgotPassword: {
|
|
39
|
+
title: "Zresetuj hasło",
|
|
40
|
+
lead: "Podaj e-mail swojego konta, a wyślemy Ci link do ustawienia nowego hasła.",
|
|
41
|
+
submit: "Wyślij link",
|
|
42
|
+
pending: "Wysyłanie…",
|
|
43
|
+
sent: "Jeśli istnieje konto z tym adresem, wysłaliśmy na niego link do zmiany hasła. Link działa przez {ttlMinutes} minut.",
|
|
44
|
+
backToLogin: "Wróć do logowania",
|
|
45
|
+
},
|
|
46
|
+
resetPassword: {
|
|
47
|
+
title: "Ustaw nowe hasło",
|
|
48
|
+
lead: "Zostaniesz wylogowany na wszystkich urządzeniach.",
|
|
49
|
+
submit: "Ustaw hasło",
|
|
50
|
+
pending: "Zapisywanie…",
|
|
51
|
+
success: "Hasło zostało zmienione. Zaloguj się nowym hasłem.",
|
|
52
|
+
invalidTitle: "Ten link nie działa",
|
|
53
|
+
invalidBody: "Link wygasł albo został już użyty. Poproś o nowy.",
|
|
54
|
+
requestNew: "Wyślij nowy link",
|
|
55
|
+
},
|
|
56
|
+
resetMail: {
|
|
57
|
+
subject: "Zresetuj hasło",
|
|
58
|
+
greeting: "Dzień dobry,",
|
|
59
|
+
intro: "Otrzymaliśmy prośbę o zresetowanie hasła do Twojego konta. Otwórz ten link, aby ustawić nowe:",
|
|
60
|
+
action: "Ustaw nowe hasło",
|
|
61
|
+
expiry: "Link działa przez {duration} i tylko raz.",
|
|
62
|
+
minutes: { one: "{count} minutę", few: "{count} minuty", many: "{count} minut", other: "{count} minuty" },
|
|
63
|
+
ignore: "Jeśli to nie Ty, zignoruj tę wiadomość: Twoje hasło się nie zmieni.",
|
|
64
|
+
},
|
|
65
|
+
logout: {
|
|
66
|
+
submit: "Wyloguj się",
|
|
67
|
+
},
|
|
68
|
+
errors: {
|
|
69
|
+
auth: {
|
|
70
|
+
invalid_credentials: "Nieprawidłowy e-mail lub hasło.",
|
|
71
|
+
email_invalid: "Podaj prawidłowy adres e-mail.",
|
|
72
|
+
email_taken: "Konto z tym adresem e-mail już istnieje.",
|
|
73
|
+
password_too_short: "Hasło jest za krótkie.",
|
|
74
|
+
password_too_long: "Hasło jest za długie.",
|
|
75
|
+
consent_required: "Aby założyć konto, zaakceptuj regulamin.",
|
|
76
|
+
registration_closed: "Rejestracja jest zamknięta.",
|
|
77
|
+
current_password_invalid: "Obecne hasło jest nieprawidłowe.",
|
|
78
|
+
unauthenticated: "Sesja wygasła. Zaloguj się ponownie.",
|
|
79
|
+
forbidden: "Nie masz dostępu do tej funkcji.",
|
|
80
|
+
reset_token_invalid: "Ten link wygasł albo został już użyty. Poproś o nowy.",
|
|
81
|
+
password_reset_unavailable: "Reset hasła jest niedostępny.",
|
|
82
|
+
},
|
|
83
|
+
security: {
|
|
84
|
+
rate_limited: "Zbyt wiele prób. Odczekaj kilka minut i spróbuj ponownie.",
|
|
85
|
+
client_unidentified: "Nie udało się ustalić, skąd przyszło to żądanie. Spróbuj ponownie później.",
|
|
86
|
+
},
|
|
87
|
+
core: {
|
|
88
|
+
database_failed: "Coś poszło nie tak po naszej stronie. Spróbuj ponownie za chwilę.",
|
|
89
|
+
unexpected: "Coś poszło nie tak po naszej stronie. Spróbuj ponownie za chwilę.",
|
|
90
|
+
},
|
|
91
|
+
},
|
|
92
|
+
};
|
|
@@ -0,0 +1,216 @@
|
|
|
1
|
+
"use server";
|
|
2
|
+
|
|
3
|
+
// The auth server actions. Each one identifies the client and counts its attempt (inside the
|
|
4
|
+
// server functions) before any work, reads the user from the session cookie (never from a bound
|
|
5
|
+
// argument, which the client controls, docs/02 §8), and turns unexpected failures into
|
|
6
|
+
// `safeError` codes. Next refuses an action whose Origin does not match the host. Every redirect
|
|
7
|
+
// goes through the app's `rewriteRedirect` (`resolveRedirectTarget`).
|
|
8
|
+
import { errorLogLabel, safeError, type SoftureConfig } from "@softure-ai/core";
|
|
9
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
10
|
+
import { identifyClient } from "@softure-ai/security/server";
|
|
11
|
+
import { headers } from "next/headers";
|
|
12
|
+
import { redirect } from "next/navigation";
|
|
13
|
+
import { after } from "next/server";
|
|
14
|
+
import { z } from "zod";
|
|
15
|
+
import type { AuthFormErrorCode, AuthFormField, AuthFormState } from "../contract.js";
|
|
16
|
+
import { resolveRedirectTarget } from "../redirect-target.js";
|
|
17
|
+
import { toSafeNextPath } from "../safe-next-path.js";
|
|
18
|
+
import { changePassword } from "../server/change-password.js";
|
|
19
|
+
import { loginUser } from "../server/login.js";
|
|
20
|
+
import { getAuthRoutes } from "../server/options.js";
|
|
21
|
+
import { deliverPasswordReset, requestPasswordReset, resetPassword } from "../server/password-reset.js";
|
|
22
|
+
import { registerUser } from "../server/register.js";
|
|
23
|
+
import { logoutSession } from "../server/sessions.js";
|
|
24
|
+
import { getAuthContext } from "./context.js";
|
|
25
|
+
import { PASSWORD_RESET_DONE_PARAM } from "./params.js";
|
|
26
|
+
import { clearSessionCookie, readSessionToken, writeSessionCookie } from "./session-cookie.js";
|
|
27
|
+
|
|
28
|
+
/** Longer values are cut: the server functions refuse them anyway, and nothing huge is echoed back. */
|
|
29
|
+
const MAX_FIELD_LENGTH = 4096;
|
|
30
|
+
const text = z
|
|
31
|
+
.string()
|
|
32
|
+
.catch("")
|
|
33
|
+
.transform((value) => value.slice(0, MAX_FIELD_LENGTH));
|
|
34
|
+
|
|
35
|
+
const loginInput = z.object({ email: text, password: text, next: text });
|
|
36
|
+
const registerInput = z.object({ email: text, password: text, next: text, consent: z.string().nullable().catch(null) });
|
|
37
|
+
const changePasswordInput = z.object({ currentPassword: text, newPassword: text });
|
|
38
|
+
const forgotPasswordInput = z.object({ email: text });
|
|
39
|
+
const resetPasswordInput = z.object({ token: text, newPassword: text });
|
|
40
|
+
|
|
41
|
+
const FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
|
|
42
|
+
"auth.email_invalid": "email",
|
|
43
|
+
"auth.email_taken": "email",
|
|
44
|
+
"auth.password_too_short": "password",
|
|
45
|
+
"auth.password_too_long": "password",
|
|
46
|
+
"auth.consent_required": "consent",
|
|
47
|
+
};
|
|
48
|
+
|
|
49
|
+
const CHANGE_FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
|
|
50
|
+
"auth.current_password_invalid": "currentPassword",
|
|
51
|
+
"auth.password_too_short": "newPassword",
|
|
52
|
+
"auth.password_too_long": "newPassword",
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
const RESET_FIELD_OF: Partial<Record<AuthFormErrorCode, AuthFormField>> = {
|
|
56
|
+
"auth.password_too_short": "newPassword",
|
|
57
|
+
"auth.password_too_long": "newPassword",
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
function failure(error: AuthFormErrorCode, options: { field?: AuthFormField; email?: string } = {}): AuthFormState {
|
|
61
|
+
return { status: "error", error, ...options };
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function readForm<T extends z.ZodType>(schema: T, formData: FormData): z.output<T> {
|
|
65
|
+
const raw = Object.fromEntries([...formData.keys()].map((key) => [key, formData.get(key)]));
|
|
66
|
+
// Every field has a `catch`, so parsing cannot fail.
|
|
67
|
+
return schema.parse(raw);
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function reportFailure(operation: string, error: unknown): AuthFormErrorCode {
|
|
71
|
+
console.error(`@softure-ai/auth: ${operation} failed: ${errorLogLabel(error)}`);
|
|
72
|
+
return safeError(error).error;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function loginAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
|
|
76
|
+
const config = getSoftureConfig();
|
|
77
|
+
const input = readForm(loginInput, formData);
|
|
78
|
+
const client = identifyClient({ config }, await headers());
|
|
79
|
+
if (!client.ok) return failure(client.error, { email: input.email });
|
|
80
|
+
|
|
81
|
+
let result;
|
|
82
|
+
try {
|
|
83
|
+
result = await loginUser(await getAuthContext(config), { email: input.email, password: input.password, clientKey: client.value });
|
|
84
|
+
} catch (error) {
|
|
85
|
+
return failure(reportFailure("login", error), { email: input.email });
|
|
86
|
+
}
|
|
87
|
+
if (!result.ok) return failure(result.error, { email: input.email });
|
|
88
|
+
|
|
89
|
+
await endPreviousSession(config);
|
|
90
|
+
await writeSessionCookie(config, result.value.session);
|
|
91
|
+
redirect(await resolveRedirectTarget(config, toSafeNextPath(input.next, getAuthRoutes(config).afterLogin)));
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
export async function registerAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
|
|
95
|
+
const config = getSoftureConfig();
|
|
96
|
+
const input = readForm(registerInput, formData);
|
|
97
|
+
const client = identifyClient({ config }, await headers());
|
|
98
|
+
if (!client.ok) return failure(client.error, { email: input.email });
|
|
99
|
+
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await registerUser(await getAuthContext(config), {
|
|
103
|
+
email: input.email,
|
|
104
|
+
password: input.password,
|
|
105
|
+
// A checked HTML checkbox sends "on" (or its value); an unchecked one sends nothing.
|
|
106
|
+
hasConsented: input.consent !== null,
|
|
107
|
+
clientKey: client.value,
|
|
108
|
+
});
|
|
109
|
+
} catch (error) {
|
|
110
|
+
return failure(reportFailure("registration", error), { email: input.email });
|
|
111
|
+
}
|
|
112
|
+
if (!result.ok) return failure(result.error, { field: FIELD_OF[result.error], email: input.email });
|
|
113
|
+
|
|
114
|
+
await endPreviousSession(config);
|
|
115
|
+
await writeSessionCookie(config, result.value.session);
|
|
116
|
+
redirect(await resolveRedirectTarget(config, toSafeNextPath(input.next, getAuthRoutes(config).afterLogin)));
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
export async function changePasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
|
|
120
|
+
const config = getSoftureConfig();
|
|
121
|
+
const input = readForm(changePasswordInput, formData);
|
|
122
|
+
const token = await readSessionToken(config);
|
|
123
|
+
if (token === null) return failure("auth.unauthenticated");
|
|
124
|
+
|
|
125
|
+
try {
|
|
126
|
+
const result = await changePassword(await getAuthContext(config), {
|
|
127
|
+
sessionToken: token,
|
|
128
|
+
currentPassword: input.currentPassword,
|
|
129
|
+
newPassword: input.newPassword,
|
|
130
|
+
});
|
|
131
|
+
return result.ok ? { status: "ok" } : failure(result.error, { field: CHANGE_FIELD_OF[result.error] });
|
|
132
|
+
} catch (error) {
|
|
133
|
+
return failure(reportFailure("password change", error));
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Asks for a reset link. The answer depends only on the buckets and the email's shape, never on
|
|
139
|
+
* whether the account exists: the link is issued and handed to the app's sender after the
|
|
140
|
+
* response, so neither the sender's time nor its failure shows here.
|
|
141
|
+
*/
|
|
142
|
+
export async function forgotPasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
|
|
143
|
+
const config = getSoftureConfig();
|
|
144
|
+
const input = readForm(forgotPasswordInput, formData);
|
|
145
|
+
const client = identifyClient({ config }, await headers());
|
|
146
|
+
if (!client.ok) return failure(client.error, { email: input.email });
|
|
147
|
+
|
|
148
|
+
let result;
|
|
149
|
+
try {
|
|
150
|
+
result = await requestPasswordReset(await getAuthContext(config), { email: input.email, clientKey: client.value });
|
|
151
|
+
} catch (error) {
|
|
152
|
+
return failure(reportFailure("password reset request", error), { email: input.email });
|
|
153
|
+
}
|
|
154
|
+
if (!result.ok) return failure(result.error, { field: FIELD_OF[result.error], email: input.email });
|
|
155
|
+
|
|
156
|
+
const { email } = result.value;
|
|
157
|
+
after(async () => {
|
|
158
|
+
try {
|
|
159
|
+
await deliverPasswordReset(await getAuthContext(config), email);
|
|
160
|
+
} catch (error) {
|
|
161
|
+
reportFailure("password reset delivery", error);
|
|
162
|
+
}
|
|
163
|
+
});
|
|
164
|
+
return { status: "ok" };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/**
|
|
168
|
+
* Sets a new password with the token from a reset link, then goes to the login page, which says so.
|
|
169
|
+
* A redirect, not an `ok` state: without JavaScript the reset page renders again after the action,
|
|
170
|
+
* and its token is used by then.
|
|
171
|
+
*/
|
|
172
|
+
export async function resetPasswordAction(_previous: AuthFormState, formData: FormData): Promise<AuthFormState> {
|
|
173
|
+
const config = getSoftureConfig();
|
|
174
|
+
const input = readForm(resetPasswordInput, formData);
|
|
175
|
+
const client = identifyClient({ config }, await headers());
|
|
176
|
+
if (!client.ok) return failure(client.error);
|
|
177
|
+
|
|
178
|
+
let result;
|
|
179
|
+
try {
|
|
180
|
+
result = await resetPassword(await getAuthContext(config), {
|
|
181
|
+
token: input.token,
|
|
182
|
+
newPassword: input.newPassword,
|
|
183
|
+
clientKey: client.value,
|
|
184
|
+
});
|
|
185
|
+
} catch (error) {
|
|
186
|
+
return failure(reportFailure("password reset", error));
|
|
187
|
+
}
|
|
188
|
+
if (!result.ok) return failure(result.error, { field: RESET_FIELD_OF[result.error] });
|
|
189
|
+
redirect(await resolveRedirectTarget(config, `${getAuthRoutes(config).login}?${PASSWORD_RESET_DONE_PARAM}=1`));
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/** Ends the session the browser held before a login or register, so it cannot be reused. */
|
|
193
|
+
async function endPreviousSession(config: SoftureConfig): Promise<void> {
|
|
194
|
+
const previous = await readSessionToken(config);
|
|
195
|
+
if (previous === null) return;
|
|
196
|
+
try {
|
|
197
|
+
await logoutSession(await getAuthContext(config), previous);
|
|
198
|
+
} catch (error) {
|
|
199
|
+
reportFailure("ending the previous session", error);
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/** Ends the request's session and goes to `afterLogout`. The cookie is cleared even if the delete fails. */
|
|
204
|
+
export async function logoutAction(): Promise<void> {
|
|
205
|
+
const config = getSoftureConfig();
|
|
206
|
+
const token = await readSessionToken(config);
|
|
207
|
+
if (token !== null) {
|
|
208
|
+
try {
|
|
209
|
+
await logoutSession(await getAuthContext(config), token);
|
|
210
|
+
} catch (error) {
|
|
211
|
+
reportFailure("logout", error);
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
await clearSessionCookie(config);
|
|
215
|
+
redirect(await resolveRedirectTarget(config, getAuthRoutes(config).afterLogout));
|
|
216
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
// What the adapter hands the server functions: the registered config, the process-wide database
|
|
2
|
+
// handle and the wall clock. Request scope (cookies, headers) stays in this folder.
|
|
3
|
+
import { systemClock, type SoftureConfig } from "@softure-ai/core";
|
|
4
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
5
|
+
import { getSharedDatabase } from "@softure-ai/db";
|
|
6
|
+
import type { AuthContext } from "../server/sessions.js";
|
|
7
|
+
|
|
8
|
+
export async function getAuthContext(config: SoftureConfig = getSoftureConfig()): Promise<AuthContext> {
|
|
9
|
+
if (config.database === null) {
|
|
10
|
+
throw new Error("@softure-ai/auth: softure.config.ts has no database; auth needs one");
|
|
11
|
+
}
|
|
12
|
+
const { db } = await getSharedDatabase(config.database.url);
|
|
13
|
+
return { db, clock: systemClock, config };
|
|
14
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
// The signed-in user and their roles for server components, actions and route handlers. React's
|
|
2
|
+
// `cache` makes each one lookup per request, however many components ask; nothing is cached
|
|
3
|
+
// across requests, so a revoked role is gone on the next one.
|
|
4
|
+
import { err, ok, type Err, type Ok } from "@softure-ai/core";
|
|
5
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
6
|
+
import { notFound, redirect } from "next/navigation";
|
|
7
|
+
import { cache } from "react";
|
|
8
|
+
import type { AuthUser } from "../contract.js";
|
|
9
|
+
import { resolveRedirectTarget } from "../redirect-target.js";
|
|
10
|
+
import { toSafeNextPath } from "../safe-next-path.js";
|
|
11
|
+
import { getAuthRoutes } from "../server/options.js";
|
|
12
|
+
import { assertDeclaredRole, findUserRoles } from "../server/roles.js";
|
|
13
|
+
import { findSessionUser } from "../server/sessions.js";
|
|
14
|
+
import { getAuthContext } from "./context.js";
|
|
15
|
+
import { toUrlSearchParams, type PageSearchParams } from "./search-params.js";
|
|
16
|
+
import { readSessionToken } from "./session-cookie.js";
|
|
17
|
+
|
|
18
|
+
/** The user of the request's session, or null. Database failures propagate to the error page. */
|
|
19
|
+
export const getCurrentUser = cache(async (): Promise<AuthUser | null> => {
|
|
20
|
+
const config = getSoftureConfig();
|
|
21
|
+
const token = await readSessionToken(config);
|
|
22
|
+
if (token === null) return null;
|
|
23
|
+
return findSessionUser(await getAuthContext(config), token);
|
|
24
|
+
});
|
|
25
|
+
|
|
26
|
+
export interface RequireUserOptions {
|
|
27
|
+
/** Where to come back after login; a same-origin path. */
|
|
28
|
+
readonly next?: string;
|
|
29
|
+
/**
|
|
30
|
+
* A page's own search params (awaited), handed to the app's `rewriteRedirect` so the login URL
|
|
31
|
+
* can keep the page's channel tag. Without them the rewrite reads as for an action.
|
|
32
|
+
*/
|
|
33
|
+
readonly searchParams?: PageSearchParams | undefined;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The signed-in user; without one, a redirect to the login page (with `next` when given), through
|
|
38
|
+
* the app's `rewriteRedirect`.
|
|
39
|
+
*/
|
|
40
|
+
export async function requireUser(options: RequireUserOptions = {}): Promise<AuthUser> {
|
|
41
|
+
const user = await getCurrentUser();
|
|
42
|
+
if (user !== null) return user;
|
|
43
|
+
const config = getSoftureConfig();
|
|
44
|
+
const login = getAuthRoutes(config).login;
|
|
45
|
+
const next = options.next === undefined ? null : toSafeNextPath(options.next, "");
|
|
46
|
+
const path = next === null || next === "" ? login : `${login}?next=${encodeURIComponent(next)}`;
|
|
47
|
+
const searchParams = options.searchParams === undefined ? undefined : toUrlSearchParams(options.searchParams);
|
|
48
|
+
redirect(await resolveRedirectTarget(config, path, searchParams));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
const NO_ROLES: ReadonlySet<string> = new Set();
|
|
52
|
+
|
|
53
|
+
/** The roles of the request's user; none without a session. */
|
|
54
|
+
export const getCurrentUserRoles = cache(async (): Promise<ReadonlySet<string>> => {
|
|
55
|
+
const user = await getCurrentUser();
|
|
56
|
+
if (user === null) return NO_ROLES;
|
|
57
|
+
return findUserRoles(await getAuthContext(), user);
|
|
58
|
+
});
|
|
59
|
+
|
|
60
|
+
/** The signed-in user when they hold `role`, else null. Throws for an undeclared role. */
|
|
61
|
+
async function findUserWithRole(role: string): Promise<AuthUser | null> {
|
|
62
|
+
assertDeclaredRole(getSoftureConfig(), role);
|
|
63
|
+
const user = await getCurrentUser();
|
|
64
|
+
if (user === null) return null;
|
|
65
|
+
return (await getCurrentUserRoles()).has(role) ? user : null;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* For pages, layouts and route handlers: the signed-in user when they hold `role`; for anyone
|
|
70
|
+
* else, signed in or not, Next's "not found", so the surface does not reveal that it exists.
|
|
71
|
+
*/
|
|
72
|
+
export async function requireRole(role: string): Promise<AuthUser> {
|
|
73
|
+
const user = await findUserWithRole(role);
|
|
74
|
+
if (user === null) notFound();
|
|
75
|
+
return user;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* For server actions: the signed-in user when they hold `role`, else `auth.forbidden` (also
|
|
80
|
+
* without a session), for the action to return to its form. Call it before reading any input.
|
|
81
|
+
*/
|
|
82
|
+
export async function authorizeRole(role: string): Promise<Ok<AuthUser> | Err<"auth.forbidden">> {
|
|
83
|
+
const user = await findUserWithRole(role);
|
|
84
|
+
return user === null ? err("auth.forbidden") : ok(user);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/** For UI decisions such as showing a link; never the access check itself. */
|
|
88
|
+
export async function hasRole(role: string): Promise<boolean> {
|
|
89
|
+
return (await findUserWithRole(role)) !== null;
|
|
90
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// The Next.js adapter of @softure-ai/auth: pages, server actions, the session route and the
|
|
2
|
+
// current-user and role helpers (docs/02-module-standard.md §8). The route guard is `@softure-ai/auth/proxy`.
|
|
3
|
+
export {
|
|
4
|
+
changePasswordAction,
|
|
5
|
+
forgotPasswordAction,
|
|
6
|
+
loginAction,
|
|
7
|
+
logoutAction,
|
|
8
|
+
registerAction,
|
|
9
|
+
resetPasswordAction,
|
|
10
|
+
} from "./actions.js";
|
|
11
|
+
export {
|
|
12
|
+
authorizeRole,
|
|
13
|
+
getCurrentUser,
|
|
14
|
+
getCurrentUserRoles,
|
|
15
|
+
hasRole,
|
|
16
|
+
requireRole,
|
|
17
|
+
requireUser,
|
|
18
|
+
type RequireUserOptions,
|
|
19
|
+
} from "./current-user.js";
|
|
20
|
+
export { LogoutButton, type LogoutButtonProps } from "./logout-button.js";
|
|
21
|
+
export { getAuthMessages } from "./messages.js";
|
|
22
|
+
export { type AuthPageProps, ChangePasswordPage, ForgotPasswordPage, LoginPage, RegisterPage, ResetPasswordPage } from "./pages.js";
|
|
23
|
+
export { getSessionRoute } from "./route.js";
|
|
24
|
+
export type { PageSearchParams } from "./search-params.js";
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// A logout button for the app's own pages: a plain form posting to `logoutAction`, so it works
|
|
2
|
+
// without JavaScript. Server component.
|
|
3
|
+
import { getSoftureConfig } from "@softure-ai/core/next";
|
|
4
|
+
import { Button, type ButtonVariant } from "@softure-ai/ui";
|
|
5
|
+
import { logoutAction } from "./actions.js";
|
|
6
|
+
import { getAuthMessages } from "./messages.js";
|
|
7
|
+
|
|
8
|
+
export interface LogoutButtonProps {
|
|
9
|
+
readonly variant?: ButtonVariant;
|
|
10
|
+
readonly className?: string;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
export function LogoutButton({ variant = "secondary", className }: LogoutButtonProps) {
|
|
14
|
+
const messages = getAuthMessages(getSoftureConfig());
|
|
15
|
+
return (
|
|
16
|
+
<form action={logoutAction} className={className}>
|
|
17
|
+
<Button type="submit" variant={variant}>
|
|
18
|
+
{messages.logout.submit}
|
|
19
|
+
</Button>
|
|
20
|
+
</form>
|
|
21
|
+
);
|
|
22
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import type { SoftureConfig } from "@softure-ai/core";
|
|
2
|
+
import type { AuthMessages } from "../messages/index.js";
|
|
3
|
+
import { getAuthModule } from "../server/options.js";
|
|
4
|
+
|
|
5
|
+
/** The module's copy in the app's locale, with the app's overrides applied. */
|
|
6
|
+
export function getAuthMessages(config: SoftureConfig): AuthMessages {
|
|
7
|
+
// The module factory merged the dictionaries; their shape is the module's own.
|
|
8
|
+
return getAuthModule(config).messages[config.locale] as AuthMessages;
|
|
9
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
// Next.js has no `exports` map, so NodeNext resolution (tsconfig.base.json) only finds
|
|
2
|
+
// `next/navigation.js` and `next/headers.js`. The code must still import the bare specifiers:
|
|
3
|
+
// Next's bundler aliases them per runtime, and the `.js` form bypasses the alias (measured:
|
|
4
|
+
// `next build` failed to collect a route handler importing `next/navigation.js`, MODULE_UNPARSABLE
|
|
5
|
+
// on the vendored app-router context). These declarations give the bare specifiers their types.
|
|
6
|
+
declare module "next/navigation" {
|
|
7
|
+
export * from "next/navigation.js";
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
declare module "next/headers" {
|
|
11
|
+
export * from "next/headers.js";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
declare module "next/server" {
|
|
15
|
+
export * from "next/server.js";
|
|
16
|
+
}
|