SPB Git

Repository Public

ItemEditor.tsx 17.3 KB 238 lines tsx

1// Item editor: type picker, template fields, generator popover, URL rules with lookalike warning, TOTP validation.2import { useEffect, useMemo, useRef, useState } from "react";3import { type CustomField, estimateBits, type FieldDef, type FieldKind, type Item, type ItemType, lookalike, newItem, parseOrigin, parseTotp, savedDomains, TEMPLATES, type UrlMatch } from "../../../../packages/protocol/src/index.ts";4import type { ItemView, VaultView } from "../core/engine.ts";5import { engine } from "../state.ts";6import { Badge, Btn, Callout, ErrorText, Field, Icon, IconBtn, useAction } from "./common.tsx";7import { GeneratorPanel, StrengthMeter } from "./Generator.tsx";8import { TotpRow } from "./ItemBody.tsx";9import { canWrite, ITEM_TYPES, keyOf, MULTILINE_SECRETS, TYPE_ICON } from "./itemmeta.ts";1011export interface EditorTarget { vaultId: string; id: string | null; item: Item | null }1213const TYPE_HINT: Record<ItemType, string> = {14  login: "Username, password, one-time code", passkey: "A passkey stored for a website", card: "Payment card details", identity: "Passport, licence, ID card",15  note: "Free text, kept encrypted", wifi: "Network name and password", license: "Software licence key", document: "Files with notes",16  "ssh-key": "Key pair and passphrase", "api-token": "Service token and scopes", certificate: "Certificate and private key", database: "Connection credentials", env: "A .env file for a project",17};1819export function TypePicker({ onPick, onCancel }: { onPick: (t: ItemType) => void; onCancel: () => void }) {20  return (21    <div className="editor" data-testid="type-picker">22      <header className="editor-head"><IconBtn icon="back" label="Cancel" onClick={onCancel} /><h1>New item</h1></header>23      <p className="muted">What would you like to store?</p>24      <ul className="type-grid">25        {ITEM_TYPES.map((t, i) => (26          <li key={t}><button type="button" className="type-card" onClick={() => onPick(t)} data-testid={`type-${t}`} autoFocus={i === 0}>27            <span className="type-icon"><Icon name={TYPE_ICON[t]} size={20} /></span>28            <span><strong>{TEMPLATES[t].label}</strong><small>{TYPE_HINT[t]}</small></span>29          </button></li>30        ))}31      </ul>32    </div>33  );34}3536function SecretInput({ value, onChange, multiline, testid, id }: { value: string; onChange: (v: string) => void; multiline?: boolean; testid?: string; id?: string }) {37  const [shown, setShown] = useState(false);38  return (39    <div className="input-row">40      {multiline41        ? <textarea id={id} className={`input mono${shown ? "" : " concealed"}`} rows={4} value={value} onChange={(e) => onChange(e.target.value)} spellCheck={false} autoComplete="off" autoCapitalize="none" data-testid={testid} />42        : <input id={id} className="input mono" type={shown ? "text" : "password"} value={value} onChange={(e) => onChange(e.target.value)} spellCheck={false} autoComplete="new-password" autoCapitalize="none" data-1p-ignore data-lpignore="true" data-testid={testid} />}43      <IconBtn icon={shown ? "eyeOff" : "eye"} label={shown ? "Hide" : "Show"} aria-pressed={shown} onClick={() => setShown(!shown)} />44    </div>45  );46}4748const DATE_RE = /^\d{4}-\d{2}-\d{2}$/;49function DateInput({ value, onChange, testid }: { value: string; onChange: (v: string) => void; testid?: string }) {50  return value && !DATE_RE.test(value.slice(0, 10))51    ? <input className="input" value={value} onChange={(e) => onChange(e.target.value)} data-testid={testid} />52    : <input className="input" type="date" value={value.slice(0, 10)} onChange={(e) => onChange(e.target.value)} data-testid={testid} />;53}5455function totpError(v: string): string { if (!v.trim()) return ""; try { parseTotp(v); return ""; } catch (e: any) { return `Not a valid setup key: ${e?.message ?? "invalid"}`; } }5657export function ItemEditor({ target, vaults, items, onSaved, onCancel, onDirty }: {58  target: EditorTarget & { item: Item }; vaults: VaultView[]; items: ItemView[]; onSaved: (key: string) => void; onCancel: () => void; onDirty: (dirty: boolean) => void;59}) {60  const isNew = target.id === null;61  const [draft, setDraft] = useState<Item>(target.item);62  const [vaultId, setVaultId] = useState(target.vaultId);63  const [tagText, setTagText] = useState("");64  const [genFor, setGenFor] = useState<string | null>(null);65  const [tried, setTried] = useState(false);66  const act = useAction();67  const initial = useRef(JSON.stringify(target.item));68  const tpl = TEMPLATES[draft.type];69  const writable = vaults.filter(canWrite);70  const dirty = JSON.stringify(draft) !== initial.current || tagText.trim() !== "";71  useEffect(() => { onDirty(dirty); }, [dirty]);72  useEffect(() => () => onDirty(false), []);73  useEffect(() => {74    if (!dirty) return;75    const guard = (e: BeforeUnloadEvent) => { e.preventDefault(); };76    window.addEventListener("beforeunload", guard);77    return () => window.removeEventListener("beforeunload", guard);78  }, [dirty]);7980  const others = useMemo(() => savedDomains(items.filter((v) => !(v.vaultId === target.vaultId && v.id === target.id) && !v.item.trashedAt).map((v) => v.item)), [items]);81  const set = (patch: Partial<Item>) => setDraft((d) => ({ ...d, ...patch }));82  const setField = (k: string, v: string) => setDraft((d) => ({ ...d, fields: { ...d.fields, [k]: v } }));83  const setUrl = (i: number, patch: Partial<{ url: string; match: UrlMatch }>) => set({ urls: draft.urls.map((u, j) => (j === i ? { ...u, ...patch } : u)) });84  const setCustom = (i: number, patch: Partial<CustomField>) => set({ custom: draft.custom.map((c, j) => (j === i ? { ...c, ...patch } : c)) });85  const addTags = (text: string) => { const add = text.split(",").map((t) => t.trim().replace(/^#/, "")).filter(Boolean); if (add.length) set({ tags: [...new Set([...draft.tags, ...add])].slice(0, 50) }); setTagText(""); };8687  const totpKeys = tpl.fields.filter((f) => f.kind === "totp").map((f) => f.key);88  const totpBad = totpKeys.some((k) => totpError(draft.fields[k] ?? "")) || draft.custom.some((c) => c.kind === "totp" && totpError(c.value));89  const titleMissing = !draft.title.trim();9091  const save = () => {92    setTried(true);93    if (titleMissing || totpBad) return;94    void act.run(async () => {95      const tags = tagText.trim() ? [...new Set([...draft.tags, ...tagText.split(",").map((t) => t.trim()).filter(Boolean)])] : draft.tags;96      const fields = Object.fromEntries(Object.entries(draft.fields).filter(([, v]) => v !== ""));97      const item: Item = { ...draft, title: draft.title.trim(), fields, tags, urls: draft.urls.filter((u) => u.url.trim()).map((u) => ({ ...u, url: u.url.trim() })), custom: draft.custom.filter((c) => c.label.trim() || c.value) };98      const id = await engine.saveItem(vaultId, target.id, item);99      onDirty(false);100      onSaved(keyOf({ vaultId, id }));101    });102  };103104  const renderField = (f: FieldDef) => {105    const v = draft.fields[f.key] ?? "", tid = `field-${f.key}`;106    if (f.kind === "secret") {107      const isPw = f.key === "password" || f.key === "passphrase";108      return (109        <div key={f.key} className="field-block">110          <Field label={f.label}><SecretInput value={v} onChange={(x) => setField(f.key, x)} multiline={MULTILINE_SECRETS.has(f.key)} testid={tid} /></Field>111          {isPw && (112            <>113              <div className="row between wrap">114                {v ? <StrengthMeter bits={estimateBits(v)} label="estimated" /> : <span />}115                <Btn small icon="dice" onClick={() => setGenFor(genFor === f.key ? null : f.key)} aria-expanded={genFor === f.key} data-testid={`gen-open-${f.key}`}>{genFor === f.key ? "Close generator" : "Generate"}</Btn>116              </div>117              {genFor === f.key && <div className="popover" role="group" aria-label="Password generator"><GeneratorPanel onUse={(x) => { setField(f.key, x); setGenFor(null); }} /></div>}118            </>119          )}120        </div>121      );122    }123    if (f.kind === "totp") {124      const err = totpError(v);125      return (126        <div key={f.key} className="field-block">127          <Field label={f.label} hint="Paste the setup key (base32) or an otpauth:// address from the site's two-step settings." error={err || undefined}>128            <SecretInput value={v} onChange={(x) => setField(f.key, x.trim())} testid={tid} />129          </Field>130          {v && !err && <div className="totp-preview"><span className="muted small">Current code</span><TotpRow value={v} /></div>}131        </div>132      );133    }134    if (f.kind === "multiline") return <Field key={f.key} label={f.label}>{MULTILINE_SECRETS.has(f.key) ? <SecretInput value={v} onChange={(x) => setField(f.key, x)} multiline testid={tid} /> : <textarea className="input mono" rows={4} value={v} onChange={(e) => setField(f.key, e.target.value)} spellCheck={false} data-testid={tid} />}</Field>;135    if (f.kind === "date") return <Field key={f.key} label={f.label}><DateInput value={v} onChange={(x) => setField(f.key, x)} testid={tid} /></Field>;136    return <Field key={f.key} label={f.label}><input className="input" value={v} onChange={(e) => setField(f.key, e.target.value)} autoComplete="off" autoCapitalize="none" spellCheck={false} data-testid={tid} /></Field>;137  };138139  return (140    <form className="editor" data-testid="item-editor" onSubmit={(e) => { e.preventDefault(); save(); }} noValidate>141      <header className="editor-head">142        <IconBtn icon="back" label="Cancel" onClick={onCancel} />143        <h1>{isNew ? `New ${tpl.label.toLowerCase()}` : `Edit ${tpl.label.toLowerCase()}`}</h1>144        <div className="row"><Btn onClick={onCancel} className="hide-mobile">Cancel</Btn><Btn variant="primary" type="submit" icon="check" busy={act.busy} data-testid="save">Save</Btn></div>145      </header>146      <ErrorText text={act.error} />147148      <div className="editor-section">149        <Field label="Title" error={tried && titleMissing ? "Give this item a title" : undefined}>150          <input className="input title-input" value={draft.title} onChange={(e) => set({ title: e.target.value })} maxLength={500} autoFocus autoComplete="off" data-testid="field-title" aria-invalid={tried && titleMissing} />151        </Field>152        {tpl.fields.map(renderField)}153      </div>154155      <div className="editor-section">156        <div className="section-head"><h2>Websites</h2><Btn small icon="plus" onClick={() => set({ urls: [...draft.urls, { url: "", match: "domain" }] })} data-testid="add-url">Add address</Btn></div>157        {draft.urls.length === 0 && <p className="muted small">Addresses decide where this item is offered. Matching uses the registrable domain by default.</p>}158        {draft.urls.map((u, i) => {159          const o = u.url.trim() ? parseOrigin(u.url) : null, warn = u.url.trim() ? lookalike(u.url, others) : null;160          const insecure = /^http:\/\//i.test(u.url.trim());161          return (162            <div key={i} className="url-edit">163              <div className="input-row">164                <input className="input" value={u.url} onChange={(e) => setUrl(i, { url: e.target.value })} placeholder="https://example.com" inputMode="url" autoCapitalize="none" spellCheck={false} autoComplete="off" aria-label={`Address ${i + 1}`} data-testid={`url-${i}`} />165                <select className="input auto" value={u.match} onChange={(e) => setUrl(i, { match: e.target.value as UrlMatch })} aria-label={`Match rule for address ${i + 1}`}>166                  <option value="domain">Domain</option><option value="host">Host</option><option value="exact">Exact</option><option value="never">Never</option>167                </select>168                <IconBtn icon="x" label={`Remove address ${i + 1}`} onClick={() => set({ urls: draft.urls.filter((_, j) => j !== i) })} />169              </div>170              <div className="url-notes">171                {o && <span className="muted small">Matches <strong className="mono">{u.match === "domain" ? o.domain ?? o.host : u.match === "host" ? o.host : u.match === "exact" ? "this exact address" : "nothing (never offered)"}</strong></span>}172                {u.url.trim() && !o && <Badge kind="brass" icon="alert">not a web address</Badge>}173                {insecure && <Badge kind="danger" icon="alert">insecure (http)</Badge>}174              </div>175              {warn && (176                <Callout kind="danger" title="Possible look-alike domain">177                  <p data-testid="lookalike">{warn.reason === "mixed-script" ? <><strong className="mono">{warn.page}</strong> mixes alphabets in one label, a common phishing trick.</> : <><strong className="mono">{warn.page}</strong> closely resembles <strong className="mono">{warn.resembles}</strong>, which you already saved. Check the spelling before saving a password for it.</>}</p>178                </Callout>179              )}180            </div>181          );182        })}183      </div>184185      <div className="editor-section">186        <div className="section-head"><h2>Custom fields</h2><Btn small icon="plus" onClick={() => set({ custom: [...draft.custom, { label: "", value: "", kind: "text" }] })} data-testid="add-custom">Add field</Btn></div>187        {draft.custom.map((c, i) => (188          <div key={i} className="custom-edit">189            <div className="input-row">190              <input className="input" value={c.label} onChange={(e) => setCustom(i, { label: e.target.value })} placeholder="Label" aria-label={`Custom field ${i + 1} label`} maxLength={200} data-testid={`custom-label-${i}`} />191              <select className="input auto" value={c.kind} onChange={(e) => setCustom(i, { kind: e.target.value as FieldKind })} aria-label={`Custom field ${i + 1} type`}>192                <option value="text">Text</option><option value="secret">Secret</option><option value="url">URL</option><option value="multiline">Multiline</option><option value="date">Date</option>193              </select>194              <IconBtn icon="x" label={`Remove custom field ${i + 1}`} onClick={() => set({ custom: draft.custom.filter((_, j) => j !== i) })} />195            </div>196            {c.kind === "secret" || c.kind === "totp" ? <SecretInput value={c.value} onChange={(x) => setCustom(i, { value: x })} testid={`custom-value-${i}`} />197              : c.kind === "multiline" ? <textarea className="input" rows={3} value={c.value} onChange={(e) => setCustom(i, { value: e.target.value })} aria-label={`Custom field ${i + 1} value`} data-testid={`custom-value-${i}`} />198              : c.kind === "date" ? <DateInput value={c.value} onChange={(x) => setCustom(i, { value: x })} testid={`custom-value-${i}`} />199              : <input className="input" value={c.value} onChange={(e) => setCustom(i, { value: e.target.value })} aria-label={`Custom field ${i + 1} value`} autoComplete="off" spellCheck={false} data-testid={`custom-value-${i}`} />}200          </div>201        ))}202      </div>203204      <div className="editor-section">205        <Field label="Notes"><textarea className="input" rows={4} value={draft.notes} onChange={(e) => set({ notes: e.target.value })} data-testid="field-notes" /></Field>206        <Field label="Tags" hint="Press Enter or comma to add">207          <div className="tag-input">208            {draft.tags.map((t) => <span key={t} className="chip">{t}<button type="button" aria-label={`Remove tag ${t}`} onClick={() => set({ tags: draft.tags.filter((x) => x !== t) })}><Icon name="x" size={12} /></button></span>)}209            <input value={tagText} onChange={(e) => { if (e.target.value.includes(",")) addTags(e.target.value); else setTagText(e.target.value); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); addTags(tagText); } else if (e.key === "Backspace" && !tagText && draft.tags.length) set({ tags: draft.tags.slice(0, -1) }); }} onBlur={() => tagText.trim() && addTags(tagText)} maxLength={64} aria-label="Add tag" data-testid="field-tags" />210          </div>211        </Field>212        <div className="grid-2">213          <Field label="Vault" hint={isNew ? undefined : "Use “Move to vault” on the item to change it."}>214            <select className="input" value={vaultId} onChange={(e) => setVaultId(e.target.value)} disabled={!isNew} data-testid="field-vault">215              {(isNew ? writable : vaults.filter((v) => v.vaultId === vaultId)).map((v) => <option key={v.vaultId} value={v.vaultId}>{v.meta.name}</option>)}216            </select>217          </Field>218          <Field label="Expires on" hint="Optional — shown in the Security Center 30 days ahead."><DateInput value={draft.expiresAt ?? ""} onChange={(x) => set({ expiresAt: x || undefined })} testid="field-expires" /></Field>219        </div>220        {tpl.section === "developer" && (221          <Field label="Rotate every (days)" hint="Optional rotation schedule; the Security Center flags the secret when it is due.">222            <input className="input" type="number" min={1} max={3650} value={draft.rotateEveryDays ?? ""} onChange={(e) => { const n = Math.floor(Number(e.target.value)); set({ rotateEveryDays: e.target.value && n > 0 ? Math.min(n, 3650) : undefined }); }} data-testid="field-rotate" />223          </Field>224        )}225        <label className="check"><input type="checkbox" checked={draft.favorite} onChange={(e) => set({ favorite: e.target.checked })} /><span>Favorite</span></label>226      </div>227228      <footer className="editor-foot">229        {tried && (titleMissing || totpBad) && <span className="field-error" role="alert">{titleMissing ? "A title is required." : "Fix the one-time code setup key."}</span>}230        <Btn onClick={onCancel}>Cancel</Btn>231        <Btn variant="primary" type="submit" icon="check" busy={act.busy} data-testid="save-bottom">Save</Btn>232      </footer>233    </form>234  );235}236237export const blankItem = (type: ItemType) => newItem(type);238
Files main
Menu

Theme