This commit is contained in:
JCEEE
2026-09-14 15:36:55 +01:00
37 changed files with 2396 additions and 464 deletions
+2 -2
View File
@@ -235,8 +235,8 @@ export async function redeemOtp(opts: { famSlug: string; username: string; otp:
if (!issued || Date.now() - issued > OTP_TTL_MS) throw new Error('Code expired');
const authPb = createPbClient();
await authPb
const { record } = await authPb
.collection('users')
.authWithPassword(fullUsername, derivePassword(famSlug, handleName));
return authPb.authStore.token;
return { token: authPb.authStore.token, userId: record.id };
}
+54
View File
@@ -262,6 +262,54 @@ async function ensureOtp(ids: Record<string, string>): Promise<void> {
});
}
// Child shared-device PINs. Superuser-only rules (like `otp`) — all access
// goes through server endpoints with session-role checks, so children can
// never read siblings' pins via PB rules.
async function ensurePins(ids: Record<string, string>): Promise<void> {
if (await getCollection('pins')) return;
const famsId = ids.fams || (await getCollection('fams'))?.id;
const usersId = ids.users || (await getCollection('users'))?.id;
if (!famsId || !usersId) throw new Error('fams/users collection not found');
await createCollection({
name: 'pins',
type: 'base',
listRule: null,
viewRule: null,
createRule: null,
updateRule: null,
deleteRule: null,
fields: [
{
name: 'famId',
type: 'relation',
required: true,
collectionId: famsId,
maxSelect: 1,
cascadeDelete: false
},
{
name: 'userId',
type: 'relation',
required: true,
collectionId: usersId,
maxSelect: 1,
cascadeDelete: false
},
{ name: 'pin', type: 'text', required: false }
]
});
}
// Idempotent field-add for the shared-device idle lock (0 = off, else mins).
async function ensureSettingsFields(): Promise<void> {
const settingsCol = await getCollection('settings');
if (!settingsCol) return;
const has = (n: string) => settingsCol.fields.some((f: any) => f.name === n);
if (has('lockMins')) return;
settingsCol.fields.push({ name: 'lockMins', type: 'number', required: false });
await updateCollection(settingsCol.id, { fields: settingsCol.fields });
}
// Platform access codes — the codes that enable access to the platform. They're
// global (not fam-scoped) and managed via the platform admin page (superuser
// only), so all rules are null like `otp`. A code grants a family a subscription
@@ -404,6 +452,7 @@ async function ensureSchema(): Promise<void> {
await ensureUsers(ids);
await ensureOtp(ids);
await ensurePins(ids);
console.log('[migrate] Schema bootstrapped.');
}
@@ -473,11 +522,16 @@ export async function migrate(): Promise<void> {
// return) so new platform collections/fields/seed land on existing installs.
await ensureUserFields();
await ensureFamFields();
await ensureSettingsFields();
await ensureBonusFields();
await ensureTemplateFields();
await ensureAssignedChoreFields();
await ensureAccessCodes();
await ensurePlatform();
// Superuser-only collections also land on EXISTING installs (ensureSchema's
// early return skips them). Like ensureOtp before it, ensurePins no-ops when
// the collection already exists.
await ensurePins({});
await ensureDefaultSeasons();
if (await isDemo()) {
await seedDemoFamily();
+50
View File
@@ -0,0 +1,50 @@
import { randomBytes } from 'node:crypto';
import { createSuperClient } from '$lib/server/pocketbase';
// Child shared-device PINs. Superuser-only collection (like `otp`): every
// read/write goes through server endpoints with session-role checks, so a
// child can never read a sibling's PIN via PB rules.
export const PIN_RE = /^\d{3}$/;
export function generatePin(): string {
const n = randomBytes(2).readUIntBE(0, 2) % 1000;
return n.toString().padStart(3, '0');
}
async function getPinRow(userId: string) {
const pb = await createSuperClient();
return pb
.collection('pins')
.getFirstListItem(`userId='${userId}'`)
.catch(() => null);
}
export async function getPin(userId: string): Promise<string | null> {
const row = await getPinRow(userId);
return row?.pin || null;
}
export async function hasPin(userId: string): Promise<boolean> {
return (await getPin(userId)) !== null;
}
export async function setPin(famId: string, userId: string, pin: string): Promise<void> {
const pb = await createSuperClient();
const row = await getPinRow(userId);
if (row) {
await pb.collection('pins').update(row.id, { pin });
} else {
await pb.collection('pins').create({ famId, userId, pin });
}
}
export async function resetPin(famId: string, userId: string): Promise<string> {
const pin = generatePin();
await setPin(famId, userId, pin);
return pin;
}
export async function verifyPin(userId: string, pin: string): Promise<boolean> {
const row = await getPinRow(userId);
return !!row && row.pin === pin;
}
+51 -7
View File
@@ -1,22 +1,66 @@
import type { Cookies } from '@sveltejs/kit';
// The PocketBase JWT lives in a single cookie shared by:
// PocketBase JWTs live in cookies shared by:
// - the server hooks (authRefresh -> locals.user)
// - the client SDK (seeded from page.data.pbToken -> authenticated famStore reads/subscribe)
// httpOnly keeps the token out of reach of browser JS/XSS; the client receives
// httpOnly keeps tokens out of reach of browser JS/XSS; the client receives
// the token server-side via the layout load (pbToken) and seeds pb.authStore.
// Secure flag is set in prod so it's only sent over HTTPS.
export const SESSION_COOKIE = 'pb_token';
// Shared-device multi-session: children hold ONE cookie per account
// (`pb_token_<userId>`); `pb_active` names which one is the current session.
// Parents stay on the single `pb_token`.
export const CHILD_COOKIE_PREFIX = 'pb_token_';
export const ACTIVE_COOKIE = 'pb_active';
const MAX_AGE = 60 * 60 * 24 * 5; // 5 days — matches the PB users auth token duration
export function setSessionCookie(cookies: Cookies, token: string) {
cookies.set(SESSION_COOKIE, token, {
function cookieOpts() {
return {
httpOnly: true,
sameSite: 'lax',
sameSite: 'lax' as const,
path: '/',
maxAge: MAX_AGE,
secure: import.meta.env.PROD
});
};
}
export function setSessionCookie(cookies: Cookies, token: string) {
cookies.set(SESSION_COOKIE, token, cookieOpts());
}
export function childSessionCookie(userId: string) {
return `${CHILD_COOKIE_PREFIX}${userId}`;
}
export function setChildSessionCookie(cookies: Cookies, userId: string, token: string) {
cookies.set(childSessionCookie(userId), token, cookieOpts());
}
export function clearChildSession(cookies: Cookies, userId: string) {
cookies.delete(childSessionCookie(userId), { path: '/' });
}
export function setActiveChild(cookies: Cookies, userId: string) {
cookies.set(ACTIVE_COOKIE, userId, cookieOpts());
}
export function clearActiveChild(cookies: Cookies) {
cookies.delete(ACTIVE_COOKIE, { path: '/' });
}
// Ids of every child that has a session cookie on this device.
export function scanChildSessions(cookies: Cookies): string[] {
return cookies
.getAll()
.filter((c) => c.name.startsWith(CHILD_COOKIE_PREFIX))
.map((c) => c.name.slice(CHILD_COOKIE_PREFIX.length))
.filter(Boolean);
}
// Remove every child session on this device (logout-all).
export function clearDeviceSessions(cookies: Cookies) {
for (const id of scanChildSessions(cookies)) clearChildSession(cookies, id);
clearActiveChild(cookies);
}
export function clearSessionCookie(cookies: Cookies) {
@@ -50,4 +94,4 @@ export function setPlatformSession(cookies: Cookies, token: string) {
export function clearPlatformSession(cookies: Cookies) {
cookies.delete(PLATFORM_SESSION_COOKIE, { path: '/' });
}
}