runloopable / web /src /connectors /LoginsPanel.tsx
fsanyoto's picture
Deploy AIOS web (React glide grid + FastAPI slice)
89af3b2 verified
Raw History Blame Contribute Delete
13.9 kB
import { useCallback, useEffect, useRef, useState } from "react";
import { API_V1, CREDENTIALS, checkTenant } from "../apiContract";
import { isAdmin, me, type SessionUser } from "../shell/session";
export interface LoginMeta {
id: string;
label: string;
origin: string;
username: string;
secondFactor: string;
scope: string;
owner: string;
status: string;
allowedActions: string;
consentAt: string;
preview: string;
}
export interface LoginsResponse {
logins: LoginMeta[];
budget: { monthlyCapUsd: number; spentUsd: number;
perRun: { steps: number; usd: number; minutes: number } } | null;
}
const MAX_LOGINS = 40;
const ORIGIN_REFUSAL = "Amazon, bank and Odoo sites cannot be saved as a Login.";
const STATUS_LABELS: Record<string, string> = {
signed_in: "Signed in", "signed in": "Signed in", "Signed in": "Signed in",
needs_sign_in: "Needs sign-in", "needs sign-in": "Needs sign-in", "Needs sign-in": "Needs sign-in",
expired: "Expired", Expired: "Expired", revoked: "Revoked", Revoked: "Revoked",
};
const string = (raw: unknown) => typeof raw === "string" ? raw : "";
const record = (raw: unknown): Record<string, unknown> | null =>
raw && typeof raw === "object" && !Array.isArray(raw) ? raw as Record<string, unknown> : null;
const amount = (raw: unknown): raw is number =>
typeof raw === "number" && Number.isFinite(raw) && raw >= 0;
/** Copy metadata by name so a damaged response cannot seed a secret field. */
export function parseLoginsResponse(raw: unknown): LoginsResponse | null {
const body = record(raw);
if (!body || !Array.isArray(body.logins)) return null;
const logins: LoginMeta[] = [];
const ids = new Set<string>();
for (const item of body.logins) {
const entry = record(item);
if (!entry || !string(entry.id) || !string(entry.label) || ids.has(string(entry.id))) return null;
ids.add(string(entry.id));
logins.push({
id: string(entry.id), label: string(entry.label), origin: string(entry.origin),
username: string(entry.username), secondFactor: string(entry.secondFactor),
scope: string(entry.scope), owner: string(entry.owner), status: string(entry.status),
allowedActions: string(entry.allowedActions), consentAt: string(entry.consentAt),
preview: "……",
});
}
const budget = record(body.budget);
const perRun = record(budget?.perRun);
return { logins, budget: budget && perRun && amount(budget.monthlyCapUsd)
&& amount(budget.spentUsd) && amount(perRun.steps) && amount(perRun.usd) && amount(perRun.minutes)
? { monthlyCapUsd: budget.monthlyCapUsd, spentUsd: budget.spentUsd,
perRun: { steps: perRun.steps, usd: perRun.usd, minutes: perRun.minutes } } : null };
}
export function mayRevokeLogin(entry: LoginMeta, user: SessionUser | null): boolean {
if (!user || STATUS_LABELS[entry.status] === "Revoked") return false;
return entry.scope === "business" ? isAdmin(user)
: entry.scope === "personal" && Boolean(entry.owner) && entry.owner === user.username;
}
/** The server remains the authority for bank and tenant Odoo origin checks. */
export function loginOriginError(site: string): string {
if (!site.trim()) return "";
try {
const url = new URL(site.trim());
const labels = url.hostname.toLowerCase().split(".");
if (labels.includes("amazon") || labels.includes("amazonaws") || labels.includes("sellercentral")
|| labels.includes("odoo")) return ORIGIN_REFUSAL;
if (!["https:", "http:"].includes(url.protocol) || url.username || url.password)
return "Enter a website address beginning with https:// or http://.";
return "";
} catch {
return "Enter a website address beginning with https:// or http://.";
}
}
async function readResponse(res: Response): Promise<unknown> {
if (checkTenant(res)) throw new Error("Your session changed. Reopen Logins.");
const body: unknown = await res.json().catch(() => null);
if (!res.ok) throw new Error(string(record(record(body)?.error)?.message) || "Logins could not be updated.");
return body;
}
function LoginForm({ user, onSaved, onCancel }: {
user: SessionUser; onSaved: () => void; onCancel: () => void;
}) {
const [label, setLabel] = useState("");
const [site, setSite] = useState("");
const [username, setUsername] = useState("");
const [password, setPassword] = useState("");
const [totpSeed, setTotpSeed] = useState("");
const [secondFactor, setSecondFactor] = useState("none");
const [scope, setScope] = useState("personal");
const [consent, setConsent] = useState(false);
const [busy, setBusy] = useState(false);
const saving = useRef(false);
const [error, setError] = useState("");
const originError = loginOriginError(site);
const consentSite = site.trim() && !originError ? new URL(site.trim()).origin : "this site";
const complete = label.trim() && site.trim() && username.trim() && password && consent
&& !originError && (secondFactor !== "authenticator" || totpSeed.trim())
&& (scope !== "business" || isAdmin(user));
async function save() {
if (saving.current || !complete) return;
saving.current = true;
setBusy(true);
setError("");
try {
await readResponse(await fetch(`${API_V1}/logins`, {
method: "POST", credentials: CREDENTIALS, headers: { "Content-Type": "application/json" },
body: JSON.stringify({ label: label.trim(), origin: new URL(site.trim()).origin,
username: username.trim(), password, secondFactor, scope, consent: true,
...(secondFactor === "authenticator" ? { totpSeed: totpSeed.trim() } : {}) }),
}));
setPassword("");
setTotpSeed("");
onSaved();
} catch (failure) {
let message = failure instanceof Error ? failure.message : "Cannot reach the server.";
for (const secret of [password, totpSeed]) if (secret) message = message.split(secret).join("[hidden]");
setError(message);
} finally {
saving.current = false;
setBusy(false);
}
}
return <form className="conn-kc-form conn-logins-form" onSubmit={(event) => { event.preventDefault(); void save(); }}>
<div className="conn-kc-field">
<label htmlFor="conn-login-label">Label</label>
<input id="conn-login-label" value={label} maxLength={80} disabled={busy}
onChange={(event) => setLabel(event.target.value)} autoComplete="off" />
</div>
<div className="conn-kc-field">
<label htmlFor="conn-login-site">Site</label>
<input id="conn-login-site" type="url" value={site} maxLength={2048} disabled={busy}
onChange={(event) => setSite(event.target.value)} autoComplete="off"
aria-invalid={Boolean(originError)} aria-describedby="conn-login-site-error" />
<div id="conn-login-site-error" className="conn-kc-message-slot">
{originError ? <p className="conn-kc-note conn-logins-refusal" role="alert">{originError}</p> : null}
</div>
</div>
<div className="conn-kc-field">
<label htmlFor="conn-login-username">Username</label>
<input id="conn-login-username" value={username} maxLength={320} disabled={busy}
onChange={(event) => setUsername(event.target.value)} autoComplete="off" />
</div>
<div className="conn-kc-field">
<label htmlFor="conn-login-password">Password</label>
<input id="conn-login-password" type="password" value={password} disabled={busy}
onChange={(event) => setPassword(event.target.value)} autoComplete="new-password" />
</div>
<div className="conn-kc-field">
<label htmlFor="conn-login-factor">Second factor</label>
<select id="conn-login-factor" value={secondFactor} disabled={busy}
onChange={(event) => { setSecondFactor(event.target.value); setTotpSeed(""); }}>
<option value="none">None</option><option value="authenticator">Authenticator</option>
<option value="text">Text</option><option value="email">Email</option><option value="push">Push</option>
</select>
</div>
{secondFactor === "authenticator" ? <div className="conn-kc-field">
<label htmlFor="conn-login-totp">Authenticator secret</label>
<input id="conn-login-totp" type="password" value={totpSeed} disabled={busy}
onChange={(event) => setTotpSeed(event.target.value)} autoComplete="new-password" />
</div> : null}
<div className="conn-kc-field">
<label htmlFor="conn-login-scope">Scope</label>
<select id="conn-login-scope" value={scope} disabled={busy}
onChange={(event) => setScope(event.target.value)} aria-describedby={!isAdmin(user) ? "conn-login-admin" : undefined}>
<option value="personal">Personal</option><option value="business" disabled={!isAdmin(user)}>Business</option>
</select>
{!isAdmin(user) ? <p id="conn-login-admin" className="conn-kc-note">Administrators only</p> : null}
</div>
<label className="conn-logins-consent" htmlFor="conn-login-consent">
<input id="conn-login-consent" type="checkbox" checked={consent} disabled={busy}
onChange={(event) => setConsent(event.target.checked)} />
<span>I authorise Loopable to sign in to {consentSite} as {username.trim() || "this username"} on my behalf,
and I am allowed to under that site’s terms.</span>
</label>
<div className="conn-kc-message-slot">
{error ? <p className="conn-kc-error" role="alert">{error}</p> : null}
</div>
<div className="conn-kc-actions set-actions">
<button type="button" className="conn-kc-btn" disabled={busy} onClick={onCancel}>Cancel</button>
<button type="submit" className="conn-kc-btn is-primary" disabled={busy || !complete}>{busy ? "Saving" : "Save"}</button>
</div>
</form>;
}
export default function LoginsPanel({ onChanged }: { onChanged: () => void }) {
const [data, setData] = useState<LoginsResponse | null>(null);
const [user, setUser] = useState<SessionUser | null>(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState("");
const [adding, setAdding] = useState(false);
const [busyId, setBusyId] = useState("");
const mutating = useRef(false);
const [version, setVersion] = useState(0);
const refresh = useCallback(() => setVersion((current) => current + 1), []);
useEffect(() => {
let dead = false;
setLoading(true);
setData(null);
setUser(null);
setError("");
void (async () => {
try {
const [identity, raw] = await Promise.all([me(), fetch(`${API_V1}/logins`, {
credentials: CREDENTIALS, cache: "no-store",
}).then(readResponse)]);
if (dead) return;
if (!identity) throw new Error("Your session could not be read. Reopen Logins.");
const parsed = parseLoginsResponse(raw);
if (!parsed) throw new Error("Logins could not be read. Try again.");
setUser(identity);
setData(parsed);
} catch (failure) {
if (!dead) setError(failure instanceof Error ? failure.message : "Cannot reach the server.");
} finally {
if (!dead) setLoading(false);
}
})();
return () => { dead = true; };
}, [version]);
async function revoke(entry: LoginMeta) {
if (mutating.current || !mayRevokeLogin(entry, user)) return;
mutating.current = true;
setBusyId(entry.id);
setError("");
try {
await readResponse(await fetch(`${API_V1}/logins/${encodeURIComponent(entry.id)}/revoke`, {
method: "POST", credentials: CREDENTIALS,
}));
refresh();
onChanged();
} catch (failure) {
setError(failure instanceof Error ? failure.message : "Cannot reach the server.");
} finally {
mutating.current = false;
setBusyId("");
}
}
const atLimit = (data?.logins.length ?? 0) >= MAX_LOGINS;
return <section className="conn-logins" aria-label="Logins">
{loading ? <p className="conn-kc-note" role="status">Loading Logins.</p> : null}
{error ? <div className="conn-kc-message-slot"><p className="conn-kc-error" role="alert">{error}</p>
{!data ? <button type="button" className="conn-kc-btn" onClick={refresh}>Try again</button> : null}</div> : null}
{!loading && data?.logins.length === 0 ? <p className="conn-kc-empty">No Logins yet.</p> : null}
{data && data.logins.length > 0 ? <ul className="conn-kc-list conn-logins-list">
{data.logins.map((entry) => <li className="conn-kc-row" key={entry.id} data-login-id={entry.id}>
<dl className="conn-kc-main conn-logins-meta">
<div><dt>Label</dt><dd className="conn-kc-label">{entry.label}</dd></div>
<div><dt>Site</dt><dd>{entry.origin}</dd></div>
<div><dt>Username</dt><dd>{entry.username}</dd></div>
<div><dt>Scope</dt><dd>{entry.scope === "business" ? "Business" : entry.scope === "personal" ? "Personal" : "Unavailable"}</dd></div>
<div><dt>Password</dt><dd className="conn-logins-preview">{entry.preview}</dd></div>
</dl>
{mayRevokeLogin(entry, user) ? <div className="conn-kc-controls set-actions">
<button type="button" className="conn-kc-btn is-danger" disabled={Boolean(busyId)}
onClick={() => void revoke(entry)}>Revoke</button>
</div> : null}
</li>)}
</ul> : null}
{adding && user ? <LoginForm user={user} onCancel={() => setAdding(false)} onSaved={() => {
setAdding(false); refresh(); onChanged();
}} /> : <div className="conn-kc-actions set-actions">
<button type="button" className="conn-kc-btn is-primary"
disabled={loading || !data || !user || atLimit || Boolean(busyId)}
aria-describedby={atLimit ? "conn-login-limit" : undefined} onClick={() => setAdding(true)}>Add</button>
</div>}
{atLimit ? <p id="conn-login-limit" className="conn-kc-note">You have reached 40 Logins.</p> : null}
</section>;
}