Sync 2: device-token bearer auth + linked-devices UI (M8)
CI & Build / Python lint (push) Successful in 2s
CI & Build / TypeScript typecheck (push) Successful in 5s
CI & Build / Python tests (push) Successful in 10s
CI & Build / Build & push image (push) Successful in 33s

Native clients (Tauri/Android) authenticate sync with a long-lived device
bearer token, alongside the existing web session cookie.

Backend:
- security.py: generate_token() (secrets.token_urlsafe) + hash_token()
  (SHA-256 — device tokens are already high-entropy, so no slow KDF; keeps
  per-request bearer auth cheap). Only the hash is stored.
- device_tokens table (migration 0016): id, user_id, token_hash (unique),
  name, created_at, last_used_at.
- login_required now accepts `Authorization: Bearer <token>` OR the session
  cookie. Session path stays DB-free (fast); bearer path looks up the token
  hash, sets g.user_id, and stamps last_used_at.
- Endpoints: POST /api/auth/device-login (public; email+password → token,
  the native first-link flow), POST /api/auth/devices (session/bearer →
  token, web "link a device"), GET /api/auth/devices (list), DELETE
  /api/auth/devices/<id> (revoke). All owner-scoped; token shown once.

Frontend:
- Per-user (not admin) /account view "Linked devices": create a token
  (one-time reveal + copy), list devices (name, linked/last-synced), revoke
  with confirm. Top-bar device icon for all users; devices Pinia store.

