SPB Git

Repository Public

Relay.tsx 11.8 KB 173 lines tsx

1// SP Vault Relay: share an item with an account or by link; lists of sent and received shares.2import { useCallback, useEffect, useState } from "react";3import type { Item } from "../../../../packages/protocol/src/index.ts";4import { copyText, dateTime, engine, onLive, relTime, reportError, toast } from "../state.ts";5import { Badge, Btn, Callout, Dialog, Empty, ErrorText, EXPIRY_OPTIONS, Field, Fingerprint, PageHead, Section, Segmented, Skeleton, useAction } from "./common.tsx";6import { ItemBody } from "./ItemBody.tsx";7import { canWrite } from "./itemmeta.ts";89type Account = Awaited<ReturnType<typeof engine.lookupAccount>>;1011/** Handle lookup with the fingerprint to compare out of band. */12export function AccountLookup({ value, onChange }: { value: Account | null; onChange: (a: Account | null) => void }) {13  const [handle, setHandle] = useState("");14  const act = useAction();15  const lookup = () => act.run(async () => { onChange(null); onChange(await engine.lookupAccount(handle)); });16  return (17    <div className="stack">18      <Field label="Recipient handle">19        <div className="input-row">20          <input className="input" value={handle} onChange={(e) => { setHandle(e.target.value.toLowerCase().trim()); onChange(null); }} onKeyDown={(e) => { if (e.key === "Enter") { e.preventDefault(); if (handle) void lookup(); } }} autoCapitalize="none" spellCheck={false} autoComplete="off" data-autofocus data-testid="lookup-handle" />21          <Btn onClick={lookup} busy={act.busy} disabled={!/^[a-z0-9][a-z0-9._-]{1,31}$/.test(handle)} data-testid="lookup-go">Look up</Btn>22        </div>23      </Field>24      <ErrorText text={act.error} />25      {value && (26        <Callout kind="warn" title={`Verify ${value.handle}'s fingerprint`}>27          <p><Fingerprint value={value.fingerprint} big /></p>28          <p>Compare it with what {value.handle} sees under Settings → About security, using another channel (in person, a call). The server supplied these keys: if the fingerprint differs, do not continue.</p>29        </Callout>30      )}31    </div>32  );33}3435export function ShareDialog({ item, onClose }: { item: Item; onClose: () => void }) {36  const [mode, setMode] = useState<"link" | "account">("link");37  const [recipient, setRecipient] = useState<Account | null>(null);38  const [expiry, setExpiry] = useState(86400);39  const [maxViews, setMaxViews] = useState("1");40  const [url, setUrl] = useState("");41  const [sent, setSent] = useState(false);42  const act = useAction();43  const views = maxViews.trim() === "" ? undefined : Math.max(1, Math.min(1000, Math.floor(Number(maxViews)) || 1));4445  const share = () => act.run(async () => {46    if (mode === "link") setUrl(await engine.shareByLink(item, location.origin, expiry, views ?? 1));47    else { await engine.shareWithAccount(item, recipient!, expiry, views); setSent(true); toast(`Shared with ${recipient!.handle}`, "ok"); }48  });4950  if (url) {51    return (52      <Dialog title="Share link" onClose={onClose} footer={<Btn variant="primary" onClick={onClose} data-testid="share-done">Done</Btn>}>53        <div className="stack">54          <p>This link is shown <strong>once</strong>. Copy it now and send it over a channel you trust.</p>55          <div className="input-row">56            <input className="input mono" readOnly value={url} data-testid="share-url" onFocus={(e) => e.target.select()} aria-label="Share link" />57            <Btn variant="primary" icon="copy" onClick={() => copyText(url, "Share link")} data-testid="share-copy">Copy</Btn>58          </div>59          <Callout kind="warn" title="Anyone holding the full link can read this item">60            <p>The part after <span className="mono">#</span> is the decryption key; it is never sent to the server. The link works {views === 1 ? "once" : `${views ?? 1} times`} and until it expires. Revoking it later erases the stored ciphertext but cannot un-see what was already opened.</p>61          </Callout>62        </div>63      </Dialog>64    );65  }66  if (sent) {67    return <Dialog title="Shared" onClose={onClose} footer={<Btn variant="primary" onClick={onClose}>Done</Btn>}><p>{recipient!.handle} will find “{item.title || "Untitled"}” under Shared. It was encrypted for their account key and signed with yours.</p></Dialog>;68  }69  return (70    <Dialog title={`Share “${item.title || "Untitled"}”`} onClose={onClose}71      footer={<><Btn onClick={onClose}>Cancel</Btn><Btn variant="primary" icon="share" onClick={share} busy={act.busy} disabled={mode === "account" && !recipient} data-testid="share-go">{mode === "link" ? "Create link" : "Share"}</Btn></>}>72      <div className="stack">73        <Segmented label="Share method" value={mode} onChange={setMode} options={[{ value: "link", label: "By link" }, { value: "account", label: "To an account" }]} />74        <p className="muted">A copy of the item as it is now (without attachments or password history) is encrypted in this browser. {mode === "link" ? "A link carrying the key is created." : "Only the recipient's account can decrypt it."} Later edits are not shared.</p>75        {mode === "account" && <AccountLookup value={recipient} onChange={setRecipient} />}76        <div className="grid-2">77          <Field label="Expires after"><select className="input" value={expiry} onChange={(e) => setExpiry(Number(e.target.value))} data-testid="share-expiry">{EXPIRY_OPTIONS.map((o) => <option key={o.value} value={o.value}>{o.label}</option>)}</select></Field>78          <Field label="Maximum views" hint={mode === "account" ? "Empty = unlimited until expiry" : "1 = one-time link"}><input className="input" type="number" min={1} max={1000} value={maxViews} onChange={(e) => setMaxViews(e.target.value)} data-testid="share-views" /></Field>79        </div>80        <p className="fine">Sharing is a sensitive action: your passkey is requested if it was not used in the last few minutes.</p>81        <ErrorText text={act.error} />82      </div>83    </Dialog>84  );85}8687function ReceivedDialog({ share, onClose }: { share: any; onClose: () => void }) {88  const [opened, setOpened] = useState<Awaited<ReturnType<typeof engine.openShare>> | null>(null);89  const vaults = engine.vaults().filter(canWrite);90  const [vaultId, setVaultId] = useState(vaults[0]?.vaultId ?? "");91  const act = useAction(), save = useAction();92  const open = () => act.run(async () => { setOpened(await engine.openShare(share.id)); });93  const limited = share.maxViews != null;94  return (95    <Dialog title={opened ? opened.item.title || "Shared item" : `Shared by ${share.senderHandle}`} onClose={onClose} wide={!!opened}>96      {!opened ? (97        <div className="stack">98          <p>Opening counts as a view{limited ? ` (${share.views} of ${share.maxViews} used)` : ""} and is recorded in the sender's activity log.</p>99          <ErrorText text={act.error} />100          <div className="row end"><Btn onClick={onClose}>Cancel</Btn><Btn variant="primary" onClick={open} busy={act.busy} data-autofocus data-testid="received-open">Open</Btn></div>101        </div>102      ) : (103        <div className="stack">104          <Callout kind={opened.fingerprintKnown ? "ok" : "info"} title={`Signed by ${opened.from}`}>105            <p>{opened.fingerprintKnown ? "The signing key is the one this device already saw for this sender." : "First item from this sender on this device: their signing key is now remembered, and a later change will be refused."}</p>106          </Callout>107          <ItemBody item={opened.item} />108          <ErrorText text={save.error} />109          <div className="row end wrap">110            {vaults.length > 1 && <select className="input auto" value={vaultId} onChange={(e) => setVaultId(e.target.value)} aria-label="Target vault">{vaults.map((v) => <option key={v.vaultId} value={v.vaultId}>{v.meta.name}</option>)}</select>}111            <Btn onClick={onClose}>Close</Btn>112            <Btn variant="primary" icon="download" busy={save.busy} disabled={!vaultId} data-testid="received-save" onClick={() => save.run(async () => {113              const now = new Date().toISOString();114              await engine.saveItem(vaultId, null, { ...opened.item, favorite: false, attachments: [], passwordHistory: [], conflictOf: undefined, trashedAt: undefined, createdAt: now, updatedAt: now });115              toast("Saved to your vault", "ok"); onClose();116            })}>Save to vault</Btn>117          </div>118        </div>119      )}120    </Dialog>121  );122}123124export function RelayPage({ onBack }: { onBack: () => void }) {125  const [data, setData] = useState<{ sent: any[]; received: any[] } | null>(null);126  const [error, setError] = useState("");127  const [opening, setOpening] = useState<any>(null);128  const load = useCallback(async () => { try { setData(await engine.shares()); setError(""); } catch (e) { reportError(e); setError("The list of shares could not be loaded."); } }, []);129  useEffect(() => { void load(); return onLive(["shares", "activity"], () => void load()); }, [load]);130  const revoke = async (id: string) => { try { await engine.revokeShare(id); toast("Share revoked. The stored ciphertext was erased.", "ok"); await load(); } catch (e) { reportError(e); } };131  const status = (s: any) => s.revoked ? <Badge kind="danger">revoked</Badge> : s.expired ? <Badge>expired</Badge> : s.maxViews != null && s.views >= s.maxViews ? <Badge>used up</Badge> : <Badge kind="ok">active</Badge>;132  const live = (s: any) => !s.revoked && !s.expired && !(s.maxViews != null && s.views >= s.maxViews);133  return (134    <div className="page" data-testid="relay-page">135      <PageHead title="Shared" sub="One-off encrypted copies of items, sent to an account or by link. For lasting shared access, add a member to a vault instead." onBack={onBack} actions={<Btn icon="refresh" small onClick={load}>Refresh</Btn>} />136      <ErrorText text={error} />137      {!data && !error ? <Skeleton rows={3} /> : data && (138        <>139          <Section title="Received">140            {data.received.length === 0 ? <Empty icon="inbox" title="Nothing shared with you">Items other members send to your handle appear here until they expire.</Empty> : (141              <ul className="rows" data-testid="received-list">142                {data.received.map((s) => (143                  <li key={s.id} className="row-card">144                    <div className="row-main"><strong>From {s.senderHandle}</strong><span className="muted">Received {relTime(s.createdAt)} · expires {dateTime(s.expiresAt)}{s.maxViews != null ? ` · ${s.views}/${s.maxViews} views` : ""}</span></div>145                    <Btn small variant="primary" onClick={() => setOpening(s)} disabled={!live(s)} data-testid="received-row-open">Open</Btn>146                  </li>147                ))}148              </ul>149            )}150          </Section>151          <Section title="Sent">152            {data.sent.length === 0 ? <Empty icon="share" title="Nothing shared yet">Open an item and choose Share… to send a one-off encrypted copy.</Empty> : (153              <ul className="rows" data-testid="sent-list">154                {data.sent.map((s) => (155                  <li key={s.id} className="row-card">156                    <div className="row-main">157                      <strong>{s.kind === "link" ? "Link" : `To ${s.recipientHandle ?? "an account"}`} {status(s)}</strong>158                      <span className="muted">Created {relTime(s.createdAt)} · {s.views}{s.maxViews != null ? ` of ${s.maxViews}` : ""} view{s.views === 1 && s.maxViews == null ? "" : "s"} · expires {dateTime(s.expiresAt)}</span>159                    </div>160                    {live(s) && <Btn small variant="danger" onClick={() => revoke(s.id)} data-testid="share-revoke">Revoke</Btn>}161                  </li>162                ))}163              </ul>164            )}165          </Section>166          <p className="fine">The server never sees what was shared — only who shared with whom, when, and how many times it was opened. Titles are not listed here for that reason.</p>167        </>168      )}169      {opening && <ReceivedDialog share={opening} onClose={() => { setOpening(null); void load(); }} />}170    </div>171  );172}173
Files main
Menu

Theme