@poadio/starter-next 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/.dockerignore +9 -0
  2. package/.env.example +8 -0
  3. package/Dockerfile +29 -0
  4. package/README.md +141 -2
  5. package/bun.lock +156 -0
  6. package/gitignore +37 -0
  7. package/next.config.ts +14 -0
  8. package/package.json +70 -4
  9. package/public/logo.svg +1 -0
  10. package/public/providers/google.svg +1 -0
  11. package/public/providers/keycloak.svg +1 -0
  12. package/scripts/dev.mjs +68 -0
  13. package/scripts/env.mjs +130 -0
  14. package/scripts/env.test.mjs +71 -0
  15. package/src/app/(auth)/login/login-form.tsx +258 -0
  16. package/src/app/(auth)/login/page.tsx +16 -0
  17. package/src/app/(auth)/mfa/mfa-form.tsx +55 -0
  18. package/src/app/(auth)/mfa/page.tsx +16 -0
  19. package/src/app/(auth)/reset/page.tsx +16 -0
  20. package/src/app/(auth)/reset/reset-form.tsx +51 -0
  21. package/src/app/app/account/account.css +36 -0
  22. package/src/app/app/account/account.tsx +476 -0
  23. package/src/app/app/account/page.tsx +18 -0
  24. package/src/app/app/dashboard.tsx +58 -0
  25. package/src/app/app/hello/[name]/page.tsx +38 -0
  26. package/src/app/app/layout.tsx +12 -0
  27. package/src/app/app/page.tsx +18 -0
  28. package/src/app/app/public/page.tsx +15 -0
  29. package/src/app/app/public/public-content.tsx +31 -0
  30. package/src/app/globals.css +271 -0
  31. package/src/app/home.css +186 -0
  32. package/src/app/home.tsx +92 -0
  33. package/src/app/icon.svg +1 -0
  34. package/src/app/layout.tsx +58 -0
  35. package/src/app/not-found.tsx +6 -0
  36. package/src/app/page.tsx +6 -0
  37. package/src/app/providers.tsx +24 -0
  38. package/src/app/setup/page.tsx +39 -0
  39. package/src/app/shell.css +752 -0
  40. package/src/app.meta.ts +41 -0
  41. package/src/components/brand.tsx +15 -0
  42. package/src/components/captcha.tsx +93 -0
  43. package/src/components/link-button.tsx +9 -0
  44. package/src/components/rich.tsx +14 -0
  45. package/src/components/shell/app-menu.tsx +127 -0
  46. package/src/components/shell/app-shell.tsx +268 -0
  47. package/src/components/shell/page-title.tsx +29 -0
  48. package/src/components/shell/switches.tsx +35 -0
  49. package/src/components/shell/use-layout.ts +123 -0
  50. package/src/core/auth.tsx +227 -0
  51. package/src/core/env.server.ts +27 -0
  52. package/src/core/env.tsx +46 -0
  53. package/src/core/guards.tsx +74 -0
  54. package/src/core/messages.ts +18 -0
  55. package/src/core/providers.ts +32 -0
  56. package/src/core/theme-script.ts +7 -0
  57. package/src/core/theme.tsx +37 -0
  58. package/src/i18n/client.tsx +47 -0
  59. package/src/i18n/en.ts +228 -0
  60. package/src/i18n/fr.ts +251 -0
  61. package/src/i18n/index.ts +38 -0
  62. package/src/i18n/server.ts +19 -0
  63. package/tsconfig.json +21 -0
