feat(supabase): auth, profile and roles services; professional columns on profiles; OAuth + TOTP config

- packages/supabase: signIn/signUp/OAuth/reset/updatePassword/signOut wrappers with a closed AuthFailure kind, fetch/update own profile, own platform roles
- migration 20261011100000: practice_name, professional_title, siret (format-checked, column grants); pgTAP 009; database.types regenerated
- config.toml: TOTP enroll/verify on, [auth.external.google|apple] via env(), wildcard redirect URLs
- app config: authProviders (APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS), entrypoint env.js, DEPLOY table
- TODO: Step 7 plan
This commit is contained in:
bchanot committed 2026-10-11 23:16:13 +02:00
1 parent c746952d7f
commit b10b227ee9
13 files changed
+427 -10

No files matched your search

+11
View File
@@ -114,6 +114,17 @@ feat/findings-tree-v2 merged (FindingsTreePicker tracked in HEAD); all work belo
- [ ] 6.7 follow-ups recorded for Step 13: catalog asset cap aligned with the archive cap (2 MiB), allowlist sanitiser at upload, app canvas sanitiser (EVAL-011)
- [ ] 5 follow-up: allowlist SVG sanitiser before Storage-served assets (Step 13); orphan findings UX (D5) at the report UX step; report:compare residuals (ZodError reason genericised, v3 lines computed once, long template lines); 16 MiB attachment cap without direct test
- [ ] Step 7 — identity: auth, profile, roles, /app shell (started 2026-10-11, branch feature/step-07-identity-app-shell; direction graphique validée par l'utilisateur: identité actuelle conservée, maquettes = référence externe non versionnée). Scope decisions: professional fields = additive migration on profiles (practice_name, professional_title, siret free text, verification = later domain); MFA = documented gap (TOTP disabled in config, no has_mfa helper, no admin table); no TanStack Query (zustand store suffices); legacy routes untouched and unauthenticated; /app visible from Home only when Supabase is configured
- [ ] 7.0 plan + branch + ctx7 cache (supabase-js auth, config.toml providers)
- [ ] 7.1 config: appConfig.authProviders (APP_AUTH_PROVIDERS / VITE_AUTH_PROVIDERS, google|apple), entrypoint + env.example + DEPLOY table; config.toml: TOTP enroll/verify on, [auth.external.google|apple] via env(), redirect URLs; packages/supabase: auth service wrappers (typed errors), profile read/update service
- [ ] 7.2 migration 20261011100000_profiles_professional: practice_name, professional_title, siret (+ CHECKs, column grants); pgTAP 009; database.types regenerated (real stack) + schema-types map
- [ ] 7.3 app state: authStore (status loading|signed_out|signed_in, session, user, profile, roles), bootstrap on getSession + onAuthStateChange, profile fetch, roles fetch; locale sync (profile.locale → localeStore on sign-in, localeStore → profiles.locale while signed in); AuthProvider in App
- [ ] 7.4 auth screens: /login (email+password, OAuth buttons per authProviders, links), /signup (display name, email, password ×2, policy hints, "check your inbox" state), /forgot-password, /reset-password (PASSWORD_RECOVERY → new password), /auth/callback (code exchange → /app); AuthLayout (brand, cream card); not-configured state
- [ ] 7.5 /app shell: RequireAuth guard (redirect /login?next=), AppLayout (desktop sidebar: dashboard, account, local tool link, logout; mobile top bar + drawer), /app dashboard (welcome, profile completeness card, local tool card, no fake stats)
- [ ] 7.6 /app/account: personal (display, first, last, phone), professional (title, practice, siret), preferences (locale, timezone), security (change password, logout, MFA gap note), roles badge read-only
- [ ] 7.7 Home coexistence: "Mon espace / Se connecter" entry on the header when configured; characterisation tests T12 unchanged with default config
- [ ] 7.8 tests: config, authStore (fake client), locale sync, forms (validation, errors, submit), guard redirect, layout nav, account save; i18n parity; pgTAP; root check + docker build
- [ ] 7.9 docs: SUPABASE.md auth section (providers env, Mailpit, MFA gap), CLAUDE.md map/architecture, CHANGELOG, plan note; memory (BDR, LRN, EVAL, journal); verifier + security gates; stop for user validation
---
## Phase A — DONE (kept for reference)
+1
View File
@@ -82,6 +82,7 @@ each one explicitly.
| `APP_TAGLINE` | yes | `Outils pour ostéopathes animaliers` | Hero tagline on Home. |
| `APP_SUPABASE_URL` | no | empty | Supabase project URL exposed to the browser. Empty = app runs without backend (current mode). |
| `APP_SUPABASE_ANON_KEY` | no | empty | Supabase anon (publishable) key. Public by design, data stays behind RLS. Never the service_role key. |
| `APP_AUTH_PROVIDERS` | no | empty | OAuth buttons on the auth screens, comma-separated (`google,apple`). The Supabase project must enable the same providers; empty = email/password only. |
| `PORT` | no | `8080` | Container listen port. Must be `>=1024` — the container runs as a non-root `nginx` user and cannot bind privileged ports. |
No secrets are required in this file: the anon key is public by design and
+28 -2
View File
@@ -1,5 +1,5 @@
/// <reference types="vite/client" />
import type { SupabaseConnection } from '@faunosteo/supabase'
import type { OAuthProvider, SupabaseConnection } from '@faunosteo/supabase'
/**
* Runtime application config.
@@ -15,6 +15,8 @@ export interface AppConfig {
tagline: string
/** null = no backend configured; the app keeps its local-only behaviour. */
supabase: SupabaseConnection | null
/** OAuth buttons to show on the auth screens; the server must enable the same providers. */
authProviders: OAuthProvider[]
}
/** Shape written by docker/entrypoint.sh (flat strings, empty = unset). */
@@ -25,6 +27,8 @@ export interface RuntimeConfig {
tagline?: string
supabaseUrl?: string
supabaseAnonKey?: string
/** Comma-separated: "google,apple". */
authProviders?: string
}
declare global {
@@ -33,7 +37,7 @@ declare global {
}
}
const DEFAULTS: Omit<AppConfig, 'supabase'> = {
const DEFAULTS: Omit<AppConfig, 'supabase' | 'authProviders'> = {
siteName: 'Faunosteo',
brandName: 'Faunosteo',
footerName: 'Faunosteo',
@@ -61,6 +65,25 @@ export function resolveSupabaseConnection(
return null
}
const KNOWN_PROVIDERS: readonly string[] = ['google', 'apple']
/** "google, apple" → ['google', 'apple']; unknown names are dropped (warned in DEV). */
export function resolveAuthProviders(
raw: string | undefined,
): OAuthProvider[] {
const names = (nonEmpty(raw) ?? '')
.split(',')
.map((name) => name.trim().toLowerCase())
.filter((name) => name !== '')
const known = names.filter((name): name is OAuthProvider =>
KNOWN_PROVIDERS.includes(name),
)
if (known.length !== names.length && import.meta.env.DEV) {
console.warn(`[config] unknown auth provider in "${raw}"; ignored`)
}
return [...new Set(known)]
}
export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
return {
siteName:
@@ -81,6 +104,9 @@ export function resolveConfig(runtime: RuntimeConfig = {}): AppConfig {
runtime.supabaseUrl ?? import.meta.env.VITE_SUPABASE_URL,
runtime.supabaseAnonKey ?? import.meta.env.VITE_SUPABASE_ANON_KEY,
),
authProviders: resolveAuthProviders(
runtime.authProviders ?? import.meta.env.VITE_AUTH_PROVIDERS,
),
}
}
+5 -1
View File
@@ -21,6 +21,9 @@ TAGLINE=$(js_escape "${APP_TAGLINE:-Outils pour ostéopathes animaliers}")
# The service-role key must never be set here.
SUPABASE_URL=$(js_escape "${APP_SUPABASE_URL:-}")
SUPABASE_ANON_KEY=$(js_escape "${APP_SUPABASE_ANON_KEY:-}")
# OAuth buttons offered by the auth screens ("google,apple"); the Supabase
# project must enable the same providers.
AUTH_PROVIDERS=$(js_escape "${APP_AUTH_PROVIDERS:-}")
cat > "$ENV_JS" <<EOF
window.__APP_CONFIG__ = {
@@ -29,7 +32,8 @@ window.__APP_CONFIG__ = {
footerName: "${FOOTER_NAME}",
tagline: "${TAGLINE}",
supabaseUrl: "${SUPABASE_URL}",
supabaseAnonKey: "${SUPABASE_ANON_KEY}"
supabaseAnonKey: "${SUPABASE_ANON_KEY}",
authProviders: "${AUTH_PROVIDERS}"
};
EOF
+154
View File
@@ -0,0 +1,154 @@
import type { AuthError, Provider, Session, User } from '@supabase/supabase-js'
import type { FaunosteoClient } from './client'
/** OAuth providers the app may offer. Phone and others wait for later steps. */
export type OAuthProvider = Extract<Provider, 'google' | 'apple'>
/**
* Closed set of reasons the UI knows how to phrase. Everything GoTrue reports
* is folded into one of these; the raw message never reaches the screen.
*/
export type AuthFailureKind =
| 'invalid_credentials'
| 'email_not_confirmed'
| 'user_exists'
| 'weak_password'
| 'same_password'
| 'invalid_email'
| 'rate_limited'
| 'link_expired'
| 'session_expired'
| 'provider_disabled'
| 'network'
| 'unknown'
export class AuthFailure extends Error {
readonly kind: AuthFailureKind
constructor(kind: AuthFailureKind, cause?: unknown) {
super(`auth: ${kind}`, { cause })
this.name = 'AuthFailure'
this.kind = kind
}
}
const CODE_TO_KIND: Record<string, AuthFailureKind> = {
invalid_credentials: 'invalid_credentials',
email_not_confirmed: 'email_not_confirmed',
user_already_exists: 'user_exists',
email_exists: 'user_exists',
weak_password: 'weak_password',
same_password: 'same_password',
email_address_invalid: 'invalid_email',
validation_failed: 'invalid_email',
over_request_rate_limit: 'rate_limited',
over_email_send_rate_limit: 'rate_limited',
otp_expired: 'link_expired',
flow_state_not_found: 'link_expired',
flow_state_expired: 'link_expired',
bad_code_verifier: 'link_expired',
session_expired: 'session_expired',
session_not_found: 'session_expired',
refresh_token_not_found: 'session_expired',
provider_disabled: 'provider_disabled',
oauth_provider_not_supported: 'provider_disabled',
email_provider_disabled: 'provider_disabled',
signup_disabled: 'provider_disabled',
}
/** Maps a GoTrue error to a closed kind; code first, HTTP status as fallback. */
export function classifyAuthError(error: AuthError): AuthFailureKind {
const code = (error as { code?: string }).code
if (code && CODE_TO_KIND[code]) return CODE_TO_KIND[code]
if (error.status === 429) return 'rate_limited'
if (error.status === 400 && /invalid login/i.test(error.message)) {
return 'invalid_credentials'
}
if (error.status === undefined || error.status === 0) return 'network'
return 'unknown'
}
function fail(error: AuthError): never {
throw new AuthFailure(classifyAuthError(error), error)
}
export interface EmailPasswordCredentials {
email: string
password: string
}
export interface SignUpInput extends EmailPasswordCredentials {
displayName: string
/** Stored in user metadata; the profile trigger reads it. */
locale: 'fr' | 'en'
/** Absolute URL the confirmation link lands on. */
emailRedirectTo: string
}
export interface SignUpResult {
/** Null while the email is not confirmed (confirmations enabled). */
session: Session | null
user: User | null
}
export async function signInWithPassword(
client: FaunosteoClient,
credentials: EmailPasswordCredentials,
): Promise<Session> {
const { data, error } = await client.auth.signInWithPassword(credentials)
if (error) fail(error)
return data.session
}
export async function signUpWithPassword(
client: FaunosteoClient,
input: SignUpInput,
): Promise<SignUpResult> {
const { data, error } = await client.auth.signUp({
email: input.email,
password: input.password,
options: {
emailRedirectTo: input.emailRedirectTo,
data: { display_name: input.displayName, locale: input.locale },
},
})
if (error) fail(error)
return { session: data.session, user: data.user }
}
/** Starts the redirect flow; the browser leaves the page on success. */
export async function signInWithOAuth(
client: FaunosteoClient,
provider: OAuthProvider,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.signInWithOAuth({
provider,
options: { redirectTo },
})
if (error) fail(error)
}
export async function sendPasswordReset(
client: FaunosteoClient,
email: string,
redirectTo: string,
): Promise<void> {
const { error } = await client.auth.resetPasswordForEmail(email, {
redirectTo,
})
if (error) fail(error)
}
/** Needs a live session (recovery link or signed-in user). */
export async function updatePassword(
client: FaunosteoClient,
password: string,
): Promise<void> {
const { error } = await client.auth.updateUser({ password })
if (error) fail(error)
}
export async function signOut(client: FaunosteoClient): Promise<void> {
const { error } = await client.auth.signOut()
if (error) fail(error)
}
+9
View File
@@ -306,6 +306,9 @@ export type Database = {
locale: string
phone: string | null
phone_verified_at: string | null
practice_name: string | null
professional_title: string | null
siret: string | null
timezone: string
updated_at: string
}
@@ -320,6 +323,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
@@ -333,6 +339,9 @@ export type Database = {
locale?: string
phone?: string | null
phone_verified_at?: string | null
practice_name?: string | null
professional_title?: string | null
siret?: string | null
timezone?: string
updated_at?: string
}
+23 -3
View File
@@ -15,12 +15,32 @@ export { Constants } from './database.types'
import type { Enums, Tables } from './database.types'
/** Row of public.profiles. */
export type Profile = Tables<'profiles'>
/** Row of public.profile_roles. */
export type ProfileRole = Tables<'profile_roles'>
export {
AuthFailure,
classifyAuthError,
sendPasswordReset,
signInWithOAuth,
signInWithPassword,
signOut,
signUpWithPassword,
updatePassword,
type AuthFailureKind,
type EmailPasswordCredentials,
type OAuthProvider,
type SignUpInput,
type SignUpResult,
} from './auth'
export {
fetchOwnProfile,
ProfileError,
updateOwnProfile,
type OwnProfilePatch,
type Profile,
} from './profiles'
/** owner | admin | moderator | support. Not a professional status. */
export type PlatformRole = Enums<'platform_role'>
export { fetchOwnPlatformRoles, type PlatformRole } from './platform-roles'
export { publishSheetVersion } from './anatomical-sheets'
/** Row of public.species. */
+18
View File
@@ -0,0 +1,18 @@
import type { FaunosteoClient } from './client'
import type { Enums } from './database.types'
export type PlatformRole = Enums<'platform_role'>
/** Active platform roles of the signed-in user (RLS: own rows, or any as admin). */
export async function fetchOwnPlatformRoles(
client: FaunosteoClient,
userId: string,
): Promise<PlatformRole[]> {
const { data, error } = await client
.from('profile_roles')
.select('role')
.eq('user_id', userId)
.is('revoked_at', null)
if (error) throw new Error(error.message, { cause: error })
return data.map((row) => row.role)
}
+55
View File
@@ -0,0 +1,55 @@
import type { FaunosteoClient } from './client'
import type { Tables, TablesUpdate } from './database.types'
export type Profile = Tables<'profiles'>
/** Columns the signed-in user may change (column grant in the profiles migrations). */
export type OwnProfilePatch = Pick<
TablesUpdate<'profiles'>,
| 'display_name'
| 'first_name'
| 'last_name'
| 'phone'
| 'locale'
| 'timezone'
| 'practice_name'
| 'professional_title'
| 'siret'
>
export class ProfileError extends Error {
readonly code: string | null
constructor(message: string, code: string | null, cause?: unknown) {
super(message, { cause })
this.name = 'ProfileError'
this.code = code
}
}
/** The row RLS lets the user see: their own. Null when the trigger has not run yet. */
export async function fetchOwnProfile(
client: FaunosteoClient,
userId: string,
): Promise<Profile | null> {
const { data, error } = await client
.from('profiles')
.select('*')
.eq('id', userId)
.maybeSingle()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}
export async function updateOwnProfile(
client: FaunosteoClient,
userId: string,
patch: OwnProfilePatch,
): Promise<Profile> {
const { data, error } = await client
.from('profiles')
.update(patch)
.eq('id', userId)
.select('*')
.single()
if (error) throw new ProfileError(error.message, error.code, error)
return data
}
@@ -86,6 +86,9 @@ const expectedColumns = {
'locale',
'phone',
'phone_verified_at',
'practice_name',
'professional_title',
'siret',
'timezone',
'updated_at',
],
+25 -4
View File
@@ -69,7 +69,12 @@ enabled = false
enabled = true
# Vite dev server of apps/app
site_url = "http://127.0.0.1:5173"
additional_redirect_urls = ["http://127.0.0.1:5173", "http://localhost:5173"]
additional_redirect_urls = [
"http://127.0.0.1:5173",
"http://localhost:5173",
"http://127.0.0.1:5173/**",
"http://localhost:5173/**",
]
jwt_expiry = 3600
enable_refresh_token_rotation = true
refresh_token_reuse_interval = 10
@@ -107,9 +112,25 @@ enable_confirmations = false
max_enrolled_factors = 10
[auth.mfa.totp]
# Enrolment opens with the identity step (mandatory for platform staff).
enroll_enabled = false
verify_enabled = false
# Server side ready since Step 7; the enrolment UI and the has_mfa() helper
# enforcing it for platform staff are still to come (SUPABASE.md §11).
enroll_enabled = true
verify_enabled = true
# OAuth providers (Step 7). Values come from the environment: the CLI reads
# supabase/.env (gitignored) or the shell. Disabled until the ids exist.
# Google: https://supabase.com/docs/guides/auth/social-login/auth-google
[auth.external.google]
enabled = false
client_id = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_CLIENT_ID)"
secret = "env(SUPABASE_AUTH_EXTERNAL_GOOGLE_SECRET)"
skip_nonce_check = false
# Apple needs a paid developer account + a Services ID (BACKEND_ARCHITECTURE §2).
[auth.external.apple]
enabled = false
client_id = "env(SUPABASE_AUTH_EXTERNAL_APPLE_CLIENT_ID)"
secret = "env(SUPABASE_AUTH_EXTERNAL_APPLE_SECRET)"
[edge_runtime]
# No Edge Function before the files/webhooks steps; keeps the local stack light.
@@ -0,0 +1,23 @@
-- Step 7 identity: professional information on the account profile.
-- Free text declared by the practitioner, shown in "Mon compte". Verification
-- (SIRET check, documents, badge) belongs to the Professional Verification
-- domain (DOMAIN_MAP §2) and lands with its own tables; nothing here is trusted.
alter table public.profiles
add column practice_name text
constraint profiles_practice_name_length check (char_length(practice_name) between 1 and 120),
add column professional_title text
constraint profiles_professional_title_length check (char_length(professional_title) between 1 and 80),
-- French SIRET: 14 digits, format only (no Luhn, no registry lookup).
add column siret text
constraint profiles_siret_format check (siret ~ '^[0-9]{14}$');
comment on column public.profiles.practice_name is
'Cabinet / practice name declared by the user. Unverified.';
comment on column public.profiles.professional_title is
'Professional title declared by the user (e.g. ostéopathe animalier). Unverified.';
comment on column public.profiles.siret is
'SIRET declared by the user, 14 digits, format-checked only. Verification = later domain.';
-- Same rule as the other user-editable columns: column-level UPDATE, own row through RLS.
grant update (practice_name, professional_title, siret) on public.profiles to authenticated;
@@ -0,0 +1,72 @@
-- Professional columns on profiles: own-row update, format checks, denied paths.
begin;
select plan(13);
insert into auth.users (id, email) values
('00000000-0000-0000-0000-00000000000a', 'alice@test.local'),
('00000000-0000-0000-0000-00000000000b', 'bob@test.local');
select has_column('public', 'profiles', 'practice_name', 'practice_name exists');
select has_column('public', 'profiles', 'professional_title', 'professional_title exists');
select has_column('public', 'profiles', 'siret', 'siret exists');
select is(
(select count(*)::int from information_schema.column_privileges
where table_schema = 'public' and table_name = 'profiles' and grantee = 'authenticated'
and privilege_type = 'UPDATE'
and column_name in ('practice_name', 'professional_title', 'siret')),
3,
'authenticated may update the three professional columns'
);
set local role authenticated;
select set_config('request.jwt.claims', '{"sub":"00000000-0000-0000-0000-00000000000a","role":"authenticated"}', true);
select lives_ok(
$$ update public.profiles
set practice_name = 'Cabinet Équilibre', professional_title = 'Ostéopathe animalier', siret = '12345678901234'
where id = '00000000-0000-0000-0000-00000000000a' $$,
'alice fills her professional information'
);
select is(
(select siret from public.profiles where id = '00000000-0000-0000-0000-00000000000a'),
'12345678901234',
'siret stored as declared'
);
select throws_ok(
$$ update public.profiles set siret = '1234' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'siret must be 14 digits'
);
select throws_ok(
$$ update public.profiles set siret = '1234567890123a' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'siret refuses letters'
);
select throws_ok(
$$ update public.profiles set practice_name = '' where id = '00000000-0000-0000-0000-00000000000a' $$,
'23514', null, 'empty practice_name refused (null clears it)'
);
select lives_ok(
$$ update public.profiles set siret = null, practice_name = null where id = '00000000-0000-0000-0000-00000000000a' $$,
'alice clears her professional information'
);
-- Bob's row is invisible to alice: the update touches zero rows.
select is(
(select count(*)::int from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
0,
'alice does not see bob'
);
select lives_ok(
$$ update public.profiles set practice_name = 'Hijack'
where id = '00000000-0000-0000-0000-00000000000b' $$,
'writing an invisible row raises nothing'
);
reset role;
select is(
(select practice_name from public.profiles where id = '00000000-0000-0000-0000-00000000000b'),
null,
'bob untouched'
);
select * from finish();
rollback;