feat(web): keep the dashboard session in the httpOnly cookie
The dashboard stops storing the API token in localStorage (CodeQL js/clear-text-storage-of-sensitive-data). - every request goes out with credentials; writes carry the session's CSRF token - session state lives in memory and comes from GET /auth/session, kept in sync across tabs with a BroadcastChannel - pages guard with useRequireSignIn instead of reading the token - the token earlier versions left in localStorage is wiped on load - SECURITY.md: the code-scanning example for disposition 3 now says the tracked issue has shipped Closes #33
This commit is contained in:
8 files changed
+150
-94
No files matched your search
@@ -18,6 +18,13 @@ The format follows [Keep a Changelog](https://keepachangelog.com/) and the proje
|
||||
and needs no CSRF token. New settings: `AUTH_COOKIE_SECURE`,
|
||||
`AUTH_COOKIE_SAMESITE`, `AUTH_COOKIE_MAX_AGE_DAYS`. CORS now allows
|
||||
credentials for the configured `SOKHAN_CORS_ORIGINS` (#33).
|
||||
- The dashboard no longer keeps the API token in `localStorage`, where an
|
||||
XSS could read it (CodeQL `js/clear-text-storage-of-sensitive-data`). It
|
||||
relies on the httpOnly session cookie, sends the CSRF token on writes,
|
||||
learns who is signed in from `GET /auth/session`, and wipes the token
|
||||
earlier versions left in `localStorage`. **Self-hosters:**
|
||||
`SOKHAN_CORS_ORIGINS` must list the dashboard's origin, and a plain-http
|
||||
install on a LAN address needs `AUTH_COOKIE_SECURE=false` (#33).
|
||||
|
||||
### Added
|
||||
|
||||
|
||||
+2
-1
@@ -38,7 +38,8 @@ silence:
|
||||
which uses scrypt).
|
||||
3. **Track as an issue** — when a fix needs design work (for example
|
||||
moving the dashboard token from localStorage to an httpOnly cookie
|
||||
implies a CSRF layer and is roadmap work, not a drive-by patch).
|
||||
implied a CSRF layer: it was tracked as #33 and has since shipped, so
|
||||
the dashboard no longer keeps the token in script-readable storage).
|
||||
|
||||
Dismissed alerts stay visible in the Security tab with their
|
||||
justification, so the reasoning is auditable rather than hidden.
|
||||
@@ -10,10 +10,10 @@ import {
|
||||
deleteJob,
|
||||
downloadTranscript,
|
||||
getJob,
|
||||
getToken,
|
||||
type JobDetail,
|
||||
type TranscriptFormat,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
const POLL_INTERVAL_MS = 3000;
|
||||
@@ -80,12 +80,9 @@ export default function JobDetailPage() {
|
||||
const [deleting, setDeleting] = useState(false);
|
||||
const [deleteError, setDeleteError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) {
|
||||
router.replace("/login");
|
||||
return;
|
||||
}
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
|
||||
|
||||
@@ -3,14 +3,14 @@
|
||||
import { useEffect, useRef, useState } from "react";
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { Clock, Search } from "lucide-react";
|
||||
import { Link, useRouter } from "@/i18n/navigation";
|
||||
import { Link } from "@/i18n/navigation";
|
||||
import {
|
||||
ApiError,
|
||||
getToken,
|
||||
listJobs,
|
||||
searchJobs,
|
||||
type JobListItem,
|
||||
} from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
import { ProgressBar, StatusBadge } from "@/components/job-bits";
|
||||
|
||||
function formatDate(iso: string, locale: string): string {
|
||||
@@ -29,16 +29,13 @@ export default function JobsPage() {
|
||||
const tc = useTranslations("common");
|
||||
const te = useTranslations("errors");
|
||||
const locale = useLocale();
|
||||
const router = useRouter();
|
||||
const nf = new Intl.NumberFormat(locale);
|
||||
|
||||
const [query, setQuery] = useState("");
|
||||
const [items, setItems] = useState<JobListItem[] | null>(null);
|
||||
const [listError, setListError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
const seqRef = useRef(0);
|
||||
useEffect(() => {
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
import { useEffect, useState, type FormEvent } from "react";
|
||||
import { useTranslations } from "next-intl";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, login, register, setToken, tokenLogin } from "@/lib/api";
|
||||
import { ApiError, login, register, startSession, tokenLogin } from "@/lib/api";
|
||||
import { useSession } from "@/lib/session";
|
||||
|
||||
type Mode = "login" | "register" | "code";
|
||||
@@ -78,7 +78,7 @@ export default function LoginPage() {
|
||||
: mode === "register"
|
||||
? await register(email.trim(), password)
|
||||
: await tokenLogin(code.trim());
|
||||
setToken(result.api_token, result.email);
|
||||
startSession(result);
|
||||
} catch (error) {
|
||||
setPending(false);
|
||||
if (error instanceof ApiError) {
|
||||
|
||||
@@ -4,7 +4,8 @@ import { useEffect, useRef, useState, type DragEvent, type FormEvent } from "rea
|
||||
import { useLocale, useTranslations } from "next-intl";
|
||||
import { ChevronDown, FileText, Mic, Square, Upload } from "lucide-react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import { ApiError, getQuota, getToken, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { ApiError, getQuota, uploadJob, type QuotaInfo } from "@/lib/api";
|
||||
import { useRequireSignIn } from "@/lib/session";
|
||||
|
||||
function formatFileSize(bytes: number): string {
|
||||
if (bytes < 1024) return `${bytes} B`;
|
||||
@@ -43,9 +44,7 @@ export default function NewJobPage() {
|
||||
const recorderRef = useRef<MediaRecorder | null>(null);
|
||||
const chunksRef = useRef<Blob[]>([]);
|
||||
|
||||
useEffect(() => {
|
||||
if (!getToken()) router.replace("/login");
|
||||
}, [router]);
|
||||
useRequireSignIn();
|
||||
|
||||
useEffect(() => {
|
||||
let active = true;
|
||||
|
||||
+102
-57
@@ -1,13 +1,16 @@
|
||||
// Browser client for the Sokhan REST API. Authenticated requests carry the
|
||||
// stored API token as a Bearer header; a 401 clears the token and bounces
|
||||
// the user back to the login screen.
|
||||
// Browser client for the Sokhan REST API. The dashboard authenticates with
|
||||
// the httpOnly session cookie the API sets at sign-in: script never sees the
|
||||
// token, every request goes out with credentials, and writes carry the
|
||||
// session's CSRF token. A 401 marks the session signed out and bounces the
|
||||
// user back to the login screen.
|
||||
|
||||
const API_BASE = process.env.NEXT_PUBLIC_API_BASE || "http://localhost:8000";
|
||||
|
||||
export const TOKEN_STORAGE_KEY = "sokhan_token";
|
||||
export const EMAIL_STORAGE_KEY = "sokhan_email";
|
||||
/** Fired on this tab whenever the stored session changes (sign-in or out). */
|
||||
/** Fired on this tab whenever the session state changes. */
|
||||
export const SESSION_CHANGE_EVENT = "sokhan:session-change";
|
||||
// Earlier versions kept the token in localStorage; it is wiped on load.
|
||||
const LEGACY_STORAGE_KEYS = ["sokhan_token", "sokhan_email"];
|
||||
const SAFE_METHODS = new Set(["GET", "HEAD"]);
|
||||
|
||||
export type JobStatus = "queued" | "processing" | "completed" | "failed";
|
||||
export type TranscriptFormat = "txt" | "srt" | "vtt" | "json" | "docx";
|
||||
@@ -16,6 +19,14 @@ export interface AuthResponse {
|
||||
id: string;
|
||||
email: string;
|
||||
api_token: string;
|
||||
csrf_token: string | null;
|
||||
}
|
||||
|
||||
export interface SessionState {
|
||||
/** "unknown" until GET /auth/session has answered once. */
|
||||
status: "unknown" | "signedIn" | "signedOut";
|
||||
email: string | null;
|
||||
csrfToken: string | null;
|
||||
}
|
||||
|
||||
export interface QuotaInfo {
|
||||
@@ -95,53 +106,93 @@ export class ApiError extends Error {
|
||||
}
|
||||
}
|
||||
|
||||
export function getToken(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(TOKEN_STORAGE_KEY);
|
||||
}
|
||||
const UNKNOWN_SESSION: SessionState = { status: "unknown", email: null, csrfToken: null };
|
||||
const SIGNED_OUT: SessionState = { status: "signedOut", email: null, csrfToken: null };
|
||||
|
||||
export function getEmail(): string | null {
|
||||
if (typeof window === "undefined") return null;
|
||||
return window.localStorage.getItem(EMAIL_STORAGE_KEY);
|
||||
}
|
||||
let session: SessionState = UNKNOWN_SESSION;
|
||||
let sessionRequest: Promise<void> | null = null;
|
||||
let otherTabs: BroadcastChannel | null = null;
|
||||
|
||||
function notifySessionChange(): void {
|
||||
function setSession(next: SessionState, broadcast = true): void {
|
||||
session = next;
|
||||
if (typeof window === "undefined") return;
|
||||
window.dispatchEvent(new Event(SESSION_CHANGE_EVENT));
|
||||
if (broadcast) otherTabs?.postMessage("changed");
|
||||
}
|
||||
|
||||
export function setToken(token: string, email?: string): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.setItem(TOKEN_STORAGE_KEY, token);
|
||||
if (email) window.localStorage.setItem(EMAIL_STORAGE_KEY, email);
|
||||
else window.localStorage.removeItem(EMAIL_STORAGE_KEY);
|
||||
notifySessionChange();
|
||||
/** The current session snapshot; a new object only when it changes. */
|
||||
export function getSessionState(): SessionState {
|
||||
return session;
|
||||
}
|
||||
|
||||
export function clearToken(): void {
|
||||
if (typeof window === "undefined") return;
|
||||
window.localStorage.removeItem(TOKEN_STORAGE_KEY);
|
||||
window.localStorage.removeItem(EMAIL_STORAGE_KEY);
|
||||
notifySessionChange();
|
||||
/** The server snapshot: nothing is known before hydration. */
|
||||
export function getUnknownSessionState(): SessionState {
|
||||
return UNKNOWN_SESSION;
|
||||
}
|
||||
|
||||
/** Ask the API who is signed in (deduplicated while a request is in flight). */
|
||||
export function loadSession(): Promise<void> {
|
||||
if (typeof window === "undefined") return Promise.resolve();
|
||||
if (!otherTabs && "BroadcastChannel" in window) {
|
||||
otherTabs = new BroadcastChannel("sokhan-session");
|
||||
otherTabs.onmessage = () => {
|
||||
sessionRequest = null;
|
||||
void loadSession();
|
||||
};
|
||||
for (const key of LEGACY_STORAGE_KEYS) {
|
||||
try {
|
||||
window.localStorage.removeItem(key);
|
||||
} catch {
|
||||
// Storage disabled: nothing to clean up.
|
||||
}
|
||||
}
|
||||
}
|
||||
sessionRequest ??= (async () => {
|
||||
try {
|
||||
const response = await fetch(`${API_BASE}/auth/session`, { credentials: "include" });
|
||||
if (!response.ok) {
|
||||
setSession(SIGNED_OUT, false);
|
||||
return;
|
||||
}
|
||||
const body = (await response.json()) as { email: string; csrf_token: string };
|
||||
setSession({ status: "signedIn", email: body.email, csrfToken: body.csrf_token }, false);
|
||||
} catch {
|
||||
setSession(SIGNED_OUT, false);
|
||||
} finally {
|
||||
sessionRequest = null;
|
||||
}
|
||||
})();
|
||||
return sessionRequest;
|
||||
}
|
||||
|
||||
/** Record a successful sign-in; the API has already set the cookie. */
|
||||
export function startSession(auth: AuthResponse): void {
|
||||
setSession({ status: "signedIn", email: auth.email, csrfToken: auth.csrf_token });
|
||||
}
|
||||
|
||||
function csrfHeaders(method: string, headers: Headers): Headers {
|
||||
if (!SAFE_METHODS.has(method) && session.csrfToken) {
|
||||
headers.set("X-CSRF-Token", session.csrfToken);
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Revoke the token on the server, then forget it locally. The local
|
||||
* session is cleared even when the API is unreachable or already rejects
|
||||
* the token, so signing out always works from the user's point of view.
|
||||
* Revoke the session on the server (which also clears the cookie), then
|
||||
* mark it signed out locally. The local sign-out happens even when the API
|
||||
* is unreachable, so signing out always works from the user's point of view.
|
||||
*/
|
||||
export async function logout(): Promise<void> {
|
||||
const token = getToken();
|
||||
if (token) {
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: "POST",
|
||||
headers: { Authorization: `Bearer ${token}` },
|
||||
});
|
||||
} catch {
|
||||
// Offline or API down: the local sign-out below still happens.
|
||||
}
|
||||
try {
|
||||
await fetch(`${API_BASE}/auth/logout`, {
|
||||
method: "POST",
|
||||
credentials: "include",
|
||||
headers: csrfHeaders("POST", new Headers()),
|
||||
});
|
||||
} catch {
|
||||
// Offline or API down: the local sign-out below still happens.
|
||||
}
|
||||
clearToken();
|
||||
setSession(SIGNED_OUT);
|
||||
}
|
||||
|
||||
function redirectToLogin(): void {
|
||||
@@ -153,7 +204,7 @@ function redirectToLogin(): void {
|
||||
|
||||
function handleAuthFailure(response: Response): void {
|
||||
if (response.status === 401) {
|
||||
clearToken();
|
||||
setSession(SIGNED_OUT);
|
||||
redirectToLogin();
|
||||
}
|
||||
}
|
||||
@@ -168,15 +219,16 @@ interface RequestOptions {
|
||||
async function requestJson<T>(path: string, options: RequestOptions = {}): Promise<T> {
|
||||
const { method = "GET", body, headers: extraHeaders, authenticated = false } = options;
|
||||
|
||||
const headers = new Headers(extraHeaders);
|
||||
if (authenticated) {
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
}
|
||||
const headers = csrfHeaders(method, new Headers(extraHeaders));
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}${path}`, { method, headers, body });
|
||||
response = await fetch(`${API_BASE}${path}`, {
|
||||
method,
|
||||
headers,
|
||||
body,
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
}
|
||||
@@ -266,15 +318,12 @@ export async function searchJobs(query: string): Promise<JobListResponse> {
|
||||
}
|
||||
|
||||
export async function deleteJob(id: string): Promise<void> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(`${API_BASE}/jobs/${encodeURIComponent(id)}`, {
|
||||
method: "DELETE",
|
||||
headers,
|
||||
headers: csrfHeaders("DELETE", new Headers()),
|
||||
credentials: "include",
|
||||
});
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
@@ -285,15 +334,11 @@ export async function deleteJob(id: string): Promise<void> {
|
||||
}
|
||||
|
||||
export async function downloadTranscript(id: string, format: TranscriptFormat): Promise<Blob> {
|
||||
const headers = new Headers();
|
||||
const token = getToken();
|
||||
if (token) headers.set("Authorization", `Bearer ${token}`);
|
||||
|
||||
let response: Response;
|
||||
try {
|
||||
response = await fetch(
|
||||
`${API_BASE}/jobs/${encodeURIComponent(id)}/transcript?format=${format}`,
|
||||
{ headers },
|
||||
{ credentials: "include" },
|
||||
);
|
||||
} catch {
|
||||
throw new ApiError(0, "network error");
|
||||
|
||||
+28
-18
@@ -1,27 +1,29 @@
|
||||
// Reactive view of the stored session for client components. The token
|
||||
// lives in localStorage (see api.ts); this hook re-renders on sign-in and
|
||||
// sign-out in this tab (SESSION_CHANGE_EVENT) and in other tabs ("storage").
|
||||
// Reactive view of the dashboard session for client components. The token
|
||||
// itself lives in an httpOnly cookie the page cannot read, so the state
|
||||
// comes from GET /auth/session (see api.ts) and is kept in sync across this
|
||||
// tab (SESSION_CHANGE_EVENT) and other tabs (a BroadcastChannel).
|
||||
|
||||
import { useSyncExternalStore } from "react";
|
||||
import { SESSION_CHANGE_EVENT, getEmail, getToken } from "@/lib/api";
|
||||
import { useEffect, useSyncExternalStore } from "react";
|
||||
import { useRouter } from "@/i18n/navigation";
|
||||
import {
|
||||
SESSION_CHANGE_EVENT,
|
||||
getSessionState,
|
||||
getUnknownSessionState,
|
||||
loadSession,
|
||||
} from "@/lib/api";
|
||||
|
||||
// Accounts created by the Telegram bot get a synthetic address that means
|
||||
// nothing to the user, so it is not shown.
|
||||
const SYNTHETIC_EMAIL_SUFFIX = "@telegram.sokhan.local";
|
||||
|
||||
function subscribe(onChange: () => void): () => void {
|
||||
window.addEventListener("storage", onChange);
|
||||
window.addEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
return () => {
|
||||
window.removeEventListener("storage", onChange);
|
||||
window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
};
|
||||
if (getSessionState().status === "unknown") void loadSession();
|
||||
return () => window.removeEventListener(SESSION_CHANGE_EVENT, onChange);
|
||||
}
|
||||
|
||||
const onServer = () => false;
|
||||
|
||||
export interface Session {
|
||||
/** False during SSR and the first client render, before storage is readable. */
|
||||
/** False during SSR and until the API has said who is signed in. */
|
||||
ready: boolean;
|
||||
signedIn: boolean;
|
||||
/** The account email, or null when unknown or a Telegram placeholder. */
|
||||
@@ -29,9 +31,17 @@ export interface Session {
|
||||
}
|
||||
|
||||
export function useSession(): Session {
|
||||
const ready = useSyncExternalStore(subscribe, () => true, onServer);
|
||||
const signedIn = useSyncExternalStore(subscribe, () => getToken() !== null, onServer);
|
||||
const storedEmail = useSyncExternalStore(subscribe, getEmail, () => null);
|
||||
const email = storedEmail && !storedEmail.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? storedEmail : null;
|
||||
return { ready, signedIn, email };
|
||||
const state = useSyncExternalStore(subscribe, getSessionState, getUnknownSessionState);
|
||||
const email =
|
||||
state.email && !state.email.endsWith(SYNTHETIC_EMAIL_SUFFIX) ? state.email : null;
|
||||
return { ready: state.status !== "unknown", signedIn: state.status === "signedIn", email };
|
||||
}
|
||||
|
||||
/** Send a signed-out visitor to the login page once the session is known. */
|
||||
export function useRequireSignIn(): void {
|
||||
const { ready, signedIn } = useSession();
|
||||
const router = useRouter();
|
||||
useEffect(() => {
|
||||
if (ready && !signedIn) router.replace("/login");
|
||||
}, [ready, signedIn, router]);
|
||||
}
|
||||
Reference in new issue
Block a user