import m, {MithrilComponent} from '@garage44/mithril' import {Button, Card, FieldSelect, FieldText} from '@garage44/mithril/components' import {askConfirm} from '@/components/confirm' import {act} from '@/lib/actions' import {api} from '@/lib/api' import type {Account} from '@/lib/api' import {age} from '@/lib/format' import {bind, local} from '@/lib/reactive' import {$s} from '@/lib/store' const ROLES = [ {value: 'viewer', label: 'viewer: sees the page'}, {value: 'operator', label: 'operator: drains, releases, deploys, decides'}, {value: 'steer', label: 'steer: also types into agent sessions'}, {value: 'admin', label: 'admin: also manages accounts and settings'}, ] /** The page a setup token opens, as `midas account add` prints it. */ const setupLink = (token: string) => `${location.origin}/setup/${token}` /** How an account stands, in a few words. */ function state(a: Account): string { if (a.locked) return 'locked after failed logins' if (!a.ready) return a.setup_pending ? 'setup link sent, not set up yet' : 'not set up' const seen = a.last_seen ? `seen ${age(a.last_seen)} ago` : 'not logged in' return `${seen} ยท ${a.recovery_left} recovery codes left` } /** * The people who log in to this page (accounts.rs), managed as `midas account` * does: add one, change a role, start one over, remove one. A new or reset * account gets a setup link, shown here once, to send its holder; they choose * the password and the authenticator themselves. Your own account is not * changed from here: that is how the last admin locks everyone out. */ export class Accounts extends MithrilComponent { s = local({ list: null as Account[] | null, name: '', role: 'operator', /** The setup link just made, and whose: shown until dismissed. */ link: null as {name: string; url: string} | null, error: '', }) oninit() { void this.load() } async load() { try { this.s.list = (await api.accounts()).sort((a, b) => a.name.localeCompare(b.name)) } catch (e) { this.s.error = (e as Error).message } } /** A role chosen is a role set: no Save for one field. */ roleOf(a: Account) { const reload = () => this.load() return { get value() { return a.role }, set value(role: string) { if (role !== a.role) void act(`${a.name} is ${role}`, async () => { await api.setAccountRole(a.name, role) await reload() }) }, } } account(a: Account) { const mine = a.name === $s.account return (
  • {a.name} {mine ? (you) : null}
    {state(a)}
    ({value: r.value, label: r.value}))} />
  • ) } view() { const {list, link} = this.s if (!list) return this.s.error ?

    {this.s.error}

    : null const name = this.s.name.trim() const valid = /^[a-z0-9_-]{1,40}$/.test(name) && !list.some((a) => a.name === name) return [ {link ? ( ) : null} , act(`${name} added`, async () => { this.s.link = {name, url: setupLink((await api.addAccount(name, this.s.role)).token)} this.s.name = '' await this.load() }) } > Add , ]} > , ] } }