/** * How people sign in here, for the Hub (3.5.0, heartbeat `stats.signIn`, contracts 1.13.0): the * mode, the Accounts this site is linked to, and the last sign-in that failed to start or finish. * A site in `accounts` mode without a link can't sign anyone in; the Hub raises an alert for it. */ import { accountsLink } from './client'; import { authMode, getSetting, setSetting } from './mode'; export const LAST_ERROR_KEY = 'accounts_last_signin_error'; type LastError = { at: string; code: string; message: string }; /** Keeps the last failure (a code and a sentence; never tokens or cookies). */ export async function recordSignInError(code: string, message: string, now = new Date()): Promise { const value: LastError = { at: now.toISOString(), code: code.slice(0, 60), message: message.replace(/\s+/g, ' ').slice(0, 500) }; await setSetting(LAST_ERROR_KEY, JSON.stringify(value)).catch(() => {}); } /** A sign-in that worked clears it. */ export async function clearSignInError(): Promise { if (await getSetting(LAST_ERROR_KEY).catch(() => null)) await setSetting(LAST_ERROR_KEY, null).catch(() => {}); } export async function signInStatus(): Promise<{ mode: 'local' | 'accounts'; accounts: { installId: string; url: string } | null; lastError: LastError | null }> { const [mode, link, raw] = await Promise.all([authMode(), accountsLink(), getSetting(LAST_ERROR_KEY).catch(() => null)]); let lastError: LastError | null = null; try { const parsed = raw ? JSON.parse(raw) : null; if (parsed && typeof parsed.at === 'string' && typeof parsed.code === 'string' && typeof parsed.message === 'string') lastError = parsed; } catch { /* an unreadable value is no error */ } return { mode, accounts: link ? { installId: link.installId, url: link.url } : null, lastError }; }