The Profile tab was a read-only avatar/name/email stub. It is now a real
form, modeled on the profile surfaces of GitHub/Slack/Nextcloud and scoped
to what a knowledge tool uses: display name, bio (280 chars with counter),
location, occupation, organization and website; email stays read-only
(sign-in identity). Copy explains where the name appears (shares) and
that public bookmark links never reveal identity.
Schema: migration 024_user_profile.sql + schema.sql add five nullable
text columns to User (db-converge green, fresh and upgraded paths).
models.User, userFromObject and the auth identity projection carry them,
so GET /api/me serves the stored truth (Go re-reads identity per request).
PATCH /api/me applies partial allowlisted edits: empty string clears to
NULL, rune-based caps (120/280/120/120/120), website <=2048 and http(s)
with a host; the answer is the fresh identity projection. User has no
version column (identity, not a collaborative collection), so this follows
the settings-save shape rather than the 409 contract; view-as writes stay
blocked by the middleware.
Session propagation: the auth.ts jwt callback gains an "update" trigger
that re-syncs name/email/image from Go via the same assertion the data
proxy signs (fail-quiet when Go is unreachable). The component calls
useSession().update({}) after a save — the {} argument is load-bearing:
in next-auth v5 a bare update() only re-fetches the session, it does not
fire the trigger (caught by the new browser regression). The top bar name
refreshes without a re-login.
Verified: full Go integration suite green incl. new TestProfileUpdate
(partial edits, clearing, rune caps, URL validation, auth gate);
db-converge green; web lint/SSR-lint/build 0 errors; full browser
regressions pass incl. the new profile round-trip (save → toast → top-bar
refresh → form values intact → Save re-disables on a clean baseline).
256 lines
12 KiB
TypeScript
256 lines
12 KiB
TypeScript
import NextAuth, { CredentialsSignin } from 'next-auth'
|
|
import CredentialsProvider from 'next-auth/providers/credentials'
|
|
import jwt from 'jsonwebtoken'
|
|
import { createHmac } from 'node:crypto'
|
|
import { getOidcStatus, passwordAuthEnabled } from '@/lib/oidc-config'
|
|
|
|
// Review SEC-2: browser IP attestation for Go's rate limiting (see lib/api.ts
|
|
// for the identical semantics used by the data proxy). Duplicated here to keep
|
|
// auth.ts import-free of lib/api.ts (avoiding a lib/api.ts → @/auth → lib/api.ts
|
|
// cycle); both helpers must stay in sync.
|
|
const observedClientIP = (headers: Headers): string | null => {
|
|
if (process.env.TRUSTED_PROXY !== '1') return null
|
|
const ip = headers.get('x-real-ip')
|
|
return ip && ip.trim() ? ip.trim() : null
|
|
}
|
|
const signClientIP = (secret: string, ip: string): { ts: string; sig: string } => {
|
|
const ts = String(Math.floor(Date.now() / 1000))
|
|
return { ts, sig: createHmac('sha256', secret).update(`${ip}|${ts}`).digest('hex') }
|
|
}
|
|
|
|
// Exchange a verified Authelia identity for a local Go user. The Next server
|
|
// is the only holder of AUTH_SECRET; Go accepts the resulting oidc-provision
|
|
// token only on this endpoint. The OIDC subject is an account-link key, never
|
|
// a local User.id.
|
|
const provisionAuthelia = async (account: any, profile: any): Promise<{ id: string; role?: string; tokenVersion: number } | null> => {
|
|
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
|
const issuer = process.env.OIDC_ISSUER?.trim()
|
|
const subject = typeof account?.providerAccountId === 'string' ? account.providerAccountId : ''
|
|
if (!secret || !issuer || !subject) return null
|
|
const serviceToken = jwt.sign(
|
|
{ typ: 'oidc-provision', aud: 'superbrain-api' },
|
|
secret,
|
|
{ algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' },
|
|
)
|
|
const controller = new AbortController()
|
|
const timer = setTimeout(() => controller.abort(), 5000)
|
|
try {
|
|
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/oidc/identity`, {
|
|
method: 'POST',
|
|
headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${serviceToken}` },
|
|
cache: 'no-store',
|
|
signal: controller.signal,
|
|
body: JSON.stringify({
|
|
issuer,
|
|
subject,
|
|
email: profile?.email ?? null,
|
|
emailVerified: profile?.email_verified === true,
|
|
name: profile?.name ?? profile?.preferred_username ?? null,
|
|
image: profile?.picture ?? null,
|
|
}),
|
|
})
|
|
if (!response.ok) {
|
|
// 409 means the local account needs explicit linking; never bypass it.
|
|
console.error(`oidc provision: Go answered ${response.status}`)
|
|
return null
|
|
}
|
|
const data = await response.json()
|
|
const id = data?.user?.id
|
|
const tokenVersion = data?.tokenVersion
|
|
if (typeof id !== 'string' || typeof tokenVersion !== 'number') {
|
|
console.error('oidc provision: malformed Go response')
|
|
return null
|
|
}
|
|
return { id, role: typeof data.user.role === 'string' ? data.user.role : undefined, tokenVersion }
|
|
} catch (error) {
|
|
const kind = error instanceof Error ? error.name : 'Error'
|
|
console.error(`oidc provision: Go unreachable (${kind})`)
|
|
return null
|
|
} finally {
|
|
clearTimeout(timer)
|
|
}
|
|
}
|
|
|
|
// NextAuth owns the browser session and the client-managed OIDC flow.
|
|
// Password verification and data ownership live in Go, not Prisma.
|
|
export const { handlers, auth, signIn, signOut } = NextAuth({
|
|
trustHost: true,
|
|
// Same precedence as Go (config.Secret) and lib/api.ts, so a deployment
|
|
// with both variables set can never sign and verify with different values.
|
|
secret: process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET,
|
|
session: { strategy: 'jwt' },
|
|
pages: { signIn: '/login' },
|
|
providers: [
|
|
...(getOidcStatus().enabled ? [{
|
|
id: 'authelia', name: 'Authelia', type: 'oidc',
|
|
issuer: process.env.OIDC_ISSUER,
|
|
clientId: process.env.OIDC_CLIENT_ID,
|
|
clientSecret: process.env.OIDC_CLIENT_SECRET,
|
|
// Auth.js defaults to PKCE-only for OIDC providers and omits `state`,
|
|
// but Authelia hard-rejects authorization requests without a state
|
|
// param ("must be at least 8 characters"). Send both.
|
|
checks: ['pkce', 'state'],
|
|
authorization: { params: { scope: 'openid profile email' } },
|
|
profile(profile: any) {
|
|
return { id: profile.sub, name: profile.name ?? profile.preferred_username ?? profile.sub,
|
|
email: profile.email, image: profile.picture ?? null }
|
|
},
|
|
} as any] : []),
|
|
// AUTH_MODE=oidc (core/federated shape): the credentials provider is not
|
|
// registered at all — Go refuses /api/auth/login there too, so this is
|
|
// defense in depth, not the only barrier.
|
|
...(passwordAuthEnabled() ? [CredentialsProvider({
|
|
credentials: { email: { label: 'Email', type: 'email' }, password: { label: 'Password', type: 'password' } },
|
|
async authorize(credentials, request) {
|
|
if (!credentials?.email || !credentials?.password) return null
|
|
// Review SEC-1: browser logins arrive through this NextAuth path, not
|
|
// the data proxy — without attested headers Go buckets every user on
|
|
// this server's address (Compose) or exempted them entirely
|
|
// (loopback, same-host setups), and one attacker could lock out any
|
|
// account. NextAuth v5 passes the credentials Request as the second
|
|
// argument; sign the observed browser IP the same way lib/api.ts does.
|
|
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
|
const headers: Record<string, string> = { 'Content-Type': 'application/json' }
|
|
const ip = observedClientIP(request?.headers ?? new Headers())
|
|
if (ip && secret) {
|
|
const { ts, sig } = signClientIP(secret, ip)
|
|
headers['x-superbrain-client-ip'] = ip
|
|
headers['x-superbrain-client-ts'] = ts
|
|
headers['x-superbrain-client-sig'] = sig
|
|
}
|
|
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/login`, {
|
|
method: 'POST', headers, cache: 'no-store',
|
|
body: JSON.stringify({ email: credentials.email, password: credentials.password }),
|
|
})
|
|
if (!response.ok) {
|
|
// Review M-8: surface Go's 429 as a distinct CredentialsSignin code
|
|
// so the login UI can say "too many attempts" instead of "invalid
|
|
// credentials" or "check your connection". Auth.js carries `code`
|
|
// through to the client's signIn() result. The status field remains
|
|
// for server-side callers/tests.
|
|
if (response.status === 429) {
|
|
const err = new CredentialsSignin() as CredentialsSignin & { status?: number; retryAfter?: string }
|
|
err.code = 'throttled'
|
|
err.status = 429
|
|
const retry = response.headers.get('retry-after')
|
|
if (retry) err.retryAfter = retry
|
|
throw err
|
|
}
|
|
return null
|
|
}
|
|
const data = await response.json()
|
|
// Carry Go's tokenVersion into the NextAuth JWT so every assertion
|
|
// this session signs is revocable by a version bump ("sign out
|
|
// everywhere") — review SEC-02.
|
|
return { ...data.user, tokenVersion: data.tokenVersion }
|
|
},
|
|
})] : []),
|
|
],
|
|
callbacks: {
|
|
async signIn({ account }) {
|
|
// Authelia identities are exchanged for local Go users in the jwt callback.
|
|
return account?.provider === 'authelia' || account?.provider === 'credentials'
|
|
},
|
|
async jwt({ token, user, account, profile, trigger }) {
|
|
if (trigger === 'signIn' && account?.provider === 'authelia') {
|
|
const local = await provisionAuthelia(account, profile)
|
|
if (!local) throw new Error('Authelia identity mapping failed')
|
|
token.id = local.id
|
|
token.ver = local.tokenVersion
|
|
token.role = local.role
|
|
return token
|
|
}
|
|
if (user) {
|
|
token.id = user.id
|
|
token.ver = user.tokenVersion
|
|
token.role = user.role
|
|
}
|
|
if (trigger === 'update' && typeof token.id === 'string' && typeof token.ver === 'number') {
|
|
// Profile edits (Settings → Profile) call useSession().update({})
|
|
// so the session identity re-syncs from Go — the top bar and
|
|
// profile header reflect a new name without a re-login. (A bare
|
|
// update() only re-fetches; the data argument is what fires this
|
|
// trigger in next-auth v5.) Same assertion the data proxy signs;
|
|
// fail-quiet keeps the old values when Go is unreachable (the save
|
|
// itself already succeeded or failed loudly).
|
|
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
|
if (secret) {
|
|
try {
|
|
const assertion = jwt.sign({ uid: token.id, ver: token.ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })
|
|
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/me`, {
|
|
headers: { Authorization: `Bearer ${assertion}` },
|
|
cache: 'no-store',
|
|
signal: AbortSignal.timeout(5000),
|
|
})
|
|
if (response.ok) {
|
|
const u = (await response.json())?.user
|
|
if (u) {
|
|
token.name = u.name ?? null
|
|
token.email = u.email ?? null
|
|
token.picture = u.image ?? null
|
|
}
|
|
}
|
|
} catch { /* keep the previous identity */ }
|
|
}
|
|
}
|
|
return token
|
|
},
|
|
async session({ session, token }) {
|
|
if (session.user) {
|
|
session.user.id = token.id as string
|
|
session.user.ver = token.ver
|
|
session.user.role = token.role
|
|
}
|
|
return session
|
|
},
|
|
},
|
|
events: {
|
|
// Review AUTH-LIFECYCLE: a browser sign-out must reach Go's revocation.
|
|
// Without this the tokenVersion never bumps on NextAuth sign-out:
|
|
// previously minted assertions stay valid for the rest of their (≤120s)
|
|
// lifetime and the user's Go cookie sessions survive the logout. Go's
|
|
// /api/auth/signout means "sign out everywhere" — deliberately the same
|
|
// semantics here. Fail-open: if Go is unreachable the local sign-out
|
|
// still completes, degrading to the previous behavior. Review CR-02:
|
|
// this event is the backstop — the UI's explicit /api/session/revoke
|
|
// call is what makes revocation failure user-visible; here the outcome
|
|
// is inspected, deadline-bound, and logged without secrets.
|
|
async signOut(message) {
|
|
const token = 'token' in message ? message.token : null
|
|
const secret = process.env.NEXTAUTH_SECRET || process.env.AUTH_SECRET
|
|
const id = typeof token?.id === 'string' ? token.id : ''
|
|
const ver = typeof token?.ver === 'number' ? token.ver : 0
|
|
if (!secret || !id || ver < 1) return
|
|
const controller = new AbortController()
|
|
const timer = setTimeout(() => controller.abort(), 5000)
|
|
try {
|
|
const response = await fetch(`${process.env.API_BASE_URL || 'http://localhost:8080'}/api/auth/signout`, {
|
|
method: 'POST',
|
|
headers: {
|
|
'Content-Type': 'application/json',
|
|
// Same short-lived assertion the data proxy signs (lib/api.ts).
|
|
Authorization: `Bearer ${jwt.sign({ uid: id, ver, typ: 'assertion' }, secret, { algorithm: 'HS256', issuer: 'superbrain', expiresIn: '60s' })}`,
|
|
},
|
|
cache: 'no-store',
|
|
signal: controller.signal,
|
|
})
|
|
if (response.status === 401) {
|
|
// The assertion was rejected — overwhelmingly because an explicit
|
|
// revoke already bumped the tokenVersion (the revocation this call
|
|
// exists to guarantee has then already happened). Nothing to retry.
|
|
console.warn(`signout event: revocation assertion rejected (401) for user ${id}; session is revoked or expired`)
|
|
} else if (!response.ok) {
|
|
// Local sign-out still proceeds, but global revocation did NOT
|
|
// happen: other sessions/assertions survive. Make it visible.
|
|
console.error(`signout event: Go revocation failed with ${response.status} for user ${id}; other sessions may remain active`)
|
|
}
|
|
} catch (error) {
|
|
const kind = error instanceof Error ? error.name : 'Error'
|
|
console.error(`signout event: Go revocation unreachable for user ${id} (${kind}); other sessions may remain active`)
|
|
} finally {
|
|
clearTimeout(timer)
|
|
}
|
|
},
|
|
},
|
|
})
|