From 9040c426e8f8b5dbb9a80c87c557d9c3320d07b2 Mon Sep 17 00:00:00 2001 From: tyuXX Date: Thu, 26 Nov 2026 22:08:25 +0000 Subject: [PATCH] fix(client): fix xterm container overflow and IME ghost chars and add Passkey UI --- src/client/css/base.css | 44 +++++++- src/client/ts/dialogs.ts | 80 +++++++++++++++ src/client/ts/state.ts | 3 +- src/client/ts/views/auth-view.ts | 60 ++++++++++- src/client/ts/views/settings-view.ts | 90 ++++++++++++++++ src/client/ts/views/terminal-view.ts | 147 +++++++++++++++++++++++++-- src/client/ts/views/xterm-runtime.ts | 25 +++++ src/client/ts/webauthn.ts | 136 +++++++++++++++++++++++++ 8 files changed, 571 insertions(+), 14 deletions(-) create mode 100644 src/client/ts/webauthn.ts diff --git a/src/client/css/base.css b/src/client/css/base.css index 3379270..8c2fb2e 100644 --- a/src/client/css/base.css +++ b/src/client/css/base.css @@ -116,6 +116,8 @@ body { padding: 12px; max-width: 1400px; width: 100%; + min-width: 0; + overflow-x: hidden; margin: 0 auto; } @@ -142,6 +144,8 @@ body { border: 1px solid var(--border); padding: 12px; margin-bottom: 12px; + min-width: 0; + max-width: 100%; } .panel-region { @@ -267,7 +271,7 @@ body[data-safe-mode="true"] .mutating-action { input, select, -textarea { +textarea:not(.xterm-helper-textarea) { width: 100%; min-height: 40px; padding: 6px 8px; @@ -525,19 +529,53 @@ dialog::backdrop { } .term-shell { + width: 100%; + max-width: 100%; + min-width: 0; + overflow: hidden; + position: relative; border: 1px solid var(--border); background: var(--bg); contain: layout style paint; } .term-viewport { + position: relative; width: 100%; + max-width: 100%; + min-width: 0; height: 55dvh; - min-height: 260px; - padding: 4px; + min-height: 240px; + padding: 0; + overflow: hidden; background: var(--bg); } +.term-viewport .xterm { + width: 100%; + height: 100%; + padding: 4px; + overflow: hidden; +} + +.xterm .xterm-helper-textarea { + min-height: 0 !important; + width: 0 !important; + height: 0 !important; + padding: 0 !important; + border: 0 !important; + margin: 0 !important; +} + +.xterm .composition-view { + background: var(--bg-elevated) !important; + color: var(--accent) !important; +} + +.xterm .composition-view:empty { + display: none !important; +} + .touch-keybar { display: flex; flex-wrap: wrap; diff --git a/src/client/ts/dialogs.ts b/src/client/ts/dialogs.ts index 2c36b9d..9d5bd91 100644 --- a/src/client/ts/dialogs.ts +++ b/src/client/ts/dialogs.ts @@ -4,6 +4,7 @@ import { extractErrorMessage, type ClientAuthRequirements, } from './state.js'; +import { getPasskeyAssertion, isWebAuthnSupported } from './webauthn.js'; export interface DiffModalData { revisionId: number; @@ -32,6 +33,7 @@ export function promptStepUp( const totpMode = reqs?.totpMode ?? 'any'; const pwLabels = reqs?.passwordLabels ?? [{ id: 'pw-primary', label: 'Password' }]; const totpLabels = reqs?.totpLabels ?? [{ id: 'totp-primary', label: 'Authenticator' }]; + const passkeyCount = reqs?.passkeyCount ?? 0; descEl.textContent = policy === 'every-action' @@ -42,6 +44,40 @@ export function promptStepUp( const pwInputs: HTMLInputElement[] = []; const codeInputs: HTMLInputElement[] = []; + if (method === 'passkey') { + if (passkeyCount === 0) { + fieldsEl.append( + el( + 'p', + { class: 'warn-text' }, + 'Step-Up Method is set to Passkey, but no passkeys are enrolled yet.', + ), + ); + } else if (!isWebAuthnSupported()) { + fieldsEl.append( + el( + 'p', + { class: 'warn-text' }, + 'WebAuthn Passkeys require HTTPS or localhost.', + ), + ); + } + } + + let passkeyBtn: HTMLButtonElement | null = null; + if (passkeyCount > 0 && isWebAuthnSupported()) { + passkeyBtn = el( + 'button', + { + type: 'button', + class: method === 'passkey' ? 'btn btn-primary' : 'btn', + autofocus: method === 'passkey' ? true : undefined, + }, + 'Verify with Passkey', + ); + fieldsEl.append(passkeyBtn); + } + if (method === 'password' || method === 'both') { const count = pwMode === 'all' ? Math.max(1, pwLabels.length) : 1; for (let i = 0; i < count; i++) { @@ -85,9 +121,18 @@ export function promptStepUp( let settled = false; errEl.textContent = ''; + const submitBtn = form.querySelector('button[type="submit"]') as HTMLButtonElement | null; + if (submitBtn) { + submitBtn.hidden = method === 'passkey'; + } + const finish = (ok: boolean) => { if (settled) return; settled = true; + if (passkeyBtn && onPasskeyClick) { + passkeyBtn.removeEventListener('click', onPasskeyClick); + } + if (submitBtn) submitBtn.hidden = false; form.removeEventListener('submit', onSubmit); cancelBtn.removeEventListener('click', onCancel); dialog.removeEventListener('close', onClose); @@ -99,6 +144,41 @@ export function promptStepUp( const onCancel = () => finish(false); const onClose = () => finish(false); + const onPasskeyClick = passkeyBtn + ? async () => { + errEl.textContent = ''; + passkeyBtn!.disabled = true; + try { + const optsRes = await apiFetch<{ + challengeId: string; + options: Parameters[0]; + }>('/api/auth/passkeys/step-up/options', { + method: 'POST', + body: {}, + allowStepUpRetry: false, + }); + const assertion = await getPasskeyAssertion(optsRes.options); + const res = await apiFetch<{ elevatedUntil: number | null }>( + '/api/auth/passkeys/step-up/verify', + { + method: 'POST', + body: { challengeId: optsRes.challengeId, response: assertion }, + allowStepUpRetry: false, + }, + ); + onElevated(res.elevatedUntil); + finish(true); + } catch (err) { + errEl.textContent = extractErrorMessage(err); + passkeyBtn!.disabled = false; + } + } + : null; + + if (passkeyBtn && onPasskeyClick) { + passkeyBtn.addEventListener('click', onPasskeyClick); + } + const onSubmit = async (ev: Event) => { ev.preventDefault(); errEl.textContent = ''; diff --git a/src/client/ts/state.ts b/src/client/ts/state.ts index 824bcaf..2297f17 100644 --- a/src/client/ts/state.ts +++ b/src/client/ts/state.ts @@ -75,7 +75,7 @@ export interface ClientSecuritySettings { passwordMode: 'any' | 'all'; totpMode: 'any' | 'all'; stepUpPolicy: 'off' | 'every-action' | '5m' | '1h' | '24h' | 'session'; - stepUpMethod: 'totp' | 'password' | 'both'; + stepUpMethod: 'totp' | 'password' | 'both' | 'passkey'; elevateOnLogin: boolean; keepElevationOnSafeMode: boolean; enableEmergencySecretsBackup: boolean; @@ -89,6 +89,7 @@ export interface ClientAuthRequirements { totpMode: 'any' | 'all'; totpCount: number; totpLabels: Array<{ id: string; label: string }>; + passkeyCount: number; stepUpPolicy: ClientSecuritySettings['stepUpPolicy']; stepUpMethod: ClientSecuritySettings['stepUpMethod']; } diff --git a/src/client/ts/views/auth-view.ts b/src/client/ts/views/auth-view.ts index 3c45823..d183e36 100644 --- a/src/client/ts/views/auth-view.ts +++ b/src/client/ts/views/auth-view.ts @@ -4,6 +4,7 @@ import { extractErrorMessage, type ClientAuthRequirements, } from '../state.js'; +import { getPasskeyAssertion, isWebAuthnSupported } from '../webauthn.js'; interface BootstrapData { secretBase32: string; @@ -206,11 +207,66 @@ export async function renderAuthView( 'p', { class: 'muted' }, requireTotp - ? 'Authenticate with password and TOTP 2FA (or a recovery code).' - : 'TOTP login requirement is disabled in Security Settings — password sign-in only.', + ? 'Authenticate with a Passkey, or enter your password and TOTP 2FA (or recovery code).' + : 'TOTP login requirement is disabled — sign in with Passkey or password.', ), ); + const passkeyCount = reqs?.passkeyCount ?? 0; + if (passkeyCount > 0) { + const pkMsg = el('p', { class: 'form-msg err-text', 'aria-live': 'polite' }); + if (isWebAuthnSupported()) { + const pkBtn = el( + 'button', + { type: 'button', class: 'btn btn-primary', style: 'width:100%' }, + 'Sign In with Passkey', + ); + pkBtn.addEventListener('click', async () => { + pkMsg.textContent = ''; + pkBtn.disabled = true; + try { + const optsRes = await apiFetch<{ + challengeId: string; + options: Parameters[0]; + }>('/api/auth/passkeys/login/options', { + method: 'POST', + body: {}, + }); + const assertion = await getPasskeyAssertion(optsRes.options); + const verifyRes = await apiFetch<{ csrfToken: string }>('/api/auth/passkeys/login/verify', { + method: 'POST', + body: { + challengeId: optsRes.challengeId, + response: assertion, + initialSafeMode, + }, + }); + setCsrfToken(verifyRes.csrfToken); + await onAuthenticated(); + } catch (err) { + pkMsg.textContent = extractErrorMessage(err); + pkBtn.disabled = false; + } + }); + wrap.append( + el( + 'div', + { class: 'stack', style: 'margin-bottom:12px;padding-bottom:12px;border-bottom:1px solid var(--border)' }, + pkBtn, + pkMsg, + ), + ); + } else { + wrap.append( + el( + 'p', + { class: 'muted' }, + `${passkeyCount} passkey(s) enrolled — passkey login requires HTTPS or localhost.`, + ), + ); + } + } + const form = el('form', { class: 'stack' }); const userInput = el('input', { id: 'login-username', diff --git a/src/client/ts/views/settings-view.ts b/src/client/ts/views/settings-view.ts index cd06a24..c6edea3 100644 --- a/src/client/ts/views/settings-view.ts +++ b/src/client/ts/views/settings-view.ts @@ -7,6 +7,7 @@ import { type ClientSecuritySettings, type ClientState, } from '../state.js'; +import { createPasskeyCredential, isWebAuthnSupported } from '../webauthn.js'; interface SessionRow { idPrefix: string; @@ -31,6 +32,7 @@ interface AuditRow { interface FactorsData { passwords: Array<{ id: string; label: string; createdAt: number }>; totps: Array<{ id: string; label: string; createdAt: number }>; + passkeys: Array<{ id: string; name: string; transports: string[]; createdAt: number }>; unusedRecoveryCodes: number; security: ClientSecuritySettings; recoveryBackup: { @@ -205,6 +207,7 @@ export async function renderSettingsView( el('option', { value: 'totp', selected: sec.stepUpMethod === 'totp' ? true : undefined }, 'TOTP Authenticator'), el('option', { value: 'password', selected: sec.stepUpMethod === 'password' ? true : undefined }, 'Password only (no app switching on phone)'), el('option', { value: 'both', selected: sec.stepUpMethod === 'both' ? true : undefined }, 'Password + TOTP'), + el('option', { value: 'passkey', selected: sec.stepUpMethod === 'passkey' ? true : undefined }, 'Passkey / Biometric (WebAuthn)'), ); const applyPreset = (preset: 'relaxed' | 'balanced' | 'strict' | 'paranoid') => { @@ -488,6 +491,93 @@ export async function renderSettingsView( factorsGrid.append(pwPanel, totpPanel); root.append(factorsGrid); + // 3b. WebAuthn / Passkeys Management + const pkPanel = el('section', { class: 'panel panel-region' }); + pkPanel.append( + el('h2', {}, `Passkeys / WebAuthn (${factorsRes.passkeys.length})`), + el( + 'p', + { class: 'muted' }, + isWebAuthnSupported() + ? 'Enroll device biometrics or hardware security keys for one-tap passwordless sign-in and Step-Up verification.' + : 'Passkeys require HTTPS (e.g. Cloudflare Tunnel) or http://localhost — plain HTTP or raw IP URLs block navigator.credentials.', + ), + ); + const pkList = el('div', { class: 'stack' }); + const pkMsg = el('p', { class: 'form-msg' }); + for (const pk of factorsRes.passkeys) { + const rmBtn = el( + 'button', + { type: 'button', class: 'btn btn-sm btn-danger mutating-action' }, + 'Remove', + ); + rmBtn.addEventListener('click', async () => { + const ok = await confirmDialog('dialog-confirm', `Remove passkey "${pk.name}"?`); + if (!ok) return; + try { + await apiFetch(`/api/auth/factors/passkeys/${encodeURIComponent(pk.id)}`, { + method: 'DELETE', + }); + await onReloadState(); + } catch (err) { + pkMsg.className = 'form-msg err-text'; + pkMsg.textContent = extractErrorMessage(err); + } + }); + pkList.append( + el( + 'div', + { class: 'row-between' }, + el( + 'span', + { class: 'mono' }, + `${pk.name} (${pk.id.slice(0, 12)}…) — ${fmtTime(pk.createdAt)}`, + ), + rmBtn, + ), + ); + } + + const pkLabelInput = el('input', { placeholder: 'Passkey label (e.g. Pixel / Firefox / YubiKey)' }); + const addPkBtn = el( + 'button', + { + type: 'button', + class: 'btn btn-sm btn-primary mutating-action', + disabled: !isWebAuthnSupported() ? true : undefined, + }, + '+ Register Passkey', + ); + addPkBtn.addEventListener('click', async () => { + pkMsg.textContent = ''; + const label = pkLabelInput.value.trim() || `Passkey #${factorsRes.passkeys.length + 1}`; + try { + const optsRes = await apiFetch<{ + challengeId: string; + options: Parameters[0]; + }>('/api/auth/factors/passkeys/register/options', { + method: 'POST', + body: { label }, + }); + const credential = await createPasskeyCredential(optsRes.options); + await apiFetch('/api/auth/factors/passkeys/register/verify', { + method: 'POST', + body: { challengeId: optsRes.challengeId, response: credential }, + }); + await onReloadState(); + } catch (err) { + pkMsg.className = 'form-msg err-text'; + pkMsg.textContent = extractErrorMessage(err); + } + }); + + pkPanel.append( + pkList, + el('div', { class: 'row', style: 'margin-top:8px' }, el('div', { style: 'flex:1' }, pkLabelInput), addPkBtn), + pkMsg, + ); + root.append(pkPanel); + // 4. Local Emergency Secrets Backup Panel const rb = factorsRes.recoveryBackup; const backupPanel = el('section', { class: 'panel panel-region' }); diff --git a/src/client/ts/views/terminal-view.ts b/src/client/ts/views/terminal-view.ts index e1a728b..0c747f4 100644 --- a/src/client/ts/views/terminal-view.ts +++ b/src/client/ts/views/terminal-view.ts @@ -5,7 +5,12 @@ import { apiFetch } from '../api.js'; import { confirmDialog } from '../dialogs.js'; import { el, extractErrorMessage, fmtTime, type ClientState, type ServerEntry } from '../state.js'; import type { MultiplexWsClient } from '../ws-client.js'; -import { createFittedTerminal, ensureXtermCss, readXtermTheme } from './xterm-runtime.js'; +import { + clearTerminalComposition, + createFittedTerminal, + ensureXtermCss, + readXtermTheme, +} from './xterm-runtime.js'; interface PtySessionInfo { sessionId: string; @@ -316,6 +321,7 @@ export async function renderTerminalView( let term: Terminal | null = null; let fitAddon: FitAddon | null = null; + let suppressCompositionUntil = 0; const sendPtyInput = (raw: string) => { if (!current || current.exited) return; @@ -350,10 +356,12 @@ export async function renderTerminalView( ); const applyFontAndFit = () => { - if (!term || !fitAddon) return; + if (!term || !fitAddon || !termContainer.isConnected) return; term.options.fontSize = fontSize; term.options.theme = readXtermTheme(); fitAddon.fit(); + termContainer.scrollLeft = 0; + termContainer.scrollTop = 0; wsClient.send({ type: 'pty:resize', sessionId: current.sessionId, @@ -385,28 +393,38 @@ export async function renderTerminalView( await renderTerminalView(root, state, wsClient); }); - // Mobile Touch-Key Bar + // Mobile Touch-Key Bar (prevent pointer/mouse focus steal so Android IME does not jump or leave ghosts) const touchBar = el('div', { class: 'touch-keybar', role: 'toolbar', 'aria-label': 'Mobile Terminal Keys' }); + const keepTermFocus = (btn: HTMLButtonElement) => { + btn.addEventListener('pointerdown', (e) => e.preventDefault()); + btn.addEventListener('mousedown', (e) => e.preventDefault()); + }; const makeTouchBtn = (label: string, onPress: () => void) => { const btn = el('button', { type: 'button', class: 'touch-key' }, label); + keepTermFocus(btn); btn.addEventListener('click', () => { + if (term) clearTerminalComposition(term, termContainer); onPress(); term?.focus(); }); return btn; }; const ctrlBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Ctrl'); + keepTermFocus(ctrlBtn); ctrlBtn.addEventListener('click', () => { ctrlSticky = !ctrlSticky; ctrlBtn.classList.toggle('active', ctrlSticky); ctrlBtn.setAttribute('aria-pressed', ctrlSticky ? 'true' : 'false'); + if (term) clearTerminalComposition(term, termContainer); term?.focus(); }); const altBtn = el('button', { type: 'button', class: 'touch-key', 'aria-pressed': 'false' }, 'Alt'); + keepTermFocus(altBtn); altBtn.addEventListener('click', () => { altSticky = !altSticky; altBtn.classList.toggle('active', altSticky); altBtn.setAttribute('aria-pressed', altSticky ? 'true' : 'false'); + if (term) clearTerminalComposition(term, termContainer); term?.focus(); }); @@ -416,6 +434,7 @@ export async function renderTerminalView( ctrlBtn, altBtn, makeTouchBtn('Ctrl+C', () => sendPtyInput('\x03')), + makeTouchBtn('Ctrl+X', () => sendPtyInput('\x18')), makeTouchBtn('↑', () => sendPtyInput('\x1b[A')), makeTouchBtn('↓', () => sendPtyInput('\x1b[B')), makeTouchBtn('←', () => sendPtyInput('\x1b[D')), @@ -451,7 +470,91 @@ export async function renderTerminalView( term = created.term; fitAddon = created.fitAddon; + const consumeStickyText = (text: string): boolean => { + if (!ctrlSticky && !altSticky) return false; + if (!text) return false; + const ch = text.slice(-1); + suppressCompositionUntil = Date.now() + 140; + sendPtyInput(ch); + if (term) { + clearTerminalComposition(term, termContainer); + window.setTimeout(() => { + if (term && termContainer.isConnected) clearTerminalComposition(term, termContainer); + }, 20); + } + return true; + }; + + const ta = term.textarea; + const textareaCleanups: Array<() => void> = []; + if (ta) { + const addTa = ( + evt: K, + handler: (e: HTMLElementEventMap[K]) => void, + ) => { + ta.addEventListener(evt, handler as EventListener, true); + textareaCleanups.push(() => ta.removeEventListener(evt, handler as EventListener, true)); + }; + + addTa('keydown', (ev) => { + if ((ctrlSticky || altSticky) && !ev.ctrlKey && !ev.altKey && !ev.metaKey && ev.key.length === 1) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + consumeStickyText(ev.key); + } + }); + + addTa('beforeinput', (ev) => { + const ie = ev as InputEvent; + if (Date.now() < suppressCompositionUntil) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + return; + } + if ((ctrlSticky || altSticky) && ie.data && consumeStickyText(ie.data)) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + } + }); + + addTa('compositionupdate', (ev) => { + const ce = ev as CompositionEvent; + if (Date.now() < suppressCompositionUntil) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + clearTerminalComposition(term!, termContainer); + return; + } + if ((ctrlSticky || altSticky) && ce.data && consumeStickyText(ce.data)) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + } + }); + + addTa('input', (ev) => { + if (Date.now() < suppressCompositionUntil) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + clearTerminalComposition(term!, termContainer); + } + }); + + addTa('compositionend', (ev) => { + if (Date.now() < suppressCompositionUntil) { + ev.preventDefault(); + ev.stopImmediatePropagation(); + clearTerminalComposition(term!, termContainer); + return; + } + window.setTimeout(() => { + const comp = termContainer.querySelector('.composition-view'); + if (comp && !comp.textContent) comp.classList.remove('active'); + }, 30); + }); + } + const dataDisposable = term.onData((data) => { + if (Date.now() < suppressCompositionUntil) return; sendPtyInput(data); }); @@ -464,11 +567,35 @@ export async function renderTerminalView( }); }); - const onWindowResize = () => { - if (!termContainer.isConnected) return; - fitAddon?.fit(); + let fitRaf: number | null = null; + let lastFitCols = term.cols; + let lastFitRows = term.rows; + const scheduleFit = () => { + if (fitRaf !== null) return; + fitRaf = window.requestAnimationFrame(() => { + fitRaf = null; + if (!term || !fitAddon || !termContainer.isConnected) return; + fitAddon.fit(); + termContainer.scrollLeft = 0; + termContainer.scrollTop = 0; + if (term.cols !== lastFitCols || term.rows !== lastFitRows) { + lastFitCols = term.cols; + lastFitRows = term.rows; + wsClient.send({ + type: 'pty:resize', + sessionId: current.sessionId, + cols: term.cols, + rows: term.rows, + }); + } + }); }; - window.addEventListener('resize', onWindowResize); + + window.addEventListener('resize', scheduleFit); + window.visualViewport?.addEventListener('resize', scheduleFit); + const ro = + typeof ResizeObserver !== 'undefined' ? new ResizeObserver(() => scheduleFit()) : null; + ro?.observe(termContainer); const unsubFrame = wsClient.onFrame((frame: ServerWsFrame) => { if (!term || !termContainer.isConnected) return; @@ -486,8 +613,12 @@ export async function renderTerminalView( }); currentCleanup = () => { + if (fitRaf !== null) window.cancelAnimationFrame(fitRaf); unsubFrame(); - window.removeEventListener('resize', onWindowResize); + ro?.disconnect(); + window.removeEventListener('resize', scheduleFit); + window.visualViewport?.removeEventListener('resize', scheduleFit); + for (const fn of textareaCleanups) fn(); dataDisposable.dispose(); resizeDisposable.dispose(); term?.dispose(); diff --git a/src/client/ts/views/xterm-runtime.ts b/src/client/ts/views/xterm-runtime.ts index 38eaf3a..60a9198 100644 --- a/src/client/ts/views/xterm-runtime.ts +++ b/src/client/ts/views/xterm-runtime.ts @@ -46,11 +46,30 @@ export function readXtermTheme(): ITheme { }; } +export function clearTerminalComposition(term: Terminal, container: HTMLElement): void { + const compView = container.querySelector('.composition-view'); + if (compView) { + compView.classList.remove('active'); + compView.textContent = ''; + } + + const ta = term.textarea; + if (ta && ta.value.length > 0) { + ta.value = ''; + // Re-focusing resets mobile IME composing buffer so ghost characters cannot linger + ta.blur(); + ta.focus({ preventScroll: true }); + } + term.refresh(0, Math.max(0, term.rows - 1)); +} + export function createFittedTerminal( container: HTMLElement, fontSize: number, ): { term: Terminal; fitAddon: FitAddon } { const term = new Terminal({ + cols: 40, + rows: 20, cursorBlink: true, fontFamily: 'ui-monospace, "Cascadia Code", "JetBrains Mono", Menlo, Consolas, monospace', fontSize, @@ -60,6 +79,12 @@ export function createFittedTerminal( const fitAddon = new FitAddon(); term.loadAddon(fitAddon); term.open(container); + if (term.textarea) { + term.textarea.setAttribute('autocomplete', 'off'); + term.textarea.setAttribute('enterkeyhint', 'send'); + } fitAddon.fit(); + container.scrollLeft = 0; + container.scrollTop = 0; return { term, fitAddon }; } diff --git a/src/client/ts/webauthn.ts b/src/client/ts/webauthn.ts new file mode 100644 index 0000000..28041ad --- /dev/null +++ b/src/client/ts/webauthn.ts @@ -0,0 +1,136 @@ +function bufferToBase64Url(buf: ArrayBuffer | Uint8Array): string { + const bytes = buf instanceof Uint8Array ? buf : new Uint8Array(buf); + let bin = ''; + for (let i = 0; i < bytes.length; i++) { + bin += String.fromCharCode(bytes[i]!); + } + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, ''); +} + +function base64UrlToUint8Array(b64url: string): Uint8Array { + const pad = b64url.length % 4 === 0 ? '' : '='.repeat(4 - (b64url.length % 4)); + const b64 = b64url.replace(/-/g, '+').replace(/_/g, '/') + pad; + const bin = atob(b64); + const out = new Uint8Array(new ArrayBuffer(bin.length)); + for (let i = 0; i < bin.length; i++) { + out[i] = bin.charCodeAt(i); + } + return out; +} + +export function isWebAuthnSupported(): boolean { + return ( + typeof window !== 'undefined' && + typeof window.PublicKeyCredential !== 'undefined' && + window.isSecureContext + ); +} + +interface RawCreationOptions { + rp: PublicKeyCredentialRpEntity; + user: { id: string; name: string; displayName: string }; + challenge: string; + pubKeyCredParams: PublicKeyCredentialParameters[]; + timeout?: number; + excludeCredentials?: Array<{ + id: string; + type?: PublicKeyCredentialType; + transports?: AuthenticatorTransport[]; + }>; + authenticatorSelection?: AuthenticatorSelectionCriteria; + attestation?: AttestationConveyancePreference; +} + +interface RawRequestOptions { + challenge: string; + timeout?: number; + rpId?: string; + allowCredentials?: Array<{ + id: string; + type?: PublicKeyCredentialType; + transports?: AuthenticatorTransport[]; + }>; + userVerification?: UserVerificationRequirement; +} + +export async function createPasskeyCredential( + rawOptions: RawCreationOptions, +): Promise> { + const publicKey: PublicKeyCredentialCreationOptions = { + rp: rawOptions.rp, + user: { + id: base64UrlToUint8Array(rawOptions.user.id), + name: rawOptions.user.name, + displayName: rawOptions.user.displayName, + }, + challenge: base64UrlToUint8Array(rawOptions.challenge), + pubKeyCredParams: rawOptions.pubKeyCredParams, + timeout: rawOptions.timeout, + authenticatorSelection: rawOptions.authenticatorSelection, + attestation: rawOptions.attestation ?? 'none', + excludeCredentials: (rawOptions.excludeCredentials ?? []).map((c) => ({ + id: base64UrlToUint8Array(c.id), + type: c.type ?? 'public-key', + transports: c.transports, + })), + }; + + const cred = (await navigator.credentials.create({ publicKey })) as PublicKeyCredential | null; + if (!cred) { + throw new Error('Passkey creation cancelled or returned empty credential'); + } + const att = cred.response as AuthenticatorAttestationResponse & { + getTransports?: () => string[]; + }; + return { + id: cred.id, + rawId: bufferToBase64Url(cred.rawId), + type: cred.type, + authenticatorAttachment: + (cred as PublicKeyCredential & { authenticatorAttachment?: string }).authenticatorAttachment ?? + undefined, + clientExtensionResults: cred.getClientExtensionResults?.() ?? {}, + response: { + clientDataJSON: bufferToBase64Url(att.clientDataJSON), + attestationObject: bufferToBase64Url(att.attestationObject), + transports: typeof att.getTransports === 'function' ? att.getTransports() : [], + }, + }; +} + +export async function getPasskeyAssertion( + rawOptions: RawRequestOptions, +): Promise> { + const publicKey: PublicKeyCredentialRequestOptions = { + challenge: base64UrlToUint8Array(rawOptions.challenge), + timeout: rawOptions.timeout, + rpId: rawOptions.rpId, + userVerification: rawOptions.userVerification ?? 'preferred', + allowCredentials: (rawOptions.allowCredentials ?? []).map((c) => ({ + id: base64UrlToUint8Array(c.id), + type: c.type ?? 'public-key', + transports: c.transports, + })), + }; + + const cred = (await navigator.credentials.get({ publicKey })) as PublicKeyCredential | null; + if (!cred) { + throw new Error('Passkey verification cancelled'); + } + const assertion = cred.response as AuthenticatorAssertionResponse; + return { + id: cred.id, + rawId: bufferToBase64Url(cred.rawId), + type: cred.type, + authenticatorAttachment: + (cred as PublicKeyCredential & { authenticatorAttachment?: string }).authenticatorAttachment ?? + undefined, + clientExtensionResults: cred.getClientExtensionResults?.() ?? {}, + response: { + clientDataJSON: bufferToBase64Url(assertion.clientDataJSON), + authenticatorData: bufferToBase64Url(assertion.authenticatorData), + signature: bufferToBase64Url(assertion.signature), + userHandle: assertion.userHandle ? bufferToBase64Url(assertion.userHandle) : undefined, + }, + }; +}