towards multi-user

This commit is contained in:
Davide Scaini
2026-04-08 19:37:10 +02:00
parent 36a91362d9
commit f76cc0ce7e
18 changed files with 1248 additions and 30 deletions
+14
View File
@@ -1,7 +1,11 @@
import { defineConfig } from "astro/config";
import { loadEnv } from "vite";
import svelte from "@astrojs/svelte";
import tailwind from "@astrojs/tailwind";
const env = loadEnv(process.env.NODE_ENV ?? 'development', process.cwd(), '');
const serveTarget = env.PUBLIC_EDIT_URL || 'http://localhost:4041';
export default defineConfig({
integrations: [svelte(), tailwind()],
devToolbar: { enabled: false },
@@ -14,5 +18,15 @@ export default defineConfig({
esbuildOptions: { target: 'es2022' },
},
build: { target: 'es2022' },
// Proxy /api/* to bincio serve/edit so cookies work same-origin in dev.
// In production nginx handles this — same pattern, no code change needed.
server: {
proxy: {
'/api': {
target: serveTarget,
changeOrigin: true,
},
},
},
},
});
+17 -3
View File
@@ -28,6 +28,13 @@
.join(' ');
}
/** Base URL of the site (passed from Astro). */
export let base: string = '/';
/** When set, load this index URL instead of the root (for per-user profile pages). */
export let profileIndexUrl: string = '';
/** When set, only show activities from this handle. */
export let filterHandle: string = '';
const PAGE_SIZE = 60;
let all: ActivitySummary[] = [];
@@ -54,8 +61,13 @@
sport = (new URLSearchParams(window.location.search).get('sport') as Sport | 'all') ?? 'all';
mounted = true;
try {
const index = await loadIndex(import.meta.env.BASE_URL);
all = index.activities.filter(a => a.privacy !== 'private');
const indexUrl = profileIndexUrl
? `${base}data/${profileIndexUrl}`
: `${base}data/index.json`;
const index = await loadIndex(base, indexUrl);
let activities = index.activities.filter(a => a.privacy !== 'private');
if (filterHandle) activities = activities.filter(a => a.handle === filterHandle);
all = activities;
} catch (e: any) {
error = e.message;
} finally {
@@ -117,7 +129,9 @@
<!-- header -->
<div class="flex items-start justify-between gap-2 mb-3">
<div class="flex-1 min-w-0">
<p class="text-xs text-zinc-500 mb-0.5">{formatDate(a.started_at)}</p>
<p class="text-xs text-zinc-500 mb-0.5">
{formatDate(a.started_at)}{#if a.handle} · <a href={`${import.meta.env.BASE_URL}${a.handle}/`} class="hover:text-zinc-300 transition-colors" on:click|stopPropagation>@{a.handle}</a>{/if}
</p>
<h3 class="font-semibold text-white truncate group-hover:text-[--accent] transition-colors">
{a.title}
</h3>
+30 -1
View File
@@ -1,11 +1,31 @@
---
import { readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
interface Props {
title?: string;
description?: string;
/** Set true on pages that must remain accessible without auth (login, register). */
public?: boolean;
}
const { title = 'BincioActivity', description = 'Your personal activity stats' } = Astro.props;
const { title = 'BincioActivity', description = 'Your personal activity stats', public: isPublicPage = false } = Astro.props;
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? '';
const baseUrl = import.meta.env.BASE_URL ?? '/';
// Detect whether this instance is private (multi-user, requires login to view).
let instancePrivate = false;
try {
const candidates = [
process.env.BINCIO_DATA_DIR,
resolve(process.cwd(), 'public', 'data'),
resolve(process.cwd(), '..', 'bincio_data'),
].filter(Boolean) as string[];
const dataDir = candidates.find(d => { try { readFileSync(join(d, 'index.json')); return true; } catch { return false; } });
if (dataDir) {
const root = JSON.parse(readFileSync(join(dataDir, 'index.json'), 'utf-8'));
instancePrivate = root?.instance?.private === true;
}
} catch { /* non-fatal */ }
---
<!doctype html>
<html lang="en" data-theme="dark">
@@ -28,6 +48,15 @@ const baseUrl = import.meta.env.BASE_URL ?? '/';
});
</script>
<!-- Auth wall: redirect to /login/ on private instances when not authenticated -->
{instancePrivate && !isPublicPage && (
<script is:inline>
fetch('/api/me', { credentials: 'include' })
.then(r => { if (r.status === 401 || r.status === 404) window.location.replace('/login/'); })
.catch(() => {});
</script>
)}
<style is:global>
/* ── Theme tokens ─────────────────────────────────────────────────────── */
:root, [data-theme="dark"] {
+56 -8
View File
@@ -58,28 +58,76 @@ function emptyIndex(): BASIndex {
// ── Public API ────────────────────────────────────────────────────────────────
/**
* Load the activity index, merging the server's copy with any locally-stored
* activities. Local entries override server entries with the same ID.
* Resolve shards from a BASIndex into a flat activity list.
*
* Handles two shard types transparently:
* - handle shards: multi-user manifest (url = "{handle}/index.json")
* - year shards: per-user pagination (url = "index-2025.json")
*
* Shard URLs are resolved relative to the index URL that declared them.
* All shard fetches run concurrently. Errors are silently skipped so a
* single unavailable shard doesn't break the whole feed.
*/
export async function loadIndex(baseUrl: string): Promise<BASIndex> {
async function resolveShards(
index: BASIndex,
indexUrl: string,
): Promise<ActivitySummary[]> {
if (!index.shards?.length) return index.activities ?? [];
const base = indexUrl.substring(0, indexUrl.lastIndexOf('/') + 1);
const shardResults = await Promise.allSettled(
index.shards.map(async shard => {
const url = shard.url.startsWith('http') ? shard.url : `${base}${shard.url}`;
const sub = await fetchJSON<BASIndex>(url);
// Recursively resolve nested shards (e.g. user shard that itself paginates)
const activities = await resolveShards(sub, url);
// Tag each activity with the handle declared in the shard entry
if (shard.handle) {
return activities.map(a => ({ ...a, handle: shard.handle }));
}
return activities;
}),
);
const own = index.activities ?? [];
const fromShards = shardResults.flatMap(r => r.status === 'fulfilled' ? r.value : []);
return [...own, ...fromShards];
}
/**
* Load the activity index, resolving any shards (multi-user or pagination),
* then merging with locally-stored activities from IndexedDB.
*
* Single-user indexes with no shards work exactly as before — zero overhead.
*
* @param baseUrl Site base URL (used for IDB local activities)
* @param indexUrl Full URL of the index to load (defaults to baseUrl + data/index.json)
*/
export async function loadIndex(baseUrl: string, indexUrl?: string): Promise<BASIndex> {
indexUrl = indexUrl ?? `${baseUrl}data/index.json`;
const [serverResult, localResult] = await Promise.allSettled([
fetchJSON<BASIndex>(`${baseUrl}data/index.json`),
fetchJSON<BASIndex>(indexUrl),
listLocalActivities(),
]);
const server = serverResult.status === 'fulfilled' ? serverResult.value : null;
const local = localResult.status === 'fulfilled' ? localResult.value : [];
if (local.length === 0) return server ?? emptyIndex();
if (!server) return { ...emptyIndex(), activities: local as ActivitySummary[] };
const serverActivities = server
? await resolveShards(server, indexUrl)
: [];
if (local.length === 0 && !server) return emptyIndex();
// Local overrides server for the same ID; new local entries are appended
const merged = new Map<string, ActivitySummary>();
for (const a of server.activities ?? []) merged.set(a.id, a);
for (const a of serverActivities) merged.set(a.id, a);
for (const a of local as ActivitySummary[]) merged.set(a.id, a);
return {
...server,
...(server ?? emptyIndex()),
activities: [...merged.values()].sort(
(a, b) => (b.started_at ?? '').localeCompare(a.started_at ?? ''),
),
+7 -2
View File
@@ -70,6 +70,8 @@ export interface ActivitySummary {
track_url: string | null;
/** ~20 [lat, lon] pairs for card thumbnail — no separate fetch needed. */
preview_coords: [number, number][] | null;
/** Set on multi-user instances — the handle of the activity owner. */
handle?: string;
}
export interface AthleteZones {
@@ -81,9 +83,12 @@ export interface AthleteZones {
export interface BASIndex {
bas_version: string;
owner: { handle: string; display_name: string; avatar_url: string | null; athlete?: AthleteZones };
owner?: { handle: string; display_name: string; avatar_url?: string | null; athlete?: AthleteZones };
instance?: { name?: string; url?: string };
generated_at: string;
shards: Array<{ year: number; url: string; count: number }>;
// Shards can be user shards (multi-user manifest) or year shards (pagination).
// handle present → user shard; year present → pagination shard.
shards: Array<{ url: string; handle?: string; year?: number; count?: number }>;
activities: ActivitySummary[];
}
+26 -6
View File
@@ -9,18 +9,38 @@ export async function getStaticPaths() {
try {
const candidates = [
process.env.BINCIO_DATA_DIR,
resolve(process.cwd(), 'public', 'data'), // symlinked by `bincio render`
resolve(process.cwd(), 'public', 'data'),
resolve(process.cwd(), '..', 'bincio_data'),
].filter(Boolean) as string[];
const dataDir = candidates.find(d => { try { readFileSync(join(d, 'index.json')); return true; } catch { return false; } })!;
const raw = readFileSync(join(dataDir, 'index.json'), 'utf-8');
const index: BASIndex = JSON.parse(raw);
const dataDir = candidates.find(d => {
try { readFileSync(join(d, 'index.json')); return true; } catch { return false; }
})!;
return index.activities
const root: BASIndex = JSON.parse(readFileSync(join(dataDir, 'index.json'), 'utf-8'));
// Collect activities from root (single-user) or walk shards (multi-user)
function readActivities(indexPath: string): ActivitySummary[] {
try {
const idx: BASIndex = JSON.parse(readFileSync(indexPath, 'utf-8'));
const own = idx.activities ?? [];
const fromShards = (idx.shards ?? []).flatMap(s => {
const shardPath = join(dataDir, s.url);
return readActivities(shardPath);
});
return [...own, ...fromShards];
} catch {
return [];
}
}
const activities = readActivities(join(dataDir, 'index.json'));
const athlete = root.owner?.athlete ?? null;
return activities
.filter(a => a.privacy !== 'private' && a.id)
.map(a => ({
params: { id: a.id },
props: { activity: a, athlete: index.owner.athlete ?? null },
props: { activity: a, athlete },
}));
} catch {
return [];
+98
View File
@@ -0,0 +1,98 @@
---
import Base from '../../layouts/Base.astro';
---
<Base title="Invites — BincioActivity">
<div class="max-w-lg mx-auto mt-12 px-4">
<div class="flex items-center justify-between mb-6">
<h1 class="text-2xl font-bold text-white">Your invites</h1>
<button id="gen-btn"
class="px-4 py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white text-sm font-medium transition-opacity">
Generate invite
</button>
</div>
<p id="invite-error" class="text-red-400 text-sm mb-4 hidden"></p>
<ul id="invite-list" class="space-y-3">
<li class="text-zinc-500 text-sm">Loading…</li>
</ul>
</div>
</Base>
<script>
const listEl = document.getElementById('invite-list')!;
const errEl = document.getElementById('invite-error')!;
function renderInvite(inv: { code: string; used: boolean; used_by: string | null; created_at: number }) {
const li = document.createElement('li');
li.className = 'flex items-center justify-between rounded-xl bg-zinc-900 border border-zinc-800 px-4 py-3';
const date = new Date(inv.created_at * 1000).toLocaleDateString('en-GB', { day: 'numeric', month: 'short', year: 'numeric' });
const registerUrl = `${window.location.origin}/register/?code=${inv.code}`;
li.innerHTML = `
<div>
<span class="font-mono text-lg tracking-widest ${inv.used ? 'text-zinc-600 line-through' : 'text-white'}">${inv.code}</span>
<p class="text-xs text-zinc-500 mt-0.5">
${inv.used ? `Used by @${inv.used_by}` : `Created ${date}`}
</p>
</div>
${!inv.used ? `
<button data-link="${registerUrl}"
class="copy-btn text-xs px-3 py-1.5 rounded-lg bg-zinc-800 hover:bg-zinc-700 text-zinc-300 transition-colors">
Copy link
</button>
` : ''}
`;
return li;
}
async function loadInvites() {
try {
const r = await fetch('/api/invites', { credentials: 'include' });
if (r.status === 401) {
window.location.href = `/login/?next=${encodeURIComponent(window.location.pathname)}`;
return;
}
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const invites = await r.json();
listEl.innerHTML = '';
if (invites.length === 0) {
listEl.innerHTML = '<li class="text-zinc-500 text-sm">No invites yet.</li>';
return;
}
for (const inv of invites) listEl.appendChild(renderInvite(inv));
// Copy link buttons
listEl.querySelectorAll('.copy-btn').forEach(btn => {
btn.addEventListener('click', () => {
navigator.clipboard.writeText((btn as HTMLElement).dataset.link ?? '');
btn.textContent = 'Copied!';
setTimeout(() => { btn.textContent = 'Copy link'; }, 2000);
});
});
} catch (e: any) {
errEl.textContent = e.message;
errEl.classList.remove('hidden');
}
}
document.getElementById('gen-btn')?.addEventListener('click', async () => {
errEl.classList.add('hidden');
try {
const r = await fetch('/api/invites', { method: 'POST', credentials: 'include' });
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Could not generate invite';
errEl.classList.remove('hidden');
return;
}
await loadInvites();
} catch (e: any) {
errEl.textContent = e.message;
errEl.classList.remove('hidden');
}
});
loadInvites();
</script>
+68
View File
@@ -0,0 +1,68 @@
---
import Base from '../../layouts/Base.astro';
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? '';
---
<Base title="Login — BincioActivity" public={true}>
<div class="max-w-sm mx-auto mt-16 px-4">
<h1 class="text-2xl font-bold text-white mb-6 text-center">Sign in</h1>
<form id="login-form" class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
<input id="handle" name="handle" type="text" autocomplete="username"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="your handle" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="current-password"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
required />
</div>
<p id="login-error" class="text-red-400 text-sm hidden"></p>
<button type="submit"
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
Sign in
</button>
</form>
{editUrl && (
<p class="text-center text-zinc-500 text-sm mt-6">
Have an invite? <a href="/register/" class="text-[--accent] hover:underline">Create account</a>
</p>
)}
</div>
</Base>
<script>
const editUrl = import.meta.env.PUBLIC_EDIT_URL ?? (document.getElementById('login-form')?.dataset.editUrl ?? '');
document.getElementById('login-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const handle = (form.querySelector('#handle') as HTMLInputElement).value.trim();
const password = (form.querySelector('#password') as HTMLInputElement).value;
const errEl = document.getElementById('login-error')!;
errEl.classList.add('hidden');
try {
const r = await fetch('/api/auth/login', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ handle, password }),
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Invalid credentials';
errEl.classList.remove('hidden');
return;
}
const next = new URLSearchParams(window.location.search).get('next') ?? '/';
window.location.href = next;
} catch {
errEl.textContent = 'Could not reach server';
errEl.classList.remove('hidden');
}
});
</script>
+87
View File
@@ -0,0 +1,87 @@
---
import Base from '../../layouts/Base.astro';
---
<Base title="Create account — BincioActivity" public={true}>
<div class="max-w-sm mx-auto mt-16 px-4">
<h1 class="text-2xl font-bold text-white mb-6 text-center">Create account</h1>
<form id="register-form" class="space-y-4">
<div>
<label class="block text-sm text-zinc-400 mb-1" for="code">Invite code</label>
<input id="code" name="code" type="text" autocomplete="off"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white font-mono uppercase tracking-widest placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="XXXXXXXX" maxlength="8" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="handle">Handle</label>
<input id="handle" name="handle" type="text" autocomplete="username"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="lowercase, letters and numbers" required />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="display_name">Display name <span class="text-zinc-600">(optional)</span></label>
<input id="display_name" name="display_name" type="text"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white placeholder-zinc-500 focus:outline-none focus:border-[--accent]"
placeholder="Your Name" />
</div>
<div>
<label class="block text-sm text-zinc-400 mb-1" for="password">Password</label>
<input id="password" name="password" type="password" autocomplete="new-password"
class="w-full px-3 py-2 rounded-lg bg-zinc-900 border border-zinc-700 text-white focus:outline-none focus:border-[--accent]"
minlength="8" required />
<p class="text-zinc-600 text-xs mt-1">At least 8 characters</p>
</div>
<p id="reg-error" class="text-red-400 text-sm hidden"></p>
<button type="submit"
class="w-full py-2 rounded-lg bg-[--accent] hover:opacity-90 text-white font-medium transition-opacity">
Create account
</button>
</form>
<p class="text-center text-zinc-500 text-sm mt-6">
Already have an account? <a href="/login/" class="text-[--accent] hover:underline">Sign in</a>
</p>
</div>
</Base>
<script>
// Pre-fill invite code from query param
const code = new URLSearchParams(window.location.search).get('code');
if (code) {
const input = document.getElementById('code') as HTMLInputElement;
if (input) input.value = code.toUpperCase();
}
document.getElementById('register-form')?.addEventListener('submit', async (e) => {
e.preventDefault();
const form = e.target as HTMLFormElement;
const errEl = document.getElementById('reg-error')!;
errEl.classList.add('hidden');
const body = {
code: (form.querySelector('#code') as HTMLInputElement).value.trim().toUpperCase(),
handle: (form.querySelector('#handle') as HTMLInputElement).value.trim().toLowerCase(),
display_name: (form.querySelector('#display_name') as HTMLInputElement).value.trim(),
password: (form.querySelector('#password') as HTMLInputElement).value,
};
try {
const r = await fetch('/api/register', {
method: 'POST',
credentials: 'include',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
if (!r.ok) {
const d = await r.json().catch(() => ({}));
errEl.textContent = d.detail ?? 'Registration failed';
errEl.classList.remove('hidden');
return;
}
window.location.href = '/';
} catch {
errEl.textContent = 'Could not reach server';
errEl.classList.remove('hidden');
}
});
</script>
+48
View File
@@ -0,0 +1,48 @@
---
/**
* Per-user profile page: /u/{handle}/
*
* In multi-user mode, getStaticPaths reads the root index.json shard manifest
* to discover all handles. In single-user mode this page is never generated.
*/
import { readFileSync } from 'node:fs';
import { join, resolve } from 'node:path';
import Base from '../../layouts/Base.astro';
import ActivityFeed from '../../components/ActivityFeed.svelte';
export async function getStaticPaths() {
try {
const candidates = [
process.env.BINCIO_DATA_DIR,
resolve(process.cwd(), 'public', 'data'),
resolve(process.cwd(), '..', 'bincio_data'),
].filter(Boolean) as string[];
const dataDir = candidates.find(d => {
try { readFileSync(join(d, 'index.json')); return true; } catch { return false; }
});
if (!dataDir) return [];
const root = JSON.parse(readFileSync(join(dataDir, 'index.json'), 'utf-8'));
const shards: Array<{ handle?: string; url: string }> = root.shards ?? [];
const handles = shards.map(s => s.handle).filter(Boolean) as string[];
return handles.map(handle => ({
params: { handle },
props: { handle, indexUrl: `${handle}/index.json` },
}));
} catch {
return [];
}
}
const { handle, indexUrl } = Astro.props as { handle: string; indexUrl: string };
const base = import.meta.env.BASE_URL;
---
<Base title={`@${handle} — BincioActivity`}>
<div class="max-w-5xl mx-auto px-4 pt-6 pb-2">
<h1 class="text-2xl font-bold text-white mb-1">@{handle}</h1>
<p class="text-zinc-500 text-sm">Activities by this user</p>
</div>
<ActivityFeed {base} filterHandle={handle} profileIndexUrl={indexUrl} client:only="svelte" />
</Base>