1 Commits

Author SHA1 Message Date
linumiq_net-user bcf3c19cee security update 2026-05-31 10:19:27 +02:00
58 changed files with 19 additions and 5489 deletions
-6
View File
@@ -15,9 +15,3 @@ yarn-error.log*
# Dev environment secrets (never commit)
.env.production
# Next.js build output
.next/
out/
*.tsbuildinfo
next-env.d.ts
+3 -3
View File
@@ -1,12 +1,12 @@
# syntax=docker/dockerfile:1.7
FROM node:24.16.0-alpine AS deps
FROM node:20.18.0-alpine AS deps
WORKDIR /app
RUN apk add --no-cache libc6-compat
COPY package.json ./
RUN npm install --no-audit --no-fund --loglevel=error
FROM node:24.16.0-alpine AS builder
FROM node:20.18.0-alpine AS builder
WORKDIR /app
ENV NEXT_TELEMETRY_DISABLED=1
COPY --from=deps /app/node_modules ./node_modules
@@ -20,7 +20,7 @@ ENV NEXT_PUBLIC_SUPABASE_URL=$NEXT_PUBLIC_SUPABASE_URL \
NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL
RUN npm run build
FROM node:24.16.0-alpine AS runner
FROM node:20.18.0-alpine AS runner
WORKDIR /app
ENV NODE_ENV=production \
NEXT_TELEMETRY_DISABLED=1 \
-34
View File
@@ -1,34 +0,0 @@
'use client';
import Link from 'next/link';
import { usePathname } from 'next/navigation';
const LINKS = [
{ href: '/admin', label: 'Overview', exact: true },
{ href: '/admin/users', label: 'Users', exact: false },
{ href: '/admin/tunnels', label: 'Tunnels', exact: false },
{ href: '/admin/reserved', label: 'Reserved', exact: false },
{ href: '/admin/audit', label: 'Audit Log', exact: false },
];
export function AdminNav() {
const pathname = usePathname();
return (
<nav className="admin-nav">
{LINKS.map((l) => {
const active = l.exact
? pathname === l.href
: pathname === l.href || pathname.startsWith(`${l.href}/`);
return (
<Link
key={l.href}
href={l.href}
className={active ? 'admin-nav-link active' : 'admin-nav-link'}
>
{l.label}
</Link>
);
})}
</nav>
);
}
-216
View File
@@ -1,216 +0,0 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatDate } from '@/lib/format';
import type { AuditItem } from '@/lib/admin/list';
import { SortHeader, downloadUrl, type SortOrder } from '../table-ui';
const PER_PAGE = 50;
export function AuditTable({
initialEntries,
initialTotal,
}: {
initialEntries: AuditItem[];
initialTotal: number;
}) {
const [entries, setEntries] = useState<AuditItem[]>(initialEntries);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [action, setAction] = useState('');
const [targetType, setTargetType] = useState('');
const [sort, setSort] = useState('created_at');
const [order, setOrder] = useState<SortOrder>('desc');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const queryParams = useCallback(() => {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
sort,
order,
});
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
return params;
}, [page, action, targetType, sort, order]);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/admin/audit?${queryParams().toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
entries: AuditItem[];
total: number;
};
setEntries(data.entries);
setTotal(data.total);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [queryParams]);
// First page is server-rendered; skip the on-mount fetch to avoid racing the
// SSR session-cookie refresh (which intermittently 401'd).
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
function onSort(col: string) {
setPage(1);
if (col === sort) {
setOrder((o) => (o === 'asc' ? 'desc' : 'asc'));
} else {
setSort(col);
setOrder('asc');
}
}
function exportCsv() {
const params = new URLSearchParams({ sort, order });
if (action.trim()) params.set('action', action.trim());
if (targetType.trim()) params.set('target_type', targetType.trim());
downloadUrl(`/api/admin/audit/export?${params.toString()}`);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
return (
<div>
<h1>Audit log</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Filter action (e.g. tunnel.delete)"
value={action}
onChange={(e) => {
setPage(1);
setAction(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<input
type="text"
placeholder="Filter target_type (user/tunnel…)"
value={targetType}
onChange={(e) => {
setPage(1);
setTargetType(e.target.value);
}}
style={{ maxWidth: 240 }}
/>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
<div className="toolbar-actions">
<button
className="secondary btn-sm"
type="button"
onClick={exportCsv}
>
Export CSV
</button>
</div>
</div>
{error && <p className="error">{error}</p>}
{loading ? (
<p className="muted">Loading</p>
) : entries.length === 0 ? (
<p className="muted">No audit entries.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<SortHeader
label="When"
col="created_at"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Actor"
col="actor_email"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Action"
col="action"
sort={sort}
order={order}
onSort={onSort}
/>
<th>Target</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{entries.map((e) => (
<tr key={e.id}>
<td>{formatDate(e.created_at)}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.actor_email ?? e.actor_id ?? '—'}
</td>
<td>{e.action}</td>
<td style={{ wordBreak: 'break-all' }}>
{e.target_type ? `${e.target_type}:` : ''}
{e.target_id ?? ''}
</td>
<td>
<code className="muted">
{JSON.stringify(e.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
-20
View File
@@ -1,20 +0,0 @@
import { getAuditList } from '@/lib/admin/list';
import { AuditTable } from './audit-table';
export const dynamic = 'force-dynamic';
export const revalidate = 0;
const PER_PAGE = 50;
export default async function AdminAuditPage() {
// Initial load on the server (admin session already validated by the layout)
// so the first paint never races the client session-cookie refresh.
const { entries, total } = await getAuditList({
page: 1,
perPage: PER_PAGE,
action: '',
targetType: '',
});
return <AuditTable initialEntries={entries} initialTotal={total} />;
}
-31
View File
@@ -1,31 +0,0 @@
import Link from 'next/link';
import { requireAdmin } from '@/lib/auth/admin-guard';
import { AdminNav } from './admin-nav';
export const dynamic = 'force-dynamic';
export default async function AdminLayout({
children,
}: {
children: React.ReactNode;
}) {
const user = await requireAdmin();
return (
<div className="admin-shell">
<aside className="admin-sidebar">
<div className="admin-brand">Admin</div>
<AdminNav />
<div className="admin-sidebar-footer">
<div className="muted" style={{ wordBreak: 'break-all' }}>
{user.email}
</div>
<Link href="/dashboard" className="admin-back">
Back to dashboard
</Link>
</div>
</aside>
<section className="admin-content">{children}</section>
</div>
);
}
-121
View File
@@ -1,121 +0,0 @@
import Link from 'next/link';
import { computeMetrics } from '@/lib/admin/metrics';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { formatBytes, formatDate } from '@/lib/format';
export const dynamic = 'force-dynamic';
export const revalidate = 0;
type OverQuotaRow = {
user_id: string;
subdomain: string;
bytes_used: number;
quota_bytes: number;
};
export default async function AdminOverviewPage() {
const metrics = await computeMetrics();
const admin = getSupabaseAdmin();
// Recent signups (latest 5 users).
const { data: recentUsersData } = await withAdminRetry(() =>
admin.auth.admin.listUsers({
page: 1,
perPage: 5,
}),
);
const recentUsers = recentUsersData?.users ?? [];
// Over-quota tunnels (compute in memory).
const { data: tunnelsData } = await admin
.from('tunnels')
.select('user_id, subdomain, bytes_used, quota_bytes');
const overQuota = ((tunnelsData ?? []) as OverQuotaRow[])
.filter((t) => t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes)
.slice(0, 5);
const kpis: { label: string; value: string }[] = [
{ label: 'Total users', value: String(metrics.totalUsers) },
{ label: 'Total tunnels', value: String(metrics.totalTunnels) },
{ label: 'Active tunnels', value: String(metrics.activeTunnels) },
{ label: 'Inactive tunnels', value: String(metrics.inactiveTunnels) },
{ label: 'Over quota', value: String(metrics.overQuota) },
{ label: 'Active last 24h', value: String(metrics.recentlyActive) },
{ label: 'Signups (7d)', value: String(metrics.signups7d) },
{ label: 'Signups (30d)', value: String(metrics.signups30d) },
{ label: 'Bandwidth used', value: formatBytes(metrics.bytesUsedTotal) },
{ label: 'Total quota', value: formatBytes(metrics.quotaTotal) },
];
return (
<div>
<h1>Overview</h1>
<div className="kpi-grid">
{kpis.map((k) => (
<div className="kpi-card" key={k.label}>
<div className="kpi-value">{k.value}</div>
<div className="kpi-label">{k.label}</div>
</div>
))}
</div>
<div className="admin-cols">
<div className="card">
<h2>Recent signups</h2>
{recentUsers.length === 0 ? (
<p className="muted">No users yet.</p>
) : (
<table className="admin-table">
<thead>
<tr>
<th>Email</th>
<th>Joined</th>
</tr>
</thead>
<tbody>
{recentUsers.map((u) => (
<tr key={u.id}>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
)}
</div>
<div className="card">
<h2>Over-quota tunnels</h2>
{overQuota.length === 0 ? (
<p className="muted">None over quota.</p>
) : (
<table className="admin-table">
<thead>
<tr>
<th>Subdomain</th>
<th>Usage</th>
</tr>
</thead>
<tbody>
{overQuota.map((t) => (
<tr key={t.user_id}>
<td>{t.subdomain}</td>
<td>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</td>
</tr>
))}
</tbody>
</table>
)}
</div>
</div>
</div>
);
}
-175
View File
@@ -1,175 +0,0 @@
'use client';
import { useCallback, useEffect, useState } from 'react';
import { formatDate } from '@/lib/format';
type Reserved = { name: string; created_at: string };
export default function AdminReservedPage() {
const [reserved, setReserved] = useState<Reserved[]>([]);
const [hardcoded, setHardcoded] = useState<string[]>([]);
const [name, setName] = useState('');
const [loading, setLoading] = useState(true);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busy, setBusy] = useState(false);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch('/api/admin/reserved');
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
reserved: Reserved[];
hardcoded: string[];
};
setReserved(data.reserved);
setHardcoded(data.hardcoded);
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, []);
useEffect(() => {
load();
}, [load]);
async function add(e: React.FormEvent) {
e.preventDefault();
const value = name.trim().toLowerCase();
if (!value) return;
setBusy(true);
setError(null);
setNotice(null);
try {
const res = await fetch('/api/admin/reserved', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ name: value }),
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setName('');
setNotice(`Reserved '${value}'`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
async function remove(n: string) {
if (!window.confirm(`Remove reserved subdomain '${n}'?`)) return;
setBusy(true);
setError(null);
setNotice(null);
try {
const res = await fetch(
`/api/admin/reserved?name=${encodeURIComponent(n)}`,
{ method: 'DELETE' },
);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setNotice(`Removed '${n}'`);
await load();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(false);
}
}
return (
<div>
<h1>Reserved subdomains</h1>
<div className="card">
<h2>Add reserved subdomain</h2>
<form onSubmit={add}>
<div className="row">
<input
type="text"
value={name}
onChange={(e) => setName(e.target.value.toLowerCase())}
placeholder="e.g. status"
autoCapitalize="none"
autoCorrect="off"
spellCheck={false}
style={{ maxWidth: 280 }}
/>
<button type="submit" className="btn-sm" disabled={busy || !name}>
Add
</button>
</div>
</form>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
</div>
<div className="card">
<h2>Database reserved</h2>
{loading ? (
<p className="muted">Loading</p>
) : reserved.length === 0 ? (
<p className="muted">None reserved in the database.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>Name</th>
<th>Added</th>
<th></th>
</tr>
</thead>
<tbody>
{reserved.map((r) => (
<tr key={r.name}>
<td>{r.name}</td>
<td>{formatDate(r.created_at)}</td>
<td>
<button
type="button"
className="btn-danger btn-sm"
disabled={busy}
onClick={() => remove(r.name)}
>
Remove
</button>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
</div>
<div className="card">
<h2>Built-in reserved</h2>
<p className="muted">
These are hardcoded in the app and always reserved (cannot be removed
here).
</p>
<div className="row" style={{ flexWrap: 'wrap', gap: 6 }}>
{hardcoded.map((h) => (
<span key={h} className="badge">
{h}
</span>
))}
</div>
</div>
</div>
);
}
-64
View File
@@ -1,64 +0,0 @@
'use client';
/**
* Small shared client helpers for the admin tables: a clickable sortable
* column header and a CSV-download trigger. Kept dependency-free and
* dark-theme consistent with globals.css.
*/
export type SortOrder = 'asc' | 'desc';
export function SortHeader({
label,
col,
sort,
order,
onSort,
className,
}: {
label: string;
col: string;
sort: string;
order: SortOrder;
onSort: (col: string) => void;
className?: string;
}) {
const active = sort === col;
const indicator = active ? (order === 'asc' ? '▲' : '▼') : '↕';
return (
<th
className={`th-sort${active ? ' sorted' : ''}${
className ? ` ${className}` : ''
}`}
onClick={() => onSort(col)}
role="button"
tabIndex={0}
aria-sort={active ? (order === 'asc' ? 'ascending' : 'descending') : 'none'}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
onSort(col);
}
}}
>
{label}
<span className="sort-ind" aria-hidden="true">
{indicator}
</span>
</th>
);
}
/**
* Triggers a browser download of a same-origin URL. The server sets
* Content-Disposition: attachment, so the cookie-authenticated GET streams the
* CSV straight to a file.
*/
export function downloadUrl(url: string): void {
const a = document.createElement('a');
a.href = url;
a.rel = 'noopener';
document.body.appendChild(a);
a.click();
a.remove();
}
-20
View File
@@ -1,20 +0,0 @@
import { getTunnelsList } from '@/lib/admin/list';
import { TunnelsTable } from './tunnels-table';
export const dynamic = 'force-dynamic';
export const revalidate = 0;
const PER_PAGE = 25;
export default async function AdminTunnelsPage() {
// Initial load on the server (admin session already validated by the layout)
// so the first paint never races the client session-cookie refresh.
const { tunnels, total } = await getTunnelsList({
page: 1,
perPage: PER_PAGE,
search: '',
status: null,
});
return <TunnelsTable initialTunnels={tunnels} initialTotal={total} />;
}
-553
View File
@@ -1,553 +0,0 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import { formatBytes, formatDate } from '@/lib/format';
import type { TunnelItem } from '@/lib/admin/list';
import { SortHeader, downloadUrl, type SortOrder } from '../table-ui';
const PER_PAGE = 25;
type BulkResult = { ok: number; fail: number };
export function TunnelsTable({
initialTunnels,
initialTotal,
}: {
initialTunnels: TunnelItem[];
initialTotal: number;
}) {
const [tunnels, setTunnels] = useState<TunnelItem[]>(initialTunnels);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [status, setStatus] = useState('');
const [sort, setSort] = useState('created_at');
const [order, setOrder] = useState<SortOrder>('desc');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [busyId, setBusyId] = useState<string | null>(null);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [bulkBusy, setBulkBusy] = useState(false);
const [bulkProgress, setBulkProgress] = useState<string | null>(null);
const queryParams = useCallback(() => {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
sort,
order,
});
if (search.trim()) params.set('search', search.trim());
if (status) params.set('status', status);
return params;
}, [page, search, status, sort, order]);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/admin/tunnels?${queryParams().toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as { tunnels: TunnelItem[]; total: number };
setTunnels(data.tunnels);
setTotal(data.total);
setSelected(new Set());
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [queryParams]);
// First page is server-rendered; skip the on-mount fetch to avoid racing the
// SSR session-cookie refresh (which intermittently 401'd).
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
function onSort(col: string) {
setPage(1);
if (col === sort) {
setOrder((o) => (o === 'asc' ? 'desc' : 'asc'));
} else {
setSort(col);
setOrder('asc');
}
}
async function act(
id: string,
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
): Promise<unknown | null> {
if (confirmMsg && !window.confirm(confirmMsg)) return null;
setBusyId(id);
setError(null);
setNotice(null);
try {
const res = await fetch(url, { credentials: 'same-origin', ...init });
const body = (await res.json().catch(() => ({}))) as {
error?: string;
[k: string]: unknown;
};
if (!res.ok) throw new Error(body.error ?? `Request failed (${res.status})`);
setNotice(`${label} succeeded`);
await load();
return body;
} catch (e) {
setError((e as Error).message);
return null;
} finally {
setBusyId(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
async function onToggleActive(t: TunnelItem) {
await act(
t.user_id,
t.is_active ? 'Deactivate' : 'Activate',
`/api/admin/tunnels/${t.user_id}/active`,
jsonInit({ is_active: !t.is_active }),
);
}
async function onRegenerate(t: TunnelItem) {
const body = (await act(
t.user_id,
'Regenerate token',
`/api/admin/tunnels/${t.user_id}/regenerate-token`,
{ method: 'POST' },
`Regenerate the token for ${t.subdomain}? The old token stops working.`,
)) as { token?: string } | null;
if (body?.token) {
window.prompt('New token (copy it now):', body.token);
}
}
async function onResetUsage(t: TunnelItem) {
await act(
t.user_id,
'Reset usage',
`/api/admin/tunnels/${t.user_id}/reset-usage`,
{ method: 'POST' },
`Reset bandwidth usage for ${t.subdomain} to zero?`,
);
}
async function onSetQuota(t: TunnelItem) {
const input = window.prompt(
`New quota in GiB for ${t.subdomain}:`,
String(Math.round(t.quota_bytes / 1024 ** 3)),
);
if (input === null) return;
const gib = Number(input);
if (!Number.isFinite(gib) || gib <= 0) {
setError('Quota must be a positive number of GiB');
return;
}
await act(
t.user_id,
'Set quota',
`/api/admin/tunnels/${t.user_id}/quota`,
jsonInit({ quota_bytes: Math.round(gib * 1024 ** 3) }),
);
}
async function onReassign(t: TunnelItem) {
const input = window.prompt(
`New subdomain for ${t.owner_email ?? t.subdomain}:`,
t.subdomain,
);
if (input === null) return;
await act(
t.user_id,
'Reassign',
`/api/admin/tunnels/${t.user_id}/reassign`,
jsonInit({ subdomain: input.trim().toLowerCase() }),
);
}
async function onDelete(t: TunnelItem) {
await act(
t.user_id,
'Delete tunnel',
`/api/admin/tunnels/${t.user_id}`,
{ method: 'DELETE' },
`Delete the tunnel ${t.subdomain}? This frees the subdomain.`,
);
}
function toggleRow(id: string) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
const pageIds = tunnels.map((t) => t.user_id);
const allSelected =
pageIds.length > 0 && pageIds.every((id) => selected.has(id));
function toggleAll() {
setSelected((prev) => {
if (pageIds.every((id) => prev.has(id))) return new Set();
return new Set(pageIds);
});
}
async function runBulk(
label: string,
perItem: (t: TunnelItem) => Promise<boolean>,
confirmMsg?: string,
) {
const targets = tunnels.filter((t) => selected.has(t.user_id));
if (targets.length === 0) return;
if (confirmMsg && !window.confirm(confirmMsg)) return;
setBulkBusy(true);
setError(null);
setNotice(null);
const result: BulkResult = { ok: 0, fail: 0 };
for (let i = 0; i < targets.length; i++) {
setBulkProgress(`${label}: ${i + 1}/${targets.length}`);
try {
const ok = await perItem(targets[i]);
if (ok) result.ok++;
else result.fail++;
} catch {
result.fail++;
}
// Tiny inter-op pacing: strictly sequential (concurrency 1) with a small
// gap so we never burst the admin API; single refresh after all settle.
if (i < targets.length - 1) {
await new Promise((r) => setTimeout(r, 75));
}
}
setBulkProgress(null);
setBulkBusy(false);
const parts = [`${result.ok} ${label.toLowerCase()}`];
if (result.fail) parts.push(`${result.fail} failed`);
setNotice(parts.join(', '));
await load();
}
async function setActiveOne(t: TunnelItem, active: boolean): Promise<boolean> {
const res = await fetch(`/api/admin/tunnels/${t.user_id}/active`, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ is_active: active }),
});
return res.ok;
}
async function deleteOne(t: TunnelItem): Promise<boolean> {
const res = await fetch(`/api/admin/tunnels/${t.user_id}`, {
method: 'DELETE',
credentials: 'same-origin',
});
return res.ok;
}
function exportCsv() {
const params = new URLSearchParams({ sort, order });
if (search.trim()) params.set('search', search.trim());
if (status) params.set('status', status);
downloadUrl(`/api/admin/tunnels/export?${params.toString()}`);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
const selectedCount = selected.size;
return (
<div>
<h1>Tunnels</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Search subdomain…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 260 }}
/>
<select
value={status}
onChange={(e) => {
setPage(1);
setStatus(e.target.value);
}}
style={{
padding: '0.6rem 0.75rem',
background: 'var(--bg)',
color: 'var(--fg)',
border: '1px solid var(--border)',
borderRadius: 6,
}}
>
<option value="">All statuses</option>
<option value="active">Active</option>
<option value="inactive">Inactive</option>
<option value="over_quota">Over quota</option>
</select>
<button className="secondary btn-sm" type="button" onClick={load}>
Refresh
</button>
<div className="toolbar-actions">
<button
className="secondary btn-sm"
type="button"
onClick={exportCsv}
>
Export CSV
</button>
</div>
</div>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
{selectedCount > 0 && (
<div className="bulk-bar">
<span className="bulk-count">{selectedCount} selected</span>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() => runBulk('Activated', (t) => setActiveOne(t, true))}
>
Activate
</button>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() =>
runBulk('Deactivated', (t) => setActiveOne(t, false))
}
>
Deactivate
</button>
<button
className="btn-danger btn-sm"
type="button"
disabled={bulkBusy}
onClick={() =>
runBulk(
'Deleted',
deleteOne,
`Delete ${selectedCount} selected tunnel(s)? This frees their subdomains.`,
)
}
>
Delete
</button>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() => setSelected(new Set())}
>
Clear
</button>
{bulkProgress && <span className="muted">{bulkProgress}</span>}
</div>
)}
{loading ? (
<p className="muted">Loading</p>
) : tunnels.length === 0 ? (
<p className="muted">No tunnels found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th className="col-check">
<input
type="checkbox"
aria-label="Select all on page"
checked={allSelected}
onChange={toggleAll}
/>
</th>
<SortHeader
label="Subdomain"
col="subdomain"
sort={sort}
order={order}
onSort={onSort}
/>
<th>Owner</th>
<SortHeader
label="Status"
col="is_active"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Usage"
col="usage_pct"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Last seen"
col="last_seen_at"
sort={sort}
order={order}
onSort={onSort}
/>
<th>Actions</th>
</tr>
</thead>
<tbody>
{tunnels.map((t) => (
<tr
key={t.user_id}
className={selected.has(t.user_id) ? 'row-selected' : undefined}
>
<td className="col-check">
<input
type="checkbox"
aria-label={`Select ${t.subdomain}`}
checked={selected.has(t.user_id)}
onChange={() => toggleRow(t.user_id)}
/>
</td>
<td>{t.subdomain}</td>
<td style={{ wordBreak: 'break-all' }}>
{t.owner_email ?? '—'}
</td>
<td>
{t.is_active ? (
<span className="badge badge-ok">active</span>
) : (
<span className="badge">inactive</span>
)}
</td>
<td style={{ minWidth: 140 }}>
<div>
{formatBytes(t.bytes_used)} / {formatBytes(t.quota_bytes)}
</div>
<div className="progress" style={{ marginTop: 4 }}>
<div
style={{
width: `${Math.min(100, t.usage_pct).toFixed(1)}%`,
background:
t.usage_pct >= 100
? 'var(--danger)'
: 'var(--accent)',
}}
/>
</div>
</td>
<td>{formatDate(t.last_seen_at)}</td>
<td>
<div className="row" style={{ flexWrap: 'wrap', gap: 4 }}>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onToggleActive(t)}
>
{t.is_active ? 'Deactivate' : 'Activate'}
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onSetQuota(t)}
>
Quota
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onResetUsage(t)}
>
Reset
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onReassign(t)}
>
Reassign
</button>
<button
type="button"
className="secondary btn-sm"
disabled={busyId === t.user_id}
onClick={() => onRegenerate(t)}
>
Token
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={busyId === t.user_id}
onClick={() => onDelete(t)}
>
Delete
</button>
</div>
</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
-180
View File
@@ -1,180 +0,0 @@
import { notFound } from 'next/navigation';
import Link from 'next/link';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { createSupabaseServerClient } from '@/lib/supabase/server';
import { isUuid } from '@/lib/admin/validators';
import { formatBytes, formatDate } from '@/lib/format';
import { UserActions } from './user-actions';
export const dynamic = 'force-dynamic';
export const revalidate = 0;
type TunnelRow = {
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
last_seen_at: string | null;
created_at: string;
};
type AuditRow = {
id: number;
actor_email: string | null;
action: string;
target_type: string | null;
target_id: string | null;
details: Record<string, unknown>;
created_at: string;
};
export default async function AdminUserDetailPage({
params,
}: {
params: { id: string };
}) {
if (!isUuid(params.id)) notFound();
const admin = getSupabaseAdmin();
const supabase = createSupabaseServerClient();
const {
data: { user: currentUser },
} = await supabase.auth.getUser();
const { data: userRes, error } = await withAdminRetry(() =>
admin.auth.admin.getUserById(params.id),
);
if (error || !userRes.user) notFound();
const u = userRes.user;
const role = (u.app_metadata?.role as string | undefined) ?? 'user';
const bannedUntil =
(u as unknown as { banned_until?: string | null }).banned_until ?? null;
const banned = !!bannedUntil && new Date(bannedUntil).getTime() > Date.now();
const { data: tunnel } = await admin
.from('tunnels')
.select(
'subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
)
.eq('user_id', params.id)
.maybeSingle<TunnelRow>();
const { data: audit } = await admin
.from('admin_audit_log')
.select(
'id, actor_email, action, target_type, target_id, details, created_at',
)
.eq('target_id', params.id)
.order('created_at', { ascending: false })
.limit(25);
const isSelf = currentUser?.id === params.id;
return (
<div>
<p className="muted">
<Link href="/admin/users"> Users</Link>
</p>
<h1 style={{ wordBreak: 'break-all' }}>{u.email ?? u.id}</h1>
<div className="card">
<h2>Account</h2>
<div className="kv">
<div className="k">User ID</div>
<div style={{ wordBreak: 'break-all' }}>{u.id}</div>
<div className="k">Role</div>
<div>
{role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</div>
<div className="k">Status</div>
<div>
{banned ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</div>
<div className="k">Created</div>
<div>{formatDate(u.created_at)}</div>
<div className="k">Last sign-in</div>
<div>{formatDate(u.last_sign_in_at)}</div>
</div>
<UserActions
userId={u.id}
role={role}
banned={banned}
isSelf={isSelf}
/>
</div>
<div className="card">
<h2>Tunnel</h2>
{tunnel ? (
<div className="kv">
<div className="k">Subdomain</div>
<div>{tunnel.subdomain}.linumiq.net</div>
<div className="k">Status</div>
<div>{tunnel.is_active ? 'Active' : 'Inactive'}</div>
<div className="k">Usage</div>
<div>
{formatBytes(tunnel.bytes_used)} /{' '}
{formatBytes(tunnel.quota_bytes)}
</div>
<div className="k">Last seen</div>
<div>{formatDate(tunnel.last_seen_at)}</div>
<div className="k">Created</div>
<div>{formatDate(tunnel.created_at)}</div>
<div className="k">Manage</div>
<div>
<Link href="/admin/tunnels">Go to tunnels </Link>
</div>
</div>
) : (
<p className="muted">No tunnel claimed.</p>
)}
</div>
<div className="card">
<h2>Audit history</h2>
{audit && audit.length > 0 ? (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th>When</th>
<th>Action</th>
<th>By</th>
<th>Details</th>
</tr>
</thead>
<tbody>
{(audit as AuditRow[]).map((a) => (
<tr key={a.id}>
<td>{formatDate(a.created_at)}</td>
<td>{a.action}</td>
<td>{a.actor_email ?? '—'}</td>
<td>
<code className="muted">
{JSON.stringify(a.details ?? {})}
</code>
</td>
</tr>
))}
</tbody>
</table>
</div>
) : (
<p className="muted">No audit entries.</p>
)}
</div>
</div>
);
}
-123
View File
@@ -1,123 +0,0 @@
'use client';
import { useState } from 'react';
import { useRouter } from 'next/navigation';
type Props = {
userId: string;
role: string;
banned: boolean;
isSelf: boolean;
};
export function UserActions({ userId, role, banned, isSelf }: Props) {
const router = useRouter();
const [busy, setBusy] = useState<string | null>(null);
const [error, setError] = useState<string | null>(null);
const [success, setSuccess] = useState<string | null>(null);
async function call(
label: string,
url: string,
init: RequestInit,
confirmMsg?: string,
) {
if (confirmMsg && !window.confirm(confirmMsg)) return;
setBusy(label);
setError(null);
setSuccess(null);
try {
const res = await fetch(url, init);
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
setSuccess(`${label} succeeded`);
router.refresh();
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(null);
}
}
const jsonInit = (body: unknown): RequestInit => ({
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return (
<div style={{ marginTop: '1rem' }}>
{error && <p className="error">{error}</p>}
{success && <p className="success">{success}</p>}
<div className="row" style={{ flexWrap: 'wrap' }}>
{role === 'admin' ? (
<button
type="button"
className="secondary btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot change your own role' : undefined}
onClick={() =>
call(
'Demote',
`/api/admin/users/${userId}/role`,
jsonInit({ role: 'user' }),
)
}
>
Demote to user
</button>
) : (
<button
type="button"
className="btn-sm"
disabled={isSelf || busy !== null}
onClick={() =>
call(
'Promote',
`/api/admin/users/${userId}/role`,
jsonInit({ role: 'admin' }),
)
}
>
Promote to admin
</button>
)}
<button
type="button"
className="secondary btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot ban yourself' : undefined}
onClick={() =>
call(
banned ? 'Unban' : 'Ban',
`/api/admin/users/${userId}/ban`,
jsonInit({ banned: !banned }),
)
}
>
{banned ? 'Unban' : 'Ban'}
</button>
<button
type="button"
className="btn-danger btn-sm"
disabled={isSelf || busy !== null}
title={isSelf ? 'You cannot delete yourself' : undefined}
onClick={() =>
call(
'Delete',
`/api/admin/users/${userId}`,
{ method: 'DELETE' },
'Permanently delete this user and their tunnel? This cannot be undone.',
).then(() => router.push('/admin/users'))
}
>
Delete user
</button>
</div>
</div>
);
}
-28
View File
@@ -1,28 +0,0 @@
import { getUsersList } from '@/lib/admin/list';
import { requireAdmin } from '@/lib/auth/admin-guard';
import { UsersTable } from './users-table';
export const dynamic = 'force-dynamic';
export const revalidate = 0;
const PER_PAGE = 25;
export default async function AdminUsersPage() {
// Initial load runs on the server (the admin session is already validated by
// the admin layout's requireAdmin()), so the first paint never races the
// client session-cookie refresh.
const admin = await requireAdmin();
const { users, total } = await getUsersList({
page: 1,
perPage: PER_PAGE,
search: '',
});
return (
<UsersTable
initialUsers={users}
initialTotal={total}
currentUserId={admin.id}
/>
);
}
-391
View File
@@ -1,391 +0,0 @@
'use client';
import { useCallback, useEffect, useRef, useState } from 'react';
import Link from 'next/link';
import { formatBytes, formatDate } from '@/lib/format';
import type { AdminUserItem } from '@/lib/admin/list';
import { SortHeader, downloadUrl, type SortOrder } from '../table-ui';
const PER_PAGE = 25;
function isBanned(u: AdminUserItem): boolean {
return !!u.banned_until && new Date(u.banned_until).getTime() > Date.now();
}
type BulkResult = { ok: number; fail: number; skipped: number };
export function UsersTable({
initialUsers,
initialTotal,
currentUserId,
}: {
initialUsers: AdminUserItem[];
initialTotal: number;
currentUserId: string;
}) {
const [users, setUsers] = useState<AdminUserItem[]>(initialUsers);
const [total, setTotal] = useState(initialTotal);
const [page, setPage] = useState(1);
const [search, setSearch] = useState('');
const [sort, setSort] = useState('created_at');
const [order, setOrder] = useState<SortOrder>('desc');
const [loading, setLoading] = useState(false);
const [error, setError] = useState<string | null>(null);
const [notice, setNotice] = useState<string | null>(null);
const [selected, setSelected] = useState<Set<string>>(new Set());
const [bulkBusy, setBulkBusy] = useState(false);
const [bulkProgress, setBulkProgress] = useState<string | null>(null);
const queryParams = useCallback(() => {
const params = new URLSearchParams({
page: String(page),
perPage: String(PER_PAGE),
sort,
order,
});
if (search.trim()) params.set('search', search.trim());
return params;
}, [page, search, sort, order]);
const load = useCallback(async () => {
setLoading(true);
setError(null);
try {
const res = await fetch(`/api/admin/users?${queryParams().toString()}`, {
credentials: 'same-origin',
});
if (!res.ok) {
const b = (await res.json().catch(() => ({}))) as { error?: string };
throw new Error(b.error ?? `Request failed (${res.status})`);
}
const data = (await res.json()) as {
users: AdminUserItem[];
total: number;
};
setUsers(data.users);
setTotal(data.total);
setSelected(new Set());
} catch (e) {
setError((e as Error).message);
} finally {
setLoading(false);
}
}, [queryParams]);
// The first page is rendered from server-supplied data (see the parent server
// component), so skip the initial on-mount fetch — that on-mount request used
// to race the SSR session-cookie refresh and intermittently 401.
const didMount = useRef(false);
useEffect(() => {
if (!didMount.current) {
didMount.current = true;
return;
}
const t = setTimeout(load, 250);
return () => clearTimeout(t);
}, [load]);
function onSort(col: string) {
setPage(1);
if (col === sort) {
setOrder((o) => (o === 'asc' ? 'desc' : 'asc'));
} else {
setSort(col);
setOrder('asc');
}
}
function toggleRow(id: string) {
setSelected((prev) => {
const next = new Set(prev);
if (next.has(id)) next.delete(id);
else next.add(id);
return next;
});
}
const pageIds = users.map((u) => u.id);
const allSelected =
pageIds.length > 0 && pageIds.every((id) => selected.has(id));
function toggleAll() {
setSelected((prev) => {
if (pageIds.every((id) => prev.has(id))) return new Set();
return new Set(pageIds);
});
}
async function runBulk(
label: string,
perItem: (u: AdminUserItem) => Promise<'ok' | 'fail' | 'skip'>,
confirmMsg?: string,
) {
const targets = users.filter((u) => selected.has(u.id));
if (targets.length === 0) return;
if (confirmMsg && !window.confirm(confirmMsg)) return;
setBulkBusy(true);
setError(null);
setNotice(null);
const result: BulkResult = { ok: 0, fail: 0, skipped: 0 };
for (let i = 0; i < targets.length; i++) {
setBulkProgress(`${label}: ${i + 1}/${targets.length}`);
try {
const r = await perItem(targets[i]);
if (r === 'ok') result.ok++;
else if (r === 'skip') result.skipped++;
else result.fail++;
} catch {
result.fail++;
}
// Tiny inter-op pacing: keep the per-row mutations strictly sequential
// (concurrency 1) with a small gap so we never burst the GoTrue admin
// API, then refresh ONCE after every op has settled (below).
if (i < targets.length - 1) {
await new Promise((r) => setTimeout(r, 75));
}
}
setBulkProgress(null);
setBulkBusy(false);
const parts = [`${result.ok} ${label.toLowerCase()}`];
if (result.skipped) parts.push(`${result.skipped} skipped (self)`);
if (result.fail) parts.push(`${result.fail} failed`);
setNotice(parts.join(', '));
await load();
}
async function banOne(
u: AdminUserItem,
banned: boolean,
): Promise<'ok' | 'fail' | 'skip'> {
if (u.id === currentUserId) return 'skip';
const res = await fetch(`/api/admin/users/${u.id}/ban`, {
method: 'POST',
credentials: 'same-origin',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ banned }),
});
return res.ok ? 'ok' : 'fail';
}
async function deleteOne(
u: AdminUserItem,
): Promise<'ok' | 'fail' | 'skip'> {
if (u.id === currentUserId) return 'skip';
const res = await fetch(`/api/admin/users/${u.id}`, {
method: 'DELETE',
credentials: 'same-origin',
});
return res.ok ? 'ok' : 'fail';
}
function exportCsv() {
const params = new URLSearchParams({ sort, order });
if (search.trim()) params.set('search', search.trim());
downloadUrl(`/api/admin/users/export?${params.toString()}`);
}
const totalPages = Math.max(1, Math.ceil(total / PER_PAGE));
const selectedCount = selected.size;
return (
<div>
<h1>Users</h1>
<div className="row" style={{ marginBottom: '1rem', flexWrap: 'wrap' }}>
<input
type="text"
placeholder="Search by email…"
value={search}
onChange={(e) => {
setPage(1);
setSearch(e.target.value);
}}
style={{ maxWidth: 320 }}
/>
<button className="secondary btn-sm" onClick={load} type="button">
Refresh
</button>
<div className="toolbar-actions">
<button
className="secondary btn-sm"
type="button"
onClick={exportCsv}
>
Export CSV
</button>
</div>
</div>
{error && <p className="error">{error}</p>}
{notice && <p className="success">{notice}</p>}
{selectedCount > 0 && (
<div className="bulk-bar">
<span className="bulk-count">{selectedCount} selected</span>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() => runBulk('Banned', (u) => banOne(u, true))}
>
Ban
</button>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() => runBulk('Unbanned', (u) => banOne(u, false))}
>
Unban
</button>
<button
className="btn-danger btn-sm"
type="button"
disabled={bulkBusy}
onClick={() =>
runBulk(
'Deleted',
deleteOne,
`Delete ${selectedCount} selected user(s)? This cannot be undone. Your own account is skipped.`,
)
}
>
Delete
</button>
<button
className="secondary btn-sm"
type="button"
disabled={bulkBusy}
onClick={() => setSelected(new Set())}
>
Clear
</button>
{bulkProgress && <span className="muted">{bulkProgress}</span>}
</div>
)}
{loading ? (
<p className="muted">Loading</p>
) : users.length === 0 ? (
<p className="muted">No users found.</p>
) : (
<div className="admin-table-wrap">
<table className="admin-table">
<thead>
<tr>
<th className="col-check">
<input
type="checkbox"
aria-label="Select all on page"
checked={allSelected}
onChange={toggleAll}
/>
</th>
<SortHeader
label="Email"
col="email"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Role"
col="role"
sort={sort}
order={order}
onSort={onSort}
/>
<th>Status</th>
<th>Tunnel</th>
<th>Usage</th>
<SortHeader
label="Last sign-in"
col="last_sign_in_at"
sort={sort}
order={order}
onSort={onSort}
/>
<SortHeader
label="Created"
col="created_at"
sort={sort}
order={order}
onSort={onSort}
/>
</tr>
</thead>
<tbody>
{users.map((u) => (
<tr
key={u.id}
className={selected.has(u.id) ? 'row-selected' : undefined}
>
<td className="col-check">
<input
type="checkbox"
aria-label={`Select ${u.email ?? u.id}`}
checked={selected.has(u.id)}
onChange={() => toggleRow(u.id)}
/>
</td>
<td>
<Link href={`/admin/users/${u.id}`}>
{u.email ?? u.id}
</Link>
</td>
<td>
{u.role === 'admin' ? (
<span className="badge badge-admin">admin</span>
) : (
<span className="badge">user</span>
)}
</td>
<td>
{isBanned(u) ? (
<span className="badge badge-banned">banned</span>
) : u.email_confirmed_at ? (
<span className="badge badge-ok">confirmed</span>
) : (
<span className="badge">unconfirmed</span>
)}
</td>
<td>{u.tunnel ? u.tunnel.subdomain : '—'}</td>
<td>
{u.tunnel
? `${formatBytes(u.tunnel.bytes_used)} / ${formatBytes(
u.tunnel.quota_bytes,
)}`
: '—'}
</td>
<td>{formatDate(u.last_sign_in_at)}</td>
<td>{formatDate(u.created_at)}</td>
</tr>
))}
</tbody>
</table>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button
className="secondary btn-sm"
type="button"
disabled={page <= 1}
onClick={() => setPage((p) => Math.max(1, p - 1))}
>
Prev
</button>
<span className="muted">
Page {page} of {totalPages} ({total} total)
</span>
<button
className="secondary btn-sm"
type="button"
disabled={page >= totalPages}
onClick={() => setPage((p) => p + 1)}
>
Next
</button>
</div>
</div>
);
}
-73
View File
@@ -1,73 +0,0 @@
import { type NextRequest, NextResponse } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getAuditList } from '@/lib/admin/list';
import { logAdminAction } from '@/lib/auth/audit';
import { toCsv, EXPORT_MAX_ROWS } from '@/lib/admin/csv';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const action = url.searchParams.get('action') ?? '';
const targetType = url.searchParams.get('target_type') ?? '';
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
// Respect action/target_type filters + sort, full set (capped). Audit
// details already exclude secrets (no tokens are ever logged).
const { entries } = await getAuditList({
page: 1,
perPage: EXPORT_MAX_ROWS,
action,
targetType,
sort,
order,
});
const header = [
'created_at',
'actor_email',
'action',
'target_type',
'target_id',
'details',
];
const rows = entries.map((e) => [
e.created_at,
e.actor_email ?? '',
e.action,
e.target_type ?? '',
e.target_id ?? '',
JSON.stringify(e.details ?? {}),
]);
const csv = toCsv(header, rows);
await logAdminAction(auth.user, {
action: 'audit.export',
target_type: 'audit',
details: { count: rows.length, capped: rows.length >= EXPORT_MAX_ROWS },
});
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="audit.csv"',
'Cache-Control': 'no-store',
Pragma: 'no-cache',
},
});
} catch (e) {
console.error('admin audit export failed', e);
return NextResponse.json(
{ error: 'internal error' },
{ status: 500, headers: { 'Cache-Control': 'no-store' } },
);
}
}
-36
View File
@@ -1,36 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
import { getAuditList } from '@/lib/admin/list';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const page = parsePageParam(url.searchParams.get('page'), 1);
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 50, 100);
const action = url.searchParams.get('action') ?? '';
const targetType = url.searchParams.get('target_type') ?? '';
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
const { entries, total } = await getAuditList({
page,
perPage,
action,
targetType,
sort,
order,
});
return jsonNoStore({ entries, total, page, perPage });
} catch (e) {
console.error('admin audit list failed', e);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
}
-14
View File
@@ -1,14 +0,0 @@
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { computeMetrics } from '@/lib/admin/metrics';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const metrics = await computeMetrics();
return jsonNoStore(metrics);
}
-99
View File
@@ -1,99 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { RESERVED_SUBDOMAINS } from '@/lib/validation';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
const NAME_RE = /^[a-z0-9-]{1,63}$/;
export async function GET() {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('reserved_subdomains')
.select('name, created_at')
.order('name', { ascending: true });
if (error) {
console.error('admin reserved list failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
return jsonNoStore({
reserved: data ?? [],
hardcoded: Array.from(RESERVED_SUBDOMAINS).sort(),
});
}
export async function POST(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
let body: { name?: unknown };
try {
body = (await req.json()) as { name?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
if (typeof body.name !== 'string') {
return jsonNoStore({ error: 'name must be a string' }, { status: 400 });
}
const name = body.name.trim().toLowerCase();
if (!NAME_RE.test(name)) {
return jsonNoStore(
{ error: 'name must be 163 chars, lowercase az, 09, hyphen' },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
const { error } = await admin
.from('reserved_subdomains')
.upsert({ name }, { onConflict: 'name' });
if (error) {
console.error('admin reserved add failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
await logAdminAction(auth.user, {
action: 'reserved.add',
target_type: 'reserved_subdomain',
target_id: name,
});
return jsonNoStore({ ok: true, name });
}
export async function DELETE(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const name = (url.searchParams.get('name') ?? '').trim().toLowerCase();
if (!name) {
return jsonNoStore({ error: 'name is required' }, { status: 400 });
}
const admin = getSupabaseAdmin();
const { error } = await admin
.from('reserved_subdomains')
.delete()
.eq('name', name);
if (error) {
console.error('admin reserved remove failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
await logAdminAction(auth.user, {
action: 'reserved.remove',
target_type: 'reserved_subdomain',
target_id: name,
});
return jsonNoStore({ ok: true });
}
@@ -1,66 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid, parseBoolean } from '@/lib/admin/validators';
import { setTunnelActive } from '@/lib/redis';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
let body: { is_active?: unknown };
try {
body = (await req.json()) as { is_active?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
const isActive = parseBoolean(body.is_active);
if (isActive === null) {
return jsonNoStore(
{ error: 'is_active must be a boolean' },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('tunnels')
.update({ is_active: isActive })
.eq('user_id', id)
.select('subdomain')
.maybeSingle<{ subdomain: string }>();
if (error) {
console.error('admin tunnel.active failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
// Best-effort live kill-switch (never throws). Writes tunnel:active:<sub>
// = "1"/"0" with TTL so the edge gate drops/allows a live connection within
// ~1s. No-op when REDIS_URL is unset.
const redisOk = await setTunnelActive(data.subdomain, isActive);
await logAdminAction(auth.user, {
action: isActive ? 'tunnel.activate' : 'tunnel.deactivate',
target_type: 'tunnel',
target_id: id,
details: { subdomain: data.subdomain, is_active: isActive, redis: redisOk },
});
return jsonNoStore({ ok: true, is_active: isActive });
}
-63
View File
@@ -1,63 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid, parsePositiveInt } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
// 100 TiB ceiling — generous but guards against absurd values.
const MAX_QUOTA = 100 * 1024 ** 4;
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
let body: { quota_bytes?: unknown };
try {
body = (await req.json()) as { quota_bytes?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
const parsed = parsePositiveInt(body.quota_bytes, MAX_QUOTA);
if (!parsed.ok) {
return jsonNoStore(
{ error: `quota_bytes ${parsed.error}` },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('tunnels')
.update({ quota_bytes: parsed.value })
.eq('user_id', id)
.select('subdomain')
.maybeSingle<{ subdomain: string }>();
if (error) {
console.error('admin tunnel.quota failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
await logAdminAction(auth.user, {
action: 'tunnel.quota',
target_type: 'tunnel',
target_id: id,
details: { subdomain: data.subdomain, quota_bytes: parsed.value },
});
return jsonNoStore({ ok: true, quota_bytes: parsed.value });
}
@@ -1,101 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { validateSubdomain } from '@/lib/validation';
import { isSubdomainReserved } from '@/lib/admin/reserved';
import { setTunnelActive } from '@/lib/redis';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
let body: { subdomain?: unknown };
try {
body = (await req.json()) as { subdomain?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
// Same validation as the user-facing claim flow (format + hardcoded reserved).
const v = validateSubdomain(body.subdomain);
if (!v.ok) {
return jsonNoStore({ error: v.error }, { status: 400 });
}
const subdomain = v.value;
// Also reject anything reserved in the DB table.
if (await isSubdomainReserved(subdomain)) {
return jsonNoStore(
{ error: `'${subdomain}' is reserved` },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
// Reject if taken by a different tunnel (keyed by owner user_id).
const { data: existing } = await admin
.from('tunnels')
.select('user_id, subdomain')
.eq('subdomain', subdomain)
.maybeSingle<{ user_id: string; subdomain: string }>();
if (existing && existing.user_id !== id) {
return jsonNoStore({ error: 'subdomain taken' }, { status: 409 });
}
// Capture the current subdomain so we can drop the OLD hostname's live
// connection once it is freed by the rename.
const { data: current } = await admin
.from('tunnels')
.select('subdomain')
.eq('user_id', id)
.maybeSingle<{ subdomain: string }>();
const oldSubdomain = current?.subdomain ?? null;
const { data, error } = await admin
.from('tunnels')
.update({ subdomain })
.eq('user_id', id)
.select('subdomain')
.maybeSingle<{ subdomain: string }>();
if (error) {
const code = (error as { code?: string }).code;
if (code === '23505') {
return jsonNoStore({ error: 'subdomain taken' }, { status: 409 });
}
console.error('admin tunnel.reassign failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
// Best-effort: drop any live connection on the OLD subdomain so the former
// hostname stops resolving as active. No-op when REDIS_URL is unset.
if (oldSubdomain && oldSubdomain !== subdomain) {
await setTunnelActive(oldSubdomain, false);
}
await logAdminAction(auth.user, {
action: 'tunnel.reassign',
target_type: 'tunnel',
target_id: id,
details: { subdomain, previous_subdomain: oldSubdomain },
});
return jsonNoStore({ ok: true, subdomain });
}
@@ -1,49 +0,0 @@
import { type NextRequest } from 'next/server';
import { randomBytes } from 'node:crypto';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(
_req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
const token = randomBytes(32).toString('hex');
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('tunnels')
.update({ token })
.eq('user_id', id)
.select('subdomain, token')
.maybeSingle<{ subdomain: string; token: string }>();
if (error) {
console.error('admin tunnel.regenerate_token failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
await logAdminAction(auth.user, {
action: 'tunnel.regenerate_token',
target_type: 'tunnel',
target_id: id,
details: { subdomain: data.subdomain },
});
return jsonNoStore({ ok: true, token: data.token });
}
@@ -1,46 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(
_req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('tunnels')
.update({ bytes_used: 0 })
.eq('user_id', id)
.select('subdomain')
.maybeSingle<{ subdomain: string }>();
if (error) {
console.error('admin tunnel.reset_usage failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
await logAdminAction(auth.user, {
action: 'tunnel.reset_usage',
target_type: 'tunnel',
target_id: id,
details: { subdomain: data.subdomain },
});
return jsonNoStore({ ok: true });
}
-51
View File
@@ -1,51 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { setTunnelActive } from '@/lib/redis';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function DELETE(
_req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid tunnel id' }, { status: 400 });
}
const admin = getSupabaseAdmin();
const { data, error } = await admin
.from('tunnels')
.delete()
.eq('user_id', id)
.select('subdomain')
.maybeSingle<{ subdomain: string }>();
if (error) {
console.error('admin tunnel.delete failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
if (!data) {
return jsonNoStore({ error: 'tunnel not found' }, { status: 404 });
}
// Best-effort live kill-switch: write "0" so any live connection on the
// freed subdomain drops within ~1s. No-op when REDIS_URL is unset.
const redisOk = await setTunnelActive(data.subdomain, false);
await logAdminAction(auth.user, {
action: 'tunnel.delete',
target_type: 'tunnel',
target_id: id,
details: { subdomain: data.subdomain, redis: redisOk },
});
return jsonNoStore({ ok: true });
}
-79
View File
@@ -1,79 +0,0 @@
import { type NextRequest, NextResponse } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getTunnelsList } from '@/lib/admin/list';
import { logAdminAction } from '@/lib/auth/audit';
import { toCsv, EXPORT_MAX_ROWS } from '@/lib/admin/csv';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const search = url.searchParams.get('search') ?? '';
const status = url.searchParams.get('status');
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
// Respect search/status/sort but pull the full matching set (capped).
// SECURITY: the tunnel token is NEVER selected or exported.
const { tunnels } = await getTunnelsList({
page: 1,
perPage: EXPORT_MAX_ROWS,
search,
status,
sort,
order,
});
const header = [
'user_id',
'owner_email',
'subdomain',
'is_active',
'bytes_used',
'quota_bytes',
'usage_pct',
'last_seen_at',
'created_at',
];
const rows = tunnels.map((t) => [
t.user_id,
t.owner_email ?? '',
t.subdomain,
t.is_active ? 'true' : 'false',
t.bytes_used,
t.quota_bytes,
t.usage_pct.toFixed(1),
t.last_seen_at ?? '',
t.created_at,
]);
const csv = toCsv(header, rows);
await logAdminAction(auth.user, {
action: 'tunnel.export',
target_type: 'tunnel',
details: { count: rows.length, capped: rows.length >= EXPORT_MAX_ROWS },
});
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="tunnels.csv"',
'Cache-Control': 'no-store',
Pragma: 'no-cache',
},
});
} catch (e) {
console.error('admin tunnels export failed', e);
return NextResponse.json(
{ error: 'internal error' },
{ status: 500, headers: { 'Cache-Control': 'no-store' } },
);
}
}
-36
View File
@@ -1,36 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
import { getTunnelsList } from '@/lib/admin/list';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const page = parsePageParam(url.searchParams.get('page'), 1);
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 25, 100);
const search = url.searchParams.get('search') ?? '';
const status = url.searchParams.get('status'); // active|inactive|over_quota
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
const { tunnels, total } = await getTunnelsList({
page,
perPage,
search,
status,
sort,
order,
});
return jsonNoStore({ tunnels, total, page, perPage });
} catch (e) {
console.error('admin tunnels list failed', e);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
}
-69
View File
@@ -1,69 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid, parseBoolean } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
// ~100 years.
const BAN_DURATION = '876000h';
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid user id' }, { status: 400 });
}
if (id === auth.user.id) {
return jsonNoStore(
{ error: 'you cannot ban your own account' },
{ status: 400 },
);
}
let body: { banned?: unknown };
try {
body = (await req.json()) as { banned?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
const banned = parseBoolean(body.banned);
if (banned === null) {
return jsonNoStore(
{ error: 'banned must be a boolean' },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
// Retry transient empty-body / poisoned-keep-alive failures so a burst-load
// ban/unban doesn't 500. `updateUserById` is idempotent for our use
// (ban_duration set to the same value), so a retry is safe.
const { error } = await withAdminRetry(() =>
admin.auth.admin.updateUserById(id, {
ban_duration: banned ? BAN_DURATION : 'none',
} as { ban_duration: string }),
);
if (error) {
console.error('admin user.ban failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
await logAdminAction(auth.user, {
action: banned ? 'user.ban' : 'user.unban',
target_type: 'user',
target_id: id,
details: { banned },
});
return jsonNoStore({ ok: true, banned });
}
-77
View File
@@ -1,77 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function POST(
req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid user id' }, { status: 400 });
}
if (id === auth.user.id) {
return jsonNoStore(
{ error: 'you cannot change your own role' },
{ status: 400 },
);
}
let body: { role?: unknown };
try {
body = (await req.json()) as { role?: unknown };
} catch {
return jsonNoStore({ error: 'invalid json' }, { status: 400 });
}
if (body.role !== 'admin' && body.role !== 'user') {
return jsonNoStore(
{ error: "role must be 'admin' or 'user'" },
{ status: 400 },
);
}
const role = body.role;
const admin = getSupabaseAdmin();
// Merge with existing app_metadata so we don't clobber other keys. Retry the
// read on transient empty-body responses so a burst-load flake isn't
// misreported as a 404; a genuine not-found still falls through below.
const { data: existing, error: getErr } = await withAdminRetry(() =>
admin.auth.admin.getUserById(id),
);
if (getErr || !existing.user) {
return jsonNoStore({ error: 'user not found' }, { status: 404 });
}
const merged = { ...(existing.user.app_metadata ?? {}), role };
// `updateUserById` is idempotent here (same app_metadata), so retrying a
// transient empty-body write is safe.
const { error } = await withAdminRetry(() =>
admin.auth.admin.updateUserById(id, {
app_metadata: merged,
}),
);
if (error) {
console.error('admin user.role failed', error);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
await logAdminAction(auth.user, {
action: 'user.role',
target_type: 'user',
target_id: id,
details: { role },
});
return jsonNoStore({ ok: true, role });
}
-163
View File
@@ -1,163 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import { logAdminAction } from '@/lib/auth/audit';
import { isUuid } from '@/lib/admin/validators';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
type TunnelRow = {
user_id: string;
subdomain: string;
token: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
last_seen_at: string | null;
created_at: string;
};
export async function GET(
_req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid user id' }, { status: 400 });
}
const admin = getSupabaseAdmin();
// Retry transient empty-body GoTrue responses so a burst-induced flake isn't
// misreported as a 404 for a user that actually exists. A genuine not-found
// (non-transient) still falls through to the clean 404 below.
const { data: userRes, error: userErr } = await withAdminRetry(() =>
admin.auth.admin.getUserById(id),
);
if (userErr || !userRes.user) {
return jsonNoStore({ error: 'user not found' }, { status: 404 });
}
const u = userRes.user;
const { data: tunnel } = await admin
.from('tunnels')
.select(
'user_id, subdomain, token, is_active, bytes_used, quota_bytes, last_seen_at, created_at',
)
.eq('user_id', id)
.maybeSingle<TunnelRow>();
const { data: audit } = await admin
.from('admin_audit_log')
.select('id, actor_email, action, target_type, target_id, details, created_at')
.eq('target_id', id)
.order('created_at', { ascending: false })
.limit(25);
return jsonNoStore({
user: {
id: u.id,
email: u.email ?? null,
role: (u.app_metadata?.role as string | undefined) ?? 'user',
banned_until:
(u as unknown as { banned_until?: string | null }).banned_until ?? null,
email_confirmed_at: u.email_confirmed_at ?? null,
created_at: u.created_at,
last_sign_in_at: u.last_sign_in_at ?? null,
},
tunnel: tunnel
? {
subdomain: tunnel.subdomain,
is_active: tunnel.is_active,
bytes_used: tunnel.bytes_used,
quota_bytes: tunnel.quota_bytes,
last_seen_at: tunnel.last_seen_at,
created_at: tunnel.created_at,
}
: null,
audit: audit ?? [],
});
}
export async function DELETE(
_req: NextRequest,
{ params }: { params: { id: string } },
) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const { id } = params;
if (!isUuid(id)) {
return jsonNoStore({ error: 'invalid user id' }, { status: 400 });
}
if (id === auth.user.id) {
return jsonNoStore(
{ error: 'you cannot delete your own account' },
{ status: 400 },
);
}
const admin = getSupabaseAdmin();
// Confirm the user exists up front. GoTrue replies with an empty body when
// deleting a non-existent user, which supabase-js surfaces as an opaque
// JSON-parse error (no status / "not found" text); a positive existence
// check lets us return a clean 404 instead of a misleading 500. Retry the
// lookup so a transient empty body under load isn't mistaken for not-found.
const { data: existing, error: lookupErr } = await withAdminRetry(() =>
admin.auth.admin.getUserById(id),
);
if (lookupErr || !existing.user) {
return jsonNoStore({ error: 'user not found' }, { status: 404 });
}
// Delete the AUTH USER first. Only if that succeeds do we remove the tunnel
// row, so a mid-failure never leaves an orphaned auth user with a dangling
// tunnel (or half-deletes the tunnel of an already-gone user). Retry the
// delete on transient empty-body / poisoned-keep-alive responses.
const { error: delErr } = await withAdminRetry(() =>
admin.auth.admin.deleteUser(id),
);
if (delErr) {
// The delete may have actually succeeded with a truncated/empty response
// body (the transient failure mode). Re-check existence before reporting a
// 500: if the user is now gone, the deletion is effectively complete.
const { data: recheck, error: recheckErr } = await withAdminRetry(() =>
admin.auth.admin.getUserById(id),
);
if (recheckErr || !recheck?.user) {
// User is gone -> delete succeeded despite the truncated body.
} else {
console.error('admin user.delete: deleteUser failed', delErr);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
}
// The auth user is gone, so no orphaned-user state is possible. Removing the
// tunnel row is best-effort cleanup: if it fails we log server-side but still
// report the (already-completed) user deletion as successful.
const { error: tunnelErr } = await admin
.from('tunnels')
.delete()
.eq('user_id', id);
if (tunnelErr) {
console.error(
`admin user.delete: tunnel cleanup failed for ${id}`,
tunnelErr,
);
}
await logAdminAction(auth.user, {
action: 'user.delete',
target_type: 'user',
target_id: id,
});
return jsonNoStore({ ok: true });
}
-85
View File
@@ -1,85 +0,0 @@
import { type NextRequest, NextResponse } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { getUsersList } from '@/lib/admin/list';
import { logAdminAction } from '@/lib/auth/audit';
import { toCsv, EXPORT_MAX_ROWS } from '@/lib/admin/csv';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
function isBanned(banned_until: string | null): boolean {
return !!banned_until && new Date(banned_until).getTime() > Date.now();
}
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const search = url.searchParams.get('search') ?? '';
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
// Respect search/sort but pull the full matching set (capped). NOTE: never
// export secrets — the users list carries no token.
const { users } = await getUsersList({
page: 1,
perPage: EXPORT_MAX_ROWS,
search,
sort,
order,
});
const header = [
'email',
'role',
'status',
'tunnel_subdomain',
'tunnel_active',
'bytes_used',
'quota_bytes',
'created_at',
'last_sign_in_at',
];
const rows = users.map((u) => [
u.email ?? '',
u.role,
isBanned(u.banned_until)
? 'banned'
: u.email_confirmed_at
? 'confirmed'
: 'unconfirmed',
u.tunnel?.subdomain ?? '',
u.tunnel ? (u.tunnel.is_active ? 'true' : 'false') : '',
u.tunnel?.bytes_used ?? '',
u.tunnel?.quota_bytes ?? '',
u.created_at,
u.last_sign_in_at ?? '',
]);
const csv = toCsv(header, rows);
await logAdminAction(auth.user, {
action: 'user.export',
target_type: 'user',
details: { count: rows.length, capped: rows.length >= EXPORT_MAX_ROWS },
});
return new NextResponse(csv, {
status: 200,
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': 'attachment; filename="users.csv"',
'Cache-Control': 'no-store',
Pragma: 'no-cache',
},
});
} catch (e) {
console.error('admin users export failed', e);
return NextResponse.json(
{ error: 'internal error' },
{ status: 500, headers: { 'Cache-Control': 'no-store' } },
);
}
}
-34
View File
@@ -1,34 +0,0 @@
import { type NextRequest } from 'next/server';
import { requireAdminApi } from '@/lib/auth/admin-guard';
import { parsePageParam, parsePerPageParam } from '@/lib/admin/validators';
import { getUsersList } from '@/lib/admin/list';
import { jsonNoStore } from '@/lib/admin/response';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
export async function GET(req: NextRequest) {
const auth = await requireAdminApi();
if (!auth.ok) return auth.response;
const url = new URL(req.url);
const page = parsePageParam(url.searchParams.get('page'), 1);
const perPage = parsePerPageParam(url.searchParams.get('perPage'), 25, 100);
const search = url.searchParams.get('search') ?? '';
const sort = url.searchParams.get('sort');
const order = url.searchParams.get('order');
try {
const { users, total } = await getUsersList({
page,
perPage,
search,
sort,
order,
});
return jsonNoStore({ users, total, page, perPage });
} catch (e) {
console.error('admin users list failed', e);
return jsonNoStore({ error: 'internal error' }, { status: 500 });
}
}
-53
View File
@@ -1,53 +0,0 @@
import { NextResponse, type NextRequest } from 'next/server';
import type { EmailOtpType } from '@supabase/supabase-js';
import { createSupabaseServerClient } from '@/lib/supabase/server';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
/**
* Whitelist `next` to same-origin relative paths only (open-redirect guard).
* Anything that isn't a single-slash-rooted path falls back to /dashboard.
*/
function safeNext(raw: string | null): string {
if (!raw || !raw.startsWith('/') || raw.startsWith('//')) {
return '/dashboard';
}
return raw;
}
/**
* Email confirmation / OTP verification landing route.
*
* Handles both GoTrue link styles defensively:
* - token_hash template: /auth/confirm?token_hash=<hash>&type=signup -> verifyOtp
* - PKCE/code redirect: /auth/confirm?code=<code> -> exchangeCodeForSession
*
* On success the server client persists the session cookies and we redirect to
* `next` (default /dashboard). On any failure we send the user to /login with a
* verification_failed flag so they can resend a fresh confirmation email.
*/
export async function GET(request: NextRequest) {
const url = request.nextUrl;
const token_hash = url.searchParams.get('token_hash');
const type = url.searchParams.get('type') as EmailOtpType | null;
const code = url.searchParams.get('code');
const next = safeNext(url.searchParams.get('next'));
const base = process.env.NEXT_PUBLIC_APP_URL ?? url.origin;
const supabase = createSupabaseServerClient();
if (token_hash && type) {
const { error } = await supabase.auth.verifyOtp({ type, token_hash });
if (!error) {
return NextResponse.redirect(new URL(next, base));
}
} else if (code) {
const { error } = await supabase.auth.exchangeCodeForSession(code);
if (!error) {
return NextResponse.redirect(new URL(next, base));
}
}
return NextResponse.redirect(new URL('/login?error=verification_failed', base));
}
+3 -2
View File
@@ -3,7 +3,6 @@ import { createSupabaseServerClient } from '@/lib/supabase/server';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { ClaimForm } from './claim-form';
import { TokenReveal } from './token-reveal';
import { formatDate } from '@/lib/format';
export const dynamic = 'force-dynamic';
@@ -93,7 +92,9 @@ export default async function DashboardPage() {
<div className="k">Last seen</div>
<div>
{tunnel.last_seen_at ? formatDate(tunnel.last_seen_at) : 'never'}
{tunnel.last_seen_at
? new Date(tunnel.last_seen_at).toLocaleString()
: 'never'}
</div>
</div>
-263
View File
@@ -165,266 +165,3 @@ button.secondary,
gap: 0.5rem;
align-items: center;
}
/* ----------------------------------------------------------------------- */
/* Admin interface */
/* ----------------------------------------------------------------------- */
.admin-shell {
display: flex;
min-height: calc(100vh - 65px);
align-items: stretch;
}
.admin-sidebar {
width: 220px;
flex: 0 0 220px;
border-right: 1px solid var(--border);
padding: 1.5rem 1rem;
display: flex;
flex-direction: column;
gap: 1rem;
}
.admin-brand {
font-weight: 700;
font-size: 1.1rem;
letter-spacing: 0.02em;
}
.admin-nav {
display: flex;
flex-direction: column;
gap: 0.25rem;
}
.admin-nav-link {
display: block;
padding: 0.5rem 0.75rem;
border-radius: 6px;
color: var(--fg);
}
.admin-nav-link:hover {
background: var(--card);
text-decoration: none;
}
.admin-nav-link.active {
background: var(--accent);
color: var(--accent-fg);
}
.admin-sidebar-footer {
margin-top: auto;
display: flex;
flex-direction: column;
gap: 0.5rem;
border-top: 1px solid var(--border);
padding-top: 1rem;
}
.admin-back {
font-size: 0.875rem;
}
.admin-content {
flex: 1 1 auto;
padding: 2rem;
min-width: 0;
}
.admin-cols {
display: grid;
grid-template-columns: 1fr 1fr;
gap: 1rem;
}
@media (max-width: 800px) {
.admin-shell {
flex-direction: column;
}
.admin-sidebar {
width: auto;
flex: none;
border-right: none;
border-bottom: 1px solid var(--border);
}
.admin-sidebar-footer {
margin-top: 0;
}
.admin-cols {
grid-template-columns: 1fr;
}
.admin-content {
padding: 1.25rem;
}
}
/* KPI cards */
.kpi-grid {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
gap: 0.75rem;
margin: 1rem 0 1.5rem;
}
.kpi-card {
background: var(--card);
border: 1px solid var(--border);
border-radius: 8px;
padding: 1rem;
}
.kpi-value {
font-size: 1.5rem;
font-weight: 700;
}
.kpi-label {
color: var(--muted);
font-size: 0.8rem;
margin-top: 0.25rem;
}
/* Tables */
.admin-table-wrap {
overflow-x: auto;
border: 1px solid var(--border);
border-radius: 8px;
}
.admin-table {
width: 100%;
border-collapse: collapse;
font-size: 0.875rem;
}
.admin-table th,
.admin-table td {
text-align: left;
padding: 0.6rem 0.75rem;
border-bottom: 1px solid var(--border);
vertical-align: top;
}
.admin-table th {
color: var(--muted);
font-weight: 600;
background: var(--card);
white-space: nowrap;
}
.admin-table tr:last-child td {
border-bottom: none;
}
.admin-table tbody tr:hover {
background: rgba(255, 255, 255, 0.02);
}
.admin-table code {
font-family: ui-monospace, SFMono-Regular, Menlo, monospace;
font-size: 0.8rem;
word-break: break-all;
}
/* Badges */
.badge {
display: inline-block;
padding: 0.15rem 0.5rem;
border-radius: 999px;
font-size: 0.75rem;
border: 1px solid var(--border);
background: var(--bg);
color: var(--muted);
white-space: nowrap;
}
.badge-admin {
background: rgba(59, 130, 246, 0.15);
border-color: var(--accent);
color: #93c5fd;
}
.badge-banned {
background: rgba(239, 68, 68, 0.15);
border-color: var(--danger);
color: #fca5a5;
}
.badge-ok {
background: rgba(34, 197, 94, 0.15);
border-color: var(--success);
color: #86efac;
}
/* Button variants */
.btn-sm {
padding: 0.35rem 0.6rem;
font-size: 0.8rem;
}
.btn-danger {
background: var(--danger);
border-color: var(--danger);
color: #fff;
}
.btn-danger:hover {
opacity: 0.9;
}
button:disabled,
.btn:disabled {
opacity: 0.5;
cursor: not-allowed;
}
select {
font-size: 1rem;
}
/* Sortable table headers */
.th-sort {
cursor: pointer;
user-select: none;
white-space: nowrap;
}
.th-sort:hover {
color: var(--fg);
}
.th-sort .sort-ind {
margin-left: 0.3rem;
opacity: 0.5;
font-size: 0.7rem;
}
.th-sort.sorted .sort-ind {
opacity: 1;
color: var(--accent);
}
/* Checkbox / selection column */
.admin-table th.col-check,
.admin-table td.col-check {
width: 1%;
white-space: nowrap;
text-align: center;
}
.admin-table input[type='checkbox'] {
width: auto;
margin: 0;
cursor: pointer;
accent-color: var(--accent);
}
.admin-table tr.row-selected td {
background: rgba(59, 130, 246, 0.08);
}
/* Bulk action bar */
.bulk-bar {
display: flex;
align-items: center;
gap: 0.5rem;
flex-wrap: wrap;
margin: 0 0 1rem;
padding: 0.6rem 0.85rem;
background: var(--card);
border: 1px solid var(--accent);
border-radius: 8px;
}
.bulk-bar .bulk-count {
font-weight: 600;
margin-right: 0.25rem;
}
.bulk-bar .spacer {
flex: 1 1 auto;
}
.toolbar-actions {
margin-left: auto;
display: flex;
gap: 0.5rem;
}
-2
View File
@@ -19,7 +19,6 @@ export default async function RootLayout({
const {
data: { user },
} = await supabase.auth.getUser();
const isAdmin = user?.app_metadata?.role === 'admin';
return (
<html lang="en">
@@ -33,7 +32,6 @@ export default async function RootLayout({
<>
<Link href="/dashboard">Dashboard</Link>
<Link href="/billing">Billing</Link>
{isAdmin && <Link href="/admin">Admin</Link>}
<form action="/api/auth/signout" method="post" style={{ margin: 0 }}>
<button className="secondary" type="submit">
Sign out
+2 -67
View File
@@ -1,47 +1,20 @@
'use client';
import { useEffect, useState, useTransition } from 'react';
import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import type { AuthError } from '@supabase/supabase-js';
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
const RESEND_COOLDOWN = 45;
function isEmailNotConfirmed(error: AuthError): boolean {
return error.code === 'email_not_confirmed' || /not confirmed/i.test(error.message);
}
export default function LoginPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [needsConfirm, setNeedsConfirm] = useState(false);
const [resendInfo, setResendInfo] = useState<string | null>(null);
const [cooldown, setCooldown] = useState(0);
const [isPending, startTransition] = useTransition();
const [isResending, startResend] = useTransition();
useEffect(() => {
const params = new URLSearchParams(window.location.search);
if (params.get('error') === 'verification_failed') {
setError(
'Email verification failed or the link expired. Sign in below to resend a confirmation email.',
);
}
}, []);
useEffect(() => {
if (cooldown <= 0) return;
const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
return () => clearTimeout(t);
}, [cooldown]);
function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setResendInfo(null);
const supabase = createSupabaseBrowserClient();
startTransition(async () => {
const { error } = await supabase.auth.signInWithPassword({
@@ -49,14 +22,7 @@ export default function LoginPage() {
password,
});
if (error) {
if (isEmailNotConfirmed(error)) {
setNeedsConfirm(true);
setError(
'Please confirm your email address before signing in. Check your inbox or resend the confirmation email below.',
);
} else {
setError(error.message);
}
setError(error.message);
return;
}
router.push('/dashboard');
@@ -64,20 +30,6 @@ export default function LoginPage() {
});
}
function onResend() {
setResendInfo(null);
const supabase = createSupabaseBrowserClient();
startResend(async () => {
const { error } = await supabase.auth.resend({ type: 'signup', email });
if (error) {
setError(error.message);
return;
}
setResendInfo('Confirmation email sent. Check your inbox.');
setCooldown(RESEND_COOLDOWN);
});
}
return (
<div className="card">
<h1>Login</h1>
@@ -101,23 +53,6 @@ export default function LoginPage() {
onChange={(e) => setPassword(e.target.value)}
/>
{error && <p className="error">{error}</p>}
{resendInfo && <p className="success">{resendInfo}</p>}
{needsConfirm && (
<div className="row" style={{ marginTop: '0.75rem' }}>
<button
type="button"
className="secondary"
onClick={onResend}
disabled={isResending || cooldown > 0 || !email}
>
{cooldown > 0
? `Resend in ${cooldown}s`
: isResending
? 'Sending…'
: 'Resend confirmation email'}
</button>
</div>
)}
<div className="row" style={{ marginTop: '1rem' }}>
<button type="submit" disabled={isPending}>
{isPending ? 'Signing in…' : 'Sign in'}
+6 -74
View File
@@ -1,110 +1,41 @@
'use client';
import { useEffect, useState, useTransition } from 'react';
import { useState, useTransition } from 'react';
import { useRouter } from 'next/navigation';
import Link from 'next/link';
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
const RESEND_COOLDOWN = 45;
export default function SignupPage() {
const router = useRouter();
const [email, setEmail] = useState('');
const [password, setPassword] = useState('');
const [error, setError] = useState<string | null>(null);
const [submitted, setSubmitted] = useState(false);
const [resendInfo, setResendInfo] = useState<string | null>(null);
const [cooldown, setCooldown] = useState(0);
const [info, setInfo] = useState<string | null>(null);
const [isPending, startTransition] = useTransition();
const [isResending, startResend] = useTransition();
useEffect(() => {
if (cooldown <= 0) return;
const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
return () => clearTimeout(t);
}, [cooldown]);
function onSubmit(e: React.FormEvent) {
e.preventDefault();
setError(null);
setResendInfo(null);
setInfo(null);
const supabase = createSupabaseBrowserClient();
startTransition(async () => {
const { data, error } = await supabase.auth.signUp({
email,
password,
options: {
emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL ?? ''}/auth/confirm`,
},
});
if (error) {
setError(error.message);
return;
}
// GoTrue returns a decoy user with an empty `identities` array when the
// email is already registered (to avoid leaking existence). Treat it as
// "already registered" and point them at login.
if (data.user && data.user.identities?.length === 0) {
setError(
'An account with this email already exists. Try signing in instead.',
);
return;
}
if (data.session) {
router.push('/dashboard');
router.refresh();
return;
} else {
setInfo('Check your email to confirm, then sign in.');
}
setSubmitted(true);
setCooldown(RESEND_COOLDOWN);
});
}
function onResend() {
setError(null);
setResendInfo(null);
const supabase = createSupabaseBrowserClient();
startResend(async () => {
const { error } = await supabase.auth.resend({ type: 'signup', email });
if (error) {
setError(error.message);
return;
}
setResendInfo('Confirmation email sent. Check your inbox.');
setCooldown(RESEND_COOLDOWN);
});
}
if (submitted) {
return (
<div className="card">
<h1>Check your email</h1>
<p>
We sent a confirmation link to <strong>{email}</strong>. Click the
link in that email to activate your account, then sign in.
</p>
{error && <p className="error">{error}</p>}
{resendInfo && <p className="success">{resendInfo}</p>}
<div className="row" style={{ marginTop: '1rem' }}>
<button
type="button"
onClick={onResend}
disabled={isResending || cooldown > 0}
>
{cooldown > 0
? `Resend in ${cooldown}s`
: isResending
? 'Sending…'
: 'Resend confirmation email'}
</button>
<Link className="muted" href="/login">
Back to login
</Link>
</div>
</div>
);
}
return (
<div className="card">
<h1>Sign up</h1>
@@ -129,6 +60,7 @@ export default function SignupPage() {
onChange={(e) => setPassword(e.target.value)}
/>
{error && <p className="error">{error}</p>}
{info && <p className="success">{info}</p>}
<div className="row" style={{ marginTop: '1rem' }}>
<button type="submit" disabled={isPending}>
{isPending ? 'Creating…' : 'Create account'}
+2 -4
View File
@@ -7,7 +7,7 @@
# .env.production sets WEB_PROJECT / WEB_IMAGE / WEB_CONTAINER / WEB_NETWORK.
name: ${WEB_PROJECT:-web}
services:
web:
web-dev:
build:
context: .
dockerfile: Dockerfile
@@ -27,9 +27,7 @@ services:
expose:
- "3000"
networks:
default:
aliases:
- web-prod
- default
healthcheck:
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/"]
interval: 30s
-45
View File
@@ -1,45 +0,0 @@
/**
* Minimal, dependency-free CSV serialization for the admin export endpoints.
* RFC-4180 style: fields containing a comma, double-quote, CR or LF are wrapped
* in double-quotes with embedded quotes doubled. Everything is coerced to a
* string first; null/undefined become empty fields.
*/
export function csvField(v: unknown): string {
let s: string;
if (v === null || v === undefined) s = '';
else if (typeof v === 'string') s = v;
else if (typeof v === 'object') s = JSON.stringify(v);
else s = String(v);
// Spreadsheet formula-injection guard: a field whose first character is one
// of = + - @ (or a leading tab/CR) is interpreted as a formula by Excel /
// Sheets / LibreOffice. Neutralize it by prefixing a single quote BEFORE the
// RFC-4180 quote-escaping below, so the value renders as literal text.
if (s.length > 0 && /^[=+\-@\t\r]/.test(s)) {
s = `'${s}`;
}
if (/[",\r\n]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
}
export function csvRow(values: unknown[]): string {
return values.map(csvField).join(',');
}
/**
* Build a full CSV document (header + rows). A leading row is always the
* provided header. Lines are CRLF-terminated for maximal spreadsheet
* compatibility.
*/
export function toCsv(header: string[], rows: unknown[][]): string {
const lines = [csvRow(header), ...rows.map(csvRow)];
return lines.join('\r\n') + '\r\n';
}
/**
* Max rows any single export will emit. Keeps a runaway export bounded; the
* caller notes the cap in the report when hit.
*/
export const EXPORT_MAX_ROWS = 10000;
-372
View File
@@ -1,372 +0,0 @@
import type { User } from '@supabase/supabase-js';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
import {
parseOrder,
parseSort,
USER_SORTS,
TUNNEL_SORTS,
AUDIT_SORTS,
type SortOrder,
type UserSort,
type TunnelSort,
} from '@/lib/admin/sort';
/**
* Shared admin list-query logic, used by BOTH the JSON route handlers and the
* server components that render the initial page of each list. Doing the first
* load on the server (where the admin session is already validated by
* `requireAdmin()`) avoids the on-mount client fetch racing the SSR session
* cookie refresh, which previously produced intermittent 401s.
*/
export type AdminUserItem = {
id: string;
email: string | null;
role: string;
banned_until: string | null;
email_confirmed_at: string | null;
created_at: string;
last_sign_in_at: string | null;
tunnel: {
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
} | null;
};
export type TunnelItem = {
user_id: string;
owner_email: string | null;
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
usage_pct: number;
last_seen_at: string | null;
created_at: string;
};
export type AuditItem = {
id: number;
actor_id: string | null;
actor_email: string | null;
action: string;
target_type: string | null;
target_id: string | null;
details: Record<string, unknown>;
created_at: string;
};
type TunnelJoinRow = {
user_id: string;
subdomain: string;
is_active: boolean;
bytes_used: number;
quota_bytes: number;
};
type TunnelRow = TunnelJoinRow & {
last_seen_at: string | null;
created_at: string;
};
// Bound the full-email-scan search: 50 pages * 1000 = up to 50k users. Beyond
// this we stop scanning (extremely unlikely for this deployment's scale).
const USER_SCAN_MAX_PAGES = 50;
const USER_SCAN_PER_PAGE = 1000;
function userSortValue(u: User, sort: UserSort): string | number {
switch (sort) {
case 'email':
return (u.email ?? '').toLowerCase();
case 'role':
return ((u.app_metadata?.role as string | undefined) ?? 'user').toLowerCase();
case 'last_sign_in_at':
return u.last_sign_in_at ? Date.parse(u.last_sign_in_at) : 0;
case 'created_at':
default:
return u.created_at ? Date.parse(u.created_at) : 0;
}
}
function sortUsers(arr: User[], sort: UserSort, order: SortOrder): void {
const dir = order === 'asc' ? 1 : -1;
arr.sort((a, b) => {
const av = userSortValue(a, sort);
const bv = userSortValue(b, sort);
if (av < bv) return -1 * dir;
if (av > bv) return 1 * dir;
return 0;
});
}
export async function getUsersList(opts: {
page: number;
perPage: number;
search: string;
sort?: string | null;
order?: string | null;
}): Promise<{ users: AdminUserItem[]; total: number }> {
const { page, perPage } = opts;
const search = opts.search.trim().toLowerCase();
const sort = parseSort(opts.sort, USER_SORTS, 'created_at');
const order = parseOrder(opts.order, 'desc');
const admin = getSupabaseAdmin();
let pageUsers: User[];
let total: number;
// A non-default sort must order across ALL users (not just one listUsers
// page), so it shares the search path's full directory scan.
const isDefaultSort = sort === 'created_at' && order === 'desc';
const needScan = !!search || !isDefaultSort;
if (needScan) {
// Page through the user directory (bounded by USER_SCAN_MAX_PAGES),
// accumulate case-insensitive email substring matches, sort, then
// paginate the filtered+sorted set.
const matched: User[] = [];
for (let p = 1; p <= USER_SCAN_MAX_PAGES; p++) {
// Retry transient empty-body GoTrue responses so a burst-induced flake
// doesn't abort the full directory scan mid-way.
const { data, error } = await withAdminRetry(() =>
admin.auth.admin.listUsers({
page: p,
perPage: USER_SCAN_PER_PAGE,
}),
);
if (error) throw new Error(error.message);
const us = data.users;
if (us.length === 0) break;
for (const u of us) {
if (!search || (u.email ?? '').toLowerCase().includes(search)) {
matched.push(u);
}
}
if (us.length < USER_SCAN_PER_PAGE) break;
}
sortUsers(matched, sort, order);
total = matched.length;
const from = (page - 1) * perPage;
pageUsers = matched.slice(from, from + perPage);
} else {
// Common no-search, default-sort path: cheap single-page lookup. Retry
// transient empty-body responses so the post-mutation auto-refresh that
// hits this path doesn't intermittently 500.
const { data, error } = await withAdminRetry(() =>
admin.auth.admin.listUsers({ page, perPage }),
);
if (error) throw new Error(error.message);
pageUsers = data.users;
total = (data as unknown as { total?: number }).total ?? pageUsers.length;
}
// Join tunnel rows for this page's users in a single query.
const ids = pageUsers.map((u) => u.id);
const tunnelMap = new Map<string, TunnelJoinRow>();
if (ids.length > 0) {
const { data: tunnels } = await admin
.from('tunnels')
.select('user_id, subdomain, is_active, bytes_used, quota_bytes')
.in('user_id', ids);
for (const t of (tunnels ?? []) as TunnelJoinRow[]) {
tunnelMap.set(t.user_id, t);
}
}
const users: AdminUserItem[] = pageUsers.map((u) => {
const t = tunnelMap.get(u.id) ?? null;
return {
id: u.id,
email: u.email ?? null,
role: (u.app_metadata?.role as string | undefined) ?? 'user',
banned_until:
(u as unknown as { banned_until?: string | null }).banned_until ?? null,
email_confirmed_at: u.email_confirmed_at ?? null,
created_at: u.created_at,
last_sign_in_at: u.last_sign_in_at ?? null,
tunnel: t
? {
subdomain: t.subdomain,
is_active: t.is_active,
bytes_used: t.bytes_used,
quota_bytes: t.quota_bytes,
}
: null,
};
});
return { users, total };
}
function tunnelSortValue(t: TunnelRow, sort: TunnelSort): string | number {
switch (sort) {
case 'subdomain':
return t.subdomain.toLowerCase();
case 'bytes_used':
return t.bytes_used;
case 'quota_bytes':
return t.quota_bytes;
case 'is_active':
return t.is_active ? 1 : 0;
case 'last_seen_at':
return t.last_seen_at ? Date.parse(t.last_seen_at) : 0;
case 'usage_pct':
return t.quota_bytes > 0 ? t.bytes_used / t.quota_bytes : 0;
case 'created_at':
default:
return t.created_at ? Date.parse(t.created_at) : 0;
}
}
function sortTunnelRows(
arr: TunnelRow[],
sort: TunnelSort,
ascending: boolean,
): void {
const dir = ascending ? 1 : -1;
arr.sort((a, b) => {
const av = tunnelSortValue(a, sort);
const bv = tunnelSortValue(b, sort);
if (av < bv) return -1 * dir;
if (av > bv) return 1 * dir;
return 0;
});
}
export async function getTunnelsList(opts: {
page: number;
perPage: number;
search: string;
status: string | null;
sort?: string | null;
order?: string | null;
}): Promise<{ tunnels: TunnelItem[]; total: number }> {
const { page, perPage, status } = opts;
const search = opts.search.trim().toLowerCase();
const sort = parseSort(opts.sort, TUNNEL_SORTS, 'created_at');
const order = parseOrder(opts.order, 'desc');
const ascending = order === 'asc';
const admin = getSupabaseAdmin();
// The tunnels table's primary key is user_id (one tunnel per user); there is
// no `id` column. The user_id is the identifier exposed to the UI.
const cols =
'user_id, subdomain, is_active, bytes_used, quota_bytes, last_seen_at, created_at';
let rows: TunnelRow[];
let total: number;
const from = (page - 1) * perPage;
const to = from + perPage - 1;
if (status === 'over_quota') {
// Column-to-column comparison is not expressible via PostgREST filters,
// so fetch matching rows and paginate in memory.
let q = admin.from('tunnels').select(cols);
if (search) q = q.ilike('subdomain', `%${search}%`);
const { data, error } = await q;
if (error) throw new Error(error.message);
const all = ((data ?? []) as TunnelRow[]).filter(
(t) => t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes,
);
sortTunnelRows(all, sort, ascending);
total = all.length;
rows = all.slice(from, from + perPage);
} else {
let query = admin.from('tunnels').select(cols, { count: 'exact' });
if (search) query = query.ilike('subdomain', `%${search}%`);
if (status === 'active') query = query.eq('is_active', true);
else if (status === 'inactive') query = query.eq('is_active', false);
// usage_pct is computed; order by bytes_used as its closest DB proxy.
const dbCol = sort === 'usage_pct' ? 'bytes_used' : sort;
query = query.order(dbCol, { ascending }).range(from, to);
const { data, error, count } = await query;
if (error) throw new Error(error.message);
rows = (data ?? []) as TunnelRow[];
total = count ?? rows.length;
}
// Resolve owner emails via a single bounded listUsers scan rather than one
// getUserById per row. The upstream admin gateway deterministically truncates
// the first per-row lookup that immediately follows the request's auth check
// (an empty body the per-call retry can't clear), which surfaced as "—" on
// every load. A single listUsers read does not hit that pattern, so we scan
// the directory once (bounded, with the same transient-retry) and build an
// id→email map, stopping as soon as every owner on this page is resolved.
const wanted = new Set(rows.map((t) => t.user_id));
const emailById = new Map<string, string | null>();
if (wanted.size > 0) {
for (let p = 1; p <= USER_SCAN_MAX_PAGES; p++) {
const { data, error } = await withAdminRetry(() =>
admin.auth.admin.listUsers({ page: p, perPage: USER_SCAN_PER_PAGE }),
);
if (error) throw new Error(error.message);
const us = data.users;
if (us.length === 0) break;
for (const u of us) {
if (wanted.has(u.id)) emailById.set(u.id, u.email ?? null);
}
// Stop early once every owner on this tunnels page has been found.
if (rows.every((t) => emailById.has(t.user_id))) break;
if (us.length < USER_SCAN_PER_PAGE) break;
}
}
// Any owner not found in the scan falls back to "—" (null) — graceful, and a
// missing owner can never 500 the whole list.
const emails = rows.map((t) => emailById.get(t.user_id) ?? null);
const tunnels: TunnelItem[] = rows.map((t, i) => ({
user_id: t.user_id,
owner_email: emails[i],
subdomain: t.subdomain,
is_active: t.is_active,
bytes_used: t.bytes_used,
quota_bytes: t.quota_bytes,
usage_pct:
t.quota_bytes > 0
? Math.min(100, (t.bytes_used / t.quota_bytes) * 100)
: 0,
last_seen_at: t.last_seen_at,
created_at: t.created_at,
}));
return { tunnels, total };
}
export async function getAuditList(opts: {
page: number;
perPage: number;
action: string;
targetType: string;
sort?: string | null;
order?: string | null;
}): Promise<{ entries: AuditItem[]; total: number }> {
const { page, perPage } = opts;
const action = opts.action.trim();
const targetType = opts.targetType.trim();
const sort = parseSort(opts.sort, AUDIT_SORTS, 'created_at');
const ascending = parseOrder(opts.order, 'desc') === 'asc';
const admin = getSupabaseAdmin();
let query = admin
.from('admin_audit_log')
.select(
'id, actor_id, actor_email, action, target_type, target_id, details, created_at',
{ count: 'exact' },
);
if (action) query = query.eq('action', action);
if (targetType) query = query.eq('target_type', targetType);
const from = (page - 1) * perPage;
const to = from + perPage - 1;
query = query.order(sort, { ascending }).range(from, to);
const { data, error, count } = await query;
if (error) throw new Error(error.message);
const entries = (data ?? []) as AuditItem[];
return { entries, total: count ?? entries.length };
}
-83
View File
@@ -1,83 +0,0 @@
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { withAdminRetry } from '@/lib/admin/retry';
export type AdminMetrics = {
totalUsers: number;
totalTunnels: number;
activeTunnels: number;
inactiveTunnels: number;
overQuota: number;
bytesUsedTotal: number;
quotaTotal: number;
signups7d: number;
signups30d: number;
recentlyActive: number;
};
type TunnelAgg = {
is_active: boolean;
bytes_used: number;
quota_bytes: number;
last_seen_at: string | null;
};
export async function computeMetrics(): Promise<AdminMetrics> {
const admin = getSupabaseAdmin();
const { data: tunnelsData } = await admin
.from('tunnels')
.select('is_active, bytes_used, quota_bytes, last_seen_at');
const tunnels = (tunnelsData ?? []) as TunnelAgg[];
const now = Date.now();
const day = 24 * 60 * 60 * 1000;
let activeTunnels = 0;
let inactiveTunnels = 0;
let overQuota = 0;
let bytesUsedTotal = 0;
let quotaTotal = 0;
let recentlyActive = 0;
for (const t of tunnels) {
if (t.is_active) activeTunnels++;
else inactiveTunnels++;
if (t.quota_bytes > 0 && t.bytes_used >= t.quota_bytes) overQuota++;
bytesUsedTotal += Number(t.bytes_used) || 0;
quotaTotal += Number(t.quota_bytes) || 0;
if (t.last_seen_at && now - new Date(t.last_seen_at).getTime() <= day) {
recentlyActive++;
}
}
let totalUsers = 0;
let signups7d = 0;
let signups30d = 0;
const perPage = 1000;
for (let page = 1; page <= 50; page++) {
const { data, error } = await withAdminRetry(() =>
admin.auth.admin.listUsers({ page, perPage }),
);
if (error) break;
const users = data.users;
if (users.length === 0) break;
totalUsers += users.length;
for (const u of users) {
const created = new Date(u.created_at).getTime();
if (now - created <= 7 * day) signups7d++;
if (now - created <= 30 * day) signups30d++;
}
if (users.length < perPage) break;
}
return {
totalUsers,
totalTunnels: tunnels.length,
activeTunnels,
inactiveTunnels,
overQuota,
bytesUsedTotal,
quotaTotal,
signups7d,
signups30d,
recentlyActive,
};
}
-17
View File
@@ -1,17 +0,0 @@
import { getSupabaseAdmin } from '@/lib/supabase/admin';
import { RESERVED_SUBDOMAINS } from '@/lib/validation';
/**
* Returns true if the subdomain is reserved in EITHER the hardcoded fallback
* set or the reserved_subdomains DB table.
*/
export async function isSubdomainReserved(subdomain: string): Promise<boolean> {
if (RESERVED_SUBDOMAINS.has(subdomain)) return true;
const admin = getSupabaseAdmin();
const { data } = await admin
.from('reserved_subdomains')
.select('name')
.eq('name', subdomain)
.maybeSingle<{ name: string }>();
return !!data;
}
-13
View File
@@ -1,13 +0,0 @@
import { NextResponse } from 'next/server';
/**
* Wrapper around NextResponse.json that marks the response uncacheable. All
* admin API responses must never be stored by browsers, proxies, or Next's
* own caches, since they reflect privileged, frequently-changing state.
*/
export function jsonNoStore(body: unknown, init?: ResponseInit): NextResponse {
const res = NextResponse.json(body, init);
res.headers.set('Cache-Control', 'no-store');
res.headers.set('Pragma', 'no-cache');
return res;
}
-138
View File
@@ -1,138 +0,0 @@
/**
* Retry helper for GoTrue admin reads (`auth.admin.listUsers` /
* `auth.admin.getUserById`).
*
* Under a rapid burst of admin mutations (bulk ban/unban/delete) immediately
* followed by the auto list-refresh, GoTrue's admin endpoints intermittently
* return an EMPTY or TRUNCATED HTTP body. supabase-js then fails to parse the
* response and throws `Unexpected end of JSON input` (or returns an
* empty/transient `error`). The underlying request actually succeeded a moment
* later, so a small bounded retry turns these flaky failures into reliable
* reads without changing happy-path behaviour.
*
* IMPORTANT: only TRANSIENT failures are retried. Legitimate not-found (404) and
* validation (4xx) errors are returned immediately so genuine failures still
* surface as proper 4xx/5xx responses upstream.
*/
// Up to 5 attempts total (1 initial + 4 retries). Delays are applied BEFORE
// attempts 2..5 respectively and are jittered (see `jitter`), so worst-case
// added latency is ~80+150+300+600 ≈ 1.13s plus jitter — kept under ~1.5s to
// keep the admin surface snappy while reliably riding out the empty-body /
// poisoned-keep-alive window that Node 24's bundled undici amplifies.
const MAX_ATTEMPTS = 5;
const RETRY_DELAYS_MS = [80, 150, 300, 600];
/** Apply ±30% random jitter so concurrent retries don't synchronise. */
function jitter(ms: number): number {
if (ms <= 0) return 0;
const delta = ms * 0.3;
return Math.round(ms - delta + Math.random() * 2 * delta);
}
/** Loose shape that both `AuthError` and `PostgrestError` satisfy. */
type MaybeError =
| { message?: string | null; status?: number | null; code?: string | number | null }
| null
| undefined;
export type RetryOptions = {
/** Total attempts including the first. Defaults to {@link MAX_ATTEMPTS}. */
attempts?: number;
/** Backoff delays (ms) applied before each retry. Defaults to {@link RETRY_DELAYS_MS}. */
delaysMs?: number[];
};
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => setTimeout(resolve, ms));
}
/** True when a thrown/parse error looks like an empty/truncated-body failure. */
function isTransientMessage(message: string): boolean {
const m = message.toLowerCase();
return (
m.includes('unexpected end of json input') ||
m.includes('unexpected end of input') ||
m.includes('unexpected end of data') ||
// Some runtimes phrase the empty-body parse failure differently.
(m.includes('json') && m.includes('parse') && m.includes('unexpected')) ||
// Low-level network blips that also warrant a quick retry.
m.includes('fetch failed') ||
m.includes('network') ||
m.includes('econnreset') ||
m.includes('socket hang up') ||
m.includes('terminated')
);
}
/** True when a thrown value is a transient, retryable failure. */
function isTransientThrow(err: unknown): boolean {
if (err instanceof Error) return isTransientMessage(err.message);
if (typeof err === 'string') return isTransientMessage(err);
return false;
}
/**
* True when a returned supabase-js `error` is transient. We retry on 5xx and on
* empty/parse-style messages, but NEVER on legitimate not-found/validation
* (e.g. a 404 with a real "User not found" message).
*/
function isTransientError(error: MaybeError): boolean {
if (!error) return false;
const status = typeof error.status === 'number' ? error.status : undefined;
// Explicit client/validation/not-found statuses are genuine — do not retry.
if (status !== undefined && status >= 400 && status < 500) return false;
if (status !== undefined && status >= 500) return true;
const message = typeof error.message === 'string' ? error.message : '';
if (message && isTransientMessage(message)) return true;
// An error object with neither a usable status nor message is treated as an
// opaque/empty transient failure worth one more try.
if (!status && !message) return true;
return false;
}
/**
* Await an async supabase-js admin call that returns `{ data, error }` (or that
* may throw), retrying only on transient empty-body / network failures.
*
* Returns the successful (or genuinely-failed, non-transient) result. After
* exhausting all attempts it returns the last `{ data, error }` result or
* re-throws the last thrown error, so persistent failures still surface.
*/
export async function withAdminRetry<R extends { error: MaybeError }>(
fn: () => Promise<R>,
opts?: RetryOptions,
): Promise<R> {
const attempts = opts?.attempts ?? MAX_ATTEMPTS;
const delays = opts?.delaysMs ?? RETRY_DELAYS_MS;
let lastResult: R | undefined;
let lastThrown: unknown;
let threw = false;
for (let attempt = 1; attempt <= attempts; attempt++) {
try {
const result = await fn();
threw = false;
lastResult = result;
// Success, or a genuine (non-transient) error — return as-is.
if (!isTransientError(result.error)) return result;
} catch (err) {
// A non-transient throw is a real failure: surface it immediately.
if (!isTransientThrow(err)) throw err;
threw = true;
lastThrown = err;
}
if (attempt < attempts) {
const base = delays[attempt - 1] ?? delays[delays.length - 1] ?? 0;
const delay = jitter(base);
if (delay > 0) await sleep(delay);
}
}
// Exhausted all attempts on transient failures: surface the last outcome so
// the caller still sees a real error rather than a masked success.
if (threw) throw lastThrown;
return lastResult as R;
}
-45
View File
@@ -1,45 +0,0 @@
/**
* Tiny helpers to parse + whitelist server-side sort parameters for the admin
* list/export endpoints. Anything not on the per-endpoint allow-list falls
* back to that endpoint's default column, so untrusted `sort`/`order` query
* params can never reach PostgREST verbatim.
*/
export type SortOrder = 'asc' | 'desc';
export function parseOrder(
v: string | null | undefined,
fallback: SortOrder = 'desc',
): SortOrder {
return v === 'asc' || v === 'desc' ? v : fallback;
}
export function parseSort<T extends string>(
v: string | null | undefined,
allowed: readonly T[],
fallback: T,
): T {
return v && (allowed as readonly string[]).includes(v) ? (v as T) : fallback;
}
export const USER_SORTS = [
'email',
'created_at',
'last_sign_in_at',
'role',
] as const;
export type UserSort = (typeof USER_SORTS)[number];
export const TUNNEL_SORTS = [
'subdomain',
'bytes_used',
'quota_bytes',
'is_active',
'created_at',
'last_seen_at',
'usage_pct',
] as const;
export type TunnelSort = (typeof TUNNEL_SORTS)[number];
export const AUDIT_SORTS = ['created_at', 'action', 'actor_email'] as const;
export type AuditSort = (typeof AUDIT_SORTS)[number];
-44
View File
@@ -1,44 +0,0 @@
/**
* Small manual validators for admin API inputs (zod is intentionally not a
* dependency). Each returns a discriminated result.
*/
const UUID_RE =
/^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
export function isUuid(v: unknown): v is string {
return typeof v === 'string' && UUID_RE.test(v);
}
export function parseBoolean(v: unknown): boolean | null {
if (typeof v === 'boolean') return v;
return null;
}
export function parsePositiveInt(
v: unknown,
max: number,
): { ok: true; value: number } | { ok: false; error: string } {
if (typeof v !== 'number' || !Number.isFinite(v) || !Number.isInteger(v)) {
return { ok: false, error: 'must be an integer' };
}
if (v <= 0) return { ok: false, error: 'must be positive' };
if (v > max) return { ok: false, error: `must be <= ${max}` };
return { ok: true, value: v };
}
export function parsePageParam(v: string | null, fallback = 1): number {
const n = v ? Number(v) : NaN;
if (!Number.isFinite(n) || n < 1) return fallback;
return Math.floor(n);
}
export function parsePerPageParam(
v: string | null,
fallback = 25,
max = 100,
): number {
const n = v ? Number(v) : NaN;
if (!Number.isFinite(n) || n < 1) return fallback;
return Math.min(max, Math.floor(n));
}
-49
View File
@@ -1,49 +0,0 @@
import { redirect } from 'next/navigation';
import type { NextResponse } from 'next/server';
import type { User } from '@supabase/supabase-js';
import { createSupabaseServerClient } from '@/lib/supabase/server';
import { jsonNoStore } from '@/lib/admin/response';
export function isAdmin(user: User | null | undefined): boolean {
return user?.app_metadata?.role === 'admin';
}
/**
* For server components / pages. Redirects to /login if unauthenticated,
* or /dashboard if authenticated but not an admin (does not leak /admin).
*/
export async function requireAdmin(): Promise<User> {
const supabase = createSupabaseServerClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) redirect('/login');
if (!isAdmin(user)) redirect('/dashboard');
return user;
}
/**
* For route handlers. Returns the authenticated admin user, or a NextResponse
* (401 when no session, 403 when not admin) that the caller must return.
*/
export async function requireAdminApi(): Promise<
{ ok: true; user: User } | { ok: false; response: NextResponse }
> {
const supabase = createSupabaseServerClient();
const {
data: { user },
} = await supabase.auth.getUser();
if (!user) {
return {
ok: false,
response: jsonNoStore({ error: 'unauthorized' }, { status: 401 }),
};
}
if (!isAdmin(user)) {
return {
ok: false,
response: jsonNoStore({ error: 'forbidden' }, { status: 403 }),
};
}
return { ok: true, user };
}
-33
View File
@@ -1,33 +0,0 @@
import type { User } from '@supabase/supabase-js';
import { getSupabaseAdmin } from '@/lib/supabase/admin';
export type AuditEntry = {
action: string;
target_type?: string | null;
target_id?: string | null;
details?: Record<string, unknown>;
};
/**
* Best-effort audit logging. Never throws — a failed audit write must not
* break the underlying admin operation.
*/
export async function logAdminAction(
actor: User,
entry: AuditEntry,
): Promise<void> {
try {
const admin = getSupabaseAdmin();
await admin.from('admin_audit_log').insert({
actor_id: actor.id,
actor_email: actor.email ?? null,
action: entry.action,
target_type: entry.target_type ?? null,
target_id: entry.target_id ?? null,
details: entry.details ?? {},
});
} catch (e) {
// Swallow — audit failures should not surface to the client.
console.error('[audit] failed to write audit log', e);
}
}
-44
View File
@@ -1,44 +0,0 @@
export function formatBytes(n: number): string {
const num = Number(n) || 0;
if (num < 1024) return `${num} B`;
const units = ['KiB', 'MiB', 'GiB', 'TiB', 'PiB'];
let v = num / 1024;
let i = 0;
while (v >= 1024 && i < units.length - 1) {
v /= 1024;
i++;
}
return `${v.toFixed(2)} ${units[i]}`;
}
function pad(n: number): string {
return n < 10 ? `0${n}` : `${n}`;
}
// Deterministic, timezone-independent date+time formatter.
// Uses UTC getters so the server (UTC) and client (local TZ) render
// byte-identical text, avoiding React hydration mismatches (error #425).
// Output format: "YYYY-MM-DD HH:MM UTC".
export function formatDateTime(s: string | null | undefined): string {
if (!s) return '—';
const d = new Date(s);
if (Number.isNaN(d.getTime())) return '—';
const date = `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(
d.getUTCDate(),
)}`;
const time = `${pad(d.getUTCHours())}:${pad(d.getUTCMinutes())}`;
return `${date} ${time} UTC`;
}
// Date-only deterministic UTC formatter. Output format: "YYYY-MM-DD UTC".
export function formatDateOnly(s: string | null | undefined): string {
if (!s) return '—';
const d = new Date(s);
if (Number.isNaN(d.getTime())) return '—';
return `${d.getUTCFullYear()}-${pad(d.getUTCMonth() + 1)}-${pad(
d.getUTCDate(),
)} UTC`;
}
// Backwards-compatible alias: existing call sites render date+time.
export const formatDate = formatDateTime;
-171
View File
@@ -1,171 +0,0 @@
import net from 'node:net';
/**
* Minimal, dependency-free Redis client implementing just enough of the RESP
* protocol to issue a single SET command. Used for the best-effort live
* kill-switch (tunnel:active:<subdomain>). Every failure mode is swallowed —
* Redis being unavailable must NEVER break an admin operation.
*
* REDIS_URL format: redis://[:password@]host:port[/db]
*/
type RedisTarget = {
host: string;
port: number;
password?: string;
db?: number;
};
function parseRedisUrl(raw: string): RedisTarget | null {
try {
const u = new URL(raw);
if (u.protocol !== 'redis:' && u.protocol !== 'rediss:') return null;
const host = u.hostname || '127.0.0.1';
const port = u.port ? Number(u.port) : 6379;
const password = u.password ? decodeURIComponent(u.password) : undefined;
const dbStr = u.pathname.replace(/^\//, '');
const db = dbStr ? Number(dbStr) : undefined;
if (!Number.isFinite(port)) return null;
return { host, port, password, db: Number.isFinite(db) ? db : undefined };
} catch {
return null;
}
}
function encodeCommand(args: string[]): string {
let out = `*${args.length}\r\n`;
for (const a of args) {
out += `$${Buffer.byteLength(a)}\r\n${a}\r\n`;
}
return out;
}
/**
* Best-effort execution of a single RESP command (preceded by optional
* AUTH/SELECT). Resolves true when the final reply is a non-error (`+...` or
* `:...`), false otherwise. Never rejects.
*/
function runCommand(args: string[]): Promise<boolean> {
const url = process.env.REDIS_URL;
if (!url) return Promise.resolve(false);
const target = parseRedisUrl(url);
if (!target) return Promise.resolve(false);
return new Promise<boolean>((resolve) => {
let settled = false;
const done = (result: boolean) => {
if (settled) return;
settled = true;
try {
socket.destroy();
} catch {
/* ignore */
}
resolve(result);
};
const commands: string[] = [];
if (target.password) commands.push(encodeCommand(['AUTH', target.password]));
if (target.db !== undefined && target.db > 0) {
commands.push(encodeCommand(['SELECT', String(target.db)]));
}
commands.push(encodeCommand(args));
const socket = net.createConnection(
{ host: target.host, port: target.port },
() => {
try {
socket.write(commands.join(''));
} catch {
done(false);
}
},
);
socket.setTimeout(1500, () => done(false));
socket.on('error', () => done(false));
let buf = '';
const expectedReplies = commands.length;
socket.on('data', (chunk) => {
buf += chunk.toString('utf8');
// Count complete simple replies (lines terminated by \r\n).
const lines = buf.split('\r\n').filter((l) => l.length > 0);
if (lines.length >= expectedReplies) {
const last = lines[lines.length - 1];
// +OK / +... (simple string) or :N (integer, e.g. DEL count) = success.
done(last.startsWith('+') || last.startsWith(':'));
}
});
});
}
/**
* Best-effort SET. When `ttlSeconds` is a positive integer the command is
* issued as `SET key val EX <ttl>`, otherwise a plain `SET key val`. Resolves
* true on apparent success, false otherwise. Never rejects. Backward
* compatible: existing two-arg callers are unaffected.
*/
export function redisSet(
key: string,
value: string,
ttlSeconds?: number,
): Promise<boolean> {
const args = ['SET', key, value];
if (
typeof ttlSeconds === 'number' &&
Number.isFinite(ttlSeconds) &&
ttlSeconds > 0
) {
args.push('EX', String(Math.floor(ttlSeconds)));
}
return runCommand(args);
}
/**
* Best-effort DEL. Resolves true when Redis acknowledges the command (reply is
* an integer, even 0), false otherwise. Never rejects.
*/
export function redisDel(key: string): Promise<boolean> {
return runCommand(['DEL', key]);
}
/**
* TTL (seconds) written alongside the tunnel:active flag. Must match the edge
* `tunnel-active` forward_auth gate's TTL_SECONDS (currently 30) so the flag
* naturally expires in lock-step with the gate's cache. Overridable via
* TUNNEL_ACTIVE_TTL; defaults to 30.
*/
function tunnelActiveTtl(): number {
const raw = process.env.TUNNEL_ACTIVE_TTL;
if (raw) {
const n = Number(raw);
if (Number.isFinite(n) && n > 0) return Math.floor(n);
}
return 30;
}
/**
* Live kill-switch primitive. Writes the SAME key the edge gate reads:
* SET tunnel:active:<subdomain> <"1"|"0"> EX <TTL>
* "1" = ALLOW, "0" = DENY. A currently-connected tunnel is dropped within ~1s
* when "0" is written; "1" re-allows it. No-op (returns false) when REDIS_URL
* is unset — behavior then falls back to the gate's Postgres `is_active` read,
* exactly as before this wiring existed. Never throws.
*/
export async function setTunnelActive(
subdomain: string,
active: boolean,
): Promise<boolean> {
if (!process.env.REDIS_URL) return false;
if (!subdomain) return false;
try {
return await redisSet(
`tunnel:active:${subdomain}`,
active ? '1' : '0',
tunnelActiveTtl(),
);
} catch {
return false;
}
}
-41
View File
@@ -1,36 +1,7 @@
import { createClient, SupabaseClient } from '@supabase/supabase-js';
import { Agent } from 'undici';
let _admin: SupabaseClient | null = null;
/**
* Dedicated undici dispatcher for all admin-client traffic (GoTrue + PostgREST).
*
* ROOT CAUSE this addresses: GoTrue/undici intermittently returns an empty or
* truncated HTTP body when a pooled keep-alive connection is REUSED right after
* a write (bulk ban/role/delete) and then immediately read back (the auto list
* refresh). supabase-js then throws `Unexpected end of JSON input` and the
* route 500s. Node 24's bundled undici reuses connections more aggressively,
* amplifying the race.
*
* `pipelining: 0` disables request pipelining on a connection, and the bounded
* keep-alive timeouts keep idle sockets from lingering long enough to be reused
* in a half-closed state. When a request DOES still hit a poisoned socket,
* undici destroys that socket on error, so the `withAdminRetry` wrapper at the
* call sites lands on a FRESH connection rather than the same dead one. The two
* layers together eliminate the empty-body 500s.
*
* NOTE: `setGlobalDispatcher` from the npm `undici` package does NOT affect
* Node's built-in global `fetch` (it bundles its own undici), so we attach this
* dispatcher explicitly via the `dispatcher` init option, which built-in fetch
* does honour.
*/
const adminDispatcher = new Agent({
pipelining: 0,
keepAliveTimeout: 10_000,
keepAliveMaxTimeout: 10_000,
});
export function getSupabaseAdmin(): SupabaseClient {
if (_admin) return _admin;
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
@@ -40,18 +11,6 @@ export function getSupabaseAdmin(): SupabaseClient {
}
_admin = createClient(url, key, {
auth: { autoRefreshToken: false, persistSession: false },
global: {
// Force every request the admin client makes (GoTrue listUsers and
// PostgREST reads alike) to bypass Next's fetch Data Cache, so the admin
// surface always reflects current state regardless of page config, and
// route it through the dedicated keep-alive-tamed dispatcher above.
fetch: (input: RequestInfo | URL, init?: RequestInit) =>
fetch(input, {
...init,
cache: 'no-store',
dispatcher: adminDispatcher,
} as RequestInit),
},
});
return _admin;
}
+2 -48
View File
@@ -23,56 +23,10 @@ export async function middleware(request: NextRequest) {
},
);
const {
data: { user },
} = await supabase.auth.getUser();
// Defense-in-depth: guard the admin surface here in addition to the
// per-route requireAdmin()/requireAdminApi() checks.
const path = request.nextUrl.pathname;
if (path.startsWith('/admin') || path.startsWith('/api/admin')) {
// Carry any cookies Supabase rotated onto the working `response` over to a
// deny/redirect response, so a refreshed session/refresh token is always
// persisted — otherwise a fresh NextResponse would drop them and a
// concurrent request could spuriously 401. Also stamp `no-store` so these
// admin deny/redirect responses (which short-circuit before the route's
// own jsonNoStore runs) are never cached by intermediaries or the browser.
const withCookies = (res: NextResponse): NextResponse => {
response.cookies.getAll().forEach((cookie) => res.cookies.set(cookie));
res.headers.set('Cache-Control', 'no-store');
return res;
};
if (!user) {
if (path.startsWith('/api/admin')) {
return withCookies(
NextResponse.json({ error: 'unauthorized' }, { status: 401 }),
);
}
const url = request.nextUrl.clone();
url.pathname = '/login';
url.search = '';
return withCookies(NextResponse.redirect(url));
}
if (user.app_metadata?.role !== 'admin') {
if (path.startsWith('/api/admin')) {
return withCookies(
NextResponse.json({ error: 'forbidden' }, { status: 403 }),
);
}
const url = request.nextUrl.clone();
url.pathname = '/dashboard';
url.search = '';
return withCookies(NextResponse.redirect(url));
}
}
await supabase.auth.getUser();
return response;
}
export const config = {
matcher: [
'/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)',
'/admin/:path*',
'/api/admin/:path*',
],
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)'],
};
-665
View File
@@ -1,665 +0,0 @@
{
"name": "linumiq-web",
"version": "1.0.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "linumiq-web",
"version": "1.0.0",
"dependencies": {
"@supabase/ssr": "0.5.2",
"@supabase/supabase-js": "2.45.4",
"next": "14.2.15",
"react": "18.3.1",
"react-dom": "18.3.1",
"undici": "6.21.1"
},
"devDependencies": {
"@types/node": "20.16.10",
"@types/react": "18.3.11",
"@types/react-dom": "18.3.0",
"typescript": "5.6.2"
},
"engines": {
"node": ">=20"
}
},
"node_modules/@next/env": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/env/-/env-14.2.15.tgz",
"integrity": "sha512-S1qaj25Wru2dUpcIZMjxeMVSwkt8BK4dmWHHiBuRstcIyOsMapqT4A4jSB6onvqeygkSSmOkyny9VVx8JIGamQ==",
"license": "MIT"
},
"node_modules/@next/swc-darwin-arm64": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-arm64/-/swc-darwin-arm64-14.2.15.tgz",
"integrity": "sha512-Rvh7KU9hOUBnZ9TJ28n2Oa7dD9cvDBKua9IKx7cfQQ0GoYUwg9ig31O2oMwH3wm+pE3IkAQ67ZobPfEgurPZIA==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-darwin-x64": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-darwin-x64/-/swc-darwin-x64-14.2.15.tgz",
"integrity": "sha512-5TGyjFcf8ampZP3e+FyCax5zFVHi+Oe7sZyaKOngsqyaNEpOgkKB3sqmymkZfowy3ufGA/tUgDPPxpQx931lHg==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"darwin"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-gnu": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-gnu/-/swc-linux-arm64-gnu-14.2.15.tgz",
"integrity": "sha512-3Bwv4oc08ONiQ3FiOLKT72Q+ndEMyLNsc/D3qnLMbtUYTQAmkx9E/JRu0DBpHxNddBmNT5hxz1mYBphJ3mfrrw==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-arm64-musl": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-linux-arm64-musl/-/swc-linux-arm64-musl-14.2.15.tgz",
"integrity": "sha512-k5xf/tg1FBv/M4CMd8S+JL3uV9BnnRmoe7F+GWC3DxkTCD9aewFRH1s5rJ1zkzDa+Do4zyN8qD0N8c84Hu96FQ==",
"cpu": [
"arm64"
],
"license": "MIT",
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-gnu": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-gnu/-/swc-linux-x64-gnu-14.2.15.tgz",
"integrity": "sha512-kE6q38hbrRbKEkkVn62reLXhThLRh6/TvgSP56GkFNhU22TbIrQDEMrO7j0IcQHcew2wfykq8lZyHFabz0oBrA==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-linux-x64-musl": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-linux-x64-musl/-/swc-linux-x64-musl-14.2.15.tgz",
"integrity": "sha512-PZ5YE9ouy/IdO7QVJeIcyLn/Rc4ml9M2G4y3kCM9MNf1YKvFY4heg3pVa/jQbMro+tP6yc4G2o9LjAz1zxD7tQ==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"linux"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-arm64-msvc": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-win32-arm64-msvc/-/swc-win32-arm64-msvc-14.2.15.tgz",
"integrity": "sha512-2raR16703kBvYEQD9HNLyb0/394yfqzmIeyp2nDzcPV4yPjqNUG3ohX6jX00WryXz6s1FXpVhsCo3i+g4RUX+g==",
"cpu": [
"arm64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-ia32-msvc": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-win32-ia32-msvc/-/swc-win32-ia32-msvc-14.2.15.tgz",
"integrity": "sha512-fyTE8cklgkyR1p03kJa5zXEaZ9El+kDNM5A+66+8evQS5e/6v0Gk28LqA0Jet8gKSOyP+OTm/tJHzMlGdQerdQ==",
"cpu": [
"ia32"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@next/swc-win32-x64-msvc": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/@next/swc-win32-x64-msvc/-/swc-win32-x64-msvc-14.2.15.tgz",
"integrity": "sha512-SzqGbsLsP9OwKNUG9nekShTwhj6JSB9ZLMWQ8g1gG6hdE5gQLncbnbymrwy2yVmH9nikSLYRYxYMFu78Ggp7/g==",
"cpu": [
"x64"
],
"optional": true,
"os": [
"win32"
],
"engines": {
"node": ">= 10"
}
},
"node_modules/@supabase/auth-js": {
"version": "2.65.0",
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.65.0.tgz",
"integrity": "sha512-+wboHfZufAE2Y612OsKeVP4rVOeGZzzMLD/Ac3HrTQkkY4qXNjI6Af9gtmxwccE5nFvTiF114FEbIQ1hRq5uUw==",
"license": "MIT",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/functions-js": {
"version": "2.4.1",
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.4.1.tgz",
"integrity": "sha512-8sZ2ibwHlf+WkHDUZJUXqqmPvWQ3UHN0W30behOJngVh/qHHekhJLCFbh0AjkE9/FqqXtf9eoVvmYgfCLk5tNA==",
"license": "MIT",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/node-fetch": {
"version": "2.6.15",
"resolved": "https://registry.npmjs.org/@supabase/node-fetch/-/node-fetch-2.6.15.tgz",
"integrity": "sha512-1ibVeYUacxWYi9i0cf5efil6adJ9WRyZBLivgjs+AUpewx1F3xPi7gLgaASI2SmIQxPoCEjAsLAzKPgMJVgOUQ==",
"license": "MIT",
"dependencies": {
"whatwg-url": "^5.0.0"
},
"engines": {
"node": "4.x || >=6.0.0"
}
},
"node_modules/@supabase/postgrest-js": {
"version": "1.16.1",
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-1.16.1.tgz",
"integrity": "sha512-EOSEZFm5pPuCPGCmLF1VOCS78DfkSz600PBuvBND/IZmMciJ1pmsS3ss6TkB6UkuvTybYiBh7gKOYyxoEO3USA==",
"license": "MIT",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/realtime-js": {
"version": "2.10.2",
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.10.2.tgz",
"integrity": "sha512-qyCQaNg90HmJstsvr2aJNxK2zgoKh9ZZA8oqb7UT2LCh3mj9zpa3Iwu167AuyNxsxrUE8eEJ2yH6wLCij4EApA==",
"license": "MIT",
"dependencies": {
"@supabase/node-fetch": "^2.6.14",
"@types/phoenix": "^1.5.4",
"@types/ws": "^8.5.10",
"ws": "^8.14.2"
}
},
"node_modules/@supabase/ssr": {
"version": "0.5.2",
"resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.5.2.tgz",
"integrity": "sha512-n3plRhr2Bs8Xun1o4S3k1CDv17iH5QY9YcoEvXX3bxV1/5XSasA0mNXYycFmADIdtdE6BG9MRjP5CGIs8qxC8A==",
"license": "MIT",
"dependencies": {
"@types/cookie": "^0.6.0",
"cookie": "^0.7.0"
},
"peerDependencies": {
"@supabase/supabase-js": "^2.43.4"
}
},
"node_modules/@supabase/storage-js": {
"version": "2.7.0",
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.7.0.tgz",
"integrity": "sha512-iZenEdO6Mx9iTR6T7wC7sk6KKsoDPLq8rdu5VRy7+JiT1i8fnqfcOr6mfF2Eaqky9VQzhP8zZKQYjzozB65Rig==",
"license": "MIT",
"dependencies": {
"@supabase/node-fetch": "^2.6.14"
}
},
"node_modules/@supabase/supabase-js": {
"version": "2.45.4",
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.45.4.tgz",
"integrity": "sha512-E5p8/zOLaQ3a462MZnmnz03CrduA5ySH9hZyL03Y+QZLIOO4/Gs8Rdy4ZCKDHsN7x0xdanVEWWFN3pJFQr9/hg==",
"license": "MIT",
"dependencies": {
"@supabase/auth-js": "2.65.0",
"@supabase/functions-js": "2.4.1",
"@supabase/node-fetch": "2.6.15",
"@supabase/postgrest-js": "1.16.1",
"@supabase/realtime-js": "2.10.2",
"@supabase/storage-js": "2.7.0"
}
},
"node_modules/@swc/counter": {
"version": "0.1.3",
"resolved": "https://registry.npmjs.org/@swc/counter/-/counter-0.1.3.tgz",
"integrity": "sha512-e2BR4lsJkkRlKZ/qCHPw9ZaSxc0MVUd7gtbtaB7aMvHeJVYe8sOB8DBZkP2DtISHGSku9sCK6T6cnY0CtXrOCQ==",
"license": "Apache-2.0"
},
"node_modules/@swc/helpers": {
"version": "0.5.5",
"resolved": "https://registry.npmjs.org/@swc/helpers/-/helpers-0.5.5.tgz",
"integrity": "sha512-KGYxvIOXcceOAbEk4bi/dVLEK9z8sZ0uBB3Il5b1rhfClSpcX0yfRO0KmTkqR2cnQDymwLB+25ZyMzICg/cm/A==",
"license": "Apache-2.0",
"dependencies": {
"@swc/counter": "^0.1.3",
"tslib": "^2.4.0"
}
},
"node_modules/@types/cookie": {
"version": "0.6.0",
"resolved": "https://registry.npmjs.org/@types/cookie/-/cookie-0.6.0.tgz",
"integrity": "sha512-4Kh9a6B2bQciAhf7FSuMRRkUWecJgJu9nPnx3yzpsfXX/c50REIqpHY4C82bXP90qrLtXtkDxTZosYO3UpOwlA==",
"license": "MIT"
},
"node_modules/@types/node": {
"version": "20.16.10",
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.16.10.tgz",
"integrity": "sha512-vQUKgWTjEIRFCvK6CyriPH3MZYiYlNy0fKiEYHWbcoWLEgs4opurGGKlebrTLqdSMIbXImH6XExNiIyNUv3WpA==",
"license": "MIT",
"dependencies": {
"undici-types": "~6.19.2"
}
},
"node_modules/@types/phoenix": {
"version": "1.6.7",
"resolved": "https://registry.npmjs.org/@types/phoenix/-/phoenix-1.6.7.tgz",
"integrity": "sha512-oN9ive//QSBkf19rfDv45M7eZPi0eEXylht2OLEXicu5b4KoQ1OzXIw+xDSGWxSxe1JmepRR/ZH283vsu518/Q==",
"license": "MIT"
},
"node_modules/@types/prop-types": {
"version": "15.7.15",
"resolved": "https://registry.npmjs.org/@types/prop-types/-/prop-types-15.7.15.tgz",
"integrity": "sha512-F6bEyamV9jKGAFBEmlQnesRPGOQqS2+Uwi0Em15xenOxHaf2hv6L8YCVn3rPdPJOiJfPiCnLIRyvwVaqMY3MIw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/react": {
"version": "18.3.11",
"resolved": "https://registry.npmjs.org/@types/react/-/react-18.3.11.tgz",
"integrity": "sha512-r6QZ069rFTjrEYgFdOck1gK7FLVsgJE7tTz0pQBczlBNUhBNk0MQH4UbnFSwjpQLMkLzgqvBBa+qGpLje16eTQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/prop-types": "*",
"csstype": "^3.0.2"
}
},
"node_modules/@types/react-dom": {
"version": "18.3.0",
"resolved": "https://registry.npmjs.org/@types/react-dom/-/react-dom-18.3.0.tgz",
"integrity": "sha512-EhwApuTmMBmXuFOikhQLIBUn6uFg81SwLMOAUgodJF14SOBOCMdU04gDoYi0WOJJHD144TL32z4yDqCW3dnkQg==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/react": "*"
}
},
"node_modules/@types/ws": {
"version": "8.18.1",
"resolved": "https://registry.npmjs.org/@types/ws/-/ws-8.18.1.tgz",
"integrity": "sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==",
"license": "MIT",
"dependencies": {
"@types/node": "*"
}
},
"node_modules/busboy": {
"version": "1.6.0",
"resolved": "https://registry.npmjs.org/busboy/-/busboy-1.6.0.tgz",
"integrity": "sha512-8SFQbg/0hQ9xy3UNTB0YEnsNBbWfhf7RtnzpL7TkBiTBRfrQ9Fxcnz7VJsleJpyp6rVLvXiuORqjlHi5q+PYuA==",
"dependencies": {
"streamsearch": "^1.1.0"
},
"engines": {
"node": ">=10.16.0"
}
},
"node_modules/caniuse-lite": {
"version": "1.0.30001793",
"resolved": "https://registry.npmjs.org/caniuse-lite/-/caniuse-lite-1.0.30001793.tgz",
"integrity": "sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/browserslist"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/caniuse-lite"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "CC-BY-4.0"
},
"node_modules/client-only": {
"version": "0.0.1",
"resolved": "https://registry.npmjs.org/client-only/-/client-only-0.0.1.tgz",
"integrity": "sha512-IV3Ou0jSMzZrd3pZ48nLkT9DA7Ag1pnPzaiQhpW7c3RbcqqzvzzVu+L8gfqMp/8IM2MQtSiqaCxrrcfu8I8rMA==",
"license": "MIT"
},
"node_modules/cookie": {
"version": "0.7.2",
"resolved": "https://registry.npmjs.org/cookie/-/cookie-0.7.2.tgz",
"integrity": "sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==",
"license": "MIT",
"engines": {
"node": ">= 0.6"
}
},
"node_modules/csstype": {
"version": "3.2.3",
"resolved": "https://registry.npmjs.org/csstype/-/csstype-3.2.3.tgz",
"integrity": "sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==",
"dev": true,
"license": "MIT"
},
"node_modules/graceful-fs": {
"version": "4.2.11",
"resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.11.tgz",
"integrity": "sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==",
"license": "ISC"
},
"node_modules/js-tokens": {
"version": "4.0.0",
"resolved": "https://registry.npmjs.org/js-tokens/-/js-tokens-4.0.0.tgz",
"integrity": "sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==",
"license": "MIT"
},
"node_modules/loose-envify": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/loose-envify/-/loose-envify-1.4.0.tgz",
"integrity": "sha512-lyuxPGr/Wfhrlem2CL/UcnUc1zcqKAImBDzukY7Y5F/yQiNdko6+fRLevlw1HgMySw7f611UIY408EtxRSoK3Q==",
"license": "MIT",
"dependencies": {
"js-tokens": "^3.0.0 || ^4.0.0"
},
"bin": {
"loose-envify": "cli.js"
}
},
"node_modules/nanoid": {
"version": "3.3.12",
"resolved": "https://registry.npmjs.org/nanoid/-/nanoid-3.3.12.tgz",
"integrity": "sha512-ZB9RH/39qpq5Vu6Y+NmUaFhQR6pp+M2Xt76XBnEwDaGcVAqhlvxrl3B2bKS5D3NH3QR76v3aSrKaF/Kiy7lEtQ==",
"funding": [
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"bin": {
"nanoid": "bin/nanoid.cjs"
},
"engines": {
"node": "^10 || ^12 || ^13.7 || ^14 || >=15.0.1"
}
},
"node_modules/next": {
"version": "14.2.15",
"resolved": "https://registry.npmjs.org/next/-/next-14.2.15.tgz",
"integrity": "sha512-h9ctmOokpoDphRvMGnwOJAedT6zKhwqyZML9mDtspgf4Rh3Pn7UTYKqePNoDvhsWBAO5GoPNYshnAUGIazVGmw==",
"deprecated": "This version has a security vulnerability. Please upgrade to a patched version. See https://nextjs.org/blog/security-update-2025-12-11 for more details.",
"license": "MIT",
"dependencies": {
"@next/env": "14.2.15",
"@swc/helpers": "0.5.5",
"busboy": "1.6.0",
"caniuse-lite": "^1.0.30001579",
"graceful-fs": "^4.2.11",
"postcss": "8.4.31",
"styled-jsx": "5.1.1"
},
"bin": {
"next": "dist/bin/next"
},
"engines": {
"node": ">=18.17.0"
},
"optionalDependencies": {
"@next/swc-darwin-arm64": "14.2.15",
"@next/swc-darwin-x64": "14.2.15",
"@next/swc-linux-arm64-gnu": "14.2.15",
"@next/swc-linux-arm64-musl": "14.2.15",
"@next/swc-linux-x64-gnu": "14.2.15",
"@next/swc-linux-x64-musl": "14.2.15",
"@next/swc-win32-arm64-msvc": "14.2.15",
"@next/swc-win32-ia32-msvc": "14.2.15",
"@next/swc-win32-x64-msvc": "14.2.15"
},
"peerDependencies": {
"@opentelemetry/api": "^1.1.0",
"@playwright/test": "^1.41.2",
"react": "^18.2.0",
"react-dom": "^18.2.0",
"sass": "^1.3.0"
},
"peerDependenciesMeta": {
"@opentelemetry/api": {
"optional": true
},
"@playwright/test": {
"optional": true
},
"sass": {
"optional": true
}
}
},
"node_modules/picocolors": {
"version": "1.1.1",
"resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz",
"integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==",
"license": "ISC"
},
"node_modules/postcss": {
"version": "8.4.31",
"resolved": "https://registry.npmjs.org/postcss/-/postcss-8.4.31.tgz",
"integrity": "sha512-PS08Iboia9mts/2ygV3eLpY5ghnUcfLV/EXTOW1E2qYxJKGGBUtNjN76FYHnMs36RmARn41bC0AZmn+rR0OVpQ==",
"funding": [
{
"type": "opencollective",
"url": "https://opencollective.com/postcss/"
},
{
"type": "tidelift",
"url": "https://tidelift.com/funding/github/npm/postcss"
},
{
"type": "github",
"url": "https://github.com/sponsors/ai"
}
],
"license": "MIT",
"dependencies": {
"nanoid": "^3.3.6",
"picocolors": "^1.0.0",
"source-map-js": "^1.0.2"
},
"engines": {
"node": "^10 || ^12 || >=14"
}
},
"node_modules/react": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react/-/react-18.3.1.tgz",
"integrity": "sha512-wS+hAgJShR0KhEvPJArfuPVN1+Hz1t0Y6n5jLrGQbkb4urgPE/0Rve+1kMB1v/oWgHgm4WIcV+i7F2pTVj+2iQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
},
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/react-dom": {
"version": "18.3.1",
"resolved": "https://registry.npmjs.org/react-dom/-/react-dom-18.3.1.tgz",
"integrity": "sha512-5m4nQKp+rZRb09LNH59GM4BxTh9251/ylbKIbpe7TpGxfJ+9kv6BLkLBXIjjspbgbnIBNqlI23tRnTWT0snUIw==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0",
"scheduler": "^0.23.2"
},
"peerDependencies": {
"react": "^18.3.1"
}
},
"node_modules/scheduler": {
"version": "0.23.2",
"resolved": "https://registry.npmjs.org/scheduler/-/scheduler-0.23.2.tgz",
"integrity": "sha512-UOShsPwz7NrMUqhR6t0hWjFduvOzbtv7toDH1/hIrfRNIDBnnBWd0CwJTGvTpngVlmwGCdP9/Zl/tVrDqcuYzQ==",
"license": "MIT",
"dependencies": {
"loose-envify": "^1.1.0"
}
},
"node_modules/source-map-js": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.1.tgz",
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"license": "BSD-3-Clause",
"engines": {
"node": ">=0.10.0"
}
},
"node_modules/streamsearch": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/streamsearch/-/streamsearch-1.1.0.tgz",
"integrity": "sha512-Mcc5wHehp9aXz1ax6bZUyY5afg9u2rv5cqQI3mRrYkGC8rW2hM02jWuwjtL++LS5qinSyhj2QfLyNsuc+VsExg==",
"engines": {
"node": ">=10.0.0"
}
},
"node_modules/styled-jsx": {
"version": "5.1.1",
"resolved": "https://registry.npmjs.org/styled-jsx/-/styled-jsx-5.1.1.tgz",
"integrity": "sha512-pW7uC1l4mBZ8ugbiZrcIsiIvVx1UmTfw7UkC3Um2tmfUq9Bhk8IiyEIPl6F8agHgjzku6j0xQEZbfA5uSgSaCw==",
"license": "MIT",
"dependencies": {
"client-only": "0.0.1"
},
"engines": {
"node": ">= 12.0.0"
},
"peerDependencies": {
"react": ">= 16.8.0 || 17.x.x || ^18.0.0-0"
},
"peerDependenciesMeta": {
"@babel/core": {
"optional": true
},
"babel-plugin-macros": {
"optional": true
}
}
},
"node_modules/tr46": {
"version": "0.0.3",
"resolved": "https://registry.npmjs.org/tr46/-/tr46-0.0.3.tgz",
"integrity": "sha512-N3WMsuqV66lT30CrXNbEjx4GEwlow3v6rr4mCcv6prnfwhS01rkgyFdjPNBYd9br7LpXV1+Emh01fHnq2Gdgrw==",
"license": "MIT"
},
"node_modules/tslib": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/tslib/-/tslib-2.8.1.tgz",
"integrity": "sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==",
"license": "0BSD"
},
"node_modules/typescript": {
"version": "5.6.2",
"resolved": "https://registry.npmjs.org/typescript/-/typescript-5.6.2.tgz",
"integrity": "sha512-NW8ByodCSNCwZeghjN3o+JX5OFH0Ojg6sadjEKY4huZ52TqbJTJnDo5+Tw98lSy63NZvi4n+ez5m2u5d4PkZyw==",
"dev": true,
"license": "Apache-2.0",
"bin": {
"tsc": "bin/tsc",
"tsserver": "bin/tsserver"
},
"engines": {
"node": ">=14.17"
}
},
"node_modules/undici": {
"version": "6.21.1",
"resolved": "https://registry.npmjs.org/undici/-/undici-6.21.1.tgz",
"integrity": "sha512-q/1rj5D0/zayJB2FraXdaWxbhWiNKDvu8naDT2dl1yTlvJp4BLtOcp2a5BvgGNQpYYJzau7tf1WgKv3b+7mqpQ==",
"license": "MIT",
"engines": {
"node": ">=18.17"
}
},
"node_modules/undici-types": {
"version": "6.19.8",
"resolved": "https://registry.npmjs.org/undici-types/-/undici-types-6.19.8.tgz",
"integrity": "sha512-ve2KP6f/JnbPBFyobGHuerC9g1FYGn/F8n1LWTwNxCEzd6IfqTwUQcNXgEtmmQ6DlRrC1hrSrBnCZPokRrDHjw==",
"license": "MIT"
},
"node_modules/webidl-conversions": {
"version": "3.0.1",
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-3.0.1.tgz",
"integrity": "sha512-2JAn3z8AR6rjK8Sm8orRC0h/bcl/DqL7tRPdGZ4I1CjdF+EaMLmYxBHyXuKL849eucPFhvBoxMsflfOb8kxaeQ==",
"license": "BSD-2-Clause"
},
"node_modules/whatwg-url": {
"version": "5.0.0",
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-5.0.0.tgz",
"integrity": "sha512-saE57nupxk6v3HY35+jzBwYa0rKSy0XR8JSxZPwgLr7ys0IBzhGviA1/TUGJLmSVqs8pb9AnvICXEuOHLprYTw==",
"license": "MIT",
"dependencies": {
"tr46": "~0.0.3",
"webidl-conversions": "^3.0.0"
}
},
"node_modules/ws": {
"version": "8.21.0",
"resolved": "https://registry.npmjs.org/ws/-/ws-8.21.0.tgz",
"integrity": "sha512-Vsp28b7DRcimFQvrqu2Wek3z1iYxDCWqHYB8Qsnk/S4RfaCQzPGPyBNuVjJV3cd6UiKtUtp6sNM77gWvzcCH+g==",
"license": "MIT",
"engines": {
"node": ">=10.0.0"
},
"peerDependencies": {
"bufferutil": "^4.0.1",
"utf-8-validate": ">=5.0.2"
},
"peerDependenciesMeta": {
"bufferutil": {
"optional": true
},
"utf-8-validate": {
"optional": true
}
}
}
}
}
+1 -5
View File
@@ -2,9 +2,6 @@
"name": "linumiq-web",
"version": "1.0.0",
"private": true,
"engines": {
"node": ">=20"
},
"scripts": {
"dev": "next dev",
"build": "next build",
@@ -15,8 +12,7 @@
"@supabase/supabase-js": "2.45.4",
"next": "14.2.15",
"react": "18.3.1",
"react-dom": "18.3.1",
"undici": "6.21.1"
"react-dom": "18.3.1"
},
"devDependencies": {
"@types/node": "20.16.10",
-4
View File
@@ -1,4 +0,0 @@
<h2>Confirm your signup</h2>
<p>Welcome to LinumIQ Tunnels. Click the link below to confirm your email address and activate your account:</p>
<p><a href="{{ .SiteURL }}/auth/confirm?token_hash={{ .TokenHash }}&type=signup">Confirm your email</a></p>
<p>If you did not create this account, you can safely ignore this email.</p>
-48
View File
@@ -1,48 +0,0 @@
-- 0001_admin.sql
-- Additive, idempotent migration for the LinumIQ admin interface.
-- Safe to run multiple times.
-- 1. Admin audit log -------------------------------------------------------
create table if not exists public.admin_audit_log (
id bigint generated always as identity primary key,
actor_id uuid,
actor_email text,
action text not null,
target_type text,
target_id text,
details jsonb not null default '{}'::jsonb,
created_at timestamptz not null default now()
);
create index if not exists admin_audit_log_created_at_idx
on public.admin_audit_log (created_at desc);
-- 2. Reserved subdomains ---------------------------------------------------
create table if not exists public.reserved_subdomains (
name text primary key,
created_at timestamptz not null default now()
);
-- Seed with the current hardcoded reserved names (lib/validation.ts).
insert into public.reserved_subdomains (name) values
('app'),
('api'),
('www'),
('admin'),
('auth'),
('mail'),
('static')
on conflict (name) do nothing;
-- 3. Lock down with RLS, NO policies ---------------------------------------
-- RLS is enabled with NO policies so that the anon/authenticated roles cannot
-- read or write these tables at all. The application performs every admin
-- operation through the service-role client, which bypasses RLS. This keeps
-- the audit log and reserved list inaccessible to ordinary users.
alter table public.admin_audit_log enable row level security;
alter table public.reserved_subdomains enable row level security;
comment on table public.admin_audit_log is
'Admin action audit trail. RLS enabled with no policies: service-role only.';
comment on table public.reserved_subdomains is
'Reserved subdomain names (admin-managed). RLS enabled with no policies: service-role only.';
-53
View File
@@ -1,53 +0,0 @@
# Database migrations
Additive, idempotent SQL migrations for the LinumIQ web app. Each file is safe
to run multiple times.
## Applying a migration
Migrations are plain SQL applied with `psql` inside the running Supabase
Postgres container.
Default self-hosted Supabase credentials are user `postgres`, database
`postgres`. Adjust `DB_USER` / `DB_NAME` / `CONTAINER` to match your deployment.
### Production
```sh
CONTAINER=supabase-db
DB_USER=postgres
DB_NAME=postgres
docker exec -i "$CONTAINER" psql -U "$DB_USER" -d "$DB_NAME" < supabase/migrations/0001_admin.sql
```
### Development
```sh
docker exec -i supabase-dev-db psql -U postgres -d postgres < supabase/migrations/0001_admin.sql
```
## Migrations
| File | Description |
| ----------------- | --------------------------------------------------------------------------- |
| `0001_admin.sql` | `admin_audit_log` + `reserved_subdomains` tables (RLS on, service-role only) |
## Bootstrapping the first admin
The admin role lives in `auth.users.app_metadata.role`. To promote a user to
admin manually (only the service role / SQL can write `app_metadata`):
```sql
update auth.users
set raw_app_meta_data =
coalesce(raw_app_meta_data, '{}'::jsonb) || '{"role":"admin"}'::jsonb
where email = 'you@example.com';
```
Run it the same way:
```sh
docker exec -i supabase-db psql -U postgres -d postgres -c \
"update auth.users set raw_app_meta_data = coalesce(raw_app_meta_data,'{}'::jsonb) || '{\"role\":\"admin\"}'::jsonb where email = 'you@example.com';"
```