Auth - ~/lib/session.ts: Session type + loadSession/signIn/signOut/hasSession, reactive useSession hook (mock backend; replace fetch calls with your real auth endpoint when ready) - routes/login.tsx: form with email/password (mock-validated), bounces to ?next= on success - AppShell: redirects to /login when no session; account-menu Sign out now actually signs out; live session.name/email used for the appbar avatar (falls back to profile) Notifications - ~/lib/notifications.ts: persistent inbox with kinds (info/success/ warning/error), unreadCount, markRead, markAllRead, dismiss, dismissAll; seedIfEmpty for a friendly first-run - AppShell bell: 320px popover with badge, kind dots, per-row open (navigates to href) and dismiss; Mark all read + Clear actions - Hidden NotificationDispatcher in AppShell so the action bus can create real notifications via fill notif-title / notif-body / notif-kind / notif-href + click notif-create Data layer - ~/lib/api.ts: typed apiFetch<T> + api.get/post/put/patch/del, auto-attaches the session token, throws structured ApiError, signs out on 401 - ~/lib/resources.ts: example domain entity (CRUD) backed by localStorage today; each call is a 1:1 swap for api.get/post/put/del - routes/resources.tsx: real working table — search, add, inline status edit, delete; seeded demo rows on first load Tests - vitest + jsdom + @testing-library/react + @testing-library/jest-dom + vite-tsconfig-paths installed - vitest.config.ts (jsdom, globals, ~ aliases via tsconfig-paths) - vitest.setup.ts (RTL cleanup + localStorage clear between tests) - app/lib/session.test.ts and resources.test.ts as starter coverage - npm test / npm run test:watch scripts UI Control catalog - Login form, resources CRUD, notifications inbox, and the hidden notif-bridge ids tagged so the assistant can drive every new surface Threads - ThreadMessage now carries optional agentId so per-message authorship survives persona switches and handoffs Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
130 lines
3.4 KiB
TypeScript
130 lines
3.4 KiB
TypeScript
// Session — minimal auth scaffold backed by localStorage.
|
|
// Swap loadSession/signIn/signOut for real calls (cookies + server) when you
|
|
// wire a backend. The shape here matches what AppShell + useUser expect.
|
|
|
|
import { useEffect, useSyncExternalStore } from "react"
|
|
|
|
import { profileInitials } from "~/lib/profile"
|
|
|
|
export type Session = {
|
|
userId: string
|
|
name: string
|
|
email: string
|
|
token: string
|
|
// Issued at, ms since epoch.
|
|
issuedAt: number
|
|
}
|
|
|
|
const STORAGE_KEY = "crema.session"
|
|
const CHANGE_EVENT = "crema:session-change"
|
|
|
|
function readFromStorage(): Session | null {
|
|
if (typeof window === "undefined") return null
|
|
try {
|
|
const raw = localStorage.getItem(STORAGE_KEY)
|
|
if (!raw) return null
|
|
const parsed = JSON.parse(raw) as Partial<Session>
|
|
if (
|
|
typeof parsed.userId !== "string" ||
|
|
typeof parsed.email !== "string" ||
|
|
typeof parsed.token !== "string"
|
|
)
|
|
return null
|
|
return {
|
|
userId: parsed.userId,
|
|
name:
|
|
typeof parsed.name === "string" && parsed.name.trim()
|
|
? parsed.name
|
|
: parsed.email,
|
|
email: parsed.email,
|
|
token: parsed.token,
|
|
issuedAt:
|
|
typeof parsed.issuedAt === "number" ? parsed.issuedAt : Date.now(),
|
|
}
|
|
} catch {
|
|
return null
|
|
}
|
|
}
|
|
|
|
export function loadSession(): Session | null {
|
|
return readFromStorage()
|
|
}
|
|
|
|
/**
|
|
* Mock sign-in. Validates only that email + password are non-empty; returns
|
|
* a fake session. Replace with a real fetch to your auth endpoint.
|
|
*/
|
|
export async function signIn(
|
|
email: string,
|
|
password: string,
|
|
): Promise<Session> {
|
|
await new Promise((r) => setTimeout(r, 250))
|
|
if (!email.trim() || !password.trim()) {
|
|
throw new Error("Email and password are required.")
|
|
}
|
|
if (!email.includes("@")) {
|
|
throw new Error("Enter a valid email address.")
|
|
}
|
|
const session: Session = {
|
|
userId: `u-${Date.now().toString(36)}`,
|
|
name: email.split("@")[0].replace(/\W/g, " ").trim() || email,
|
|
email,
|
|
token: `dev-${Math.random().toString(36).slice(2, 14)}`,
|
|
issuedAt: Date.now(),
|
|
}
|
|
if (typeof window !== "undefined") {
|
|
localStorage.setItem(STORAGE_KEY, JSON.stringify(session))
|
|
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
|
}
|
|
return session
|
|
}
|
|
|
|
export function signOut() {
|
|
if (typeof window === "undefined") return
|
|
localStorage.removeItem(STORAGE_KEY)
|
|
window.dispatchEvent(new CustomEvent(CHANGE_EVENT))
|
|
}
|
|
|
|
/** True if a non-expired session is in storage. */
|
|
export function hasSession(): boolean {
|
|
return !!readFromStorage()
|
|
}
|
|
|
|
let cached: Session | null = null
|
|
let cacheValid = false
|
|
|
|
function subscribe(cb: () => void): () => void {
|
|
const onChange = () => {
|
|
cacheValid = false
|
|
cb()
|
|
}
|
|
window.addEventListener(CHANGE_EVENT, onChange)
|
|
window.addEventListener("storage", (e) => {
|
|
if (e.key === STORAGE_KEY) onChange()
|
|
})
|
|
return () => window.removeEventListener(CHANGE_EVENT, onChange)
|
|
}
|
|
function getSnapshot(): Session | null {
|
|
if (!cacheValid) {
|
|
cached = readFromStorage()
|
|
cacheValid = true
|
|
}
|
|
return cached
|
|
}
|
|
function getServerSnapshot(): Session | null {
|
|
return null
|
|
}
|
|
|
|
export function useSession(): Session | null {
|
|
const s = useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot)
|
|
useEffect(() => {
|
|
cacheValid = false
|
|
}, [])
|
|
return s
|
|
}
|
|
|
|
export function sessionInitials(session: Session | null): string {
|
|
if (!session) return "?"
|
|
return profileInitials(session.name || session.email)
|
|
}
|