@poadio/starter-next 0.0.0-stage → 0.2.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.
- package/.dockerignore +18 -0
- package/.env.example +8 -0
- package/Dockerfile +45 -0
- package/Dockerfile.dockerignore +18 -0
- package/README.md +197 -2
- package/bun.lock +156 -0
- package/gitignore +37 -0
- package/next.config.ts +14 -0
- package/package.json +72 -4
- package/public/logo.svg +1 -0
- package/public/providers/google.svg +1 -0
- package/public/providers/keycloak.svg +1 -0
- package/scripts/dev.mjs +92 -0
- package/scripts/env.mjs +160 -0
- package/scripts/env.test.mjs +93 -0
- package/src/app/(auth)/login/login-form.tsx +258 -0
- package/src/app/(auth)/login/page.tsx +16 -0
- package/src/app/(auth)/mfa/mfa-form.tsx +55 -0
- package/src/app/(auth)/mfa/page.tsx +16 -0
- package/src/app/(auth)/reset/page.tsx +16 -0
- package/src/app/(auth)/reset/reset-form.tsx +51 -0
- package/src/app/app/account/account.css +36 -0
- package/src/app/app/account/account.tsx +476 -0
- package/src/app/app/account/page.tsx +18 -0
- package/src/app/app/dashboard.tsx +58 -0
- package/src/app/app/hello/[name]/page.tsx +38 -0
- package/src/app/app/layout.tsx +12 -0
- package/src/app/app/page.tsx +18 -0
- package/src/app/app/public/page.tsx +15 -0
- package/src/app/app/public/public-content.tsx +31 -0
- package/src/app/globals.css +271 -0
- package/src/app/home.css +186 -0
- package/src/app/home.tsx +92 -0
- package/src/app/icon.svg +1 -0
- package/src/app/layout.tsx +59 -0
- package/src/app/not-found.tsx +6 -0
- package/src/app/page.tsx +6 -0
- package/src/app/providers.tsx +24 -0
- package/src/app/setup/page.tsx +39 -0
- package/src/app/shell.css +752 -0
- package/src/app.meta.ts +41 -0
- package/src/components/brand.tsx +15 -0
- package/src/components/captcha.tsx +93 -0
- package/src/components/link-button.tsx +9 -0
- package/src/components/rich.tsx +14 -0
- package/src/components/shell/app-menu.tsx +127 -0
- package/src/components/shell/app-shell.tsx +268 -0
- package/src/components/shell/page-title.tsx +29 -0
- package/src/components/shell/switches.tsx +35 -0
- package/src/components/shell/use-layout.ts +123 -0
- package/src/core/auth.tsx +228 -0
- package/src/core/env.server.ts +83 -0
- package/src/core/env.tsx +48 -0
- package/src/core/guards.tsx +74 -0
- package/src/core/messages.ts +18 -0
- package/src/core/providers.ts +32 -0
- package/src/core/theme-script.ts +7 -0
- package/src/core/theme.tsx +37 -0
- package/src/i18n/client.tsx +47 -0
- package/src/i18n/en.ts +228 -0
- package/src/i18n/fr.ts +251 -0
- package/src/i18n/index.ts +38 -0
- package/src/i18n/server.ts +19 -0
- package/tsconfig.json +21 -0
|
@@ -0,0 +1,123 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useCallback, useEffect, useRef, useState } from 'react';
|
|
3
|
+
|
|
4
|
+
const LOCK_KEY = 'app.rail-locked';
|
|
5
|
+
const WIDTH_KEY = 'app.rail-width';
|
|
6
|
+
|
|
7
|
+
/** En deçà, le rail ne tient plus dans le flux : le tiroir est imposé. */
|
|
8
|
+
export const NARROW_AT = 992;
|
|
9
|
+
export const RAIL_MIN = 190;
|
|
10
|
+
export const RAIL_MAX = 380;
|
|
11
|
+
export const RAIL_DEFAULT = 238;
|
|
12
|
+
/** Sous ce seuil, relâcher la poignée range le rail au lieu de le rétrécir. */
|
|
13
|
+
export const RAIL_COLLAPSE_AT = 160;
|
|
14
|
+
|
|
15
|
+
function read(key: string): string | null {
|
|
16
|
+
try {
|
|
17
|
+
return localStorage.getItem(key);
|
|
18
|
+
} catch {
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
function write(key: string, value: string): void {
|
|
23
|
+
try {
|
|
24
|
+
localStorage.setItem(key, value);
|
|
25
|
+
} catch {
|
|
26
|
+
// stockage indisponible : la préférence vaut pour la session
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
/**
|
|
31
|
+
* État du rail (repris du LayoutService du starter Angular).
|
|
32
|
+
*
|
|
33
|
+
* Le verrou est une PRÉFÉRENCE de l'utilisateur, pas un état d'affichage : le
|
|
34
|
+
* rail n'occupe la mise en page que si la préférence ET la largeur le
|
|
35
|
+
* permettent. En fenêtre étroite le tiroir s'impose, sans choix offert — et la
|
|
36
|
+
* préférence reprend d'elle-même à l'élargissement.
|
|
37
|
+
*/
|
|
38
|
+
export function useRailLayout() {
|
|
39
|
+
// Valeurs du rendu serveur ; celles du navigateur sont lues après l'hydratation
|
|
40
|
+
const [locked, setLocked] = useState(true);
|
|
41
|
+
const [railWidth, setRailWidth] = useState(RAIL_DEFAULT);
|
|
42
|
+
const [drawerOpen, setDrawerOpen] = useState(false);
|
|
43
|
+
const [resizing, setResizing] = useState(false);
|
|
44
|
+
const [viewport, setViewport] = useState(1280);
|
|
45
|
+
const [loaded, setLoaded] = useState(false);
|
|
46
|
+
|
|
47
|
+
useEffect(() => {
|
|
48
|
+
const l = read(LOCK_KEY);
|
|
49
|
+
if (l !== null) setLocked(l === '1');
|
|
50
|
+
const w = Number(read(WIDTH_KEY));
|
|
51
|
+
if (Number.isFinite(w) && w >= RAIL_MIN && w <= RAIL_MAX) setRailWidth(w);
|
|
52
|
+
setViewport(window.innerWidth);
|
|
53
|
+
setLoaded(true);
|
|
54
|
+
const onResize = () => setViewport(window.innerWidth);
|
|
55
|
+
window.addEventListener('resize', onResize, { passive: true });
|
|
56
|
+
return () => window.removeEventListener('resize', onResize);
|
|
57
|
+
}, []);
|
|
58
|
+
|
|
59
|
+
useEffect(() => {
|
|
60
|
+
if (loaded) write(LOCK_KEY, locked ? '1' : '0');
|
|
61
|
+
}, [locked, loaded]);
|
|
62
|
+
useEffect(() => {
|
|
63
|
+
if (loaded) write(WIDTH_KEY, String(railWidth));
|
|
64
|
+
}, [railWidth, loaded]);
|
|
65
|
+
|
|
66
|
+
const narrow = viewport < NARROW_AT;
|
|
67
|
+
const railInFlow = locked && !narrow;
|
|
68
|
+
|
|
69
|
+
// Passer en fenêtre étroite referme le tiroir
|
|
70
|
+
useEffect(() => {
|
|
71
|
+
if (narrow) setDrawerOpen(false);
|
|
72
|
+
}, [narrow]);
|
|
73
|
+
|
|
74
|
+
const timers = useRef<{ open?: ReturnType<typeof setTimeout>; close?: ReturnType<typeof setTimeout> }>({});
|
|
75
|
+
const clearTimers = () => {
|
|
76
|
+
clearTimeout(timers.current.open);
|
|
77
|
+
clearTimeout(timers.current.close);
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
const stow = useCallback(() => {
|
|
81
|
+
setLocked(false);
|
|
82
|
+
setDrawerOpen(false);
|
|
83
|
+
}, []);
|
|
84
|
+
|
|
85
|
+
return {
|
|
86
|
+
/** Vrai une fois la largeur et les préférences lues dans le navigateur */
|
|
87
|
+
loaded,
|
|
88
|
+
locked,
|
|
89
|
+
railWidth,
|
|
90
|
+
drawerOpen,
|
|
91
|
+
resizing,
|
|
92
|
+
narrow,
|
|
93
|
+
railInFlow,
|
|
94
|
+
setResizing,
|
|
95
|
+
toggleLock() {
|
|
96
|
+
if (narrow) return;
|
|
97
|
+
setLocked(!locked);
|
|
98
|
+
setDrawerOpen(false);
|
|
99
|
+
},
|
|
100
|
+
closeDrawer: () => setDrawerOpen(false),
|
|
101
|
+
toggleDrawer() {
|
|
102
|
+
if (!railInFlow) setDrawerOpen((v) => !v);
|
|
103
|
+
},
|
|
104
|
+
/** ⌘B : range le rail s'il est en place, sinon bascule le tiroir. */
|
|
105
|
+
toggleFromKeyboard() {
|
|
106
|
+
if (railInFlow) stow();
|
|
107
|
+
else setDrawerOpen((v) => !v);
|
|
108
|
+
},
|
|
109
|
+
/** Ouverture différée au survol du bord — un passage rapide ne déclenche rien. */
|
|
110
|
+
peek(on: boolean) {
|
|
111
|
+
if (railInFlow) return;
|
|
112
|
+
clearTimers();
|
|
113
|
+
if (on) timers.current.open = setTimeout(() => setDrawerOpen(true), 120);
|
|
114
|
+
else timers.current.close = setTimeout(() => setDrawerOpen(false), 160);
|
|
115
|
+
},
|
|
116
|
+
holdOpen: clearTimers,
|
|
117
|
+
resizeTo(px: number) {
|
|
118
|
+
if (px < RAIL_COLLAPSE_AT) stow();
|
|
119
|
+
else setRailWidth(Math.min(RAIL_MAX, Math.max(RAIL_MIN, Math.round(px))));
|
|
120
|
+
},
|
|
121
|
+
resetWidth: () => setRailWidth(RAIL_DEFAULT),
|
|
122
|
+
};
|
|
123
|
+
}
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createContext, useCallback, useContext, useEffect, useMemo, useRef, useState, type ReactNode } from 'react';
|
|
3
|
+
import { usePathname, useRouter } from 'next/navigation';
|
|
4
|
+
import { poadToast } from '@poadio/ui-react';
|
|
5
|
+
import {
|
|
6
|
+
createClient,
|
|
7
|
+
decodeJwt,
|
|
8
|
+
type AccessClaims,
|
|
9
|
+
type AuthError,
|
|
10
|
+
type AuthEvent,
|
|
11
|
+
type PoadClient,
|
|
12
|
+
type Result,
|
|
13
|
+
type Session,
|
|
14
|
+
type Settings,
|
|
15
|
+
type User,
|
|
16
|
+
} from '@poadio/client-js';
|
|
17
|
+
import { useI18n } from '@/i18n/client';
|
|
18
|
+
import { configFrom, useEnvValues, type PoadConfig } from './env';
|
|
19
|
+
import { authMessage } from './messages';
|
|
20
|
+
|
|
21
|
+
/** Entrées de /settings qui ne sont pas des fournisseurs OAuth */
|
|
22
|
+
const NOT_OAUTH = new Set(['email', 'phone', 'anonymous_users']);
|
|
23
|
+
|
|
24
|
+
/** Où mène une connexion réussie */
|
|
25
|
+
export const HOME_SIGNED_IN = '/app';
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Session côté navigateur, comme dans le starter Angular : @poadio/auth-js la
|
|
29
|
+
* garde dans localStorage (partagée entre onglets, renouvelée avant échéance).
|
|
30
|
+
* Le serveur Next.js ne la voit pas : les pages protégées le sont par une garde
|
|
31
|
+
* cliente (core/guards.tsx), l'autorisation réelle reste au RLS de poad.
|
|
32
|
+
*/
|
|
33
|
+
export interface AuthState {
|
|
34
|
+
/** Faux tant que la session (et un éventuel retour de lien e-mail ou OAuth) n'est pas traitée */
|
|
35
|
+
ready: boolean;
|
|
36
|
+
/** Déconnexion en cours : on part vers l'accueil, les gardes n'ont pas à rediriger vers /login */
|
|
37
|
+
leaving: boolean;
|
|
38
|
+
/** POAD_URL, POAD_ANON_KEY… ; null : application pas branchée (page /setup) */
|
|
39
|
+
config: PoadConfig | null;
|
|
40
|
+
/** Le client du projet : poad.auth, poad.storage, poad.from()… (null avant le navigateur) */
|
|
41
|
+
poad: PoadClient | null;
|
|
42
|
+
settings: Settings | null;
|
|
43
|
+
session: Session | null;
|
|
44
|
+
user: User | null;
|
|
45
|
+
claims: AccessClaims | null;
|
|
46
|
+
/** Nom affiché : métadonnées, sinon adresse, sinon « Invité » (session anonyme) */
|
|
47
|
+
displayName: string;
|
|
48
|
+
/** Un facteur TOTP vérifié existe mais la session n'est qu'en aal1 */
|
|
49
|
+
needsMfa: boolean;
|
|
50
|
+
oauthProviders: string[];
|
|
51
|
+
/** Exécute un appel, affiche l'erreur ou le message de succès, renvoie les données */
|
|
52
|
+
run<T>(call: () => Promise<Result<T>>, success?: string): Promise<T | null>;
|
|
53
|
+
fail(error: AuthError): void;
|
|
54
|
+
/** Adresse de retour des e-mails et des fournisseurs OAuth */
|
|
55
|
+
redirect(path?: string): string;
|
|
56
|
+
signOut(): void;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const AuthContext = createContext<AuthState | null>(null);
|
|
60
|
+
|
|
61
|
+
/** Un seul client par page, même si React monte deux fois le fournisseur (mode strict) */
|
|
62
|
+
let shared: { key: string; client: PoadClient } | null = null;
|
|
63
|
+
function clientFor(config: PoadConfig, locale: string): PoadClient {
|
|
64
|
+
const key = `${config.url}|${config.anonKey}|${config.app}`;
|
|
65
|
+
if (!shared || shared.key !== key) {
|
|
66
|
+
shared?.client.auth.dispose();
|
|
67
|
+
// app : poad.env (variables publiques, en direct) lit celles de ce front
|
|
68
|
+
shared = { key, client: createClient(config.url, config.anonKey, { app: config.app, auth: { locale } }) };
|
|
69
|
+
}
|
|
70
|
+
return shared.client;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function needsMfaFor(session: Session | null): boolean {
|
|
74
|
+
if (!session) return false;
|
|
75
|
+
const claims = decodeJwt(session.access_token) as AccessClaims | null;
|
|
76
|
+
if (!claims || claims.aal !== 'aal1') return false;
|
|
77
|
+
return (session.user?.factors ?? []).some((f) => f.status === 'verified');
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/** ?next= d'une URL, s'il est local ; sinon la page d'accueil connectée */
|
|
81
|
+
export function nextTarget(search: string | URLSearchParams | null | undefined): string {
|
|
82
|
+
const next = new URLSearchParams(search ?? '').get('next');
|
|
83
|
+
return next && next.startsWith('/') && !next.startsWith('//') ? next : HOME_SIGNED_IN;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export function AuthProvider({ children }: { children: ReactNode }) {
|
|
87
|
+
const values = useEnvValues();
|
|
88
|
+
const { t, locale } = useI18n();
|
|
89
|
+
const config = useMemo(() => configFrom(values), [values]);
|
|
90
|
+
const router = useRouter();
|
|
91
|
+
const pathname = usePathname();
|
|
92
|
+
const path = useRef(pathname);
|
|
93
|
+
path.current = pathname;
|
|
94
|
+
const tRef = useRef(t);
|
|
95
|
+
tRef.current = t;
|
|
96
|
+
|
|
97
|
+
const [ready, setReady] = useState(false);
|
|
98
|
+
const [poad, setPoad] = useState<PoadClient | null>(null);
|
|
99
|
+
const [session, setSession] = useState<Session | null>(null);
|
|
100
|
+
const [settings, setSettings] = useState<Settings | null>(null);
|
|
101
|
+
const [leaving, setLeaving] = useState(false);
|
|
102
|
+
|
|
103
|
+
// Arrivé à l'accueil après une déconnexion : les gardes reprennent la main
|
|
104
|
+
useEffect(() => {
|
|
105
|
+
if (pathname === '/') setLeaving(false);
|
|
106
|
+
}, [pathname]);
|
|
107
|
+
|
|
108
|
+
const fail = useCallback((error: AuthError) => {
|
|
109
|
+
const { title, detail } = authMessage(error, tRef.current);
|
|
110
|
+
poadToast.error(title, detail);
|
|
111
|
+
}, []);
|
|
112
|
+
|
|
113
|
+
// Le client n'existe que dans le navigateur : localStorage, URL de retour
|
|
114
|
+
useEffect(() => {
|
|
115
|
+
if (!config) {
|
|
116
|
+
setReady(true);
|
|
117
|
+
return;
|
|
118
|
+
}
|
|
119
|
+
const client = clientFor(config, locale);
|
|
120
|
+
setPoad(client);
|
|
121
|
+
let alive = true;
|
|
122
|
+
const off = client.auth.onChange((event: AuthEvent, s: Session | null) => {
|
|
123
|
+
if (!alive) return;
|
|
124
|
+
setSession(s);
|
|
125
|
+
const url = path.current;
|
|
126
|
+
if (event === 'SIGNED_OUT') {
|
|
127
|
+
// Vers l'accueil ; sans ce drapeau, la garde de la page quittée
|
|
128
|
+
// enverrait d'abord vers /login
|
|
129
|
+
setLeaving(url !== '/');
|
|
130
|
+
router.replace('/');
|
|
131
|
+
return;
|
|
132
|
+
}
|
|
133
|
+
if (event === 'SIGNED_IN') setLeaving(false);
|
|
134
|
+
if (event === 'PASSWORD_RECOVERY') router.replace('/reset');
|
|
135
|
+
else if (event === 'MFA_VERIFIED' && url.startsWith('/mfa')) router.replace(HOME_SIGNED_IN);
|
|
136
|
+
// Connexion depuis la page de démarrage (retour de lien e-mail) ; depuis
|
|
137
|
+
// /login, c'est la garde <SignedOut> qui mène à ?next=
|
|
138
|
+
else if (event === 'SIGNED_IN' && url === '/') router.replace(needsMfaFor(s) ? '/mfa' : HOME_SIGNED_IN);
|
|
139
|
+
});
|
|
140
|
+
void (async () => {
|
|
141
|
+
// Traite un retour de lien e-mail ou de fournisseur OAuth présent dans l'URL
|
|
142
|
+
await client.auth.ready();
|
|
143
|
+
if (!alive) return;
|
|
144
|
+
setSession(client.auth.session);
|
|
145
|
+
setReady(true);
|
|
146
|
+
if (client.auth.urlError) poadToast.error(tRef.current('auth.rejected'), client.auth.urlError.message);
|
|
147
|
+
if (client.auth.urlEvent === 'PASSWORD_RECOVERY') router.replace('/reset');
|
|
148
|
+
const s = await client.auth.settings();
|
|
149
|
+
if (!alive) return;
|
|
150
|
+
if (s.data) setSettings(s.data);
|
|
151
|
+
else poadToast.error(tRef.current('auth.unreachable'), `${config.url} : ${s.error.message}`);
|
|
152
|
+
})();
|
|
153
|
+
return () => {
|
|
154
|
+
alive = false;
|
|
155
|
+
off();
|
|
156
|
+
};
|
|
157
|
+
// locale : seulement à la création du client (langue des e-mails)
|
|
158
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
159
|
+
}, [config, router]);
|
|
160
|
+
|
|
161
|
+
const run = useCallback(
|
|
162
|
+
async <T,>(call: () => Promise<Result<T>>, success?: string): Promise<T | null> => {
|
|
163
|
+
const r = await call();
|
|
164
|
+
if (r.error) {
|
|
165
|
+
fail(r.error as AuthError);
|
|
166
|
+
return null;
|
|
167
|
+
}
|
|
168
|
+
if (success) poadToast.success(success);
|
|
169
|
+
return r.data;
|
|
170
|
+
},
|
|
171
|
+
[fail],
|
|
172
|
+
);
|
|
173
|
+
|
|
174
|
+
const value = useMemo<AuthState>(() => {
|
|
175
|
+
const user = session?.user ?? null;
|
|
176
|
+
const claims = session ? (decodeJwt(session.access_token) as AccessClaims | null) : null;
|
|
177
|
+
const meta = (user?.user_metadata ?? {}) as Record<string, unknown>;
|
|
178
|
+
const displayName = user ? (meta['name'] as string) || (meta['full_name'] as string) || user.email || t('common.guest') : '';
|
|
179
|
+
return {
|
|
180
|
+
ready,
|
|
181
|
+
leaving,
|
|
182
|
+
config,
|
|
183
|
+
poad,
|
|
184
|
+
settings,
|
|
185
|
+
session,
|
|
186
|
+
user,
|
|
187
|
+
claims,
|
|
188
|
+
displayName,
|
|
189
|
+
needsMfa: needsMfaFor(session),
|
|
190
|
+
oauthProviders: Object.entries(settings?.external ?? {})
|
|
191
|
+
.filter(([name, on]) => on && !NOT_OAUTH.has(name))
|
|
192
|
+
.map(([name]) => name),
|
|
193
|
+
run,
|
|
194
|
+
fail,
|
|
195
|
+
redirect: (p = '/') => new URL(p, window.location.origin).toString(),
|
|
196
|
+
signOut: () => {
|
|
197
|
+
if (poad) void run(() => poad.auth.signOut());
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}, [ready, leaving, config, poad, settings, session, run, fail, t]);
|
|
201
|
+
|
|
202
|
+
return <AuthContext.Provider value={value}>{children}</AuthContext.Provider>;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/** Tout l'état d'authentification */
|
|
206
|
+
export function useAuth(): AuthState {
|
|
207
|
+
const v = useContext(AuthContext);
|
|
208
|
+
if (!v) throw new Error('useAuth : AuthProvider manquant');
|
|
209
|
+
return v;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/** La session (null : déconnecté ou pas encore lue, voir useAuth().ready) */
|
|
213
|
+
export const useSession = (): Session | null => useAuth().session;
|
|
214
|
+
|
|
215
|
+
/** L'utilisateur connecté, ou null */
|
|
216
|
+
export const useUser = (): User | null => useAuth().user;
|
|
217
|
+
|
|
218
|
+
/**
|
|
219
|
+
* Le client du projet, une fois prêt :
|
|
220
|
+
* const poad = usePoad();
|
|
221
|
+
* await poad.from('notes').find();
|
|
222
|
+
* await poad.storage.from('documents').upload(path, file);
|
|
223
|
+
*/
|
|
224
|
+
export function usePoad(): PoadClient {
|
|
225
|
+
const { poad } = useAuth();
|
|
226
|
+
if (!poad) throw new Error('poad non configuré (POAD_URL, POAD_ANON_KEY) ou pas encore prêt');
|
|
227
|
+
return poad;
|
|
228
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
import pkg from '../../package.json';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Variables publiques du front, lues À CHAQUE REQUÊTE (jamais compilées dans
|
|
5
|
+
* le code) : la même image Docker se déploie partout.
|
|
6
|
+
*
|
|
7
|
+
* Deux sources, la seconde l'emporte :
|
|
8
|
+
* 1. les variables publiques du projet poad pour cette application
|
|
9
|
+
* (GET <POAD_URL>/env/v1?app=<POAD_APP>, Projet > Variables) : elles
|
|
10
|
+
* changent sans redéployer, et chaque front d'un même backend a les siennes ;
|
|
11
|
+
* 2. l'environnement du serveur Next.js : en local, `bun start` les prend dans
|
|
12
|
+
* .env* ou, à défaut, dans le projet poad (poad/config.toml,
|
|
13
|
+
* poad/secrets.toml) ; dans l'image Docker, `docker run -e POAD_URL=… -e POAD_ANON_KEY=…`.
|
|
14
|
+
*
|
|
15
|
+
* Seules passent au navigateur PUBLIC_*, NEXT_PUBLIC_* et POAD_URL,
|
|
16
|
+
* POAD_ANON_KEY, POAD_MAIL_URL, POAD_APP : le reste ne quitte pas le serveur.
|
|
17
|
+
*/
|
|
18
|
+
const POAD_KEYS = ['POAD_URL', 'POAD_ANON_KEY', 'POAD_MAIL_URL', 'POAD_APP'];
|
|
19
|
+
const APP_RE = /^[a-z][a-z0-9-]{0,62}$/;
|
|
20
|
+
|
|
21
|
+
export const isPublic = (key: string): boolean =>
|
|
22
|
+
key.startsWith('PUBLIC_') || key.startsWith('NEXT_PUBLIC_') || POAD_KEYS.includes(key);
|
|
23
|
+
|
|
24
|
+
type Manifest = { name?: string; poad?: { app?: string } };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Nom d'application du front : POAD_APP, sinon poad.app du package.json
|
|
28
|
+
* (écrit par poad create), sinon le nom du paquet ; '' : valeurs communes.
|
|
29
|
+
*/
|
|
30
|
+
export function appName(env: Record<string, string | undefined> = process.env, manifest: Manifest = pkg as Manifest): string {
|
|
31
|
+
if (APP_RE.test(env.POAD_APP ?? '')) return env.POAD_APP as string;
|
|
32
|
+
if (APP_RE.test(manifest.poad?.app ?? '')) return manifest.poad?.app as string;
|
|
33
|
+
const name = String(manifest.name ?? '')
|
|
34
|
+
.replace(/^@[^/]+\//, '')
|
|
35
|
+
.toLowerCase()
|
|
36
|
+
.replace(/[^a-z0-9-]+/g, '-')
|
|
37
|
+
.replace(/^[^a-z]+|-+$/g, '')
|
|
38
|
+
.slice(0, 63);
|
|
39
|
+
return APP_RE.test(name) ? name : '';
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
// Une lecture du backend par intervalle de 2 s au plus, par (URL, application)
|
|
43
|
+
const TTL = 2000;
|
|
44
|
+
const cache = new Map<string, { at: number; values: Record<string, string> }>();
|
|
45
|
+
|
|
46
|
+
/** Variables publiques du projet poad pour l'application ; {} si le backend ne répond pas */
|
|
47
|
+
export async function projectEnv(url: string, anonKey: string, app: string): Promise<Record<string, string>> {
|
|
48
|
+
const key = `${url}|${app}`;
|
|
49
|
+
const hit = cache.get(key);
|
|
50
|
+
if (hit && Date.now() - hit.at < TTL) return hit.values;
|
|
51
|
+
let values: Record<string, string> = {};
|
|
52
|
+
try {
|
|
53
|
+
const res = await fetch(`${url.replace(/\/+$/, '')}/env/v1${app ? `?app=${encodeURIComponent(app)}` : ''}`, {
|
|
54
|
+
headers: { apikey: anonKey, Authorization: `Bearer ${anonKey}` },
|
|
55
|
+
cache: 'no-store',
|
|
56
|
+
signal: AbortSignal.timeout(1500),
|
|
57
|
+
});
|
|
58
|
+
if (res.ok) {
|
|
59
|
+
const body = (await res.json()) as { variables?: Record<string, unknown> };
|
|
60
|
+
for (const [k, v] of Object.entries(body.variables ?? {})) if (k.startsWith('PUBLIC_') && typeof v === 'string') values[k] = v;
|
|
61
|
+
}
|
|
62
|
+
} catch {
|
|
63
|
+
// Backend arrêté ou injoignable : les valeurs locales seules
|
|
64
|
+
values = hit?.values ?? {};
|
|
65
|
+
}
|
|
66
|
+
cache.set(key, { at: Date.now(), values });
|
|
67
|
+
return values;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export async function publicEnv(): Promise<Record<string, string>> {
|
|
71
|
+
// Parcours dynamique de process.env : Next.js ne remplace rien à la compilation
|
|
72
|
+
const env = process.env as Record<string, string | undefined>;
|
|
73
|
+
const local = Object.fromEntries(
|
|
74
|
+
Object.keys(env)
|
|
75
|
+
.filter((k) => isPublic(k) && env[k])
|
|
76
|
+
.map((k) => [k, env[k] as string]),
|
|
77
|
+
);
|
|
78
|
+
const app = appName(env);
|
|
79
|
+
if (app) local.POAD_APP = app;
|
|
80
|
+
const remote = local.POAD_URL && local.POAD_ANON_KEY ? await projectEnv(local.POAD_URL, local.POAD_ANON_KEY, app) : {};
|
|
81
|
+
const all = { ...remote, ...local };
|
|
82
|
+
return Object.fromEntries(Object.keys(all).sort().map((k) => [k, all[k]]));
|
|
83
|
+
}
|
package/src/core/env.tsx
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createContext, useContext, type ReactNode } from 'react';
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Variables publiques, posées par le serveur à chaque requête (app/layout.tsx,
|
|
6
|
+
* core/env.server.ts). Dans un composant : useEnv('PUBLIC_API_URL') ; ailleurs
|
|
7
|
+
* (code hors React, côté navigateur) : env('PUBLIC_API_URL').
|
|
8
|
+
*/
|
|
9
|
+
let values: Record<string, string> = {};
|
|
10
|
+
|
|
11
|
+
const EnvContext = createContext<Record<string, string>>({});
|
|
12
|
+
|
|
13
|
+
export function EnvProvider({ values: v, children }: { values: Record<string, string>; children: ReactNode }) {
|
|
14
|
+
values = v;
|
|
15
|
+
return <EnvContext.Provider value={v}>{children}</EnvContext.Provider>;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export function useEnv(name: string): string | undefined {
|
|
19
|
+
return useContext(EnvContext)[name];
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** Toutes les variables publiques */
|
|
23
|
+
export const useEnvValues = (): Record<string, string> => useContext(EnvContext);
|
|
24
|
+
|
|
25
|
+
/** Valeur d'une variable : env('PUBLIC_API_URL'), env('POAD_URL') */
|
|
26
|
+
export function env(name: string): string | undefined;
|
|
27
|
+
export function env(name: string, fallback: string): string;
|
|
28
|
+
export function env(name: string, fallback?: string): string | undefined {
|
|
29
|
+
return values[name] ?? fallback;
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Projet poad de l'application */
|
|
33
|
+
export interface PoadConfig {
|
|
34
|
+
/** URL du projet poad (gateway) : POAD_URL */
|
|
35
|
+
url: string;
|
|
36
|
+
/** Clé anon du projet : publique, elle ne donne que les droits du rôle anon (POAD_ANON_KEY) */
|
|
37
|
+
anonKey: string;
|
|
38
|
+
/** Interface web des e-mails du projet local, Mailpit (POAD_MAIL_URL) */
|
|
39
|
+
mail: string | null;
|
|
40
|
+
/** Nom d'application du front : ses variables publiques à lui (POAD_APP, poad.app du package.json) */
|
|
41
|
+
app: string;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function configFrom(v: Record<string, string>): PoadConfig | null {
|
|
45
|
+
const url = v['POAD_URL'];
|
|
46
|
+
const anonKey = v['POAD_ANON_KEY'];
|
|
47
|
+
return url && anonKey ? { url, anonKey, mail: v['POAD_MAIL_URL'] ?? null, app: v['POAD_APP'] ?? '' } : null;
|
|
48
|
+
}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { useEffect, type ReactNode } from 'react';
|
|
3
|
+
import { usePathname, useRouter, useSearchParams } from 'next/navigation';
|
|
4
|
+
import { PoadSpinner } from '@poadio/ui-react';
|
|
5
|
+
import { HOME_SIGNED_IN, nextTarget, useAuth } from './auth';
|
|
6
|
+
|
|
7
|
+
/**
|
|
8
|
+
* Gardes des pages, côté navigateur : la session vit dans le navigateur
|
|
9
|
+
* (@poadio/auth-js, localStorage), le serveur Next.js ne la connaît pas.
|
|
10
|
+
* Tant que la session n'est pas lue, la garde affiche un indicateur ; ensuite
|
|
11
|
+
* elle montre la page, ou remplace l'URL (router.replace).
|
|
12
|
+
*
|
|
13
|
+
* Une garde n'est qu'un confort d'affichage : ce qui protège les données,
|
|
14
|
+
* c'est le RLS du projet poad, avec le jeton de l'utilisateur.
|
|
15
|
+
*
|
|
16
|
+
* <SignedIn>…</SignedIn> session + MFA si l'utilisateur a un facteur
|
|
17
|
+
* <SignedIn roles={['admin']}>…</SignedIn> rôle dans app_metadata.roles
|
|
18
|
+
* <SignedIn mfa={false}>…</SignedIn> sans exiger la MFA (pages /mfa, /reset)
|
|
19
|
+
* <SignedOut>…</SignedOut> pages de connexion
|
|
20
|
+
* <Configured>…</Configured> exige POAD_URL et POAD_ANON_KEY (sinon /setup)
|
|
21
|
+
*/
|
|
22
|
+
type Decision = 'wait' | 'ok' | string;
|
|
23
|
+
|
|
24
|
+
function useRedirect(decision: Decision): boolean {
|
|
25
|
+
const router = useRouter();
|
|
26
|
+
const redirect = decision !== 'wait' && decision !== 'ok';
|
|
27
|
+
useEffect(() => {
|
|
28
|
+
if (redirect) router.replace(decision);
|
|
29
|
+
}, [redirect, decision, router]);
|
|
30
|
+
return decision === 'ok';
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function Pending() {
|
|
34
|
+
return (
|
|
35
|
+
<div className="pending" role="status" aria-busy="true">
|
|
36
|
+
<PoadSpinner size={22} />
|
|
37
|
+
</div>
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function SignedIn({ mfa = true, roles, children }: { mfa?: boolean; roles?: string[]; children: ReactNode }) {
|
|
42
|
+
const auth = useAuth();
|
|
43
|
+
const pathname = usePathname();
|
|
44
|
+
const search = useSearchParams();
|
|
45
|
+
let decision: Decision = 'ok';
|
|
46
|
+
if (!auth.ready || (auth.leaving && !auth.session)) decision = 'wait';
|
|
47
|
+
else if (!auth.config) decision = '/setup';
|
|
48
|
+
else if (!auth.session) {
|
|
49
|
+
const here = pathname + (search.size ? `?${search.toString()}` : '');
|
|
50
|
+
decision = `/login?next=${encodeURIComponent(here)}`;
|
|
51
|
+
} else if (mfa && auth.needsMfa) decision = '/mfa';
|
|
52
|
+
else if (roles?.length) {
|
|
53
|
+
const has = (auth.user?.app_metadata?.['roles'] as string[] | undefined) ?? [];
|
|
54
|
+
if (!roles.some((r) => has.includes(r))) decision = HOME_SIGNED_IN;
|
|
55
|
+
}
|
|
56
|
+
return useRedirect(decision) ? <>{children}</> : <Pending />;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Pages de connexion : inutiles une fois connecté (mène à ?next=, ou à /mfa) */
|
|
60
|
+
export function SignedOut({ children }: { children: ReactNode }) {
|
|
61
|
+
const auth = useAuth();
|
|
62
|
+
const search = useSearchParams();
|
|
63
|
+
let decision: Decision = 'ok';
|
|
64
|
+
if (!auth.ready) decision = 'wait';
|
|
65
|
+
else if (!auth.config) decision = '/setup';
|
|
66
|
+
else if (auth.session) decision = auth.needsMfa ? '/mfa' : nextTarget(search);
|
|
67
|
+
return useRedirect(decision) ? <>{children}</> : <Pending />;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
export function Configured({ children }: { children: ReactNode }) {
|
|
71
|
+
const auth = useAuth();
|
|
72
|
+
// La configuration est connue dès le rendu serveur : pas d'attente
|
|
73
|
+
return useRedirect(auth.config ? 'ok' : '/setup') ? <>{children}</> : <Pending />;
|
|
74
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { AuthError } from '@poadio/client-js';
|
|
2
|
+
import type { MessageKey, Translate } from '@/i18n';
|
|
3
|
+
|
|
4
|
+
const formatDelay = (s: number): string => (s < 90 ? `${s} s` : `${Math.ceil(s / 60)} min`);
|
|
5
|
+
|
|
6
|
+
/** Message lisible pour une erreur du service auth, dans la langue de l'application */
|
|
7
|
+
export function authMessage(error: AuthError, t: Translate): { title: string; detail?: string } {
|
|
8
|
+
const known = (key: string): string | null => {
|
|
9
|
+
const text = t(key as MessageKey);
|
|
10
|
+
return text === key ? null : text;
|
|
11
|
+
};
|
|
12
|
+
if (error.code === 'weak_password') {
|
|
13
|
+
const reason = error.reasons?.[0];
|
|
14
|
+
return { title: (reason && known(`auth.weak.${reason}`)) || t('auth.err.weak_password'), detail: error.message };
|
|
15
|
+
}
|
|
16
|
+
const wait = error.retryAfter ? t('auth.retry', { delay: formatDelay(error.retryAfter) }) : undefined;
|
|
17
|
+
return { title: known(`auth.err.${error.code}`) ?? error.message, detail: wait };
|
|
18
|
+
}
|
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
/** Nom affiché des fournisseurs connus ; les autres gardent leur nom technique */
|
|
2
|
+
const LABELS: Record<string, string> = {
|
|
3
|
+
google: 'Google',
|
|
4
|
+
github: 'GitHub',
|
|
5
|
+
gitlab: 'GitLab',
|
|
6
|
+
keycloak: 'Keycloak',
|
|
7
|
+
keycloack: 'Keycloak',
|
|
8
|
+
apple: 'Apple',
|
|
9
|
+
azure: 'Microsoft',
|
|
10
|
+
slack: 'Slack',
|
|
11
|
+
linkedin: 'LinkedIn',
|
|
12
|
+
twitch: 'Twitch',
|
|
13
|
+
discord: 'Discord',
|
|
14
|
+
facebook: 'Facebook',
|
|
15
|
+
spotify: 'Spotify',
|
|
16
|
+
bitbucket: 'Bitbucket',
|
|
17
|
+
notion: 'Notion',
|
|
18
|
+
zoom: 'Zoom',
|
|
19
|
+
workos: 'WorkOS',
|
|
20
|
+
};
|
|
21
|
+
|
|
22
|
+
/** Logos fournis dans public/providers (les autres gardent l'icône générique) */
|
|
23
|
+
const LOGOS: Record<string, string> = {
|
|
24
|
+
google: '/providers/google.svg',
|
|
25
|
+
keycloak: '/providers/keycloak.svg',
|
|
26
|
+
keycloack: '/providers/keycloak.svg',
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
export const providerLogo = (name: string): string | null => LOGOS[name] ?? null;
|
|
30
|
+
|
|
31
|
+
export const providerLabel = (name: string): string =>
|
|
32
|
+
LABELS[name] ?? name.replace(/[-_]+/g, ' ').replace(/^\w/, (c) => c.toUpperCase());
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export const THEME_KEY = 'app.theme';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Posé dans <head> (app/layout.tsx), exécuté avant le premier affichage : la
|
|
5
|
+
* classe .theme-dark est sur <html> avant que la page ne se peigne, sans éclair blanc.
|
|
6
|
+
*/
|
|
7
|
+
export const THEME_SCRIPT = `(function(){try{var s=localStorage.getItem('${THEME_KEY}');var d=s?s==='dark':matchMedia('(prefers-color-scheme: dark)').matches;document.documentElement.classList.toggle('theme-dark',d)}catch(e){}})()`;
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
'use client';
|
|
2
|
+
import { createContext, useCallback, useContext, useEffect, useState, type ReactNode } from 'react';
|
|
3
|
+
import { THEME_KEY as KEY } from './theme-script';
|
|
4
|
+
|
|
5
|
+
interface Theme {
|
|
6
|
+
dark: boolean;
|
|
7
|
+
toggle(): void;
|
|
8
|
+
set(dark: boolean): void;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
const ThemeContext = createContext<Theme | null>(null);
|
|
12
|
+
|
|
13
|
+
/** Thème clair / sombre : classe .theme-dark sur <html>, choix gardé dans le navigateur */
|
|
14
|
+
export function ThemeProvider({ children }: { children: ReactNode }) {
|
|
15
|
+
const [dark, setDark] = useState(false);
|
|
16
|
+
|
|
17
|
+
// Le script de <head> a déjà choisi : on le lit après l'hydratation
|
|
18
|
+
useEffect(() => setDark(document.documentElement.classList.contains('theme-dark')), []);
|
|
19
|
+
|
|
20
|
+
const set = useCallback((d: boolean) => {
|
|
21
|
+
setDark(d);
|
|
22
|
+
document.documentElement.classList.toggle('theme-dark', d);
|
|
23
|
+
try {
|
|
24
|
+
localStorage.setItem(KEY, d ? 'dark' : 'light');
|
|
25
|
+
} catch {
|
|
26
|
+
/* stockage indisponible */
|
|
27
|
+
}
|
|
28
|
+
}, []);
|
|
29
|
+
|
|
30
|
+
return <ThemeContext.Provider value={{ dark, set, toggle: () => set(!dark) }}>{children}</ThemeContext.Provider>;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function useTheme(): Theme {
|
|
34
|
+
const v = useContext(ThemeContext);
|
|
35
|
+
if (!v) throw new Error('useTheme : ThemeProvider manquant');
|
|
36
|
+
return v;
|
|
37
|
+
}
|