loopable / web /src /settings /viewAs.ts
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
85f794d verified
Raw History Blame Contribute Delete
8.14 kB
// ---------------------------------------------------------------------------
// settings / viewAs.ts: an administrator views Loopable as one member, read only (S85-T157).
//
// The mode is tab local (sessionStorage) and bound to the administrator and tenant that started
// it. `installViewAs` wraps fetch once, before the first API call. While the mode is on, every
// same-origin `/api/` request carries `X-View-As`, for a string, URL or Request input. After
// exit, none does. Entry and exit reload the frame, so no cache or route outlives the identity.
//
// The server is the wall: `deps.py::_view_as_user` checks the administrator, the member and the
// tenant, and `refuse_view_as_write` answers 403 `view_as_read_only` to every non-GET.
// ---------------------------------------------------------------------------
import { API_V1, CREDENTIALS, VIEW_AS_HEADER } from "../apiContract";
import { withEdgeRetry } from "../net/edgeRetry";
/** Tab-local storage key. sessionStorage, so another tab or a new browser never inherits it. */
export const VIEW_AS_STORAGE_KEY = "aios.viewAs";
/** The server code for a write refused while viewing as a member. */
export const VIEW_AS_READ_ONLY = "view_as_read_only";
/** The server code for a member view it will not serve. */
export const VIEW_AS_REFUSED = "view_as_refused";
const REFUSED_FALLBACK = "This member view is unavailable.";
export interface ViewAsMode {
/** The administrator who started the view. A different signed-in account discards it. */
admin: string;
tenant: string;
/** The member's username, sent as `X-View-As`. */
target: string;
/** The member's display name when the view started. */
name: string;
}
let mode: ViewAsMode | null = null;
let refusal = "";
let installed = false;
let ready: Promise<void> | null = null;
let changed: () => void = () => {};
function norm(value: unknown): string {
return typeof value === "string" ? value.trim().toLowerCase() : "";
}
function parseMode(raw: string | null): ViewAsMode | null {
if (!raw) return null;
try {
const value = JSON.parse(raw) as Record<string, unknown>;
const admin = norm(value.admin);
const tenant = norm(value.tenant);
const target = norm(value.target);
const name = typeof value.name === "string" && value.name.trim() ? value.name.trim() : target;
return admin && tenant && target && admin !== target ? { admin, tenant, target, name } : null;
} catch {
return null;
}
}
function readStored(): ViewAsMode | null {
try {
return parseMode(window.sessionStorage.getItem(VIEW_AS_STORAGE_KEY));
} catch {
return null;
}
}
function clearStored(): void {
try {
window.sessionStorage.removeItem(VIEW_AS_STORAGE_KEY);
} catch {
/* blocked storage holds no mode */
}
}
/** Is this one of our API routes, on this origin? Third parties never see the header. */
function isApi(input: RequestInfo | URL): boolean {
try {
const url = new URL(input instanceof Request ? input.url : String(input), window.location.origin);
return url.origin === window.location.origin && /^\/api(?:\/|$)/.test(url.pathname);
} catch {
return false;
}
}
/** The same request with `X-View-As` set. A Request input is rebuilt, so its own headers stay. */
export function withViewAs(
input: RequestInfo | URL,
init: RequestInit | undefined,
target: string
): [RequestInfo | URL, RequestInit | undefined] {
if (input instanceof Request) {
const request = new Request(input, init);
request.headers.set(VIEW_AS_HEADER, target);
return [request, undefined];
}
const headers = new Headers(init?.headers);
headers.set(VIEW_AS_HEADER, target);
return [input, { ...init, headers }];
}
/**
* Confirm the stored mode against the cookie's own account, without the header. The mode starts
* only when that account is still the administrator who chose it, in the same tenant. Anything
* else, a failed read included, discards it: an account switch never inherits a member view.
*/
async function confirmMode(stored: ViewAsMode, read: typeof fetch): Promise<void> {
try {
const res = await read(`${API_V1}/auth/me`, { credentials: CREDENTIALS, cache: "no-store" });
if (res.ok) {
const body = (await res.json()) as { user?: Record<string, unknown>; tenant?: unknown } | null;
const user = body?.user;
const tenant = norm(user?.tenant) || norm(body?.tenant);
if (user?.role === "admin" && norm(user.username) === stored.admin && tenant === stored.tenant) {
mode = stored;
return;
}
}
} catch {
/* discarded below */
}
clearStored();
}
/** Keep the server's sentence when it refuses the member view itself. */
async function noteRefusal(response: Response): Promise<void> {
if (response.status !== 403) return;
try {
const body = (await response.clone().json()) as { error?: { code?: unknown; message?: unknown } } | null;
if (body?.error?.code !== VIEW_AS_REFUSED) return;
const message = body.error.message;
refusal = typeof message === "string" && message.trim() ? message.trim() : REFUSED_FALLBACK;
} catch {
/* a 403 without a JSON body is not a member view refusal */
}
}
/** A beacon cannot carry a header, so an API beacon falls back to its caller's fetch. */
function guardBeacon(): void {
try {
const nav = window.navigator;
if (typeof nav?.sendBeacon !== "function") return;
const send = nav.sendBeacon.bind(nav);
nav.sendBeacon = (url: string | URL, data?: BodyInit | null): boolean =>
mode && isApi(url) ? false : send(url, data);
} catch {
/* a locked navigator keeps its own beacon */
}
}
/**
* Install the transport once, before the first API request. `onChange` runs after entry or exit
* has written the tab's mode, and must reload the frame. Requests wait while a stored mode is
* being confirmed, so none leaves with a stale identity.
*/
export function installViewAs(onChange: () => void): void {
if (installed || typeof window === "undefined" || typeof window.fetch !== "function") return;
installed = true;
changed = onChange;
const native = window.fetch.bind(window);
const stored = readStored();
if (stored) {
ready = confirmMode(stored, withEdgeRetry(native)).finally(() => {
ready = null;
});
}
window.fetch = async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
if (!isApi(input)) return native(input, init);
if (ready) await ready;
const active = mode;
if (!active) return native(input, init);
const [request, options] = withViewAs(input, init, active.target);
const response = await native(request, options);
await noteRefusal(response);
return response;
};
guardBeacon();
}
/** The read-only flag. True only after the server-side account matched the stored mode. */
export function viewAsActive(): boolean {
return mode !== null;
}
export function viewAsMode(): ViewAsMode | null {
return mode;
}
/** The server's sentence for a refused member view, or the fallback. Empty while not viewing. */
export function viewAsRefusal(): string {
return mode ? refusal || REFUSED_FALLBACK : "";
}
/** Start viewing as `member` in this tab. Returns false when the mode cannot be stored. */
export function startViewAs(
admin: { username: string; tenant: string },
member: { username: string; name?: string }
): boolean {
if (mode || typeof window === "undefined") return false;
const next = parseMode(
JSON.stringify({ admin: admin.username, tenant: admin.tenant, target: member.username, name: member.name })
);
if (!next) return false;
try {
window.sessionStorage.setItem(VIEW_AS_STORAGE_KEY, JSON.stringify(next));
} catch {
return false;
}
changed();
return true;
}
/** Drop the mode at once without a reload, so the next request, such as sign out, has no header. */
export function clearViewAs(): void {
mode = null;
refusal = "";
if (typeof window !== "undefined") clearStored();
}
/** Leave the member view and reload as the administrator. */
export function exitViewAs(): void {
clearViewAs();
changed();
}