File size: 8,143 Bytes
85f794d | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 | // ---------------------------------------------------------------------------
// 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();
}
|