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
91 lines
3.1 KiB
TypeScript
91 lines
3.1 KiB
TypeScript
import { useCallback, useEffect, useRef, useState } from 'react'
|
|
import { api, UnauthorizedError, type DocUpdate } from '../api/client'
|
|
import { clearDraft, stashDraft } from '../lib/drafts'
|
|
|
|
export type SaveStatus = 'idle' | 'pending' | 'saving' | 'saved' | 'error' | 'signed-out'
|
|
|
|
const DEBOUNCE_MS = 1500
|
|
const SAVED_FADE_MS = 3000
|
|
|
|
// useAutoSave debounces document saves. Call schedule() on every edit; it fires
|
|
// PUT /api/docs/:id 1.5s after the last change. status drives the StatusBar:
|
|
// pending → saving → saved (fades to idle after 3s).
|
|
export function useAutoSave(docId: string | null) {
|
|
const [status, setStatus] = useState<SaveStatus>('idle')
|
|
|
|
const debounceRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
|
const fadeRef = useRef<ReturnType<typeof setTimeout>>(undefined)
|
|
const pendingRef = useRef<DocUpdate | null>(null)
|
|
// Latest doc id, read inside the timer so a doc switch doesn't save to the old one.
|
|
const docIdRef = useRef(docId)
|
|
docIdRef.current = docId
|
|
|
|
// Set once the server stops recognising the session. Further saves are
|
|
// pointless (every one would 401) and would keep overwriting the stash, so
|
|
// the loop stops here and the writing waits in localStorage instead.
|
|
const signedOutRef = useRef(false)
|
|
|
|
const flush = useCallback(async () => {
|
|
const id = docIdRef.current
|
|
const body = pendingRef.current
|
|
pendingRef.current = null
|
|
if (!id || !body) return
|
|
|
|
if (signedOutRef.current) {
|
|
stashDraft(id, body)
|
|
setStatus('signed-out')
|
|
return
|
|
}
|
|
|
|
setStatus('saving')
|
|
try {
|
|
await api.updateDoc(id, body)
|
|
clearDraft(id) // it's on the server now; the rescue copy is redundant
|
|
setStatus('saved')
|
|
clearTimeout(fadeRef.current)
|
|
fadeRef.current = setTimeout(() => setStatus('idle'), SAVED_FADE_MS)
|
|
} catch (err) {
|
|
if (err instanceof UnauthorizedError) {
|
|
// The session went away mid-draft. Keep the body — on disk, where a
|
|
// full-page trip through the identity provider can't take it with it —
|
|
// and stop trying until there's a session again.
|
|
signedOutRef.current = true
|
|
stashDraft(id, body)
|
|
setStatus('signed-out')
|
|
return
|
|
}
|
|
console.error('auto-save failed', err)
|
|
// Put the body back so the next edit retries it rather than dropping it.
|
|
pendingRef.current = { ...body, ...(pendingRef.current ?? {}) }
|
|
setStatus('error')
|
|
}
|
|
}, [])
|
|
|
|
const schedule = useCallback(
|
|
(update: DocUpdate) => {
|
|
pendingRef.current = { ...pendingRef.current, ...update }
|
|
setStatus('pending')
|
|
clearTimeout(fadeRef.current)
|
|
clearTimeout(debounceRef.current)
|
|
debounceRef.current = setTimeout(flush, DEBOUNCE_MS)
|
|
},
|
|
[flush],
|
|
)
|
|
|
|
// Save any pending edits immediately (e.g. before switching documents).
|
|
const saveNow = useCallback(() => {
|
|
clearTimeout(debounceRef.current)
|
|
return flush()
|
|
}, [flush])
|
|
|
|
useEffect(
|
|
() => () => {
|
|
clearTimeout(debounceRef.current)
|
|
clearTimeout(fadeRef.current)
|
|
},
|
|
[],
|
|
)
|
|
|
|
return { status, schedule, saveNow }
|
|
}
|