Phase 16: Petal authenticates for itself
Petal is now an OIDC client in its own right rather than trusting a header from the proxy. The Phase-0 Resolver seam was the only integration point: main.go picks the session store when Authentik is configured and the static local user otherwise, and no handler or query moved for either. internal/auth gains three pieces. session.go issues an opaque cookie token and stores only its SHA-256, so a database copy yields nothing usable; the 30-day expiry slides on every request, throttled to one write an hour, and logout deletes the row rather than just the cookie. oidc.go runs the authorization-code flow with state, nonce and PKCE, and discovers the provider lazily and on retry — an Authentik outage should block new logins without stopping Petal booting or invalidating live sessions. users.go provisions accounts from the token's claims and gates them on an allowlist that matches emails as well as subject ids, since a subject is an opaque uuid that doesn't exist until someone has already logged in once. Migration 0010 lands sessions, images and users.pair_lang together. The images table closes the capability-URL hole the Phase-0 audit flagged: a hash was previously enough to fetch anyone's picture. Rows are keyed (name, user_id) so one file can have several owners and deduplication survives; a stranger gets 404 rather than 403, the cache header drops to private, and files already on disk are claimed at startup or every image already pasted into a document would 404. On the frontend a single 401 interceptor feeds a warm bilingual sign-in overlay, drawn over a still-visible editor because nothing has been taken away. Behind it is the part that matters: a save that comes back 401 stashes its body to localStorage before anything else and stops the auto-save loop, and reopening that document after signing in merges the draft back and saves it. An expired session must not cost writing. Writing the round-trip test against a stub identity provider turned up a real bug: the one-shot state/nonce/PKCE cookies were cleared in a defer, which runs after the redirect has written the response header, so the clearing Set-Cookie was silently dropped and they lingered for their full ten minutes. Also swaps the emoji favicon for a drawn sakura, which renders as Petal's own rose palette everywhere instead of whatever each platform's font decides, and doubles as the app tile in Authentik. Migration 0010 verified against a VACUUM INTO copy of the live millenia database: counts intact, FTS still matching, the one existing image claimed. Claude-Session: https://claude.ai/code/session_016y6gyuHkQXPiEuW8RGQyua
This commit is contained in:
+45
-2
@@ -1,5 +1,5 @@
|
||||
import { useCallback, useEffect, useRef, useState } from 'react'
|
||||
import { api, type DocSummary, type Document, type Suggestion, type Tag, type TagColor } from './api/client'
|
||||
import { api, type DocSummary, type DocUpdate, type Document, type Suggestion, type Tag, type TagColor } from './api/client'
|
||||
import { useAutoSave } from './hooks/useAutoSave'
|
||||
import { useCheckpoint } from './hooks/useCheckpoint'
|
||||
import { useSpellChecker } from './hooks/useSpellChecker'
|
||||
@@ -13,6 +13,9 @@ import { GardenPanel } from './components/Garden/GardenPanel'
|
||||
import { StatusBar } from './components/StatusBar/StatusBar'
|
||||
import { PetalCompanion } from './components/Companion/PetalCompanion'
|
||||
import { UpdateBanner } from './components/UpdateBanner/UpdateBanner'
|
||||
import { SignInOverlay } from './components/Auth/SignInOverlay'
|
||||
import { useSession } from './hooks/useSession'
|
||||
import { takeDraft } from './lib/drafts'
|
||||
import { useVersionWatch } from './hooks/useVersionWatch'
|
||||
import { PetalFall } from './effects/PetalFall'
|
||||
import { useNightMode } from './hooks/useNightMode'
|
||||
@@ -24,6 +27,12 @@ export default function App() {
|
||||
// toggles the `petal-night` class on <html>; we pass the flag to the ambient
|
||||
// layer so the petals become stars.
|
||||
const night = useNightMode()
|
||||
// Who's writing, and whether the server still recognises them. `signedOut`
|
||||
// flips the moment any call comes back 401.
|
||||
const { me, signedOut } = useSession()
|
||||
// A real account to sign out of, as opposed to the hardcoded local user a
|
||||
// build without auth configured runs as.
|
||||
const account = me && me.id !== 'local' ? { name: me.display_name || me.email } : null
|
||||
const [docs, setDocs] = useState<DocSummary[]>([])
|
||||
const [currentDoc, setCurrentDoc] = useState<Document | null>(null)
|
||||
const [title, setTitle] = useState('')
|
||||
@@ -132,6 +141,35 @@ export default function App() {
|
||||
[createTag, setDocTag],
|
||||
)
|
||||
|
||||
// If the session lapsed while she was writing, the body that couldn't be
|
||||
// saved was stashed on this device. Opening the document again is where it
|
||||
// comes back: the stashed fields win over the server's older copy, and a save
|
||||
// is scheduled straight away so it stops being local-only. Version history
|
||||
// makes this safe to do silently — the server's copy is one restore away.
|
||||
const pendingRescueRef = useRef<{ id: string; body: DocUpdate } | null>(null)
|
||||
const rescueDraft = useCallback((doc: Document): Document => {
|
||||
const stashed = takeDraft(doc.id)
|
||||
if (!stashed) return doc
|
||||
const patch = Object.fromEntries(
|
||||
Object.entries(stashed.body).filter(([, v]) => v !== undefined),
|
||||
)
|
||||
if (Object.keys(patch).length === 0) return doc
|
||||
const merged = { ...doc, ...patch } as Document
|
||||
if (merged.content === doc.content && merged.title === doc.title) return doc
|
||||
// Save it, but only once this really is the open document — the auto-save
|
||||
// writes to whichever doc is current when its timer fires.
|
||||
pendingRescueRef.current = { id: doc.id, body: stashed.body }
|
||||
return merged
|
||||
}, [])
|
||||
|
||||
useEffect(() => {
|
||||
const rescued = pendingRescueRef.current
|
||||
if (rescued && currentDoc?.id === rescued.id) {
|
||||
pendingRescueRef.current = null
|
||||
schedule(rescued.body)
|
||||
}
|
||||
}, [currentDoc?.id, schedule])
|
||||
|
||||
const openDoc = useCallback(
|
||||
async (id: string) => {
|
||||
setDrawerOpen(false) // close the mobile drawer when a doc is chosen
|
||||
@@ -139,7 +177,7 @@ export default function App() {
|
||||
const leaving = currentDocRef.current
|
||||
const leavingBlank = isBlankDraft()
|
||||
await saveNow() // flush any pending edits to the doc we're leaving
|
||||
const doc = await api.getDoc(id)
|
||||
const doc = rescueDraft(await api.getDoc(id))
|
||||
setCurrentDoc(doc)
|
||||
setTitle(doc.title)
|
||||
setWordCount(doc.word_count)
|
||||
@@ -432,6 +470,7 @@ export default function App() {
|
||||
onDuplicate={handleDuplicate}
|
||||
onToggleTag={handleToggleTag}
|
||||
onCreateTag={handleCreateTag}
|
||||
account={account}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -543,6 +582,10 @@ export default function App() {
|
||||
|
||||
{updateAvailable && <UpdateBanner />}
|
||||
|
||||
{/* The session lapsed. The editor stays visible behind this — nothing has
|
||||
been taken away — and anything unsaved is already on disk. */}
|
||||
{signedOut && <SignInOverlay hasDraft={status === 'signed-out'} />}
|
||||
|
||||
<div className="petal-no-print">
|
||||
<PetalCompanion
|
||||
wordCount={wordCount}
|
||||
|
||||
Reference in New Issue
Block a user