Implement code word based remote authentication (#1)
Add comprehensive remote authentication system allowing users to log in from one device by authenticating from another trusted device. Features include: - Proof of Work (PoW) protection using PBKDF2-SHA512 to prevent abuse - Simple pairing codes (3 words) protected by dynamic PoW difficulty - Autocomplete pairing code input with error checking - Real-time WebSocket communication between devices Unlike device addition links and reset links with QR codes that only allow adding an authentication method, and that work offline over the duration of several days, this mechanism is strictly online, with 5 minute time limit.
This commit is contained in:
@@ -132,7 +132,6 @@ async function handleTerminateSession(session) {
|
||||
<RegistrationLinkModal
|
||||
v-if="showRegModal"
|
||||
:endpoint="`/auth/api/admin/orgs/${selectedUser.org_uuid}/users/${selectedUser.uuid}/create-link`"
|
||||
:auto-copy="false"
|
||||
:user-name="userDetail?.display_name || selectedUser.display_name"
|
||||
@close="$emit('closeRegModal')"
|
||||
@copied="onLinkCopied"
|
||||
|
||||
@@ -422,9 +422,9 @@ th {
|
||||
}
|
||||
|
||||
.qr-code {
|
||||
border: 1px solid var(--color-border);
|
||||
padding: 0.75rem;
|
||||
background: var(--color-surface);
|
||||
padding: 1rem;
|
||||
background: #fff;
|
||||
box-shadow: var(--shadow-soft);
|
||||
}
|
||||
|
||||
.link-container,
|
||||
|
||||
@@ -4,18 +4,17 @@
|
||||
<h1>📱 Add Another Device</h1>
|
||||
<p class="view-lede">Generate a one-time link to set up passkeys on a new device.</p>
|
||||
</header>
|
||||
<RegistrationLinkModal
|
||||
inline
|
||||
:endpoint="'/auth/api/user/create-link'"
|
||||
:user-name="userName"
|
||||
:auto-copy="false"
|
||||
:prefix-copy-with-user-name="!!userName"
|
||||
show-close-in-inline
|
||||
@copied="onCopied"
|
||||
/>
|
||||
<div class="button-row" style="margin-top:1rem;">
|
||||
<button @click="showModal = true" class="btn-primary">Generate Registration Link</button>
|
||||
<button @click="authStore.currentView = 'profile'" class="btn-secondary">Back to Profile</button>
|
||||
</div>
|
||||
<RegistrationLinkModal
|
||||
v-if="showModal"
|
||||
endpoint="/auth/api/user/create-link"
|
||||
:user-name="userName"
|
||||
@close="showModal = false"
|
||||
@copied="onCopied"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
|
||||
@@ -26,9 +25,10 @@ import RegistrationLinkModal from '@/components/RegistrationLinkModal.vue'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
const userName = ref(null)
|
||||
const showModal = ref(false)
|
||||
|
||||
const onCopied = () => {
|
||||
authStore.showMessage('Link copied to clipboard!', 'success', 2500)
|
||||
authStore.currentView = 'profile'
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
|
||||
@@ -1,9 +1,9 @@
|
||||
<template>
|
||||
<section class="view-root" data-view="profile">
|
||||
<header class="view-header">
|
||||
<h1>👋 Welcome!</h1>
|
||||
<h1>User Profile</h1>
|
||||
<Breadcrumbs :entries="breadcrumbEntries" />
|
||||
<p class="view-lede">Manage your account details and passkeys.</p>
|
||||
<p class="view-lede">Account dashboard for managing credentials and authenticating with other devices.</p>
|
||||
</header>
|
||||
|
||||
<section class="section-block">
|
||||
@@ -17,7 +17,20 @@
|
||||
update-endpoint="/auth/api/user/display-name"
|
||||
@saved="authStore.loadUserInfo()"
|
||||
@edit-name="openNameDialog"
|
||||
/>
|
||||
>
|
||||
<div class="remote-auth-inline">
|
||||
<label v-if="!showDeviceInfo" class="remote-auth-label">Code words from remote device:</label>
|
||||
<RemoteAuth
|
||||
ref="pairingEntry"
|
||||
title=""
|
||||
description=""
|
||||
placeholder="word word word"
|
||||
@completed="handlePairingCompleted"
|
||||
@error="handlePairingError"
|
||||
@device-info-visible="showDeviceInfo = $event"
|
||||
/>
|
||||
</div>
|
||||
</UserBasicInfo>
|
||||
</section>
|
||||
|
||||
<section class="section-block">
|
||||
@@ -84,11 +97,8 @@
|
||||
</section>
|
||||
<RegistrationLinkModal
|
||||
v-if="showRegLink"
|
||||
:endpoint="'/auth/api/user/create-link'"
|
||||
:auto-copy="false"
|
||||
:prefix-copy-with-user-name="false"
|
||||
endpoint="/auth/api/user/create-link"
|
||||
@close="showRegLink = false"
|
||||
@copied="showRegLink = false; authStore.showMessage('Link copied to clipboard!', 'success', 2500)"
|
||||
/>
|
||||
</section>
|
||||
</template>
|
||||
@@ -102,6 +112,7 @@ import Modal from '@/components/Modal.vue'
|
||||
import NameEditForm from '@/components/NameEditForm.vue'
|
||||
import SessionList from '@/components/SessionList.vue'
|
||||
import RegistrationLinkModal from '@/components/RegistrationLinkModal.vue'
|
||||
import RemoteAuth from '@/components/RemoteAuthPermit.vue'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { adminUiPath, makeUiHref } from '@/utils/settings'
|
||||
import passkey from '@/utils/passkey'
|
||||
@@ -116,6 +127,8 @@ const newName = ref('')
|
||||
const saving = ref(false)
|
||||
const hoveredCredentialUuid = ref(null)
|
||||
const hoveredSession = ref(null)
|
||||
const showDeviceInfo = ref(false)
|
||||
const pairingEntry = ref(null)
|
||||
|
||||
watch(showNameDialog, (newVal) => { if (newVal) newName.value = authStore.userInfo?.user?.user_name || '' })
|
||||
|
||||
@@ -138,6 +151,19 @@ const addNewCredential = async () => {
|
||||
}
|
||||
}
|
||||
|
||||
const handlePairingCompleted = () => {
|
||||
authStore.showMessage('The other device is now signed in!', 'success', 4000)
|
||||
// Reset the form after a delay
|
||||
setTimeout(() => pairingEntry.value?.reset(), 3000)
|
||||
}
|
||||
|
||||
const handlePairingError = (message) => {
|
||||
// Error is already shown in the component, optionally show global message for severe errors
|
||||
if (!message.includes('cancelled')) {
|
||||
authStore.showMessage(message, 'error', 4000)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (credential) => {
|
||||
const credentialId = credential?.credential_uuid
|
||||
if (!credentialId) return
|
||||
@@ -199,5 +225,7 @@ const saveName = async () => {
|
||||
.logout-row { gap: 1rem; }
|
||||
.logout-row.single { justify-content: flex-start; }
|
||||
.logout-note { margin: 0.75rem 0 0; color: var(--color-text-muted); font-size: 0.875rem; }
|
||||
.remote-auth-inline { display: flex; flex-direction: column; gap: 0.5rem; }
|
||||
.remote-auth-label { display: block; margin: 0; font-size: 0.875rem; color: var(--color-text-muted); font-weight: 500; }
|
||||
@media (max-width: 720px) { .logout-button { width: 100%; } }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
<template>
|
||||
<div class="qr-display">
|
||||
<div class="qr-section">
|
||||
<a :href="url" @click.prevent="copyLink" class="qr-link" title="Click to copy link">
|
||||
<canvas ref="qrCanvas" class="qr-code"></canvas>
|
||||
<div v-if="showLink && url" class="link-text">{{ displayUrl }}</div>
|
||||
</a>
|
||||
</div>
|
||||
|
||||
<div v-if="showCopyToast" class="copy-toast">
|
||||
✓ Link copied to clipboard
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, watch, nextTick, computed } from 'vue'
|
||||
import QRCode from 'qrcode/lib/browser'
|
||||
|
||||
const props = defineProps({
|
||||
url: { type: String, required: true },
|
||||
showLink: { type: Boolean, default: false }
|
||||
})
|
||||
|
||||
const emit = defineEmits(['copied'])
|
||||
|
||||
const qrCanvas = ref(null)
|
||||
const showCopyToast = ref(false)
|
||||
|
||||
let copyToastTimer = null
|
||||
|
||||
const displayUrl = computed(() => {
|
||||
if (!props.url) return ''
|
||||
return props.url.replace(/^https?:\/\//, '')
|
||||
})
|
||||
|
||||
function drawQR() {
|
||||
if (!props.url || !qrCanvas.value) {
|
||||
return
|
||||
}
|
||||
|
||||
try {
|
||||
// Clear the canvas first
|
||||
const ctx = qrCanvas.value.getContext('2d')
|
||||
ctx.clearRect(0, 0, qrCanvas.value.width, qrCanvas.value.height)
|
||||
|
||||
// Generate QR code synchronously
|
||||
QRCode.toCanvas(qrCanvas.value, props.url, {
|
||||
scale: 6,
|
||||
margin: 0,
|
||||
color: {
|
||||
dark: '#000000',
|
||||
light: '#FFFFFF'
|
||||
}
|
||||
})
|
||||
|
||||
// Remove any inline styles added by QRCode library immediately
|
||||
qrCanvas.value.removeAttribute('style')
|
||||
} catch (err) {
|
||||
console.error('QR code generation failed:', err)
|
||||
}
|
||||
}
|
||||
|
||||
async function copyLink() {
|
||||
if (!props.url) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(props.url)
|
||||
showCopyToast.value = true
|
||||
emit('copied')
|
||||
|
||||
if (copyToastTimer) clearTimeout(copyToastTimer)
|
||||
copyToastTimer = setTimeout(() => {
|
||||
showCopyToast.value = false
|
||||
}, 2000)
|
||||
} catch (err) {
|
||||
console.error('Failed to copy link:', err)
|
||||
}
|
||||
}
|
||||
|
||||
// Watch for URL changes
|
||||
watch(() => props.url, () => {
|
||||
drawQR()
|
||||
}, { immediate: true })
|
||||
|
||||
// Watch for canvas ref becoming available
|
||||
watch(qrCanvas, () => {
|
||||
if (qrCanvas.value && props.url) {
|
||||
drawQR()
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.qr-display {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
}
|
||||
|
||||
.qr-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.qr-link {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
text-decoration: none;
|
||||
color: inherit;
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.qr-code {
|
||||
display: block;
|
||||
width: 200px;
|
||||
height: 200px;
|
||||
max-width: 100%;
|
||||
object-fit: contain;
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
background: #ffffff;
|
||||
cursor: pointer;
|
||||
}
|
||||
|
||||
.link-text {
|
||||
padding: 0.5rem;
|
||||
font-size: 0.75rem;
|
||||
color: var(--color-text-muted);
|
||||
font-family: monospace;
|
||||
word-break: break-all;
|
||||
line-height: 1.2;
|
||||
transition: color 0.2s ease;
|
||||
}
|
||||
|
||||
.qr-link:hover .link-text {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.copy-toast {
|
||||
position: absolute;
|
||||
top: -2rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: var(--color-success);
|
||||
color: white;
|
||||
padding: 0.5rem 1rem;
|
||||
border-radius: var(--radius-sm);
|
||||
font-size: 0.875rem;
|
||||
z-index: 10;
|
||||
animation: fadeInOut 2s ease-in-out;
|
||||
}
|
||||
|
||||
@keyframes fadeInOut {
|
||||
0%, 100% { opacity: 0; }
|
||||
10%, 90% { opacity: 1; }
|
||||
}
|
||||
</style>
|
||||
@@ -1,147 +1,109 @@
|
||||
<template>
|
||||
<div v-if="!inline && url" class="dialog-overlay" @keydown.esc.prevent="$emit('close')">
|
||||
<div class="dialog-overlay" @keydown.esc.prevent="$emit('close')">
|
||||
<div class="device-dialog" role="dialog" aria-modal="true" aria-labelledby="regTitle">
|
||||
<div class="reg-header-row">
|
||||
<h2 id="regTitle" class="reg-title">
|
||||
📱 <span v-if="userName">Registration for {{ userName }}</span><span v-else>Device Registration Link</span>
|
||||
📱 <span v-if="userName">Registration for {{ userName }}</span><span v-else>Add Another Device</span>
|
||||
</h2>
|
||||
<button class="icon-btn" @click="$emit('close')" aria-label="Close">❌</button>
|
||||
</div>
|
||||
|
||||
<div class="device-link-section">
|
||||
<div class="qr-container">
|
||||
<a :href="url" @click.prevent="copy" class="qr-link">
|
||||
<canvas ref="qrCanvas" class="qr-code"></canvas>
|
||||
<p>{{ displayUrl }}</p>
|
||||
</a>
|
||||
<p class="reg-help">
|
||||
<span v-if="userName">The user should open this link on the device where they want to register.</span>
|
||||
<span v-else>Open or scan this link on the device you wish to register to your account.</span>
|
||||
<br><small>{{ expirationMessage }}</small>
|
||||
</p>
|
||||
<!-- Loading state -->
|
||||
<div v-if="loading" class="loading-state">
|
||||
<div class="spinner-small"></div>
|
||||
<span>Generating registration link...</span>
|
||||
</div>
|
||||
|
||||
<!-- Error state -->
|
||||
<div v-else-if="error" class="error-state">
|
||||
<p class="error-message">{{ error }}</p>
|
||||
<button class="btn-secondary" @click="generateLink">Retry</button>
|
||||
</div>
|
||||
|
||||
<!-- Success state with QR code and link -->
|
||||
<template v-else-if="linkUrl">
|
||||
<p class="reg-help">
|
||||
Scan this QR code on the new device, or copy the link and open it there.
|
||||
</p>
|
||||
|
||||
<QRCodeDisplay
|
||||
:url="linkUrl"
|
||||
:show-link="true"
|
||||
@copied="onCopied"
|
||||
/>
|
||||
|
||||
<p class="expiry-note" v-if="expiresAt">
|
||||
This link expires {{ formatDate(expiresAt).toLowerCase() }}.
|
||||
</p>
|
||||
</template>
|
||||
</div>
|
||||
|
||||
<div class="reg-actions">
|
||||
<button class="btn-secondary" @click="$emit('close')">Close</button>
|
||||
<button class="btn-primary" @click="copy">Copy Link</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div v-else-if="inline && url" class="registration-inline-wrapper">
|
||||
<div class="registration-inline-block section-block">
|
||||
<div class="section-header">
|
||||
<h2 class="inline-heading">📱 <span v-if="userName">Registration for {{ userName }}</span><span v-else>Device Registration Link</span></h2>
|
||||
</div>
|
||||
<div class="section-body">
|
||||
<div class="device-link-section">
|
||||
<div class="qr-container">
|
||||
<a :href="url" @click.prevent="copy" class="qr-link">
|
||||
<canvas ref="qrCanvas" class="qr-code"></canvas>
|
||||
<p>{{ displayUrl }}</p>
|
||||
</a>
|
||||
<p class="reg-help">
|
||||
<span v-if="userName">The user should open this link on the device where they want to register.</span>
|
||||
<span v-else>Open this link on the device you wish to connect with.</span>
|
||||
<br><small>{{ expirationMessage }}</small>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
<div class="button-row" style="margin-top:1rem;">
|
||||
<button class="btn-primary" @click="copy">Copy Link</button>
|
||||
<button v-if="showCloseInInline" class="btn-secondary" @click="$emit('close')">Close</button>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, onMounted, watch, computed, nextTick } from 'vue'
|
||||
import QRCode from 'qrcode/lib/browser'
|
||||
import { ref, onMounted } from 'vue'
|
||||
import QRCodeDisplay from '@/components/QRCodeDisplay.vue'
|
||||
import { apiJson } from '@/utils/api'
|
||||
import { formatDate } from '@/utils/helpers'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
import { apiJson, getUserFriendlyErrorMessage, shouldShowErrorToast } from '@/utils/api'
|
||||
|
||||
const authStore = useAuthStore()
|
||||
|
||||
const props = defineProps({
|
||||
endpoint: { type: String, required: true },
|
||||
autoCopy: { type: Boolean, default: true },
|
||||
userName: { type: String, default: null },
|
||||
inline: { type: Boolean, default: false },
|
||||
showCloseInInline: { type: Boolean, default: false },
|
||||
prefixCopyWithUserName: { type: Boolean, default: false }
|
||||
userName: { type: String, default: '' }
|
||||
})
|
||||
|
||||
const emit = defineEmits(['close','generated','copied'])
|
||||
const emit = defineEmits(['close', 'copied'])
|
||||
|
||||
const url = ref(null)
|
||||
const expires = ref(null)
|
||||
const qrCanvas = ref(null)
|
||||
const loading = ref(true)
|
||||
const error = ref(null)
|
||||
const linkUrl = ref(null)
|
||||
const expiresAt = ref(null)
|
||||
|
||||
const displayUrl = computed(() => url.value ? url.value.replace(/^[^:]+:\/\//,'') : '')
|
||||
async function generateLink() {
|
||||
loading.value = true
|
||||
error.value = null
|
||||
linkUrl.value = null
|
||||
expiresAt.value = null
|
||||
|
||||
const expirationMessage = computed(() => {
|
||||
const timeStr = formatDate(expires.value)
|
||||
return `⚠️ Expires ${timeStr.startsWith('In ') ? timeStr.substring(3) : timeStr} and can only be used once.`
|
||||
})
|
||||
|
||||
async function fetchLink() {
|
||||
try {
|
||||
const data = await apiJson(props.endpoint, { method: 'POST' })
|
||||
url.value = data.url
|
||||
expires.value = data.expires
|
||||
emit('generated', { url: data.url, expires: data.expires })
|
||||
await nextTick()
|
||||
drawQR()
|
||||
if (props.autoCopy) copy()
|
||||
} catch (e) {
|
||||
console.error('Failed to create link', e)
|
||||
if (shouldShowErrorToast(e)) {
|
||||
authStore.showMessage(getUserFriendlyErrorMessage(e), 'error', 4000)
|
||||
if (data.url) {
|
||||
linkUrl.value = data.url
|
||||
expiresAt.value = data.expires ? new Date(data.expires) : null
|
||||
} else {
|
||||
error.value = data.detail || 'Failed to generate link'
|
||||
}
|
||||
// Close the dialog on any error (auth cancelled, network error, etc.)
|
||||
emit('close')
|
||||
} catch (err) {
|
||||
error.value = err.message || 'Failed to generate link'
|
||||
} finally {
|
||||
loading.value = false
|
||||
}
|
||||
}
|
||||
|
||||
async function drawQR() {
|
||||
if (!url.value) return
|
||||
await nextTick()
|
||||
if (!qrCanvas.value) return
|
||||
QRCode.toCanvas(qrCanvas.value, url.value, { scale: 8 }, err => { if (err) console.error(err) })
|
||||
function onCopied() {
|
||||
emit('copied')
|
||||
}
|
||||
|
||||
async function copy() {
|
||||
if (!url.value) return
|
||||
let text = url.value
|
||||
if (props.prefixCopyWithUserName && props.userName) {
|
||||
text = `${props.userName} ${text}`
|
||||
}
|
||||
try {
|
||||
await navigator.clipboard.writeText(text)
|
||||
emit('copied', text)
|
||||
if (!props.inline) emit('close')
|
||||
} catch (_) {
|
||||
/* ignore */
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(fetchLink)
|
||||
watch(url, () => drawQR(), { flush: 'post' })
|
||||
|
||||
onMounted(() => {
|
||||
generateLink()
|
||||
})
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.icon-btn { background:none; border:none; cursor:pointer; font-size:1rem; opacity:.6; }
|
||||
.icon-btn:hover { opacity:1; }
|
||||
/* Minimal extra styling; main look comes from global styles */
|
||||
.qr-link { text-decoration:none; color:inherit; }
|
||||
.reg-header-row { display:flex; justify-content:space-between; align-items:center; gap:.75rem; margin-bottom:.75rem; }
|
||||
.reg-title { margin:0; font-size:1.25rem; font-weight:600; }
|
||||
.device-dialog { background: var(--color-surface); padding: 1.25rem 1.25rem 1rem; border-radius: var(--radius-md); max-width:480px; width:100%; box-shadow:0 6px 28px rgba(0,0,0,.25); }
|
||||
.qr-container { display:flex; flex-direction:column; align-items:center; gap:.5rem; }
|
||||
.qr-code { display:block; }
|
||||
.reg-help { margin-top:.5rem; margin-bottom:.75rem; font-size:.85rem; line-height:1.25rem; text-align:center; }
|
||||
.reg-actions { display:flex; justify-content:flex-end; gap:.5rem; margin-top:.25rem; }
|
||||
.registration-inline-block .qr-container { align-items:flex-start; }
|
||||
.registration-inline-block .reg-help { text-align:left; }
|
||||
.icon-btn { background: none; border: none; cursor: pointer; font-size: 1rem; opacity: .6; }
|
||||
.icon-btn:hover { opacity: 1; }
|
||||
.reg-header-row { display: flex; justify-content: space-between; align-items: center; gap: .75rem; margin-bottom: .75rem; }
|
||||
.reg-title { margin: 0; font-size: 1.25rem; font-weight: 600; }
|
||||
.device-dialog { background: var(--color-surface); padding: 1.25rem 1.25rem 1rem; border-radius: var(--radius-md); max-width: 480px; width: 100%; box-shadow: 0 6px 28px rgba(0,0,0,.25); }
|
||||
.reg-help { margin: .5rem 0 .75rem; font-size: .85rem; line-height: 1.4; text-align: center; color: var(--color-text-muted); }
|
||||
.reg-actions { display: flex; justify-content: flex-end; gap: .5rem; margin-top: 1rem; }
|
||||
.loading-state { display: flex; align-items: center; justify-content: center; gap: .5rem; padding: 2rem 0; color: var(--color-text-muted); }
|
||||
.error-state { text-align: center; padding: 1rem 0; }
|
||||
.error-message { color: var(--color-danger-text); margin-bottom: 1rem; }
|
||||
.expiry-note { font-size: .75rem; color: var(--color-text-muted); text-align: center; margin-top: .75rem; }
|
||||
</style>
|
||||
|
||||
@@ -0,0 +1,894 @@
|
||||
<template>
|
||||
<div class="pairing-entry">
|
||||
<form @submit.prevent="submitCode" class="pairing-form">
|
||||
<!-- Code input (shown when device info not yet received) -->
|
||||
<div v-if="!deviceInfo" class="input-row">
|
||||
<div class="input-wrapper" :class="{ 'has-error': serverError, 'is-complete': deviceInfo && !serverError, 'focused': isFocused }">
|
||||
<!-- Visual slot-machine display overlay -->
|
||||
<div class="slot-machine" :class="{ 'has-error': serverError, 'is-complete': deviceInfo && !serverError }" aria-hidden="true">
|
||||
<div v-for="(word, index) in displayWords" :key="index" class="slot-reel" :class="{ 'invalid-word': word.invalid, 'empty': !word.text && !word.typedPrefix }">
|
||||
<div class="slot-word">
|
||||
<template v-if="word.typedPrefix">
|
||||
<span class="typed-prefix">{{ word.typedPrefix }}</span><span class="hint-suffix">{{ word.hintSuffix }}</span>
|
||||
<span v-if="word.hasCursor" class="cursor-overlay" :style="{ '--cursor-pos': word.cursorCharIndex, '--word-len': word.wordLen }"></span>
|
||||
</template>
|
||||
<template v-else-if="word.text">
|
||||
{{ word.text }}
|
||||
<span v-if="word.hasCursor" class="cursor-overlay" :style="{ '--cursor-pos': word.cursorCharIndex, '--word-len': word.wordLen }"></span>
|
||||
</template>
|
||||
<template v-else>
|
||||
<span v-if="word.hasCursor" class="cursor-overlay" :style="{ '--cursor-pos': 0, '--word-len': 0 }"></span>
|
||||
</template>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<!-- Hidden input for actual text entry -->
|
||||
<input
|
||||
ref="inputRef"
|
||||
v-model="code"
|
||||
type="text"
|
||||
:placeholder="placeholder"
|
||||
autocomplete="off"
|
||||
autocapitalize="none"
|
||||
autocorrect="off"
|
||||
spellcheck="false"
|
||||
class="pairing-input hidden-input"
|
||||
@input="handleInput"
|
||||
@keydown="deferUpdateCursor"
|
||||
@mouseup="updateCursorPos"
|
||||
@focus="isFocused = true"
|
||||
@blur="isFocused = false"
|
||||
/>
|
||||
</div>
|
||||
<!-- Processing status beside input -->
|
||||
<div v-if="processingStatus" class="processing-status">
|
||||
<span class="processing-icon">{{ processingStatus === 'pow' ? '🔐' : '📡' }}</span>
|
||||
<span class="processing-spinner-small"></span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Device info display (shown when 3 words match a request) -->
|
||||
<div v-else-if="deviceInfo" class="device-info">
|
||||
<p class="device-permit-text">Permit {{ deviceInfo.action === 'register' ? 'registration' : 'login' }} to <strong>{{ deviceInfo.host }}</strong></p>
|
||||
<p class="device-meta">{{ deviceInfo.user_agent_pretty }}</p>
|
||||
|
||||
<p v-if="error" class="error-message" style="margin-top: 0.5rem;">{{ error }}</p>
|
||||
|
||||
<div class="button-row" style="margin-top: 0.75rem; display: flex; gap: 0.5rem;">
|
||||
<button
|
||||
type="button"
|
||||
class="btn-secondary"
|
||||
:disabled="loading"
|
||||
@click="deny"
|
||||
style="flex: 1;"
|
||||
>
|
||||
Deny
|
||||
</button>
|
||||
<button
|
||||
ref="submitBtnRef"
|
||||
type="submit"
|
||||
:disabled="loading"
|
||||
class="btn-primary"
|
||||
style="flex: 1;"
|
||||
>
|
||||
{{ loading ? 'Authenticating…' : 'Authorize' }}
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p v-if="error && !deviceInfo" class="error-message">{{ error }}</p>
|
||||
</form>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, nextTick, onMounted, onUnmounted, ref, watch } from 'vue'
|
||||
import { startAuthentication } from '@simplewebauthn/browser'
|
||||
import aWebSocket from '@/utils/awaitable-websocket'
|
||||
import { dec as b64dec, enc as b64enc } from '@/utils/base64url'
|
||||
import { getSettings } from '@/utils/settings'
|
||||
import { getUniqueMatch, isValidWord, isValidPrefix } from '@/utils/wordlist'
|
||||
import { solvePoW } from '@/utils/pow'
|
||||
import { useAuthStore } from '@/stores/auth'
|
||||
|
||||
const props = defineProps({
|
||||
title: { type: String, default: 'Help Another Device Sign In' },
|
||||
description: { type: String, default: 'Enter the code shown on the device that needs to sign in.' },
|
||||
placeholder: { type: String, default: 'Enter three words' },
|
||||
action: { type: String, default: 'login' } // 'login' or 'register'
|
||||
})
|
||||
|
||||
const emit = defineEmits(['completed', 'error', 'cancelled', 'back', 'register', 'deviceInfoVisible'])
|
||||
|
||||
// State
|
||||
const loading = ref(false)
|
||||
const error = ref(null)
|
||||
const settings = ref(null)
|
||||
let ws = null
|
||||
let authStore = null
|
||||
|
||||
// Try to get authStore (might fail if Pinia not installed in this app instance)
|
||||
try { authStore = useAuthStore() } catch (e) { /* ignore */ }
|
||||
|
||||
const inputRef = ref(null)
|
||||
const submitBtnRef = ref(null)
|
||||
const code = ref('')
|
||||
const isProcessing = ref(false)
|
||||
const processingStatus = ref('')
|
||||
const deviceInfo = ref(null)
|
||||
const autocompleteHint = ref('')
|
||||
|
||||
// Watch deviceInfo and emit visibility change
|
||||
watch(deviceInfo, (newVal) => {
|
||||
emit('deviceInfoVisible', !!newVal)
|
||||
})
|
||||
|
||||
const hasInvalidWord = ref(false)
|
||||
const serverError = ref(false)
|
||||
const cursorPos = ref(0)
|
||||
const isFocused = ref(false)
|
||||
let wsConnecting = false
|
||||
let currentChallenge = null
|
||||
let currentWork = null
|
||||
let powPromise = null
|
||||
let powSolution = null
|
||||
let lookupTimeout = null
|
||||
let lastLookedUpCode = null
|
||||
|
||||
// --- Helpers ---
|
||||
|
||||
function showMessage(message, type = 'info', duration = 3000) {
|
||||
if (authStore) {
|
||||
authStore.showMessage(message, type, duration)
|
||||
}
|
||||
}
|
||||
|
||||
async function fetchSettings() {
|
||||
try {
|
||||
const data = await getSettings()
|
||||
settings.value = data
|
||||
} catch (err) {
|
||||
console.warn('Unable to load settings', err)
|
||||
}
|
||||
}
|
||||
|
||||
// --- Input Mode Logic ---
|
||||
|
||||
function getWordAtCursor(input, cursor) {
|
||||
if (!input || cursor < 0) return { word: '', start: 0, end: 0 }
|
||||
let start = cursor, end = cursor
|
||||
while (start > 0 && /[a-zA-Z]/.test(input[start - 1])) start--
|
||||
while (end < input.length && /[a-zA-Z]/.test(input[end])) end++
|
||||
return { word: input.slice(start, end), start, end }
|
||||
}
|
||||
|
||||
function getWords(input) {
|
||||
return input.trim().split(/[.\s]+/).filter(w => w.length > 0)
|
||||
}
|
||||
|
||||
function countCompleteWords(input) {
|
||||
const endsWithSeparator = /[.\s]$/.test(input)
|
||||
const words = getWords(input)
|
||||
return endsWithSeparator ? words.length : Math.max(0, words.length - 1)
|
||||
}
|
||||
|
||||
function analyzeWords(input) {
|
||||
if (!input) return { valid: true, segments: [] }
|
||||
const segments = []
|
||||
const endsWithSeparator = /[.\s]$/.test(input)
|
||||
let match, regex = /([a-zA-Z]+)|([.\s]+)/g
|
||||
while ((match = regex.exec(input)) !== null) {
|
||||
if (match[1]) segments.push({ text: match[1], isWord: true, start: match.index })
|
||||
else if (match[2]) segments.push({ text: match[2], isWord: false, start: match.index })
|
||||
}
|
||||
const words = segments.filter(s => s.isWord)
|
||||
let allValid = true
|
||||
words.forEach((wordSeg, idx) => {
|
||||
const isLastWord = idx === words.length - 1
|
||||
const word = wordSeg.text.toLowerCase()
|
||||
if (isLastWord && !endsWithSeparator) wordSeg.invalid = !isValidPrefix(word)
|
||||
else wordSeg.invalid = !isValidWord(word)
|
||||
if (wordSeg.invalid) allValid = false
|
||||
})
|
||||
return { valid: allValid, segments }
|
||||
}
|
||||
|
||||
const coloredSegments = computed(() => {
|
||||
const { segments } = analyzeWords(code.value)
|
||||
return segments.map(s => ({ text: s.text, invalid: s.invalid || false }))
|
||||
})
|
||||
|
||||
function checkWordsValidity(input) { return analyzeWords(input).valid }
|
||||
function allWordsValid(input) { return getWords(input).length > 0 && getWords(input).every(w => isValidWord(w)) }
|
||||
|
||||
// Get the current partial word being typed (not yet a complete word)
|
||||
function getCurrentPartialWord(input) {
|
||||
const endsWithSeparator = /[.\s]$/.test(input)
|
||||
if (endsWithSeparator) return ''
|
||||
const match = input.match(/[a-zA-Z]+$/)
|
||||
return match ? match[0].toLowerCase() : ''
|
||||
}
|
||||
|
||||
// Calculate cursor position in the normalized display (wordIndex, charIndex within word)
|
||||
// Returns { wordIndex: number, charIndex: number } where charIndex is position within the word text
|
||||
function calcDisplayCursor(input, rawCursorPos) {
|
||||
if (!input || rawCursorPos === 0) {
|
||||
return { wordIndex: 0, charIndex: 0 }
|
||||
}
|
||||
|
||||
// Parse input to find word boundaries
|
||||
const beforeCursor = input.slice(0, rawCursorPos)
|
||||
const wordMatches = [...beforeCursor.matchAll(/[a-zA-Z]+/g)]
|
||||
|
||||
// Check if cursor is in whitespace after words
|
||||
const endsWithSeparator = /[.\s]$/.test(beforeCursor)
|
||||
|
||||
if (wordMatches.length === 0) {
|
||||
// No words before cursor, cursor is at start of first word
|
||||
return { wordIndex: 0, charIndex: 0 }
|
||||
}
|
||||
|
||||
const lastMatch = wordMatches[wordMatches.length - 1]
|
||||
const lastMatchEnd = lastMatch.index + lastMatch[0].length
|
||||
|
||||
if (endsWithSeparator || rawCursorPos > lastMatchEnd) {
|
||||
// Cursor is after the last word (in whitespace), so it's at start of next word
|
||||
return { wordIndex: Math.min(wordMatches.length, 2), charIndex: 0 }
|
||||
}
|
||||
|
||||
// Cursor is within the last word
|
||||
const charIndex = rawCursorPos - lastMatch.index
|
||||
return { wordIndex: wordMatches.length - 1, charIndex: charIndex }
|
||||
}
|
||||
|
||||
// Compute display words for slot-machine overlay (always 3 slots)
|
||||
const displayWords = computed(() => {
|
||||
const words = getWords(code.value)
|
||||
const result = []
|
||||
|
||||
// Get analysis for validation
|
||||
const { segments } = analyzeWords(code.value)
|
||||
const wordSegments = segments.filter(s => s.isWord)
|
||||
|
||||
// Get current partial word and autocomplete hint
|
||||
const partialWord = getCurrentPartialWord(code.value)
|
||||
const hint = autocompleteHint.value
|
||||
const endsWithSeparator = /[.\s]$/.test(code.value)
|
||||
|
||||
// Calculate where cursor should be displayed
|
||||
const cursor = calcDisplayCursor(code.value, cursorPos.value)
|
||||
|
||||
// Always show exactly 3 slots
|
||||
for (let i = 0; i < 3; i++) {
|
||||
const isCursorSlot = cursor.wordIndex === i
|
||||
|
||||
if (i < words.length) {
|
||||
const word = words[i].toLowerCase()
|
||||
const isInvalid = wordSegments[i]?.invalid || false
|
||||
const isLastWord = i === words.length - 1
|
||||
|
||||
if (isLastWord && !endsWithSeparator && hint && partialWord) {
|
||||
// Show typed prefix + hint suffix in the same slot
|
||||
// Total visible length is the full hint word
|
||||
const totalLen = hint.length
|
||||
result.push({
|
||||
text: '',
|
||||
typedPrefix: partialWord,
|
||||
hintSuffix: hint.slice(partialWord.length),
|
||||
invalid: isInvalid,
|
||||
hasCursor: isCursorSlot,
|
||||
cursorCharIndex: isCursorSlot ? cursor.charIndex : -1,
|
||||
wordLen: totalLen
|
||||
})
|
||||
} else {
|
||||
// Complete word - show cursor at appropriate position
|
||||
result.push({
|
||||
text: word,
|
||||
invalid: isInvalid,
|
||||
hasCursor: isCursorSlot,
|
||||
cursorCharIndex: isCursorSlot ? cursor.charIndex : -1,
|
||||
wordLen: word.length
|
||||
})
|
||||
}
|
||||
} else {
|
||||
// Empty slot
|
||||
result.push({
|
||||
text: '',
|
||||
invalid: false,
|
||||
hasCursor: isCursorSlot,
|
||||
cursorCharIndex: 0,
|
||||
wordLen: 0
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
return result
|
||||
})
|
||||
|
||||
const hasThreeValidWords = computed(() => {
|
||||
const words = getWords(code.value)
|
||||
return words.length === 3 && words.every(w => isValidWord(w))
|
||||
})
|
||||
|
||||
function normalizeCode(input) {
|
||||
return input.trim().toLowerCase().split(/[.\s]+/).filter(w => w).join('.')
|
||||
}
|
||||
|
||||
function startPowSolving() {
|
||||
if (!currentChallenge || powPromise) return
|
||||
const challenge = b64dec(currentChallenge)
|
||||
powPromise = solvePoW(challenge, currentWork).then(solution => {
|
||||
powSolution = solution
|
||||
powPromise = null
|
||||
})
|
||||
}
|
||||
|
||||
async function getPowSolution() {
|
||||
if (powSolution) { const s = powSolution; powSolution = null; return s }
|
||||
if (powPromise) { await powPromise; const s = powSolution; powSolution = null; return s }
|
||||
if (!currentChallenge) throw new Error('No PoW challenge available')
|
||||
const challenge = b64dec(currentChallenge)
|
||||
return await solvePoW(challenge, currentWork)
|
||||
}
|
||||
|
||||
function updateChallenge(pow) {
|
||||
if (pow?.challenge) {
|
||||
currentChallenge = pow.challenge
|
||||
currentWork = pow.work
|
||||
powSolution = null
|
||||
powPromise = null
|
||||
startPowSolving()
|
||||
}
|
||||
}
|
||||
|
||||
async function ensureConnection() {
|
||||
if (ws || wsConnecting) return
|
||||
wsConnecting = true
|
||||
try {
|
||||
const authHost = settings.value?.auth_host
|
||||
const wsPath = '/auth/ws/remote-auth/pair'
|
||||
const wsUrl = authHost && location.host !== authHost ? `//${authHost}${wsPath}` : wsPath
|
||||
ws = await aWebSocket(wsUrl)
|
||||
const msg = await ws.receive_json()
|
||||
if (msg.status && msg.detail) throw new Error(msg.detail)
|
||||
if (!msg.pow?.challenge) throw new Error('Server did not send PoW challenge')
|
||||
updateChallenge(msg.pow)
|
||||
} catch (err) {
|
||||
console.error('WebSocket connection error:', err)
|
||||
ws = null
|
||||
throw err
|
||||
} finally {
|
||||
wsConnecting = false
|
||||
}
|
||||
}
|
||||
|
||||
// Defer cursor position update to after browser processes the key
|
||||
function deferUpdateCursor(event) {
|
||||
// Handle Tab/Space for autocomplete immediately
|
||||
if (event.key === 'Tab' || event.key === ' ') {
|
||||
handleKeydown(event)
|
||||
return
|
||||
}
|
||||
// Defer cursor update to next tick
|
||||
setTimeout(updateCursorPos, 0)
|
||||
}
|
||||
|
||||
// Update cursor position from input
|
||||
function updateCursorPos() {
|
||||
cursorPos.value = inputRef.value?.selectionStart ?? code.value.length
|
||||
}
|
||||
|
||||
function updateAutocomplete() {
|
||||
cursorPos.value = inputRef.value?.selectionStart ?? code.value.length
|
||||
const { word, end } = getWordAtCursor(code.value, cursorPos.value)
|
||||
const completeWordCount = countCompleteWords(code.value)
|
||||
if (completeWordCount >= 3 || !word || word.length < 1 || cursorPos.value !== end) {
|
||||
autocompleteHint.value = ''
|
||||
return
|
||||
}
|
||||
const match = getUniqueMatch(word.toLowerCase())
|
||||
if (match && match !== word.toLowerCase()) autocompleteHint.value = match
|
||||
else autocompleteHint.value = ''
|
||||
}
|
||||
|
||||
function applyAutocomplete() {
|
||||
if (!autocompleteHint.value) return false
|
||||
const { word, start, end } = getWordAtCursor(code.value, cursorPos.value)
|
||||
if (!word) return false
|
||||
const before = code.value.slice(0, start)
|
||||
const wordsBefore = getWords(before).length
|
||||
const isThirdWord = wordsBefore === 2
|
||||
const suffix = isThirdWord ? '' : ' '
|
||||
const after = code.value.slice(end)
|
||||
code.value = before + autocompleteHint.value + suffix + after.trimStart()
|
||||
const newPos = start + autocompleteHint.value.length + suffix.length
|
||||
nextTick(() => {
|
||||
inputRef.value?.setSelectionRange(newPos, newPos)
|
||||
cursorPos.value = newPos
|
||||
})
|
||||
autocompleteHint.value = ''
|
||||
return true
|
||||
}
|
||||
|
||||
// Try to split concatenated words (e.g., "alienalien" -> "alien alien")
|
||||
function trySplitWords(input) {
|
||||
// Only process if there's a continuous string of letters at the end
|
||||
const match = input.match(/^(.*?)([a-zA-Z]+)$/)
|
||||
if (!match) return input
|
||||
|
||||
const prefix = match[1] // Everything before the letter sequence
|
||||
const letters = match[2].toLowerCase()
|
||||
|
||||
// Try to find valid word boundaries in the letter sequence
|
||||
const foundWords = []
|
||||
let remaining = letters
|
||||
|
||||
while (remaining.length > 0) {
|
||||
let foundWord = null
|
||||
|
||||
// Try to find the longest valid word from the start
|
||||
for (let len = Math.min(remaining.length, 6); len >= 3; len--) {
|
||||
const candidate = remaining.slice(0, len)
|
||||
if (isValidWord(candidate)) {
|
||||
foundWord = candidate
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
if (foundWord) {
|
||||
foundWords.push(foundWord)
|
||||
remaining = remaining.slice(foundWord.length)
|
||||
|
||||
// Stop after 3 words
|
||||
if (foundWords.length >= 3) {
|
||||
remaining = ''
|
||||
break
|
||||
}
|
||||
} else {
|
||||
// No valid word found, keep the remaining as-is
|
||||
foundWords.push(remaining)
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// Only return split version if we found at least one complete word
|
||||
// and there's a clear boundary (more than one segment, or the segment is a complete word)
|
||||
if (foundWords.length > 1 || (foundWords.length === 1 && isValidWord(foundWords[0]) && remaining === '')) {
|
||||
return prefix + foundWords.join(' ')
|
||||
}
|
||||
|
||||
return input
|
||||
}
|
||||
|
||||
function handleInput() {
|
||||
// Immediately update cursor position
|
||||
cursorPos.value = inputRef.value?.selectionStart ?? code.value.length
|
||||
|
||||
// First, try to auto-split concatenated words
|
||||
const splitCode = trySplitWords(code.value)
|
||||
if (splitCode !== code.value) {
|
||||
code.value = splitCode
|
||||
nextTick(() => {
|
||||
const newLen = splitCode.length
|
||||
inputRef.value?.setSelectionRange(newLen, newLen)
|
||||
cursorPos.value = newLen
|
||||
})
|
||||
}
|
||||
|
||||
const words = getWords(code.value)
|
||||
if (words.length >= 3) {
|
||||
const normalized = words.slice(0, 3).join(' ')
|
||||
if (code.value !== normalized) {
|
||||
const cursorWasAtEnd = cursorPos.value >= code.value.length
|
||||
code.value = normalized
|
||||
if (cursorWasAtEnd) {
|
||||
nextTick(() => {
|
||||
inputRef.value?.setSelectionRange(normalized.length, normalized.length)
|
||||
cursorPos.value = normalized.length
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
updateAutocomplete()
|
||||
if (lookupTimeout) { clearTimeout(lookupTimeout); lookupTimeout = null }
|
||||
deviceInfo.value = null
|
||||
error.value = null
|
||||
serverError.value = false
|
||||
hasInvalidWord.value = !checkWordsValidity(code.value)
|
||||
const currentWords = getWords(code.value)
|
||||
if (currentWords.length >= 1 && !ws && !wsConnecting) ensureConnection()
|
||||
if (currentWords.length === 3) {
|
||||
if (!allWordsValid(code.value)) return
|
||||
lookupTimeout = setTimeout(() => { lookupDeviceInfo() }, 150)
|
||||
}
|
||||
}
|
||||
|
||||
async function lookupDeviceInfo() {
|
||||
if (isProcessing.value || loading.value) return
|
||||
if (!hasThreeValidWords.value) return
|
||||
const normalizedCode = normalizeCode(code.value)
|
||||
if (normalizedCode === lastLookedUpCode && deviceInfo.value) return
|
||||
|
||||
isProcessing.value = true
|
||||
processingStatus.value = 'pow'
|
||||
error.value = null
|
||||
serverError.value = false
|
||||
|
||||
try {
|
||||
await ensureConnection()
|
||||
if (!ws) throw new Error('Failed to connect')
|
||||
const solution = await getPowSolution()
|
||||
const powB64 = b64enc(solution)
|
||||
const currentCode = normalizeCode(code.value)
|
||||
if (!hasThreeValidWords.value) return
|
||||
processingStatus.value = 'server'
|
||||
ws.send_json({ code: currentCode, pow: powB64 })
|
||||
const res = await ws.receive_json()
|
||||
updateChallenge(res.pow)
|
||||
if (typeof res.status === 'number' && res.status >= 400) {
|
||||
error.value = res.detail || 'Request failed'
|
||||
serverError.value = true
|
||||
deviceInfo.value = null
|
||||
lastLookedUpCode = null
|
||||
return
|
||||
}
|
||||
if (res.status === 'found' && res.host) {
|
||||
code.value = currentCode.replace(/\./g, ' ')
|
||||
deviceInfo.value = {
|
||||
host: res.host,
|
||||
user_agent_pretty: res.user_agent_pretty,
|
||||
client_ip: res.client_ip,
|
||||
action: res.action || 'login'
|
||||
}
|
||||
lastLookedUpCode = currentCode
|
||||
nextTick(() => { submitBtnRef.value?.focus() })
|
||||
} else {
|
||||
error.value = 'Unexpected response from server'
|
||||
serverError.value = true
|
||||
deviceInfo.value = null
|
||||
lastLookedUpCode = null
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Lookup error:', err)
|
||||
error.value = err.message || 'Lookup failed'
|
||||
serverError.value = true
|
||||
deviceInfo.value = null
|
||||
lastLookedUpCode = null
|
||||
if (ws) { ws.close(); ws = null }
|
||||
} finally {
|
||||
isProcessing.value = false
|
||||
processingStatus.value = ''
|
||||
}
|
||||
}
|
||||
|
||||
function handleKeydown(event) {
|
||||
if (event.key === 'Tab') {
|
||||
if (autocompleteHint.value) {
|
||||
const applied = applyAutocomplete()
|
||||
if (applied) { event.preventDefault(); handleInput(); return }
|
||||
}
|
||||
if (code.value.trim()) event.preventDefault()
|
||||
return
|
||||
}
|
||||
if (event.key === ' ' && autocompleteHint.value) {
|
||||
const applied = applyAutocomplete()
|
||||
if (applied) { event.preventDefault(); handleInput() }
|
||||
}
|
||||
}
|
||||
|
||||
async function submitCode() {
|
||||
if (!deviceInfo.value || loading.value) return
|
||||
loading.value = true
|
||||
error.value = null
|
||||
try {
|
||||
if (!ws) await ensureConnection()
|
||||
if (!ws) throw new Error('Failed to connect')
|
||||
const solution = await getPowSolution()
|
||||
const powB64 = b64enc(solution)
|
||||
ws.send_json({ authenticate: true, pow: powB64 })
|
||||
const res = await ws.receive_json()
|
||||
if (typeof res.status === 'number' && res.status >= 400) throw new Error(res.detail || 'Authentication failed')
|
||||
if (!res.optionsJSON) throw new Error(res.detail || 'Failed to get authentication options')
|
||||
const authResponse = await startAuthentication(res)
|
||||
ws.send_json(authResponse)
|
||||
const result = await ws.receive_json()
|
||||
if (typeof result.status === 'number' && result.status >= 400) throw new Error(result.detail || 'Authentication failed')
|
||||
if (result.status === 'success') {
|
||||
showMessage('Device authenticated successfully!', 'success', 3000)
|
||||
emit('completed')
|
||||
reset()
|
||||
} else {
|
||||
throw new Error(result.detail || 'Authentication failed')
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Pairing error:', err)
|
||||
const message = err.name === 'NotAllowedError'
|
||||
? 'Passkey authentication was cancelled'
|
||||
: (err.message || 'Authentication failed')
|
||||
error.value = message
|
||||
// Don't show toast - error is shown in dialog
|
||||
emit('error', message)
|
||||
} finally {
|
||||
loading.value = false
|
||||
if (ws) { ws.close(); ws = null }
|
||||
}
|
||||
}
|
||||
|
||||
async function deny() {
|
||||
// Send deny message to server before closing websocket
|
||||
if (ws) {
|
||||
try {
|
||||
ws.send_json({ deny: true })
|
||||
// Give the server a moment to process the denial
|
||||
await new Promise(resolve => setTimeout(resolve, 100))
|
||||
} catch (e) {
|
||||
console.error('Error sending deny message:', e)
|
||||
}
|
||||
ws.close()
|
||||
ws = null
|
||||
}
|
||||
|
||||
// Reset to initial state
|
||||
reset()
|
||||
}
|
||||
|
||||
function reset() {
|
||||
code.value = ''
|
||||
error.value = null
|
||||
serverError.value = false
|
||||
deviceInfo.value = null
|
||||
isProcessing.value = false
|
||||
processingStatus.value = ''
|
||||
autocompleteHint.value = ''
|
||||
hasInvalidWord.value = false
|
||||
lastLookedUpCode = null
|
||||
if (ws) { ws.close(); ws = null }
|
||||
currentChallenge = null
|
||||
currentWork = null
|
||||
powPromise = null
|
||||
powSolution = null
|
||||
}
|
||||
|
||||
// --- Lifecycle ---
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchSettings()
|
||||
inputRef.value?.focus()
|
||||
// Initialize cursor position
|
||||
nextTick(() => {
|
||||
cursorPos.value = inputRef.value?.selectionStart ?? 0
|
||||
})
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (lookupTimeout) { clearTimeout(lookupTimeout); lookupTimeout = null }
|
||||
if (ws) { ws.close(); ws = null }
|
||||
})
|
||||
|
||||
defineExpose({ reset, deny, code, handleInput, loading, error })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* Input Mode Styles */
|
||||
.pairing-entry {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
}
|
||||
|
||||
.pairing-form {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.input-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.input-wrapper {
|
||||
position: relative;
|
||||
display: flex;
|
||||
width: 280px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
/* Slot machine visual display (matches RemoteAuthInline) */
|
||||
.slot-machine {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0.875rem 1rem;
|
||||
background: var(--color-surface-hover, rgba(0, 0, 0, 0.03));
|
||||
border: 2px solid var(--color-border);
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
|
||||
display: flex;
|
||||
gap: 0;
|
||||
align-items: center;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
box-sizing: border-box;
|
||||
z-index: 1;
|
||||
}
|
||||
|
||||
.slot-machine.has-error {
|
||||
border-color: var(--color-error, #ef4444);
|
||||
background: var(--color-error-bg, rgba(239, 68, 68, 0.05));
|
||||
}
|
||||
|
||||
.slot-machine.is-complete {
|
||||
border-color: var(--color-success, #10b981);
|
||||
}
|
||||
|
||||
.slot-reel {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 1 1 33.333%;
|
||||
min-width: 0;
|
||||
height: 1.8em;
|
||||
overflow: visible;
|
||||
position: relative;
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.slot-reel:not(:last-child) {
|
||||
margin-right: 0.5rem;
|
||||
}
|
||||
|
||||
.slot-word {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.05em;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
color: var(--color-text);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.slot-word .typed-prefix {
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.slot-word .hint-suffix {
|
||||
color: var(--color-text-muted);
|
||||
opacity: 0.6;
|
||||
}
|
||||
|
||||
.cursor-overlay {
|
||||
position: absolute;
|
||||
width: 2px;
|
||||
height: 1.2em;
|
||||
background: var(--color-text);
|
||||
animation: none;
|
||||
pointer-events: none;
|
||||
/* Position based on character index - calculate from center of slot */
|
||||
left: calc(50% + (var(--cursor-pos) - var(--word-len, 0) / 2) * 0.65em);
|
||||
transform: translateX(-1px);
|
||||
opacity: 0;
|
||||
}
|
||||
|
||||
.input-wrapper.focused .cursor-overlay {
|
||||
opacity: 1;
|
||||
animation: cursorBlink 1s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes cursorBlink {
|
||||
0%, 49% {
|
||||
opacity: 1;
|
||||
}
|
||||
50%, 100% {
|
||||
opacity: 0;
|
||||
}
|
||||
}
|
||||
|
||||
.slot-reel.invalid-word .slot-word {
|
||||
color: var(--color-error, #ef4444);
|
||||
}
|
||||
|
||||
.slot-reel.invalid-word .slot-word .typed-prefix {
|
||||
color: var(--color-error, #ef4444);
|
||||
}
|
||||
|
||||
.slot-reel.invalid-word .cursor-overlay {
|
||||
background: var(--color-error, #ef4444);
|
||||
}
|
||||
|
||||
.slot-reel.empty .slot-word {
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
/* Hidden input - keeps focus and handles keyboard input */
|
||||
.pairing-input {
|
||||
flex: 1;
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
padding: 0.875rem 1rem;
|
||||
font-size: 1rem;
|
||||
font-family: inherit;
|
||||
border: 1px solid transparent;
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
background: transparent;
|
||||
color: transparent;
|
||||
caret-color: transparent;
|
||||
outline: none;
|
||||
box-sizing: border-box;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.pairing-input.hidden-input {
|
||||
color: transparent;
|
||||
caret-color: transparent;
|
||||
}
|
||||
|
||||
.pairing-input:disabled {
|
||||
cursor: not-allowed;
|
||||
}
|
||||
|
||||
.pairing-input::placeholder {
|
||||
color: transparent;
|
||||
}
|
||||
|
||||
.processing-status {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 0.25rem;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.processing-icon {
|
||||
font-size: 0.875rem;
|
||||
}
|
||||
|
||||
.processing-spinner-small {
|
||||
width: 12px;
|
||||
height: 12px;
|
||||
border: 2px solid var(--color-border);
|
||||
border-top-color: var(--color-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.device-info {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
}
|
||||
|
||||
.device-permit-text {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
color: var(--color-text);
|
||||
}
|
||||
|
||||
.device-meta {
|
||||
margin: 0;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-error, #ef4444);
|
||||
margin-bottom: 1rem;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,535 @@
|
||||
<template>
|
||||
<div class="remote-auth-inline">
|
||||
<!-- Success state -->
|
||||
<div v-if="completed" class="success-section">
|
||||
<p class="success-message">✅ {{ successMessage }}</p>
|
||||
</div>
|
||||
|
||||
<!-- Error state -->
|
||||
<div v-else-if="error" class="error-section">
|
||||
<p class="error-message">{{ error }}</p>
|
||||
<button class="btn-primary" @click="retry" style="margin-top: 0.75rem;">Try Again</button>
|
||||
</div>
|
||||
|
||||
<!-- Connecting phase -->
|
||||
<div v-else-if="phase === 'connecting'" class="auth-display">
|
||||
<div class="auth-content">
|
||||
<div class="pairing-code-section">
|
||||
<p class="pairing-label">Enter the code words:</p>
|
||||
<div class="slot-machine" aria-hidden="true">
|
||||
<div class="slot-reel" v-for="(word, index) in animatedWords" :key="index">
|
||||
<div class="slot-word">{{ word }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="site-url">{{ siteUrlDisplay }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="waiting-indicator">
|
||||
<div class="spinner-small"></div>
|
||||
<span>Generating code…</span>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Waiting/Authenticating phase - show codes -->
|
||||
<div v-else class="auth-display">
|
||||
<div class="auth-content">
|
||||
<div v-if="pairingCode" class="pairing-code-section">
|
||||
<p class="pairing-label">Enter the code words:</p>
|
||||
<div class="slot-machine stopped">
|
||||
<div class="slot-reel" v-for="(word, index) in displayCode.split(' ')" :key="index">
|
||||
<div class="slot-word">{{ word }}</div>
|
||||
</div>
|
||||
</div>
|
||||
<p class="site-url">{{ siteUrlDisplay }}</p>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div class="waiting-indicator">
|
||||
<div class="spinner-small"></div>
|
||||
<span>{{ waitingMessage }}</span>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { ref, computed, watch, onMounted, onUnmounted } from 'vue'
|
||||
import aWebSocket from '@/utils/awaitable-websocket'
|
||||
import { dec as b64dec, enc as b64enc } from '@/utils/base64url'
|
||||
import { getSettings } from '@/utils/settings'
|
||||
import { solvePoW } from '@/utils/pow'
|
||||
import { words } from '@/utils/wordlist'
|
||||
|
||||
const props = defineProps({
|
||||
active: { type: Boolean, default: false }
|
||||
})
|
||||
|
||||
const emit = defineEmits(['authenticated', 'cancelled', 'error', 'register'])
|
||||
|
||||
const pairingCode = ref(null)
|
||||
const completed = ref(false)
|
||||
const error = ref(null)
|
||||
const phase = ref('connecting')
|
||||
const settings = ref(null)
|
||||
const animatedWords = ref(['', '', ''])
|
||||
let ws = null
|
||||
let wordAnimationTimer = null
|
||||
|
||||
const displayCode = computed(() => pairingCode.value ? pairingCode.value.replace(/\./g, ' ') : '')
|
||||
|
||||
const siteUrlDisplay = computed(() => {
|
||||
if (!settings.value) return ''
|
||||
const authSiteUrl = settings.value.auth_site_url || `${location.protocol}//${location.host}/auth/`
|
||||
// Remove the protocol and any trailing slash
|
||||
const withoutProtocol = authSiteUrl.replace(/^https?:\/\//, '')
|
||||
return withoutProtocol.endsWith('/') ? withoutProtocol.slice(0, -1) : withoutProtocol
|
||||
})
|
||||
|
||||
const waitingMessage = computed(() => {
|
||||
return phase.value === 'authenticating'
|
||||
? 'Complete on another device…'
|
||||
: 'Waiting for authentication…'
|
||||
})
|
||||
|
||||
const successMessage = computed(() => 'Authenticated successfully!')
|
||||
|
||||
function getRandomWord() {
|
||||
return words[Math.floor(Math.random() * words.length)]
|
||||
}
|
||||
|
||||
function startWordAnimation() {
|
||||
// Initialize with random words
|
||||
animatedWords.value = [getRandomWord(), getRandomWord(), getRandomWord()]
|
||||
|
||||
let updateCount = 0
|
||||
const maxUpdates = 20 // Number of cycles before stopping
|
||||
|
||||
// Different intervals for each slot to spin independently
|
||||
const intervals = [
|
||||
setInterval(() => {
|
||||
const newWords = [...animatedWords.value]
|
||||
newWords[0] = getRandomWord()
|
||||
animatedWords.value = newWords
|
||||
}, 140),
|
||||
setInterval(() => {
|
||||
const newWords = [...animatedWords.value]
|
||||
newWords[1] = getRandomWord()
|
||||
animatedWords.value = newWords
|
||||
}, 170),
|
||||
setInterval(() => {
|
||||
const newWords = [...animatedWords.value]
|
||||
newWords[2] = getRandomWord()
|
||||
animatedWords.value = newWords
|
||||
}, 200)
|
||||
]
|
||||
|
||||
wordAnimationTimer = intervals
|
||||
|
||||
// Stop all after max updates
|
||||
setTimeout(() => {
|
||||
intervals.forEach(interval => clearInterval(interval))
|
||||
wordAnimationTimer = null
|
||||
}, maxUpdates * 170) // Average interval time
|
||||
}
|
||||
|
||||
function stopWordAnimation() {
|
||||
if (wordAnimationTimer) {
|
||||
if (Array.isArray(wordAnimationTimer)) {
|
||||
wordAnimationTimer.forEach(interval => clearInterval(interval))
|
||||
} else {
|
||||
clearInterval(wordAnimationTimer)
|
||||
}
|
||||
wordAnimationTimer = null
|
||||
}
|
||||
}
|
||||
|
||||
async function startRemoteAuth() {
|
||||
error.value = null
|
||||
completed.value = false
|
||||
pairingCode.value = null
|
||||
phase.value = 'connecting'
|
||||
|
||||
// Start word animation
|
||||
startWordAnimation()
|
||||
|
||||
try {
|
||||
settings.value = await getSettings()
|
||||
const authHost = settings.value?.auth_host
|
||||
const wsPath = '/auth/ws/remote-auth/request'
|
||||
const wsUrl = authHost && location.host !== authHost ? `//${authHost}${wsPath}` : wsPath
|
||||
|
||||
ws = await aWebSocket(wsUrl)
|
||||
|
||||
// PoW challenge
|
||||
const powChallenge = await ws.receive_json()
|
||||
if (powChallenge.pow) {
|
||||
const challenge = b64dec(powChallenge.pow.challenge)
|
||||
const nonces = await solvePoW(challenge, powChallenge.pow.work)
|
||||
ws.send_json({ pow: b64enc(nonces), action: 'login' })
|
||||
}
|
||||
|
||||
// Receive the pairing code
|
||||
const res = await ws.receive_json()
|
||||
|
||||
if (res.status) {
|
||||
throw new Error(res.detail || `Failed to create remote auth request: ${res.status}`)
|
||||
}
|
||||
|
||||
pairingCode.value = res.pairing_code
|
||||
|
||||
// Stop word animation
|
||||
stopWordAnimation()
|
||||
|
||||
phase.value = 'waiting'
|
||||
|
||||
// Wait for authentication
|
||||
while (true) {
|
||||
const msg = await ws.receive_json()
|
||||
|
||||
if (msg.status === 'locked') {
|
||||
// Someone has entered the code and is authenticating
|
||||
phase.value = 'authenticating'
|
||||
} else if (msg.status === 'paired') {
|
||||
// Legacy/compatibility: Device paired, now authenticating
|
||||
phase.value = 'authenticating'
|
||||
} else if (msg.status === 'authenticated') {
|
||||
// Success
|
||||
completed.value = true
|
||||
emit('authenticated', { session_token: msg.session_token })
|
||||
break
|
||||
} else if (msg.status === 'denied') {
|
||||
// Explicitly denied by the authenticating device
|
||||
throw new Error('Access denied')
|
||||
} else if (msg.status === 'completed') {
|
||||
// Registration flow
|
||||
if (msg.reset_token) {
|
||||
completed.value = true
|
||||
emit('register', msg.reset_token)
|
||||
}
|
||||
break
|
||||
} else if (msg.status === 'error' || msg.detail) {
|
||||
throw new Error(msg.detail || 'Remote authentication failed')
|
||||
}
|
||||
}
|
||||
} catch (err) {
|
||||
console.error('Remote authentication error:', err)
|
||||
const message = err.message || 'Authentication failed'
|
||||
error.value = message
|
||||
emit('error', message)
|
||||
} finally {
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function retry() {
|
||||
startRemoteAuth()
|
||||
}
|
||||
|
||||
function cancel() {
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
}
|
||||
emit('cancelled')
|
||||
}
|
||||
|
||||
watch(() => props.active, (newVal) => {
|
||||
if (newVal && !pairingCode.value && !error.value && !completed.value) {
|
||||
startRemoteAuth()
|
||||
}
|
||||
})
|
||||
|
||||
onMounted(() => {
|
||||
if (props.active) {
|
||||
startRemoteAuth()
|
||||
}
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
if (ws) {
|
||||
ws.close()
|
||||
ws = null
|
||||
}
|
||||
stopWordAnimation()
|
||||
})
|
||||
|
||||
defineExpose({ retry, cancel })
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.remote-auth-inline {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.loading-section {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
padding: 2rem 1rem;
|
||||
min-height: 180px;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.loading-section p {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.spinner {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: 3px solid var(--color-border);
|
||||
border-top-color: var(--color-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
@keyframes spin {
|
||||
to { transform: rotate(360deg); }
|
||||
}
|
||||
|
||||
.auth-display {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 1.25rem;
|
||||
width: 100%;
|
||||
min-height: 180px;
|
||||
}
|
||||
|
||||
.auth-content {
|
||||
display: flex;
|
||||
gap: 2rem;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex-wrap: nowrap;
|
||||
}
|
||||
|
||||
.loading-placeholder {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 0.75rem;
|
||||
width: 100%;
|
||||
padding: 1rem;
|
||||
}
|
||||
|
||||
.loading-placeholder p {
|
||||
margin: 0;
|
||||
color: var(--color-text-muted);
|
||||
font-size: 0.95rem;
|
||||
}
|
||||
|
||||
.pairing-code-section {
|
||||
flex: 0 0 auto;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 0.5rem;
|
||||
width: 280px;
|
||||
max-width: 100%;
|
||||
}
|
||||
|
||||
.pairing-label {
|
||||
margin: 0;
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-text-muted);
|
||||
font-weight: 500;
|
||||
text-align: center;
|
||||
}
|
||||
|
||||
.slot-machine {
|
||||
padding: 0.875rem 1rem;
|
||||
background: var(--color-surface-hover, rgba(0, 0, 0, 0.03));
|
||||
border: 2px solid var(--color-border);
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
user-select: none;
|
||||
pointer-events: none;
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.slot-reel {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
flex: 1;
|
||||
min-width: 0;
|
||||
height: 1.8em;
|
||||
overflow: hidden;
|
||||
position: relative;
|
||||
background: var(--color-surface, rgba(255, 255, 255, 0.5));
|
||||
border-radius: 3px;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(1) {
|
||||
animation: slotSpin 0.14s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(2) {
|
||||
animation: slotSpin 0.17s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(3) {
|
||||
animation: slotSpin 0.20s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.slot-word {
|
||||
font-size: 1.25rem;
|
||||
font-weight: 600;
|
||||
letter-spacing: 0.05em;
|
||||
text-align: center;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(1) .slot-word {
|
||||
animation: wordRoll 0.14s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(2) .slot-word {
|
||||
animation: wordRoll 0.17s ease-in-out infinite;
|
||||
}
|
||||
|
||||
.slot-machine:not(.stopped) .slot-reel:nth-child(3) .slot-word {
|
||||
animation: wordRoll 0.20s ease-in-out infinite;
|
||||
}
|
||||
|
||||
@keyframes slotSpin {
|
||||
0% {
|
||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
50% {
|
||||
box-shadow: inset 0 4px 8px rgba(0, 0, 0, 0.2);
|
||||
}
|
||||
100% {
|
||||
box-shadow: inset 0 2px 4px rgba(0, 0, 0, 0.1);
|
||||
}
|
||||
}
|
||||
|
||||
@keyframes wordRoll {
|
||||
0% {
|
||||
transform: translateY(-30%) scale(0.9);
|
||||
opacity: 0.4;
|
||||
filter: blur(1.5px);
|
||||
}
|
||||
25% {
|
||||
transform: translateY(-10%) scale(0.95);
|
||||
opacity: 0.6;
|
||||
filter: blur(1px);
|
||||
}
|
||||
50% {
|
||||
transform: translateY(0) scale(1);
|
||||
opacity: 1;
|
||||
filter: blur(0);
|
||||
}
|
||||
75% {
|
||||
transform: translateY(10%) scale(0.95);
|
||||
opacity: 0.6;
|
||||
filter: blur(1px);
|
||||
}
|
||||
100% {
|
||||
transform: translateY(30%) scale(0.9);
|
||||
opacity: 0.4;
|
||||
filter: blur(1.5px);
|
||||
}
|
||||
}
|
||||
|
||||
.site-url {
|
||||
margin: 0.5rem 0 0;
|
||||
font-size: 0.8rem;
|
||||
color: var(--color-text-muted);
|
||||
text-align: center;
|
||||
font-family: 'SF Mono', Monaco, 'Cascadia Code', 'Roboto Mono', Consolas, 'Courier New', monospace;
|
||||
opacity: 0.8;
|
||||
}
|
||||
|
||||
.waiting-indicator {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.5rem;
|
||||
padding: 0.75rem;
|
||||
background: var(--color-surface-hover, rgba(0, 0, 0, 0.02));
|
||||
border-radius: var(--radius-sm, 6px);
|
||||
font-size: 0.875rem;
|
||||
color: var(--color-text-muted);
|
||||
}
|
||||
|
||||
.spinner-small {
|
||||
width: 16px;
|
||||
height: 16px;
|
||||
border: 2px solid var(--color-border);
|
||||
border-top-color: var(--color-primary);
|
||||
border-radius: 50%;
|
||||
animation: spin 0.8s linear infinite;
|
||||
}
|
||||
|
||||
.success-section {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
min-height: 180px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.success-message {
|
||||
margin: 0;
|
||||
font-size: 1rem;
|
||||
color: var(--color-success, #10b981);
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.error-section {
|
||||
padding: 1rem;
|
||||
text-align: center;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
gap: 0.75rem;
|
||||
min-height: 180px;
|
||||
}
|
||||
|
||||
.error-message {
|
||||
margin: 0;
|
||||
font-size: 0.95rem;
|
||||
color: var(--color-error, #ef4444);
|
||||
}
|
||||
|
||||
/* Responsive adjustments */
|
||||
@media (max-width: 640px) {
|
||||
.auth-content {
|
||||
gap: 1.5rem;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
}
|
||||
|
||||
.pairing-code-section {
|
||||
width: 100%;
|
||||
max-width: 280px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 480px) {
|
||||
.pairing-code {
|
||||
font-size: 1.1rem;
|
||||
padding: 0.75rem 0.875rem;
|
||||
}
|
||||
|
||||
.pairing-code-section {
|
||||
width: 100%;
|
||||
max-width: 100%;
|
||||
}
|
||||
}
|
||||
</style>
|
||||
@@ -11,27 +11,41 @@
|
||||
<header class="view-header center">
|
||||
<h1>{{ headingTitle }}</h1>
|
||||
<p v-if="isAuthenticated" class="user-line">👤 {{ userDisplayName }}</p>
|
||||
<p class="view-lede">{{ headerMessage }}</p>
|
||||
<p class="view-lede" v-html="headerMessage"></p>
|
||||
</header>
|
||||
|
||||
<section class="section-block">
|
||||
<div class="section-body center">
|
||||
<div class="button-row center">
|
||||
<slot name="actions"
|
||||
:loading="loading"
|
||||
:can-authenticate="canAuthenticate"
|
||||
:is-authenticated="isAuthenticated"
|
||||
:authenticate="authenticateUser"
|
||||
:logout="logoutUser"
|
||||
:mode="mode">
|
||||
<!-- Default actions -->
|
||||
<button class="btn-secondary" :disabled="loading" @click="$emit('back')">Back</button>
|
||||
<button v-if="canAuthenticate" class="btn-primary" :disabled="loading" @click="authenticateUser">
|
||||
{{ loading ? (mode === 'reauth' ? 'Verifying…' : 'Signing in…') : (mode === 'reauth' ? 'Verify' : 'Login') }}
|
||||
</button>
|
||||
<button v-if="isAuthenticated && mode !== 'reauth'" class="btn-danger" :disabled="loading" @click="logoutUser">Logout</button>
|
||||
<button v-if="isAuthenticated && mode !== 'reauth'" class="btn-primary" :disabled="loading" @click="openProfile">Profile</button>
|
||||
</slot>
|
||||
<!-- Local passkey authentication view -->
|
||||
<div v-if="authView === 'local'" class="auth-view">
|
||||
<div class="button-row center">
|
||||
<slot name="actions"
|
||||
:loading="loading"
|
||||
:can-authenticate="canAuthenticate"
|
||||
:is-authenticated="isAuthenticated"
|
||||
:authenticate="authenticateUser"
|
||||
:logout="logoutUser"
|
||||
:mode="mode">
|
||||
<!-- Default actions -->
|
||||
<button class="btn-secondary" :disabled="loading" @click="$emit('back')">Back</button>
|
||||
<button v-if="canAuthenticate" class="btn-primary" :disabled="loading" @click="authenticateUser">
|
||||
{{ loading ? (mode === 'reauth' ? 'Verifying…' : 'Signing in…') : (mode === 'reauth' ? 'Verify' : 'Login') }}
|
||||
</button>
|
||||
<button v-if="isAuthenticated && mode !== 'reauth'" class="btn-danger" :disabled="loading" @click="logoutUser">Logout</button>
|
||||
<button v-if="isAuthenticated && mode !== 'reauth'" class="btn-primary" :disabled="loading" @click="openProfile">Profile</button>
|
||||
</slot>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<!-- Remote authentication view (request new remote auth) -->
|
||||
<div v-else-if="authView === 'remote'" class="auth-view">
|
||||
<RemoteAuthInline
|
||||
:active="authView === 'remote'"
|
||||
@authenticated="handleRemoteAuthenticated"
|
||||
@register="handleRemoteRegistration"
|
||||
@cancelled="switchToLocal"
|
||||
@error="handleRemoteAuthError"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
</section>
|
||||
@@ -41,10 +55,11 @@
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, onMounted, reactive, ref } from 'vue'
|
||||
import { computed, onMounted, onUnmounted, reactive, ref } from 'vue'
|
||||
import passkey from '@/utils/passkey'
|
||||
import { getSettings } from '@/utils/settings'
|
||||
import { getSettings, uiBasePath } from '@/utils/settings'
|
||||
import { fetchJson, getUserFriendlyErrorMessage } from '@/utils/api'
|
||||
import RemoteAuthInline from '@/components/RemoteAuthRequest.vue'
|
||||
|
||||
const props = defineProps({
|
||||
mode: {
|
||||
@@ -62,17 +77,15 @@ const loading = ref(false)
|
||||
const settings = ref(null)
|
||||
const userInfo = ref(null)
|
||||
const currentView = ref('initial') // 'initial', 'login', 'forbidden'
|
||||
const authView = ref('local') // 'local' or 'remote'
|
||||
let statusTimer = null
|
||||
|
||||
const isAuthenticated = computed(() => !!userInfo.value?.authenticated)
|
||||
|
||||
const canAuthenticate = computed(() => {
|
||||
if (initializing.value) return false
|
||||
// In reauth mode, allow authentication even if already authenticated
|
||||
if (props.mode === 'reauth') return true
|
||||
// In forbidden view (authenticated but lacking permissions), don't allow authentication
|
||||
if (currentView.value === 'forbidden') return false
|
||||
// In login view or initial state, allow authentication
|
||||
return true
|
||||
})
|
||||
|
||||
@@ -91,6 +104,12 @@ const headerMessage = computed(() => {
|
||||
if (currentView.value === 'forbidden') {
|
||||
return 'You lack the required permissions.'
|
||||
}
|
||||
if (authView.value === 'remote') {
|
||||
return 'Confirm from your other device. Or <a href="#" class="inline-link" data-action="local">this device</a>.'
|
||||
}
|
||||
if (canAuthenticate.value && props.mode !== 'reauth') {
|
||||
return 'Please sign in with your passkey. Or use <a href="#" class="inline-link" data-action="remote">another device</a>.'
|
||||
}
|
||||
return 'Please sign in with your passkey.'
|
||||
})
|
||||
|
||||
@@ -122,7 +141,6 @@ async function fetchSettings() {
|
||||
async function fetchUserInfo() {
|
||||
try {
|
||||
userInfo.value = await fetchJson('/auth/api/user-info', { method: 'POST' })
|
||||
// Determine view based on authentication status
|
||||
if (isAuthenticated.value && props.mode !== 'reauth') {
|
||||
currentView.value = 'forbidden'
|
||||
emit('forbidden', userInfo.value)
|
||||
@@ -131,7 +149,6 @@ async function fetchUserInfo() {
|
||||
}
|
||||
} catch (error) {
|
||||
console.error('Failed to load user info', error)
|
||||
// For 401/403 just go to login, for other errors show message
|
||||
if (error.status !== 401 && error.status !== 403) {
|
||||
showMessage(getUserFriendlyErrorMessage(error), 'error', 4000)
|
||||
}
|
||||
@@ -170,7 +187,6 @@ async function logoutUser() {
|
||||
try {
|
||||
await fetchJson('/auth/api/logout', { method: 'POST' })
|
||||
userInfo.value = null
|
||||
// Switch to login view after logout
|
||||
currentView.value = 'login'
|
||||
showMessage('Logged out. You can sign in with a different account.', 'info', 3000)
|
||||
} catch (error) {
|
||||
@@ -181,7 +197,6 @@ async function logoutUser() {
|
||||
}
|
||||
|
||||
function openProfile() {
|
||||
// Open profile in a new window with a specific name to reuse the same tab
|
||||
const profileWindow = window.open('/auth/', 'passkey_auth_profile')
|
||||
if (profileWindow) profileWindow.focus()
|
||||
}
|
||||
@@ -196,10 +211,61 @@ async function setSessionCookie(result) {
|
||||
})
|
||||
}
|
||||
|
||||
function switchToRemote() {
|
||||
authView.value = 'remote'
|
||||
}
|
||||
|
||||
function switchToLocal() {
|
||||
authView.value = 'local'
|
||||
}
|
||||
|
||||
async function handleRemoteAuthenticated(result) {
|
||||
showMessage('Authenticated from another device!', 'success', 2000)
|
||||
try {
|
||||
await setSessionCookie(result)
|
||||
} catch (error) {
|
||||
const message = error?.message || 'Failed to establish session'
|
||||
showMessage(message, 'error', 4000)
|
||||
emit('auth-error', { message, cancelled: false })
|
||||
return
|
||||
}
|
||||
emit('authenticated', result)
|
||||
}
|
||||
|
||||
function handleRemoteRegistration(token) {
|
||||
showMessage('Registration approved! Redirecting...', 'success', 2000)
|
||||
const basePath = uiBasePath() || '/auth/'
|
||||
window.location.href = `${basePath}${token}`
|
||||
}
|
||||
|
||||
function handleRemoteAuthError(errorMsg) {
|
||||
// Error is already shown in the RemoteAuth component, don't show toast
|
||||
}
|
||||
|
||||
function handleHeaderLinkClick(event) {
|
||||
const target = event.target
|
||||
if (target.tagName === 'A' && target.classList.contains('inline-link')) {
|
||||
event.preventDefault()
|
||||
const action = target.dataset.action
|
||||
if (action === 'remote') {
|
||||
switchToRemote()
|
||||
} else if (action === 'local') {
|
||||
switchToLocal()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMounted(async () => {
|
||||
await fetchSettings()
|
||||
await fetchUserInfo()
|
||||
initializing.value = false
|
||||
|
||||
// Add click handler for inline links
|
||||
document.addEventListener('click', handleHeaderLinkClick)
|
||||
})
|
||||
|
||||
onUnmounted(() => {
|
||||
document.removeEventListener('click', handleHeaderLinkClick)
|
||||
})
|
||||
|
||||
defineExpose({
|
||||
@@ -210,9 +276,8 @@ defineExpose({
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.button-row.center { display: flex; justify-content: center; gap: 0.75rem; }
|
||||
.button-row.center { display: flex; justify-content: center; gap: 0.75rem; flex-wrap: wrap; }
|
||||
.user-line { margin: 0.5rem 0 0; font-weight: 500; color: var(--color-text); }
|
||||
/* Vertically center the restricted "dialog" surface in the viewport */
|
||||
main.view-root { min-height: 100vh; align-items: center; justify-content: center; padding: 2rem 1rem; }
|
||||
.surface.surface--tight {
|
||||
max-width: 520px;
|
||||
@@ -222,4 +287,24 @@ main.view-root { min-height: 100vh; align-items: center; justify-content: center
|
||||
flex-direction: column;
|
||||
gap: 1.75rem;
|
||||
}
|
||||
|
||||
.auth-view {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
align-items: center;
|
||||
gap: 1rem;
|
||||
width: 100%;
|
||||
}
|
||||
|
||||
.view-lede :deep(.inline-link) {
|
||||
color: var(--color-primary);
|
||||
text-decoration: none;
|
||||
transition: opacity 0.15s;
|
||||
font-weight: 400;
|
||||
}
|
||||
|
||||
.view-lede :deep(.inline-link:hover) {
|
||||
opacity: 0.8;
|
||||
text-decoration: underline;
|
||||
}
|
||||
</style>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
<template>
|
||||
<div v-if="userLoaded" class="user-info">
|
||||
<div v-if="userLoaded" class="user-info" :class="{ 'has-extra': $slots.default }">
|
||||
<h3 class="user-name-heading">
|
||||
<span class="icon">👤</span>
|
||||
<span class="user-name-row">
|
||||
@@ -11,12 +11,15 @@
|
||||
<div class="org-line" v-if="orgDisplayName">{{ orgDisplayName }}</div>
|
||||
<div class="role-line" v-if="roleName">{{ roleName }}</div>
|
||||
</div>
|
||||
<span><strong>Visits:</strong></span>
|
||||
<span>{{ visits || 0 }}</span>
|
||||
<span><strong>Registered:</strong></span>
|
||||
<span>{{ formatDate(createdAt) }}</span>
|
||||
<span><strong>Last seen:</strong></span>
|
||||
<span>{{ formatDate(lastSeen) }}</span>
|
||||
<span class="info-label"><strong>Visits:</strong></span>
|
||||
<span class="info-value">{{ visits || 0 }}</span>
|
||||
<span class="info-label"><strong>Registered:</strong></span>
|
||||
<span class="info-value">{{ formatDate(createdAt) }}</span>
|
||||
<span class="info-label"><strong>Last seen:</strong></span>
|
||||
<span class="info-value">{{ formatDate(lastSeen) }}</span>
|
||||
<div v-if="$slots.default" class="user-info-extra">
|
||||
<slot></slot>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
@@ -44,13 +47,50 @@ const userLoaded = computed(() => !!props.name)
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
.user-info { display: grid; grid-template-columns: auto 1fr; gap: 10px; }
|
||||
.user-info h3 { grid-column: span 2; }
|
||||
.org-role-sub { grid-column: span 2; display:flex; flex-direction:column; margin: -0.15rem 0 0.25rem; }
|
||||
.user-info.has-extra {
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-areas:
|
||||
"heading heading"
|
||||
"org org"
|
||||
"label1 value1"
|
||||
"label2 value2"
|
||||
"label3 value3"
|
||||
"extra extra";
|
||||
}
|
||||
|
||||
.user-info:not(.has-extra) {
|
||||
grid-template-columns: auto 1fr;
|
||||
grid-template-areas:
|
||||
"heading heading"
|
||||
"org org"
|
||||
"label1 value1"
|
||||
"label2 value2"
|
||||
"label3 value3";
|
||||
}
|
||||
|
||||
@media (min-width: 769px) {
|
||||
.user-info.has-extra {
|
||||
grid-template-columns: auto 1fr 2fr;
|
||||
grid-template-areas:
|
||||
"heading heading extra"
|
||||
"org org extra"
|
||||
"label1 value1 extra"
|
||||
"label2 value2 extra"
|
||||
"label3 value3 extra";
|
||||
}
|
||||
}
|
||||
|
||||
.user-name-heading { grid-area: heading; display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap; margin: 0 0 0.25rem 0; }
|
||||
.org-role-sub { grid-area: org; display:flex; flex-direction:column; margin: -0.15rem 0 0.25rem; }
|
||||
.org-line { font-size: .7rem; font-weight:600; line-height:1.1; color: var(--color-text-muted); text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
.role-line { font-size:.65rem; color: var(--color-text-muted); line-height:1.1; }
|
||||
.user-info span { text-align: left; }
|
||||
.user-name-heading { display: flex; align-items: center; gap: 0.4rem; flex-wrap: wrap; margin: 0 0 0.25rem 0; }
|
||||
.info-label:nth-of-type(1) { grid-area: label1; }
|
||||
.info-value:nth-of-type(2) { grid-area: value1; }
|
||||
.info-label:nth-of-type(3) { grid-area: label2; }
|
||||
.info-value:nth-of-type(4) { grid-area: value2; }
|
||||
.info-label:nth-of-type(5) { grid-area: label3; }
|
||||
.info-value:nth-of-type(6) { grid-area: value3; }
|
||||
.user-info-extra { grid-area: extra; padding-left: 2rem; border-left: 1px solid var(--color-border); }
|
||||
.user-name-row { display: inline-flex; align-items: center; gap: 0.35rem; max-width: 100%; }
|
||||
.user-name-row.editing { flex: 1 1 auto; }
|
||||
.icon { flex: 0 0 auto; }
|
||||
@@ -62,5 +102,6 @@ const userLoaded = computed(() => !!props.name)
|
||||
.mini-btn:hover:not(:disabled) { background: var(--color-accent-soft); color: var(--color-accent); }
|
||||
.mini-btn:active:not(:disabled) { transform: translateY(1px); }
|
||||
.mini-btn:disabled { opacity: 0.5; cursor: not-allowed; }
|
||||
@media (max-width: 768px) { .user-info-extra { padding-left: 0; padding-top: 1rem; border-left: none; border-top: 1px solid var(--color-border); } }
|
||||
@media (max-width: 480px) { .user-name-heading { flex-direction: column; align-items: flex-start; } .user-name-row.editing { width: 100%; } .display-name { max-width: 100%; } }
|
||||
</style>
|
||||
|
||||
@@ -18,12 +18,36 @@ class AwaitableWebSocket extends WebSocket {
|
||||
}
|
||||
this.onclose = e => {
|
||||
if (!this.#opened) {
|
||||
reject(new Error(`WebSocket ${this.url} failed to connect, code ${e.code}`))
|
||||
reject(new Error(`Failed to connect to server (code ${e.code})`))
|
||||
return
|
||||
}
|
||||
this.#err = e.wasClean
|
||||
? new Error(`Websocket ${this.url} closed ${e.code}`)
|
||||
: new Error(`WebSocket ${this.url} closed with error ${e.code}`)
|
||||
// Create user-friendly close messages
|
||||
let message
|
||||
if (e.wasClean) {
|
||||
// Standard close codes
|
||||
switch (e.code) {
|
||||
case 1000: message = 'Connection closed normally'; break
|
||||
case 1001: message = 'Server is going away'; break
|
||||
case 1002: message = 'Protocol error'; break
|
||||
case 1003: message = 'Unsupported data received'; break
|
||||
case 1006: message = 'Connection lost unexpectedly'; break
|
||||
case 1007: message = 'Invalid data received'; break
|
||||
case 1008: message = 'Policy violation'; break
|
||||
case 1009: message = 'Message too large'; break
|
||||
case 1010: message = 'Extension negotiation failed'; break
|
||||
case 1011: message = 'Server encountered an error'; break
|
||||
case 1012: message = 'Server is restarting'; break
|
||||
case 1013: message = 'Server is overloaded, try again later'; break
|
||||
case 1014: message = 'Bad gateway'; break
|
||||
case 1015: message = 'TLS handshake failed'; break
|
||||
default: message = `Connection closed (code ${e.code})`
|
||||
}
|
||||
} else {
|
||||
message = e.code === 1006
|
||||
? 'Connection lost unexpectedly'
|
||||
: `Connection closed with error (code ${e.code})`
|
||||
}
|
||||
this.#err = new Error(message)
|
||||
this.#waiting.splice(0).forEach(p => p.reject(this.#err))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
/**
|
||||
* URL-safe Base64 encoding/decoding utilities.
|
||||
*
|
||||
* These functions handle base64url format (RFC 4648) which uses:
|
||||
* - '-' instead of '+'
|
||||
* - '_' instead of '/'
|
||||
* - No padding '=' characters
|
||||
*/
|
||||
|
||||
/**
|
||||
* Decode a base64url string to Uint8Array.
|
||||
* Handles both standard base64 and URL-safe base64 (with or without padding).
|
||||
* @param {string} str - Base64url encoded string
|
||||
* @returns {Uint8Array} - Decoded bytes
|
||||
*/
|
||||
export function dec(str) {
|
||||
// Convert URL-safe characters to standard base64
|
||||
const base64 = str.replace(/-/g, '+').replace(/_/g, '/')
|
||||
// Add padding if needed
|
||||
const padded = base64 + '='.repeat((4 - base64.length % 4) % 4)
|
||||
return Uint8Array.from(atob(padded), c => c.charCodeAt(0))
|
||||
}
|
||||
|
||||
/**
|
||||
* Encode a Uint8Array to base64url string.
|
||||
* @param {Uint8Array} bytes - Bytes to encode
|
||||
* @returns {string} - Base64url encoded string (no padding)
|
||||
*/
|
||||
export function enc(bytes) {
|
||||
const base64 = btoa(String.fromCharCode(...bytes))
|
||||
// Convert to URL-safe and remove padding
|
||||
return base64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
import { solvePoW, verifyPoW } from './pow.js'
|
||||
|
||||
const TRIALS = 5
|
||||
const WORK = 10
|
||||
|
||||
async function test() {
|
||||
console.log(`Running ${TRIALS} trials with ${WORK} work units...\n`)
|
||||
|
||||
const times = []
|
||||
|
||||
for (let trial = 1; trial <= TRIALS; trial++) {
|
||||
const challenge = crypto.getRandomValues(new Uint8Array(8))
|
||||
|
||||
const start = performance.now()
|
||||
const solution = await solvePoW(challenge, WORK)
|
||||
const elapsed = performance.now() - start
|
||||
|
||||
const valid = await verifyPoW(challenge, solution, WORK)
|
||||
|
||||
times.push(elapsed)
|
||||
|
||||
console.log(`Trial ${trial.toString().padStart(2)}: ${(elapsed / 1000).toFixed(3)}s, valid=${valid}`)
|
||||
}
|
||||
|
||||
const avgTime = times.reduce((a, b) => a + b, 0) / times.length
|
||||
const minTime = Math.min(...times)
|
||||
const maxTime = Math.max(...times)
|
||||
|
||||
console.log('\n--- Summary ---')
|
||||
console.log(`Trials: ${TRIALS}`)
|
||||
console.log(`Work units: ${WORK}`)
|
||||
console.log(`Avg time: ${(avgTime / 1000).toFixed(3)}s`)
|
||||
console.log(`Min time: ${(minTime / 1000).toFixed(3)}s`)
|
||||
console.log(`Max time: ${(maxTime / 1000).toFixed(3)}s`)
|
||||
}
|
||||
|
||||
test()
|
||||
@@ -0,0 +1,68 @@
|
||||
/**
|
||||
* Proof of Work utility using PBKDF2-SHA512
|
||||
*
|
||||
* The PoW requires finding nonces where PBKDF2(challenge, nonce) produces
|
||||
* output with a zero first byte. Each work unit requires finding one such nonce.
|
||||
* All valid nonces are concatenated into a solution for server verification.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Solve a Proof of Work challenge
|
||||
*
|
||||
* @param {Uint8Array|ArrayBuffer} challenge - 8-byte server-provided challenge
|
||||
* @param {number} work - Number of PBKDF2 work units required
|
||||
* @param {object} [options] - Optional parameters
|
||||
* @param {AbortSignal} [options.signal] - AbortSignal to cancel the operation
|
||||
* @returns {Promise<Uint8Array>} Solution: concatenated 8-byte nonces (8 * work bytes)
|
||||
* @throws {Error} If challenge is invalid or operation is aborted
|
||||
*/
|
||||
export async function solvePoW(challenge, work, options = {}) {
|
||||
const { signal } = options
|
||||
const startTime = performance.now()
|
||||
|
||||
// Validate inputs
|
||||
const challengeBytes = challenge instanceof ArrayBuffer
|
||||
? new Uint8Array(challenge)
|
||||
: challenge
|
||||
|
||||
if (!(challengeBytes instanceof Uint8Array) || challengeBytes.length !== 8) {
|
||||
throw new Error('Challenge must be exactly 8 bytes')
|
||||
}
|
||||
|
||||
// Import challenge as PBKDF2 key material
|
||||
const baseKey = await crypto.subtle.importKey('raw', challengeBytes, 'PBKDF2', false, ['deriveBits'])
|
||||
|
||||
// Build solution from found nonces
|
||||
const solution = new Uint8Array(8 * work)
|
||||
let totalIterations = 0
|
||||
const mask = 0x7FF // The client must work 2048x harder than the server
|
||||
|
||||
// Sequential nonce starting at zero (little-endian, using Uint32Array for efficient increment)
|
||||
const nonce = new Uint32Array(2)
|
||||
|
||||
for (let i = 0; i < work; i++) {
|
||||
if (signal?.aborted) {
|
||||
throw new DOMException('PoW operation aborted', 'AbortError')
|
||||
}
|
||||
|
||||
// Find a nonce where PBKDF2 output passes the mask check
|
||||
let result
|
||||
do {
|
||||
totalIterations++
|
||||
if (++nonce[0] === 0x100000000) ++nonce[1] // Increment 64-bit little-endian nonce
|
||||
result = new Uint32Array(await crypto.subtle.deriveBits(
|
||||
{ name: 'PBKDF2', salt: nonce, iterations: 128, hash: 'SHA-512'},
|
||||
baseKey,
|
||||
32
|
||||
))
|
||||
} while (result[0] & mask)
|
||||
solution.set(new Uint8Array(nonce.buffer), i * 8)
|
||||
}
|
||||
|
||||
const elapsed = (performance.now() - startTime) / 1000
|
||||
const expectedIterations = work * (mask + 1)
|
||||
const luckRatio = (totalIterations / expectedIterations).toFixed(1)
|
||||
const bench = totalIterations / ((mask + 1) * elapsed)
|
||||
console.log(`PoW work=${work} solved in ${elapsed.toFixed(2)}s (${luckRatio}x expected ${bench.toFixed(1)} work/s)`)
|
||||
return solution
|
||||
}
|
||||
File diff suppressed because one or more lines are too long
Reference in New Issue
Block a user