@@ -0,0 +1,130 @@
1
+ // Variables d'environnement du front, à la Next.js.
2
+ //
3
+ // Next.js lit lui-même, du moins au plus prioritaire, puis l'environnement du processus :
4
+ // .env .env.<mode> .env.local .env.<mode>.local (mode : development, production)
5
+ //
6
+ // Ce module ajoute le branchement automatique sur le projet poad local : sans
7
+ // POAD_URL ni POAD_ANON_KEY (ni dans les fichiers .env*, ni dans
8
+ // l'environnement), elles sont lues dans poad/config.toml et poad/secrets.toml
9
+ // (ce dossier ou un parent). scripts/dev.mjs les passe alors à next dev.
10
+ //
11
+ // Les valeurs ne sont JAMAIS compilées dans le code : le serveur Next.js les
12
+ // lit à chaque requête (src/core/env.server.ts) et n'envoie au navigateur que
13
+ // les variables PUBLIC_*, NEXT_PUBLIC_* et POAD_URL, POAD_ANON_KEY, POAD_MAIL_URL.
14
+ //
15
+ // node scripts/env.mjs [mode] affiche les variables que verra le navigateur (noms seulement)
16
+ import { existsSync, readFileSync } from 'node:fs';
17
+ import { dirname, join, resolve } from 'node:path';
18
+ import { fileURLToPath, pathToFileURL } from 'node:url';
19
+
20
+ export const root = resolve(dirname(fileURLToPath(import.meta.url)), '..');
21
+
22
+ const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL'];
23
+
24
+ /** Même règle que src/core/env.server.ts */
25
+ export const isPublic = (key) => key.startsWith('PUBLIC_') || key.startsWith('NEXT_PUBLIC_') || POAD_KEYS.includes(key);
26
+
27
+ /** Lecture d'un fichier .env : KEY=valeur, guillemets, commentaires, « export » */
28
+ export function parseDotenv(text) {
29
+ const out = {};
30
+ for (const raw of text.split(/\r?\n/)) {
31
+ const line = raw.trim();
32
+ if (!line || line.startsWith('#')) continue;
33
+ const m = /^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/.exec(line);
34
+ if (!m) continue;
35
+ let v = m[2];
36
+ const quoted = /^(['"])([\s\S]*)\1$/.exec(v);
37
+ if (quoted) v = quoted[1] === '"' ? quoted[2].replace(/\\n/g, '\n').replace(/\\"/g, '"') : quoted[2];
38
+ else v = v.replace(/\s+#.*$/, '').trim();
39
+ out[m[1]] = v;
40
+ }
41
+ return out;
42
+ }
43
+
44
+ /** Sections et clés d'un fichier TOML simple (pas de tableaux ni de multilignes) */
45
+ export function parseToml(file, conf = {}) {
46
+ if (!existsSync(file)) return conf;
47
+ let section = '';
48
+ for (const raw of readFileSync(file, 'utf8').split(/\r?\n/)) {
49
+ const line = raw.replace(/#.*$/, '').trim();
50
+ const s = /^\[([^\]]+)\]$/.exec(line);
51
+ if (s) {
52
+ section = s[1].trim();
53
+ continue;
54
+ }
55
+ const kv = /^([A-Za-z0-9_.-]+)\s*=\s*"?([^"]*)"?$/.exec(line);
56
+ if (kv) (conf[section] ??= {})[kv[1]] = kv[2];
57
+ }
58
+ return conf;
59
+ }
60
+
61
+ /** Dossier du projet poad (poad/config.toml) : from ou un parent, sinon null */
62
+ export function findPoadProject(from = root) {
63
+ for (let dir = from; ; dir = dirname(dir)) {
64
+ if (existsSync(join(dir, 'poad', 'config.toml'))) return dir;
65
+ if (dirname(dir) === dir) return null;
66
+ }
67
+ }
68
+
69
+ /**
70
+ * URL, clé anon et boîte e-mail du projet poad local : poad/config.toml, et
71
+ * poad/secrets.toml pour la clé (CLI 2.12 et plus ; avant, dans config.toml)
72
+ */
73
+ export function fromPoadProject(from = root) {
74
+ const dir = findPoadProject(from);
75
+ if (!dir) return {};
76
+ const conf = parseToml(join(dir, 'poad', 'config.toml'));
77
+ parseToml(join(dir, 'poad', 'secrets.toml'), conf);
78
+ const out = {};
79
+ if (conf.web?.port) out.POAD_URL = `http://localhost:${conf.web.port}`;
80
+ if (conf.auth?.anon) out.POAD_ANON_KEY = conf.auth.anon;
81
+ // [mail] depuis l'engine 0.7.0 (Mailpit), [inbucket] avant
82
+ const mail = conf.mail?.port ?? conf.inbucket?.port;
83
+ if (mail) out.POAD_MAIL_URL = `http://localhost:${mail}`;
84
+ return out;
85
+ }
86
+
87
+ /** Variables des fichiers .env*, dans l'ordre de Next.js */
88
+ export function fromDotenvFiles(mode = 'development', dir = root) {
89
+ let vars = {};
90
+ const files = ['.env', `.env.${mode}`, ...(mode === 'test' ? [] : ['.env.local']), `.env.${mode}.local`];
91
+ for (const name of files) {
92
+ const file = join(dir, name);
93
+ if (existsSync(file)) vars = { ...vars, ...parseDotenv(readFileSync(file, 'utf8')) };
94
+ }
95
+ return vars;
96
+ }
97
+
98
+ /**
99
+ * Variables du projet poad local à AJOUTER à l'environnement de next dev :
100
+ * seulement celles que ni les fichiers .env*, ni l'environnement ne donnent
101
+ * (Next.js ne remplace jamais une variable déjà présente dans le processus).
102
+ */
103
+ export function poadDefaults(mode = 'development', env = process.env, dir = root) {
104
+ const given = { ...fromDotenvFiles(mode, dir), ...env };
105
+ const out = {};
106
+ for (const [k, v] of Object.entries(fromPoadProject(dir))) {
107
+ if (given[k] === undefined || given[k] === '') out[k] = v;
108
+ }
109
+ return out;
110
+ }
111
+
112
+ /** Variables qu'aura le navigateur (même règle que le serveur) */
113
+ export function publicEnv(mode = 'development', env = process.env, dir = root) {
114
+ const vars = { ...fromPoadProject(dir), ...fromDotenvFiles(mode, dir), ...env };
115
+ return Object.fromEntries(
116
+ Object.entries(vars)
117
+ .filter(([k, v]) => isPublic(k) && v !== undefined && v !== '')
118
+ .sort(([a], [b]) => a.localeCompare(b)),
119
+ );
120
+ }
121
+
122
+ if (process.argv[1] && import.meta.url === pathToFileURL(process.argv[1]).href) {
123
+ const mode = process.argv[2] || process.env.NODE_ENV || 'development';
124
+ const env = publicEnv(mode);
125
+ // Les noms seulement : la clé anon est publique, mais n'a rien à faire dans un journal
126
+ console.log(`[env] ${mode} : ${Object.keys(env).join(', ') || 'aucune variable'}`);
127
+ if (!env.POAD_URL || !env.POAD_ANON_KEY) {
128
+ console.warn('[env] POAD_URL ou POAD_ANON_KEY manquant : `poad init` ici, ou renseignez-les dans .env.local');
129
+ }
130
+ }
@@ -0,0 +1,71 @@
1
+ // node --test scripts/*.test.mjs : variables du front et contrat du modèle (poad create)
2
+ import { test } from 'node:test';
3
+ import assert from 'node:assert/strict';
4
+ import { mkdtempSync, mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { tmpdir } from 'node:os';
6
+ import { join } from 'node:path';
7
+ import { fromPoadProject, isPublic, parseDotenv, poadDefaults, publicEnv, root } from './env.mjs';
8
+
9
+ /** Projet poad factice : poad/config.toml, poad/secrets.toml (valeurs de test, pas de vrai secret) */
10
+ function fakeProject() {
11
+ const dir = mkdtempSync(join(tmpdir(), 'starter-next-'));
12
+ mkdirSync(join(dir, 'poad'));
13
+ writeFileSync(join(dir, 'poad', 'config.toml'), '[web]\nport = 41234 # gateway\n\n[mail]\nport = 41235\n');
14
+ writeFileSync(join(dir, 'poad', 'secrets.toml'), '[auth]\nanon = "test-anon"\n');
15
+ const app = join(dir, 'app');
16
+ mkdirSync(app);
17
+ return { dir, app };
18
+ }
19
+
20
+ test('parseDotenv : guillemets, commentaires, export', () => {
21
+ assert.deepEqual(parseDotenv('# c\nA=1\nexport B="x y"\nC=\'z\' \nD=v # fin\n'), { A: '1', B: 'x y', C: 'z', D: 'v' });
22
+ });
23
+
24
+ test('isPublic : PUBLIC_*, NEXT_PUBLIC_*, POAD_URL / ANON_KEY / MAIL_URL seulement', () => {
25
+ for (const k of ['PUBLIC_X', 'NEXT_PUBLIC_Y', 'POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL']) assert.ok(isPublic(k), k);
26
+ for (const k of ['POAD_SERVICE_KEY', 'DATABASE_URL', 'SECRET', 'PATH']) assert.ok(!isPublic(k), k);
27
+ });
28
+
29
+ test('fromPoadProject : lit le projet dans un dossier parent', () => {
30
+ const { dir, app } = fakeProject();
31
+ try {
32
+ assert.deepEqual(fromPoadProject(app), { POAD_URL: 'http://localhost:41234', POAD_ANON_KEY: 'test-anon', POAD_MAIL_URL: 'http://localhost:41235' });
33
+ } finally {
34
+ rmSync(dir, { recursive: true, force: true });
35
+ }
36
+ });
37
+
38
+ test('poadDefaults : .env* et l’environnement l’emportent sur le projet poad', () => {
39
+ const { dir, app } = fakeProject();
40
+ try {
41
+ assert.deepEqual(Object.keys(poadDefaults('development', {}, app)).sort(), ['POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_URL']);
42
+ writeFileSync(join(app, '.env.local'), 'POAD_URL=https://example.test\n');
43
+ const d = poadDefaults('development', { POAD_ANON_KEY: 'from-env' }, app);
44
+ assert.deepEqual(Object.keys(d), ['POAD_MAIL_URL']);
45
+ const pub = publicEnv('development', { POAD_ANON_KEY: 'from-env', OTHER: 'no' }, app);
46
+ assert.equal(pub.POAD_URL, 'https://example.test');
47
+ assert.equal(pub.POAD_ANON_KEY, 'from-env');
48
+ assert.equal(pub.OTHER, undefined);
49
+ } finally {
50
+ rmSync(dir, { recursive: true, force: true });
51
+ }
52
+ });
53
+
54
+ test('package.json : contrat du modèle attendu par poad create', () => {
55
+ const pkg = JSON.parse(readFileSync(join(root, 'package.json'), 'utf8'));
56
+ assert.equal(pkg.name, '@poadio/starter-next');
57
+ assert.equal(pkg.publishConfig?.access, 'public');
58
+ assert.match(pkg.packageManager, /^bun@/);
59
+ const tpl = pkg.poad?.template;
60
+ assert.equal(tpl.framework, 'next');
61
+ assert.ok(tpl.label && tpl.description && tpl.port);
62
+ assert.ok(Array.isArray(tpl.gitignore) && tpl.gitignore.includes('/.next/'));
63
+ // Port gardé après poad create (qui retire poad.template)
64
+ assert.equal(pkg.poad.port, tpl.port);
65
+ for (const f of ['src', 'public', '!public/env.json', 'scripts', 'gitignore']) assert.ok(pkg.files.includes(f), f);
66
+ for (const f of ['node_modules', '.next', '.env.local', 'poad']) assert.ok(!pkg.files.includes(f), f);
67
+ });
68
+
69
+ test('gitignore (publié) et .gitignore (dépôt) sont identiques', () => {
70
+ assert.equal(readFileSync(join(root, 'gitignore'), 'utf8'), readFileSync(join(root, '.gitignore'), 'utf8'));
71
+ });
@@ -0,0 +1,258 @@
1
+ 'use client';
2
+ import { useRef, useState, type FormEvent } from 'react';
3
+ import Link from 'next/link';
4
+ import { PoadButton, PoadCard, PoadDivider, PoadField, PoadIcon, PoadInput, PoadMessage, PoadPassword, PoadTab, PoadTabs } from '@poadio/ui-react';
5
+ import type { Result } from '@poadio/client-js';
6
+ import { Brand } from '@/components/brand';
7
+ import { Captcha, type CaptchaHandle } from '@/components/captcha';
8
+ import { Rich } from '@/components/rich';
9
+ import { useAuth } from '@/core/auth';
10
+ import { providerLabel, providerLogo } from '@/core/providers';
11
+ import { useT } from '@/i18n/client';
12
+ import type { MessageKey } from '@/i18n';
13
+
14
+ type Sent = { email: string; type: 'signup' | 'email' | 'recovery' };
15
+
16
+ /** Le formulaire ne recharge jamais la page */
17
+ const submit = (fn: () => unknown) => (e: FormEvent) => {
18
+ e.preventDefault();
19
+ void fn();
20
+ };
21
+
22
+ export function LoginForm() {
23
+ const auth = useAuth();
24
+ const t = useT();
25
+ const poad = auth.poad!;
26
+ const [tab, setTab] = useState('password');
27
+ const [busy, setBusy] = useState(false);
28
+ /** Fournisseur (ou « anonymous ») en cours, pour l'indicateur du bon bouton */
29
+ const [pending, setPending] = useState<string | null>(null);
30
+ const [email, setEmail] = useState('');
31
+ const [password, setPassword] = useState('');
32
+ const [name, setName] = useState('');
33
+ const [code, setCode] = useState('');
34
+ /** Adresse à laquelle un code vient d'être envoyé, et pour quoi */
35
+ const [sent, setSent] = useState<Sent | null>(null);
36
+
37
+ /** CAPTCHA exigé par le service (/settings) */
38
+ const c = auth.settings?.captcha;
39
+ const captcha = c && c.site_key ? { provider: c.provider, siteKey: c.site_key } : null;
40
+ const [captchaToken, setCaptchaToken] = useState<string | null>(null);
41
+ const widget = useRef<CaptchaHandle>(null);
42
+ /** Envoi impossible tant que le CAPTCHA exigé n'est pas résolu */
43
+ const blocked = Boolean(captcha) && !captchaToken;
44
+ const token = captchaToken ?? undefined;
45
+
46
+ async function call<T>(fn: () => Promise<Result<T>>, success?: string): Promise<T | null> {
47
+ setBusy(true);
48
+ try {
49
+ return await auth.run(fn, success);
50
+ } finally {
51
+ setBusy(false);
52
+ // Un jeton CAPTCHA ne sert qu'une fois
53
+ widget.current?.reset();
54
+ }
55
+ }
56
+
57
+ const signIn = () => call(() => poad.auth.signInWithPassword({ email, password, captchaToken: token }));
58
+
59
+ const signUp = async () => {
60
+ const data = await call(() =>
61
+ poad.auth.signUp({ email, password, data: name ? { name } : {}, redirectTo: auth.redirect('/app'), captchaToken: token }),
62
+ );
63
+ if (data && !data.session) setSent({ email, type: 'signup' });
64
+ };
65
+
66
+ const sendLink = async () => {
67
+ const data = await call(() => poad.auth.signInWithOtp({ email, redirectTo: auth.redirect('/app'), captchaToken: token }), t('login.emailSent'));
68
+ if (data) setSent({ email, type: 'email' });
69
+ };
70
+
71
+ const sendRecovery = async () => {
72
+ const data = await call(
73
+ () => poad.auth.resetPasswordForEmail(email, { redirectTo: auth.redirect('/reset'), captchaToken: token }),
74
+ t('login.recoverySent'),
75
+ );
76
+ if (data) setSent({ email, type: 'recovery' });
77
+ };
78
+
79
+ const verify = async () => {
80
+ if (!sent) return;
81
+ const ok = await call(() => poad.auth.verifyOtp({ email: sent.email, token: code, type: sent.type }));
82
+ if (ok) {
83
+ setSent(null);
84
+ setCode('');
85
+ }
86
+ };
87
+
88
+ const resend = async () => {
89
+ if (sent?.type !== 'signup') return;
90
+ await call(() => poad.auth.resend({ type: 'signup', email: sent.email, redirectTo: auth.redirect('/app'), captchaToken: token }), t('login.resent'));
91
+ };
92
+
93
+ const oauth = async (provider: string) => {
94
+ // La page part chez le fournisseur : l'indicateur reste jusqu'au départ
95
+ setPending(provider);
96
+ await call(() => poad.auth.signInWithOAuth({ provider, redirectTo: auth.redirect('/app') }));
97
+ };
98
+
99
+ const anonymous = async () => {
100
+ setPending('anonymous');
101
+ await call(() => poad.auth.signInAnonymously({ captchaToken: token }));
102
+ setPending(null);
103
+ };
104
+
105
+ const changeTab = (value: unknown) => {
106
+ setTab(String(value));
107
+ setSent(null);
108
+ setCode('');
109
+ };
110
+
111
+ const codeForm = (label: MessageKey, canResend = false) => (
112
+ <form className="form" onSubmit={submit(verify)}>
113
+ <PoadMessage severity="info" variant="soft" size="sm">
114
+ {t('login.sentTo', { email: sent?.email ?? '' })}{' '}
115
+ {auth.config?.mail && (
116
+ <a href={auth.config.mail} target="_blank" rel="noopener">
117
+ {t('login.openMailbox')}
118
+ </a>
119
+ )}
120
+ </PoadMessage>
121
+ <PoadField label={t(label)} required>
122
+ <PoadInput mono name="code" value={code} onChange={(e) => setCode(e.target.value)} inputMode="numeric" autoComplete="one-time-code" maxLength={6} required />
123
+ </PoadField>
124
+ <div className="row">
125
+ <PoadButton type="submit" loading={busy} disabled={code.length !== 6}>
126
+ {t('login.validate')}
127
+ </PoadButton>
128
+ {canResend && (
129
+ <PoadButton type="button" variant="text" onClick={() => void resend()}>
130
+ {t('login.resend')}
131
+ </PoadButton>
132
+ )}
133
+ <PoadButton type="button" variant="text" onClick={() => setSent(null)}>
134
+ {t('login.changeEmail')}
135
+ </PoadButton>
136
+ </div>
137
+ </form>
138
+ );
139
+
140
+ const emailField = (autoComplete: string) => (
141
+ <PoadField label={t('common.email')} required>
142
+ <PoadInput type="email" name="email" value={email} onChange={(e) => setEmail(e.target.value)} autoComplete={autoComplete} required />
143
+ </PoadField>
144
+ );
145
+
146
+ return (
147
+ <section className="auth">
148
+ <div className="auth-head">
149
+ <Link href="/">
150
+ <Brand size={32} />
151
+ </Link>
152
+ <h1>{t('login.title')}</h1>
153
+ </div>
154
+
155
+ <PoadCard>
156
+ <PoadTabs value={tab} onValueChange={changeTab} variant="line" stretch>
157
+ <PoadTab value="password" label={t('login.tabPassword')}>
158
+ <form className="form" onSubmit={submit(signIn)}>
159
+ {emailField('username')}
160
+ <PoadField plain label={t('common.password')} required>
161
+ <PoadPassword name="password" value={password} onValueChange={setPassword} toggleMask autoComplete="current-password" />
162
+ </PoadField>
163
+ <div className="row">
164
+ <PoadButton type="submit" loading={busy} disabled={!email || !password || blocked}>
165
+ <PoadIcon name="log-in" size={16} /> {t('common.signIn')}
166
+ </PoadButton>
167
+ <PoadButton type="button" variant="text" onClick={() => changeTab('recovery')}>
168
+ {t('login.forgot')}
169
+ </PoadButton>
170
+ </div>
171
+ </form>
172
+ </PoadTab>
173
+
174
+ <PoadTab value="signup" label={t('login.tabSignup')}>
175
+ {sent?.type === 'signup' ? (
176
+ codeForm('login.codeSignup', true)
177
+ ) : (
178
+ <form className="form" onSubmit={submit(signUp)}>
179
+ <PoadField label={t('common.name')} optional optionalText={t('common.optional')}>
180
+ <PoadInput name="name" value={name} onChange={(e) => setName(e.target.value)} autoComplete="name" />
181
+ </PoadField>
182
+ {emailField('email')}
183
+ <PoadField plain label={t('common.password')} required hint={t('login.minLength')}>
184
+ <PoadPassword name="password" value={password} onValueChange={setPassword} toggleMask feedback autoComplete="new-password" />
185
+ </PoadField>
186
+ <PoadButton type="submit" loading={busy} disabled={!email || !password || blocked}>
187
+ <PoadIcon name="user-plus" size={16} /> {t('login.create')}
188
+ </PoadButton>
189
+ </form>
190
+ )}
191
+ </PoadTab>
192
+
193
+ <PoadTab value="otp" label={t('login.tabOtp')}>
194
+ {sent?.type === 'email' ? (
195
+ codeForm('login.codeOtp')
196
+ ) : (
197
+ <form className="form" onSubmit={submit(sendLink)}>
198
+ <p className="muted" style={{ margin: 0 }}>
199
+ {t('login.otpHelp')}
200
+ </p>
201
+ {emailField('email')}
202
+ <PoadButton type="submit" loading={busy} disabled={!email || blocked}>
203
+ <PoadIcon name="mail" size={16} /> {t('login.send')}
204
+ </PoadButton>
205
+ </form>
206
+ )}
207
+ </PoadTab>
208
+
209
+ <PoadTab value="recovery" label={t('login.tabRecovery')}>
210
+ {sent?.type === 'recovery' ? (
211
+ codeForm('login.codeRecovery')
212
+ ) : (
213
+ <form className="form" onSubmit={submit(sendRecovery)}>
214
+ <p className="muted" style={{ margin: 0 }}>
215
+ {t('login.recoveryHelp')}
216
+ </p>
217
+ {emailField('email')}
218
+ <PoadButton type="submit" loading={busy} disabled={!email || blocked}>
219
+ <PoadIcon name="key-round" size={16} /> {t('login.sendLink')}
220
+ </PoadButton>
221
+ </form>
222
+ )}
223
+ </PoadTab>
224
+ </PoadTabs>
225
+ {captcha && <Captcha ref={widget} provider={captcha.provider} siteKey={captcha.siteKey} onToken={setCaptchaToken} />}
226
+ </PoadCard>
227
+
228
+ {auth.settings && (
229
+ <>
230
+ <PoadDivider />
231
+ <div className="providers">
232
+ <span className="muted">{t('login.or')}</span>
233
+ {auth.oauthProviders.map((p) => {
234
+ const logo = providerLogo(p);
235
+ return (
236
+ <PoadButton key={p} variant="outline" block loading={pending === p} onClick={() => void oauth(p)}>
237
+ {/* eslint-disable-next-line @next/next/no-img-element */}
238
+ {logo ? <img className="provider-logo" src={logo} alt="" /> : <PoadIcon name="log-in" size={16} />}
239
+ {t('login.continueWith', { provider: providerLabel(p) })}
240
+ </PoadButton>
241
+ );
242
+ })}
243
+ {!auth.oauthProviders.length && (
244
+ <span className="muted">
245
+ <Rich text={t('login.noProvider')} />
246
+ </span>
247
+ )}
248
+ {auth.settings.external?.['anonymous_users'] && (
249
+ <PoadButton variant="text" severity="secondary" block onClick={() => void anonymous()} loading={busy && pending === 'anonymous'} disabled={blocked}>
250
+ <PoadIcon name="user" size={16} /> {t('login.anonymous')}
251
+ </PoadButton>
252
+ )}
253
+ </div>
254
+ </>
255
+ )}
256
+ </section>
257
+ );
258
+ }
@@ -0,0 +1,16 @@
1
+ import { SignedOut } from '@/core/guards';
2
+ import { titled } from '@/i18n/server';
3
+ import { LoginForm } from './login-form';
4
+
5
+ export const generateMetadata = titled('title.login');
6
+
7
+ /** Connexion : mot de passe, inscription, lien magique, oubli, fournisseurs OAuth, sans compte */
8
+ export default function LoginPage() {
9
+ return (
10
+ <div className="screen">
11
+ <SignedOut>
12
+ <LoginForm />
13
+ </SignedOut>
14
+ </div>
15
+ );
16
+ }
@@ -0,0 +1,55 @@
1
+ 'use client';
2
+ import { useState, type FormEvent } from 'react';
3
+ import { PoadButton, PoadCard, PoadField, PoadInput, PoadSelect } from '@poadio/ui-react';
4
+ import { useAuth } from '@/core/auth';
5
+ import { useT } from '@/i18n/client';
6
+
7
+ export function MfaForm() {
8
+ const auth = useAuth();
9
+ const t = useT();
10
+ const factors = (auth.user?.factors ?? [])
11
+ .filter((f) => f.status === 'verified')
12
+ .map((f) => ({ id: f.id, label: f.friendly_name || `TOTP ${f.id.slice(0, 8)}` }));
13
+ const [factorId, setFactorId] = useState<string | null>(factors[0]?.id ?? null);
14
+ const [code, setCode] = useState('');
15
+ const [busy, setBusy] = useState(false);
16
+
17
+ const verify = async (e: FormEvent) => {
18
+ e.preventDefault();
19
+ const id = factorId || factors[0]?.id;
20
+ if (!id || !auth.poad) return;
21
+ setBusy(true);
22
+ await auth.run(() => auth.poad!.auth.mfa.challengeAndVerify({ factorId: id, code }));
23
+ setBusy(false);
24
+ setCode('');
25
+ };
26
+
27
+ return (
28
+ <section className="auth">
29
+ <div className="auth-head">
30
+ <h1>{t('title.mfa')}</h1>
31
+ <p className="lead">{t('mfa.lead')}</p>
32
+ </div>
33
+ <PoadCard>
34
+ <form className="form" onSubmit={verify}>
35
+ {factors.length > 1 && (
36
+ <PoadField plain label={t('mfa.factor')}>
37
+ <PoadSelect options={factors} optionLabel="label" optionValue="id" value={factorId} onChange={(v) => setFactorId(v as string | null)} />
38
+ </PoadField>
39
+ )}
40
+ <PoadField label={t('common.code')} required>
41
+ <PoadInput mono name="code" value={code} onChange={(e) => setCode(e.target.value)} inputMode="numeric" autoComplete="one-time-code" maxLength={6} required autoFocus />
42
+ </PoadField>
43
+ <div className="row">
44
+ <PoadButton type="submit" loading={busy} disabled={code.length !== 6}>
45
+ {t('mfa.verify')}
46
+ </PoadButton>
47
+ <PoadButton type="button" variant="text" onClick={auth.signOut}>
48
+ {t('common.signOut')}
49
+ </PoadButton>
50
+ </div>
51
+ </form>
52
+ </PoadCard>
53
+ </section>
54
+ );
55
+ }
@@ -0,0 +1,16 @@
1
+ import { SignedIn } from '@/core/guards';
2
+ import { titled } from '@/i18n/server';
3
+ import { MfaForm } from './mfa-form';
4
+
5
+ export const generateMetadata = titled('title.mfa');
6
+
7
+ /** Second facteur demandé après la connexion (aal1 → aal2) */
8
+ export default function MfaPage() {
9
+ return (
10
+ <div className="screen">
11
+ <SignedIn mfa={false}>
12
+ <MfaForm />
13
+ </SignedIn>
14
+ </div>
15
+ );
16
+ }
@@ -0,0 +1,16 @@
1
+ import { SignedIn } from '@/core/guards';
2
+ import { titled } from '@/i18n/server';
3
+ import { ResetForm } from './reset-form';
4
+
5
+ export const generateMetadata = titled('title.reset');
6
+
7
+ /** Nouveau mot de passe, après le lien de réinitialisation */
8
+ export default function ResetPage() {
9
+ return (
10
+ <div className="screen">
11
+ <SignedIn mfa={false}>
12
+ <ResetForm />
13
+ </SignedIn>
14
+ </div>
15
+ );
16
+ }
@@ -0,0 +1,51 @@
1
+ 'use client';
2
+ import { useState, type FormEvent } from 'react';
3
+ import { useRouter } from 'next/navigation';
4
+ import { PoadButton, PoadCard, PoadField, PoadPassword } from '@poadio/ui-react';
5
+ import { HOME_SIGNED_IN, useAuth } from '@/core/auth';
6
+ import { useT } from '@/i18n/client';
7
+
8
+ export function ResetForm() {
9
+ const auth = useAuth();
10
+ const t = useT();
11
+ const router = useRouter();
12
+ const [password, setPassword] = useState('');
13
+ const [confirm, setConfirm] = useState('');
14
+ const [busy, setBusy] = useState(false);
15
+ const after = () => router.replace(auth.needsMfa ? '/mfa' : HOME_SIGNED_IN);
16
+
17
+ const save = async (e: FormEvent) => {
18
+ e.preventDefault();
19
+ setBusy(true);
20
+ const user = await auth.run(() => auth.poad!.auth.updateUser({ password }), t('reset.changed'));
21
+ setBusy(false);
22
+ if (user) after();
23
+ };
24
+
25
+ return (
26
+ <section className="auth">
27
+ <div className="auth-head">
28
+ <h1>{t('title.reset')}</h1>
29
+ <p className="lead">{t('reset.lead', { email: auth.user?.email ?? '' })}</p>
30
+ </div>
31
+ <PoadCard>
32
+ <form className="form" onSubmit={save}>
33
+ <PoadField plain label={t('reset.new')} required>
34
+ <PoadPassword name="password" value={password} onValueChange={setPassword} toggleMask feedback autoComplete="new-password" />
35
+ </PoadField>
36
+ <PoadField plain label={t('reset.confirm')} required error={confirm && confirm !== password ? t('reset.differ') : ''}>
37
+ <PoadPassword name="confirm" value={confirm} onValueChange={setConfirm} autoComplete="new-password" />
38
+ </PoadField>
39
+ <div className="row">
40
+ <PoadButton type="submit" loading={busy} disabled={!password || password !== confirm}>
41
+ {t('common.save')}
42
+ </PoadButton>
43
+ <PoadButton type="button" variant="text" onClick={after}>
44
+ {t('common.later')}
45
+ </PoadButton>
46
+ </div>
47
+ </form>
48
+ </PoadCard>
49
+ </section>
50
+ );
51
+ }
@@ -0,0 +1,36 @@
1
+ /* Mon compte (account.tsx) */
2
+ .account .logo {
3
+ width: 16px;
4
+ height: 16px;
5
+ }
6
+ .account .qr {
7
+ display: flex;
8
+ gap: 16px;
9
+ align-items: center;
10
+ flex-wrap: wrap;
11
+ }
12
+ .account .qr img {
13
+ width: 180px;
14
+ height: 180px;
15
+ background: #fff;
16
+ border-radius: 8px;
17
+ padding: 6px;
18
+ }
19
+ .account .list {
20
+ list-style: none;
21
+ margin: 0;
22
+ padding: 0;
23
+ display: flex;
24
+ flex-direction: column;
25
+ gap: 10px;
26
+ }
27
+ .account .list li {
28
+ display: flex;
29
+ align-items: center;
30
+ gap: 10px;
31
+ flex-wrap: wrap;
32
+ }
33
+ .account .list .grow {
34
+ flex: 1;
35
+ min-width: 12ch;
36
+ }