add shared computer feature
This commit is contained in:
@@ -194,6 +194,10 @@ export async function load(event) {
|
||||
pickerFamName: '',
|
||||
pickerChildren: [],
|
||||
deviceChildIds,
|
||||
lockMins
|
||||
lockMins,
|
||||
// Per-device shared-computer flag (cookie mirror of the localStorage
|
||||
// flag the TopNav toggle writes). Server can only hint — the client
|
||||
// re-reads localStorage on hydration.
|
||||
sharedDevice: event.cookies.get('fam_shared_device') === '1'
|
||||
};
|
||||
}
|
||||
|
||||
@@ -7,9 +7,10 @@
|
||||
import { chatStore } from '$lib/stores/chat.svelte';
|
||||
import { notices } from '$lib/stores/notices.svelte';
|
||||
import { Sidebar, TopNav, Footer, Chat, SharedPicker } from '$lib/components';
|
||||
import { chatIcon } from '$lib/components/icons';
|
||||
import { chatIcon, monitorIcon } from '$lib/components/icons';
|
||||
import { recordShortcut } from '$lib/shortcut';
|
||||
import { installLockTracking, lockDue } from '$lib/client/lock';
|
||||
import { isSharedDevice, setSharedDevice } from '$lib/client/shared-device';
|
||||
import { themeShades } from '$lib/theme';
|
||||
import '$lib/theme-patterns.css';
|
||||
import { themeDraft } from '$lib/stores/theme.svelte';
|
||||
@@ -43,13 +44,59 @@
|
||||
.map((m: any) => ({ id: m.id, name: m.name, color: m.color, username: m.username }))
|
||||
);
|
||||
|
||||
// Idle lock (children only): return to the picker after `lockMins` of no
|
||||
// interaction. localStorage-backed (see lib/client/lock.ts) so a closed
|
||||
// browser still trips the lock on next launch.
|
||||
// Shared-computer mode (per-device flag, NOT a fam setting — see
|
||||
// lib/client/shared-device.ts). Makes the PIN system functional on this
|
||||
// browser: profile switcher + idle lock. Anyone logged in (or not) can
|
||||
// flip it; server sees the cookie mirror as data.sharedDevice.
|
||||
let sharedOn = $state(
|
||||
typeof localStorage !== 'undefined' ? isSharedDevice() : !!(data as any).sharedDevice
|
||||
);
|
||||
let sharedToast = $state('');
|
||||
|
||||
async function toggleShared() {
|
||||
sharedOn = !sharedOn;
|
||||
setSharedDevice(sharedOn);
|
||||
if (!sharedOn) {
|
||||
sharedToast = '';
|
||||
return;
|
||||
}
|
||||
// Just enabled — remind about PIN state. Kids without a PIN can't be
|
||||
// picked until one is set (picker shows "ask a parent"); kids with one
|
||||
// get a nudge to remember it. Values never exposed — only set/unset.
|
||||
try {
|
||||
const res = await fetch('/api/pins/status');
|
||||
if (!res.ok) throw new Error();
|
||||
const s = await res.json();
|
||||
if (Array.isArray(s.children)) {
|
||||
// Parent view: roster of who still needs a PIN.
|
||||
const missing = s.children.filter((c: any) => !c.hasPin).map((c: any) => c.name);
|
||||
const ready = s.children.filter((c: any) => c.hasPin).map((c: any) => c.name);
|
||||
sharedToast =
|
||||
missing.length > 0
|
||||
? `Shared mode on — still need a PIN: ${missing.join(', ')} (set in Settings → Members).` +
|
||||
(ready.length > 0 ? ` Ready: ${ready.join(', ')}.` : '')
|
||||
: `Shared mode on — PINs ready for ${ready.length > 0 ? ready.join(', ') : 'everyone'}. Remind the kids!`;
|
||||
} else if (typeof s.hasPin === 'boolean') {
|
||||
// Child view: only their own state.
|
||||
sharedToast = s.hasPin
|
||||
? 'Shared mode on — remember your 3-digit PIN to switch back in!'
|
||||
: 'Shared mode on — you need a PIN first. Ask a parent to set one up.';
|
||||
} else {
|
||||
sharedToast = 'Shared mode on for this computer.';
|
||||
}
|
||||
} catch {
|
||||
sharedToast = 'Shared mode on for this computer.';
|
||||
}
|
||||
setTimeout(() => (sharedToast = ''), 8000);
|
||||
}
|
||||
|
||||
// Idle lock (children on shared devices only): return to the picker after
|
||||
// `lockMins` of no interaction. localStorage-backed (see lib/client/lock.ts)
|
||||
// so a closed browser still trips the lock on next launch.
|
||||
$effect(() => {
|
||||
const isChild = data.session?.role === 'child';
|
||||
const lockMins = Number(data.lockMins) || 0;
|
||||
if (!isChild || lockMins <= 0 || data.picker) return;
|
||||
if (!isChild || !sharedOn || lockMins <= 0 || data.picker) return;
|
||||
installLockTracking();
|
||||
if (lockDue(lockMins)) pickerOpen = true;
|
||||
if (!lockTimer) {
|
||||
@@ -258,7 +305,7 @@
|
||||
<span class="chat-badge">{chatStore.unread > 9 ? '9+' : chatStore.unread}</span>
|
||||
{/if}
|
||||
</button>
|
||||
{#if data.session && (data.deviceChildIds?.length || 0) > 0}
|
||||
{#if data.session && sharedOn && (data.deviceChildIds?.length || 0) > 0}
|
||||
<button
|
||||
class="kid-switch"
|
||||
onclick={() => (pickerOpen = true)}
|
||||
@@ -269,6 +316,16 @@
|
||||
></span>
|
||||
</button>
|
||||
{/if}
|
||||
<button
|
||||
class="shared-toggle"
|
||||
class:on={sharedOn}
|
||||
onclick={toggleShared}
|
||||
aria-label="Toggle shared computer mode"
|
||||
aria-pressed={sharedOn}
|
||||
title={sharedOn ? 'Shared computer mode is ON' : 'Mark this as a shared computer'}
|
||||
>
|
||||
{@html monitorIcon}
|
||||
</button>
|
||||
</TopNav>
|
||||
<main class="app-main" class:join-page={page.url.pathname.split('/')[2] === 'join'}>
|
||||
<div class="page-wrap">
|
||||
@@ -304,6 +361,9 @@
|
||||
{claimToast} — view dashboard →
|
||||
</a>
|
||||
{/if}
|
||||
{#if sharedToast}
|
||||
<div class="shared-toast" role="status">{sharedToast}</div>
|
||||
{/if}
|
||||
<Footer sidebar />
|
||||
</div>
|
||||
{#if chatStore.open}
|
||||
@@ -491,6 +551,42 @@
|
||||
border: 2px solid #fff;
|
||||
box-shadow: 0 0 0 1px #e2e8f0;
|
||||
}
|
||||
.shared-toggle {
|
||||
width: 40px;
|
||||
height: 40px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
background: #f3f4f6;
|
||||
color: #9ca3af;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
cursor: pointer;
|
||||
}
|
||||
.shared-toggle:hover {
|
||||
background: #e5e7eb;
|
||||
}
|
||||
.shared-toggle.on {
|
||||
background: #6366f1;
|
||||
color: #fff;
|
||||
box-shadow: 0 0 0 3px rgba(99, 102, 241, 0.25);
|
||||
}
|
||||
.shared-toast {
|
||||
position: fixed;
|
||||
bottom: 1rem;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
background: #1f2937;
|
||||
color: #fff;
|
||||
padding: 0.6rem 1.2rem;
|
||||
border-radius: 12px;
|
||||
font-size: 0.85rem;
|
||||
font-weight: 600;
|
||||
z-index: 96;
|
||||
box-shadow: 0 4px 14px rgba(0, 0, 0, 0.3);
|
||||
max-width: min(92vw, 560px);
|
||||
text-align: center;
|
||||
}
|
||||
.picker-stage {
|
||||
min-height: 100vh;
|
||||
width: 100%;
|
||||
|
||||
@@ -0,0 +1,13 @@
|
||||
import { redirect } from '@sveltejs/kit';
|
||||
|
||||
// The fam layout renders the shared-device picker when child sessions exist
|
||||
// but none is active. With an active session this route just sends you home.
|
||||
export async function load(event) {
|
||||
const session = event.locals.user;
|
||||
if (session) {
|
||||
const fam = event.params.fam;
|
||||
if (session.role === 'parent') throw redirect(303, `/${fam}`);
|
||||
throw redirect(303, `/${fam}/${encodeURIComponent(session.username || '')}`);
|
||||
}
|
||||
return {};
|
||||
}
|
||||
@@ -0,0 +1,4 @@
|
||||
<!-- Shared-device profile picker. The fam layout renders the picker itself in
|
||||
picker mode (no active session, child sessions present) — this page only
|
||||
exists so /{fam}/switch resolves as a route. -->
|
||||
<div></div>
|
||||
@@ -0,0 +1,23 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import {
|
||||
ACTIVE_COOKIE,
|
||||
childSessionCookie,
|
||||
clearChildSession,
|
||||
clearActiveChild
|
||||
} from '$lib/server/session';
|
||||
|
||||
// Remove ONE child profile from this device (picker ✕). Device-local cookie
|
||||
// surgery only — no PB writes, no session required (the picker is reachable
|
||||
// with no active user).
|
||||
export async function POST(event: RequestEvent) {
|
||||
const body = await event.request.json().catch(() => ({}));
|
||||
const { userId } = body as { userId?: string };
|
||||
if (!userId) throw error(400, 'Missing userId');
|
||||
if (!event.cookies.get(childSessionCookie(userId))) {
|
||||
throw error(400, 'No session on this device');
|
||||
}
|
||||
clearChildSession(event.cookies, userId);
|
||||
if (event.cookies.get(ACTIVE_COOKIE) === userId) clearActiveChild(event.cookies);
|
||||
return json({ ok: true });
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { getPin, setPin, verifyPin, hasPin, PIN_RE } from '$lib/server/pins';
|
||||
import { createPbClient } from '$lib/server/pocketbase';
|
||||
|
||||
// PIN status for the shared-device toggle reminders. Never reveals values:
|
||||
// - child → whether THEIR OWN pin is set (about self only);
|
||||
// - parent → per-child set/unset roster (names + booleans, no PIN values;
|
||||
// actual values stay behind the settings revealPin action).
|
||||
export async function GET(event: RequestEvent) {
|
||||
const u = event.locals.user;
|
||||
if (!u || !event.locals.pbToken) throw error(401, 'Unauthorized');
|
||||
if (u.role === 'child') {
|
||||
return json({ hasPin: await hasPin(u.id) });
|
||||
}
|
||||
if (u.role !== 'parent') throw error(403, 'Forbidden');
|
||||
const pb = createPbClient(event.locals.pbToken);
|
||||
const kids: any[] = await pb
|
||||
.collection('users')
|
||||
.getFullList({ filter: `famId = '${u.famId}' && role = 'child'` })
|
||||
.catch(() => []);
|
||||
const children = await Promise.all(
|
||||
kids.map(async (k: any) => ({
|
||||
userId: k.id,
|
||||
name: k.name || '?',
|
||||
hasPin: await hasPin(k.id)
|
||||
}))
|
||||
);
|
||||
return json({ children });
|
||||
}
|
||||
|
||||
// Child PIN management. Session-role checked here (PB rules are superuser-only
|
||||
// on `pins`): only the child themselves can set/change their own PIN.
|
||||
export async function POST(event: RequestEvent) {
|
||||
const u = event.locals.user;
|
||||
if (!u) throw error(401, 'Unauthorized');
|
||||
if (u.role !== 'child') throw error(403, 'Only children use PINs');
|
||||
|
||||
const body = await event.request.json().catch(() => ({}));
|
||||
const { action, pin, currentPin } = body as {
|
||||
action?: string;
|
||||
pin?: string;
|
||||
currentPin?: string;
|
||||
};
|
||||
if (!action || !pin || !PIN_RE.test(pin)) {
|
||||
throw error(400, 'PIN must be exactly 3 digits');
|
||||
}
|
||||
|
||||
if (action === 'set') {
|
||||
if (await getPin(u.id)) throw error(400, 'PIN already set');
|
||||
await setPin(u.famId, u.id, pin);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
// Join wizard: assign the PIN on THIS device without touching an existing
|
||||
// one (a kid joining a second shared device already has a PIN — their pin
|
||||
// works everywhere; nobody can silently reassign it).
|
||||
if (action === 'ensure') {
|
||||
if (!(await getPin(u.id))) await setPin(u.famId, u.id, pin);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
if (action === 'change') {
|
||||
const existing = await getPin(u.id);
|
||||
if (!existing) throw error(400, 'No PIN set yet');
|
||||
if (!currentPin || !(await verifyPin(u.id, currentPin))) {
|
||||
throw error(401, 'Current PIN is wrong');
|
||||
}
|
||||
await setPin(u.famId, u.id, pin);
|
||||
return json({ ok: true });
|
||||
}
|
||||
|
||||
throw error(400, 'Unknown action');
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
import { json, error } from '@sveltejs/kit';
|
||||
import type { RequestEvent } from '@sveltejs/kit';
|
||||
import { createPbClient, createSuperClient } from '$lib/server/pocketbase';
|
||||
import { childSessionCookie, setChildSessionCookie, setActiveChild } from '$lib/server/session';
|
||||
import { verifyPin } from '$lib/server/pins';
|
||||
import { derivePassword } from '$lib/server/member-otp';
|
||||
import { famUsername } from '@shared/slugify';
|
||||
|
||||
// Shared-device PIN switch. The PIN *selects* among sessions that already
|
||||
// exist on this device — it is not a credential that mints anything on a
|
||||
// fresh device. The target must have a pb_token_<userId> cookie; the PIN is
|
||||
// verified server-side via the superuser client (children must never read
|
||||
// siblings' pins), with a small per-user rate limit on the 3-digit space.
|
||||
|
||||
const MAX_TRIES = 5;
|
||||
const LOCK_MS = 30_000;
|
||||
const tries = new Map<string, { fails: number; until: number }>();
|
||||
|
||||
function checkRateLimit(userId: string) {
|
||||
const rec = tries.get(userId);
|
||||
if (rec && rec.until > Date.now()) {
|
||||
throw error(429, 'Too many attempts — try again in a few seconds');
|
||||
}
|
||||
}
|
||||
|
||||
function noteFailure(userId: string) {
|
||||
const rec = tries.get(userId) || { fails: 0, until: 0 };
|
||||
rec.fails += 1;
|
||||
if (rec.fails >= MAX_TRIES) {
|
||||
rec.until = Date.now() + LOCK_MS;
|
||||
rec.fails = 0;
|
||||
}
|
||||
tries.set(userId, rec);
|
||||
}
|
||||
|
||||
export async function POST(event: RequestEvent) {
|
||||
const body = await event.request.json().catch(() => ({}));
|
||||
const { userId, pin } = body as { userId?: string; pin?: string };
|
||||
if (!userId || !pin) throw error(400, 'Missing userId or pin');
|
||||
if (!event.cookies.get(childSessionCookie(userId))) {
|
||||
throw error(400, 'That profile has no session on this device');
|
||||
}
|
||||
|
||||
checkRateLimit(userId);
|
||||
if (!(await verifyPin(userId, String(pin)))) {
|
||||
noteFailure(userId);
|
||||
throw error(401, 'Wrong PIN — try again');
|
||||
}
|
||||
|
||||
// Ensure a usable token: refresh the device cookie; if it has expired,
|
||||
// re-mint via the derived password (server-side only — the child never
|
||||
// knows it, and a stale session heals itself on switch).
|
||||
const pb = await createSuperClient();
|
||||
const user = await pb
|
||||
.collection('users')
|
||||
.getOne(userId)
|
||||
.catch(() => null);
|
||||
if (!user || user.role !== 'child') throw error(400, 'Not a child account');
|
||||
|
||||
let freshToken = '';
|
||||
try {
|
||||
const cookieToken = event.cookies.get(childSessionCookie(userId));
|
||||
if (cookieToken) {
|
||||
const { token } = await createPbClient(cookieToken).collection('users').authRefresh();
|
||||
freshToken = token;
|
||||
}
|
||||
} catch {
|
||||
/* expired — re-mint below */
|
||||
}
|
||||
if (!freshToken) {
|
||||
// username = `{famSlug}:{handle}` — the server can always re-mint.
|
||||
const [famSlug, handleName] = (user.username || '').split(':');
|
||||
if (!famSlug || !handleName) throw error(400, 'Cannot restore session');
|
||||
const auth = createPbClient();
|
||||
const { token } = await auth
|
||||
.collection('users')
|
||||
.authWithPassword(famUsername(famSlug, handleName), derivePassword(famSlug, handleName));
|
||||
freshToken = token;
|
||||
}
|
||||
|
||||
setChildSessionCookie(event.cookies, userId, freshToken);
|
||||
setActiveChild(event.cookies, userId);
|
||||
return json({ ok: true });
|
||||
}
|
||||
Reference in New Issue
Block a user