Tests (DB-free): token hash determinism + uniqueness; device endpoints
auth-guard (401 without auth, before DB); device-login input validation.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01FRgehjoz7Yv8LkUfADxACm
This commit is contained in:
2026-07-22 22:59:52 -04:00
co-authored by Claude Opus 4.8
parent 58b88d2622
commit 3c76b50a9c
12 changed files with 475 additions and 3 deletions
+3
View File
@@ -224,6 +224,9 @@ async function signOut() {
<span class="hidden text-sm text-neutral-500 md:inline dark:text-neutral-400">{{
session.user?.display_name
}}</span>
<RouterLink to="/account" class="icon-btn" title="Linked devices" aria-label="Linked devices">
<Icon name="device" />
</RouterLink>
<RouterLink
v-if="session.user?.is_admin"
to="/settings"
+2
View File
@@ -25,6 +25,8 @@ const paths: Record<string, string> = {
history: '<path d="M3 12a9 9 0 1 0 9-9 9.75 9.75 0 0 0-6.74 2.74L3 8"/><path d="M3 3v5h5"/><path d="M12 7v5l4 2"/>',
download: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" x2="12" y1="15" y2="3"/>',
upload: '<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="17 8 12 3 7 8"/><line x1="12" x2="12" y1="3" y2="15"/>',
device: '<rect width="14" height="20" x="5" y="2" rx="2" ry="2"/><path d="M12 18h.01"/>',
copy: '<rect width="14" height="14" x="8" y="8" rx="2" ry="2"/><path d="M4 16c-1.1 0-2-.9-2-2V4c0-1.1.9-2 2-2h10c1.1 0 2 .9 2 2"/>',
};
</script>
+7
View File
@@ -27,6 +27,13 @@ const router = createRouter({
component: () => import("../views/SettingsView.vue"),
meta: { requiresAuth: true, requiresAdmin: true },
},
{
// Per-user account: linked devices (native-client sync tokens). Any user.
path: "/account",
name: "account",
component: () => import("../views/AccountView.vue"),
meta: { requiresAuth: true },
},
{
path: "/login",
name: "login",
+40
View File
@@ -0,0 +1,40 @@
import { defineStore } from "pinia";
import { ref } from "vue";
import { api } from "../api/client";
// A linked native client (Tauri/Android) that holds a device bearer token.
export interface Device {
id: string;
name: string;
created_at: string | null;
last_used_at: string | null;
}
export const useDevicesStore = defineStore("devices", () => {
const items = ref<Device[]>([]);
const loading = ref(false);
async function load(): Promise<void> {
loading.value = true;
try {
items.value = (await api.get<{ devices: Device[] }>("/api/auth/devices")).devices;
} finally {
loading.value = false;
}
}
// Issues a token for the current user; the plaintext token is returned ONCE
// (never retrievable again) for the caller to display + copy.
async function create(name: string): Promise<string> {
const res = await api.post<{ token: string; device: Device }>("/api/auth/devices", { name });
items.value.unshift(res.device);
return res.token;
}
async function revoke(id: string): Promise<void> {
await api.del(`/api/auth/devices/${id}`);
items.value = items.value.filter((d) => d.id !== id);
}
return { items, loading, load, create, revoke };
});
+177
View File
@@ -0,0 +1,177 @@
<script setup lang="ts">
import { onMounted, ref } from "vue";
import { useDevicesStore } from "../stores/devices";
import { useUiStore } from "../stores/ui";
import BaseButton from "../components/BaseButton.vue";
import Icon from "../components/Icon.vue";
// Per-user (not admin) management of linked native clients — the Tauri desktop and
// Android apps authenticate sync with a device bearer token issued here.
const devices = useDevicesStore();
const ui = useUiStore();
const error = ref("");
const newName = ref("");
const creating = ref(false);
// The freshly-issued plaintext token — shown ONCE (never retrievable again).
const freshToken = ref("");
async function load() {
error.value = "";
try {
await devices.load();
} catch {
error.value = "Couldn't load your linked devices.";
}
}
async function link() {
creating.value = true;
error.value = "";
freshToken.value = "";
try {
freshToken.value = await devices.create(newName.value.trim() || "Device");
newName.value = "";
} catch (e) {
error.value = (e as { error?: string }).error ?? "Couldn't create a device token.";
} finally {
creating.value = false;
}
}
async function copyToken() {
try {
await navigator.clipboard.writeText(freshToken.value);
ui.showToast("Token copied to clipboard.");
} catch {
ui.showToast("Couldn't copy — select and copy it manually.");
}
}
async function revoke(id: string, name: string) {
if (!window.confirm(`Revoke "${name}"? That device will need to link again to sync.`)) return;
try {
await devices.revoke(id);
} catch {
ui.showToast("Couldn't revoke that device.");
}
}
function fmt(iso: string | null): string {
if (!iso) return "never";
return new Date(iso).toLocaleString();
}
onMounted(load);
</script>
<template>
<div class="mx-auto min-h-full max-w-2xl px-4 py-8">
<header class="mb-8 flex items-center gap-3">
<RouterLink to="/" class="icon-btn" title="Back to board" aria-label="Back to board">
<svg
class="h-[18px] w-[18px]"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2"
stroke-linecap="round"
stroke-linejoin="round"
aria-hidden="true"
>
<path d="m15 18-6-6 6-6" />
</svg>
</RouterLink>
<h1 class="text-xl font-bold tracking-tight">Linked devices</h1>
</header>
<p class="mb-6 max-w-xl text-sm text-neutral-500 dark:text-neutral-400">
Link the ThoughtSync desktop or mobile app to sync your notes. Create a device token here, then
paste it into the app when it asks to connect. You can revoke a device at any time.
</p>
<!-- One-time token reveal -->
<div
v-if="freshToken"
class="mb-6 rounded-xl border border-brand/40 bg-brand/5 p-4 dark:border-brand/30 dark:bg-brand/10"
>
<p class="text-sm font-medium text-neutral-800 dark:text-neutral-100">
Copy this token now it won't be shown again.
</p>
<div class="mt-2 flex items-center gap-2">
<code
class="min-w-0 flex-1 overflow-x-auto rounded-lg border border-neutral-300 bg-white px-3 py-2 font-mono text-xs text-neutral-900 dark:border-neutral-700 dark:bg-neutral-900 dark:text-neutral-100"
>{{ freshToken }}</code
>
<button
type="button"
class="icon-btn shrink-0"
title="Copy token"
aria-label="Copy token"
@click="copyToken"
>
<Icon name="copy" />
</button>
</div>
<button
type="button"
class="mt-3 text-xs text-neutral-500 underline hover:text-neutral-700 dark:hover:text-neutral-300"
@click="freshToken = ''"
>
Done
</button>
</div>
<!-- Create a device token -->
<form class="mb-8 flex items-end gap-3" @submit.prevent="link">
<div class="flex flex-1 flex-col gap-1">
<label for="device-name" class="text-sm font-medium text-neutral-800 dark:text-neutral-200"
>Link a new device</label
>
<input
id="device-name"
v-model="newName"
type="text"
placeholder="e.g. My laptop, Pixel phone"
class="rounded-lg border border-neutral-300 bg-white px-3 py-2 text-sm text-neutral-900 shadow-sm focus:outline-none focus-visible:ring-2 focus-visible:ring-brand dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-100"
/>
</div>
<BaseButton type="submit" :loading="creating">Create token</BaseButton>
</form>
<p v-if="error" class="mb-4 text-sm text-red-600 dark:text-red-400">{{ error }}</p>
<!-- Device list -->
<div v-if="devices.loading" class="py-10 text-center text-sm text-neutral-400">Loading…</div>
<div
v-else-if="!devices.items.length"
class="rounded-xl border border-dashed border-neutral-300 py-10 text-center dark:border-neutral-700"
>
<p class="text-sm text-neutral-500 dark:text-neutral-400">No devices linked yet.</p>
</div>
<ul v-else class="flex flex-col gap-2">
<li
v-for="d in devices.items"
:key="d.id"
class="flex items-center justify-between gap-4 rounded-xl border border-neutral-200 px-4 py-3 dark:border-neutral-800"
>
<div class="flex min-w-0 items-center gap-3">
<span class="text-neutral-400"><Icon name="device" /></span>
<div class="min-w-0">
<p class="truncate text-sm font-medium text-neutral-800 dark:text-neutral-100">{{ d.name }}</p>
<p class="text-xs text-neutral-400">
Linked {{ fmt(d.created_at) }} · last synced {{ fmt(d.last_used_at) }}
</p>
</div>
</div>
<button
type="button"
class="shrink-0 rounded-md border border-neutral-300 px-2.5 py-1 text-xs text-red-600 hover:bg-red-50 focus:outline-none focus-visible:ring-2 focus-visible:ring-brand dark:border-neutral-700 dark:text-red-400 dark:hover:bg-red-950/40"
@click="revoke(d.id, d.name)"
>
Revoke
</button>
</li>
</ul>
</div>
</template>