From ef15b21495fb71be062332a7f59d53b50c0d856a Mon Sep 17 00:00:00 2001 From: pasta Date: Sat, 26 Sep 2026 15:47:55 -0500 Subject: [PATCH 1/5] feat(web): top up this browser's key budget in place MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Settings → This browser's key gains Top up key budget: an IdentityKeyLimitsUpdate that adds budget and optionally pushes the expiry out on the same key. The master key comes from the identity file or recovery phrase through the same derivation as import and revoke, is checked to be a live MASTER key, signs once and is dropped. Keys that are not Forge browser keys are refused. The new limits are read back from the chain and replace the session's keyLimits. Renew stays as the fallback, with copy on the difference. Co-Authored-By: Claude Opus 5.5 (1M context) --- forge-web/components/key-top-up-dialog.tsx | 222 +++++++++++++++++++++ forge-web/components/keys-panel.tsx | 25 ++- forge-web/contexts/auth-context.tsx | 16 +- forge-web/lib/auth/controller.ts | 67 +++++-- forge-web/lib/auth/index.ts | 12 +- forge-web/lib/auth/key-top-up.test.ts | 73 +++++++ forge-web/lib/auth/limited-key.ts | 118 ++++++++++- forge-web/lib/sdk/cost.ts | 6 + forge-web/lib/sdk/index.ts | 1 + 9 files changed, 517 insertions(+), 23 deletions(-) create mode 100644 forge-web/components/key-top-up-dialog.tsx create mode 100644 forge-web/lib/auth/key-top-up.test.ts diff --git a/forge-web/components/key-top-up-dialog.tsx b/forge-web/components/key-top-up-dialog.tsx new file mode 100644 index 000000000..dad88c940 --- /dev/null +++ b/forge-web/components/key-top-up-dialog.tsx @@ -0,0 +1,222 @@ +'use client' + +/** + * Top up this browser's key (`ux-dx-spec.md` §2.3; `IdentityKeyLimitsUpdate`, protocol 14): + * add budget to the key this browser signs with and, optionally, push its expiry out. The key + * id and the private key stay the same. The master key comes from the identity file or the + * recovery phrase, signs this one update, and is not stored (the file text lives in a ref, not + * React state, and is dropped after use; the caller mounts this only while it is open, so + * closing unmounts it and drops everything). + */ + +import { useRef, useState } from 'react' +import { CheckCircle2, KeyRound, Upload } from 'lucide-react' +import { useAuth } from '@/contexts/auth-context' +import { Dialog } from '@/components/ui/dialog' +import { Button } from '@/components/ui/button' +import { Field, Input, Textarea } from '@/components/ui/input' +import { CostPreview } from '@/components/ui/cost-preview' +import { ErrorBox } from '@/components/auth/protection-fields' +import { TOP_UP_DEFAULTS, masterMaterialFromFile, parseDashAmount, topUpExpiry } from '@/lib/auth' +import { KEY_LIMITS_UPDATE_CREDITS, previewCredits } from '@/lib/sdk' +import type { KeyLimits } from '@/lib/view/funds' +import { creditsAsDash, formatDate } from '@/lib/view/format' +import { cn, errorMessage } from '@/lib/utils' + +const DAY_MS = 24 * 60 * 60 * 1000 + +/** `yyyy-mm-dd` for a date input, in local time. */ +function isoDay(ms: number): string { + const d = new Date(ms) + return `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}` +} + +/** A date input's value as end-of-day local time (ms), or null when empty / invalid. */ +function fromIsoDay(v: string): number | null { + const m = /^(\d{4})-(\d{2})-(\d{2})$/.exec(v) + if (m === null) return null + return new Date(Number(m[1]), Number(m[2]) - 1, Number(m[3]), 23, 59, 0).getTime() +} + +export function KeyTopUpDialog({ onClose }: { onClose: () => void }): JSX.Element { + const { identity, keyLimits, topUpKey, isLoading } = useAuth() + const [amount, setAmount] = useState(String(TOP_UP_DEFAULTS.addDash)) + const current = keyLimits?.expiresAt ?? null + const suggested = Date.now() + TOP_UP_DEFAULTS.days * DAY_MS + const [extend, setExtend] = useState(current === null || current < suggested) + const [expiry, setExpiry] = useState(isoDay(suggested)) + const [mode, setMode] = useState<'file' | 'mnemonic'>('file') + const fileRef = useRef(null) + const fileInput = useRef(null) + const [fileName, setFileName] = useState('') + const [mnemonic, setMnemonic] = useState('') + const [error, setError] = useState(null) + const [done, setDone] = useState<{ before: KeyLimits | null; after: KeyLimits } | null>(null) + + let credits: bigint | null = null + let amountError: string | null = null + if (amount.trim() !== '') { + try { + credits = parseDashAmount(amount) + } catch (e) { + amountError = errorMessage(e) + } + } + let newExpiry: number | null = null + let expiryError: string | null = null + if (extend) { + try { + newExpiry = topUpExpiry(current, fromIsoDay(expiry)) + if (newExpiry === null) expiryError = 'pick a date later than the current expiry, or leave the expiry as it is' + } catch (e) { + expiryError = errorMessage(e) + } + } + const hasMaster = mode === 'file' ? fileName !== '' : mnemonic.trim() !== '' + const changes = credits !== null || newExpiry !== null + const ready = hasMaster && changes && amountError === null && expiryError === null && !isLoading + + const onFile = async (f: File): Promise => { + setError(null) + const text = await f.text() + try { + const m = masterMaterialFromFile(text) + if (m.identityId !== identity) throw new Error('that identity file is for another identity') + fileRef.current = text + setFileName(f.name) + } catch (e) { + fileRef.current = null + setFileName('') + setError(errorMessage(e)) + } + } + + const submit = async (): Promise => { + if (!ready) return + setError(null) + const before = keyLimits + try { + const input = mode === 'file' ? { fileText: fileRef.current ?? '' } : { mnemonic } + const after = await topUpKey(input, { addCredits: credits, expiresAt: newExpiry }) + fileRef.current = null + setMnemonic('') + setDone({ before, after }) + } catch (e) { + setError(errorMessage(e)) + } + } + + const dash = (c: bigint | null): string => (c === null ? '—' : `${creditsAsDash(Number(c))} DASH`) + + return ( + + {done ? ( +
+

+ Key limits updated on chain. +

+
+
+
Before
+
Now (read back from the chain)
+
Budget
+
{dash(done.before?.total ?? null)}
+
{dash(done.after.total)}
+
Left
+
{dash(done.before?.remaining ?? null)}
+
{dash(done.after.remaining)}
+
Expires
+
{done.before?.expiresAt ? formatDate(done.before.expiresAt) : '—'}
+
{done.after.expiresAt ? formatDate(done.after.expiresAt) : 'never'}
+
+

Your master key was used for this one update and was not stored.

+ +
+ ) : ( +
{ + e.preventDefault() + void submit() + }} + > +

+ Adds budget to the key this browser already signs with, so nothing here has to be re-imported. Your master key + signs this one update and is not stored. The fee comes from your identity balance. +

+ + setAmount(e.target.value)} className="font-mono" autoComplete="off" aria-invalid={amountError !== null} /> + + {amountError ?

{amountError}

: null} +
+ + {extend ? ( + + setExpiry(e.target.value)} aria-invalid={expiryError !== null} /> + + ) : null} + {expiryError ?

{expiryError}

: null} +
+ +
+ + Master key, used once + +
+ {(['file', 'mnemonic'] as const).map((m) => ( + + ))} +
+ {mode === 'file' ? ( + <> + + { + const f = e.target.files?.[0] + if (f) void onFile(f) + e.target.value = '' + }} + /> + + ) : ( + +