Compare commits
17 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f68fd22d2b | |||
| e14e909700 | |||
| 129e21529c | |||
| 37f1e7bbd5 | |||
| 8e8df7ae64 | |||
| cbd29445bb | |||
| 37f79ff1b1 | |||
| b0dba8ec0e | |||
| 17fe642168 | |||
| d317e8c758 | |||
| 1adb6e7b3f | |||
| dd0ff39890 | |||
| 535b2ef202 | |||
| 61bf6c013c | |||
| b6c4d94990 | |||
| fb4880a1d9 | |||
| aad01f1fc5 |
@@ -15,3 +15,9 @@ yarn-error.log*
|
|||||||
|
|
||||||
# Dev environment secrets (never commit)
|
# Dev environment secrets (never commit)
|
||||||
.env.production
|
.env.production
|
||||||
|
|
||||||
|
# Next.js build output
|
||||||
|
.next/
|
||||||
|
out/
|
||||||
|
*.tsbuildinfo
|
||||||
|
next-env.d.ts
|
||||||
|
|||||||
+3
-3
@@ -1,12 +1,12 @@
|
|||||||
# syntax=docker/dockerfile:1.7
|
# syntax=docker/dockerfile:1.7
|
||||||
|
|
||||||
FROM node:20.18.0-alpine AS deps
|
FROM node:24.16.0-alpine AS deps
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
RUN apk add --no-cache libc6-compat
|
RUN apk add --no-cache libc6-compat
|
||||||
COPY package.json ./
|
COPY package.json ./
|
||||||
RUN npm install --no-audit --no-fund --loglevel=error
|
RUN npm install --no-audit --no-fund --loglevel=error
|
||||||
|
|
||||||
FROM node:20.18.0-alpine AS builder
|
FROM node:24.16.0-alpine AS builder
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NEXT_TELEMETRY_DISABLED=1
|
ENV NEXT_TELEMETRY_DISABLED=1
|
||||||
COPY --from=deps /app/node_modules ./node_modules
|
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
|
NEXT_PUBLIC_APP_URL=$NEXT_PUBLIC_APP_URL
|
||||||
RUN npm run build
|
RUN npm run build
|
||||||
|
|
||||||
FROM node:20.18.0-alpine AS runner
|
FROM node:24.16.0-alpine AS runner
|
||||||
WORKDIR /app
|
WORKDIR /app
|
||||||
ENV NODE_ENV=production \
|
ENV NODE_ENV=production \
|
||||||
NEXT_TELEMETRY_DISABLED=1 \
|
NEXT_TELEMETRY_DISABLED=1 \
|
||||||
|
|||||||
@@ -0,0 +1,34 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,216 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,121 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,175 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,64 @@
|
|||||||
|
'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();
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
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} />;
|
||||||
|
}
|
||||||
@@ -0,0 +1,553 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,180 @@
|
|||||||
|
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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
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}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,391 @@
|
|||||||
|
'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>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,73 @@
|
|||||||
|
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' } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
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 1–63 chars, lowercase a–z, 0–9, 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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,101 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,46 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,51 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
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' } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,69 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,163 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
@@ -0,0 +1,85 @@
|
|||||||
|
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' } },
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
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 });
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
import { NextResponse } from 'next/server';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { jsonNoStore } from '@/lib/admin/response';
|
||||||
|
import { generateRecoveryCodes, hashRecoveryCode } from '@/lib/auth/recovery';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Generate a fresh set of recovery codes for the current user. Requires an
|
||||||
|
* aal2 session (the user just verified a factor). Any previously-issued codes
|
||||||
|
* are replaced. The plaintext codes are returned once and never persisted.
|
||||||
|
*/
|
||||||
|
export async function POST(): Promise<NextResponse> {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) return jsonNoStore({ error: 'unauthorized' }, { status: 401 });
|
||||||
|
|
||||||
|
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel();
|
||||||
|
if (aal?.currentLevel !== 'aal2') {
|
||||||
|
return jsonNoStore({ error: 'aal2_required' }, { status: 403 });
|
||||||
|
}
|
||||||
|
|
||||||
|
const codes = generateRecoveryCodes(10);
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
|
||||||
|
const del = await admin
|
||||||
|
.from('mfa_recovery_codes')
|
||||||
|
.delete()
|
||||||
|
.eq('user_id', user.id);
|
||||||
|
if (del.error) return jsonNoStore({ error: 'failed' }, { status: 500 });
|
||||||
|
|
||||||
|
const rows = codes.map((c) => ({
|
||||||
|
user_id: user.id,
|
||||||
|
code_hash: hashRecoveryCode(c),
|
||||||
|
}));
|
||||||
|
const ins = await admin.from('mfa_recovery_codes').insert(rows);
|
||||||
|
if (ins.error) return jsonNoStore({ error: 'failed' }, { status: 500 });
|
||||||
|
|
||||||
|
return jsonNoStore({ codes });
|
||||||
|
}
|
||||||
@@ -0,0 +1,66 @@
|
|||||||
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
|
import { jsonNoStore } from '@/lib/admin/response';
|
||||||
|
import { hashRecoveryCode } from '@/lib/auth/recovery';
|
||||||
|
|
||||||
|
export const runtime = 'nodejs';
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Redeem a single-use recovery code for account recovery.
|
||||||
|
*
|
||||||
|
* The user is authenticated (aal1) but locked out of step-up because they lost
|
||||||
|
* their authenticator/passkey. On a valid code we mark it used and DELETE all
|
||||||
|
* of the user's MFA factors via the admin API. GoTrue logs the user out of all
|
||||||
|
* sessions when a verified factor is deleted, so the client signs out and
|
||||||
|
* returns to /login; after signing back in (aal1, zero factors) the middleware
|
||||||
|
* forces fresh enrollment. We never fabricate an aal2 JWT.
|
||||||
|
*/
|
||||||
|
export async function POST(request: NextRequest): Promise<NextResponse> {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) return jsonNoStore({ error: 'unauthorized' }, { status: 401 });
|
||||||
|
|
||||||
|
let body: { code?: string };
|
||||||
|
try {
|
||||||
|
body = (await request.json()) as { code?: string };
|
||||||
|
} catch {
|
||||||
|
return jsonNoStore({ error: 'bad_request' }, { status: 400 });
|
||||||
|
}
|
||||||
|
const code = (body.code ?? '').trim();
|
||||||
|
if (!code) return jsonNoStore({ error: 'invalid_code' }, { status: 400 });
|
||||||
|
|
||||||
|
const admin = getSupabaseAdmin();
|
||||||
|
const hash = hashRecoveryCode(code);
|
||||||
|
|
||||||
|
const { data: match, error } = await admin
|
||||||
|
.from('mfa_recovery_codes')
|
||||||
|
.select('id')
|
||||||
|
.eq('user_id', user.id)
|
||||||
|
.eq('code_hash', hash)
|
||||||
|
.is('used_at', null)
|
||||||
|
.limit(1)
|
||||||
|
.maybeSingle<{ id: number }>();
|
||||||
|
if (error) return jsonNoStore({ error: 'failed' }, { status: 500 });
|
||||||
|
if (!match) return jsonNoStore({ error: 'invalid_code' }, { status: 400 });
|
||||||
|
|
||||||
|
const upd = await admin
|
||||||
|
.from('mfa_recovery_codes')
|
||||||
|
.update({ used_at: new Date().toISOString() })
|
||||||
|
.eq('id', match.id)
|
||||||
|
.is('used_at', null);
|
||||||
|
if (upd.error) return jsonNoStore({ error: 'failed' }, { status: 500 });
|
||||||
|
|
||||||
|
// Account recovery: remove every MFA factor so the user can re-enroll.
|
||||||
|
const { data: list } = await admin.auth.admin.mfa.listFactors({
|
||||||
|
userId: user.id,
|
||||||
|
});
|
||||||
|
for (const factor of list?.factors ?? []) {
|
||||||
|
await admin.auth.admin.mfa.deleteFactor({ id: factor.id, userId: user.id });
|
||||||
|
}
|
||||||
|
|
||||||
|
return jsonNoStore({ ok: true });
|
||||||
|
}
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
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,6 +3,7 @@ import { createSupabaseServerClient } from '@/lib/supabase/server';
|
|||||||
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
import { getSupabaseAdmin } from '@/lib/supabase/admin';
|
||||||
import { ClaimForm } from './claim-form';
|
import { ClaimForm } from './claim-form';
|
||||||
import { TokenReveal } from './token-reveal';
|
import { TokenReveal } from './token-reveal';
|
||||||
|
import { formatDate } from '@/lib/format';
|
||||||
|
|
||||||
export const dynamic = 'force-dynamic';
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
@@ -92,9 +93,7 @@ export default async function DashboardPage() {
|
|||||||
|
|
||||||
<div className="k">Last seen</div>
|
<div className="k">Last seen</div>
|
||||||
<div>
|
<div>
|
||||||
{tunnel.last_seen_at
|
{tunnel.last_seen_at ? formatDate(tunnel.last_seen_at) : 'never'}
|
||||||
? new Date(tunnel.last_seen_at).toLocaleString()
|
|
||||||
: 'never'}
|
|
||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
|
|||||||
+269
@@ -45,6 +45,12 @@ a:hover {
|
|||||||
padding: 2rem 1rem;
|
padding: 2rem 1rem;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
.stack {
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 1.25rem;
|
||||||
|
}
|
||||||
|
|
||||||
.nav {
|
.nav {
|
||||||
display: flex;
|
display: flex;
|
||||||
justify-content: space-between;
|
justify-content: space-between;
|
||||||
@@ -165,3 +171,266 @@ button.secondary,
|
|||||||
gap: 0.5rem;
|
gap: 0.5rem;
|
||||||
align-items: center;
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
|||||||
@@ -19,6 +19,7 @@ export default async function RootLayout({
|
|||||||
const {
|
const {
|
||||||
data: { user },
|
data: { user },
|
||||||
} = await supabase.auth.getUser();
|
} = await supabase.auth.getUser();
|
||||||
|
const isAdmin = user?.app_metadata?.role === 'admin';
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<html lang="en">
|
<html lang="en">
|
||||||
@@ -32,6 +33,8 @@ export default async function RootLayout({
|
|||||||
<>
|
<>
|
||||||
<Link href="/dashboard">Dashboard</Link>
|
<Link href="/dashboard">Dashboard</Link>
|
||||||
<Link href="/billing">Billing</Link>
|
<Link href="/billing">Billing</Link>
|
||||||
|
<Link href="/security">Security</Link>
|
||||||
|
{isAdmin && <Link href="/admin">Admin</Link>}
|
||||||
<form action="/api/auth/signout" method="post" style={{ margin: 0 }}>
|
<form action="/api/auth/signout" method="post" style={{ margin: 0 }}>
|
||||||
<button className="secondary" type="submit">
|
<button className="secondary" type="submit">
|
||||||
Sign out
|
Sign out
|
||||||
|
|||||||
+75
-4
@@ -1,32 +1,86 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useTransition } from 'react';
|
import { useEffect, useState, useTransition } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
|
import type { AuthError } from '@supabase/supabase-js';
|
||||||
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
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() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [error, setError] = useState<string | null>(null);
|
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 [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.',
|
||||||
|
);
|
||||||
|
} else if (params.get('mfa_reset') === '1') {
|
||||||
|
setResendInfo(
|
||||||
|
'Your two-factor methods were reset. Sign in to set up a new one.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (cooldown <= 0) return;
|
||||||
|
const t = setTimeout(() => setCooldown((c) => c - 1), 1000);
|
||||||
|
return () => clearTimeout(t);
|
||||||
|
}, [cooldown]);
|
||||||
|
|
||||||
function onSubmit(e: React.FormEvent) {
|
function onSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
|
setResendInfo(null);
|
||||||
const supabase = createSupabaseBrowserClient();
|
const supabase = createSupabaseBrowserClient();
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
const { error } = await supabase.auth.signInWithPassword({
|
const { error } = await supabase.auth.signInWithPassword({
|
||||||
email,
|
email,
|
||||||
password,
|
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);
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
// Hand off to the MFA gate: the challenge page completes step-up (or
|
||||||
|
// redirects to enrollment for users without a verified factor).
|
||||||
|
router.push('/security/challenge');
|
||||||
|
router.refresh();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function onResend() {
|
||||||
|
setResendInfo(null);
|
||||||
|
const supabase = createSupabaseBrowserClient();
|
||||||
|
startResend(async () => {
|
||||||
|
const { error } = await supabase.auth.resend({ type: 'signup', email });
|
||||||
if (error) {
|
if (error) {
|
||||||
setError(error.message);
|
setError(error.message);
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
router.push('/dashboard');
|
setResendInfo('Confirmation email sent. Check your inbox.');
|
||||||
router.refresh();
|
setCooldown(RESEND_COOLDOWN);
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -53,9 +107,26 @@ export default function LoginPage() {
|
|||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
/>
|
/>
|
||||||
{error && <p className="error">{error}</p>}
|
{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' }}>
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
<button type="submit" disabled={isPending}>
|
<button type="submit" disabled={isPending}>
|
||||||
{isPending ? 'Signing in…' : 'Sign in'}
|
{isPending ? 'Verifying…' : 'Sign in'}
|
||||||
</button>
|
</button>
|
||||||
<Link className="muted" href="/signup">
|
<Link className="muted" href="/signup">
|
||||||
Need an account?
|
Need an account?
|
||||||
|
|||||||
@@ -0,0 +1,185 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
||||||
|
import {
|
||||||
|
passkeyErrorMessage,
|
||||||
|
stepUpWithPasskey,
|
||||||
|
} from '@/lib/auth/webauthn-client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AAL2 step-up UI: verify with TOTP or passkey, or fall back to a single-use
|
||||||
|
* recovery code (which resets MFA and bounces the user back to /login to set up
|
||||||
|
* a fresh factor).
|
||||||
|
*/
|
||||||
|
export function ChallengeClient({
|
||||||
|
totpFactorId,
|
||||||
|
passkeyFactorId,
|
||||||
|
next,
|
||||||
|
}: {
|
||||||
|
totpFactorId: string | null;
|
||||||
|
passkeyFactorId: string | null;
|
||||||
|
next: string;
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const supabase = useMemo(() => createSupabaseBrowserClient(), []);
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [code, setCode] = useState('');
|
||||||
|
const [showRecovery, setShowRecovery] = useState(false);
|
||||||
|
const [recovery, setRecovery] = useState('');
|
||||||
|
|
||||||
|
function done() {
|
||||||
|
router.replace(next);
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyTotp(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
if (!totpFactorId) return;
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const { data: ch, error: ce } = await supabase.auth.mfa.challenge({
|
||||||
|
factorId: totpFactorId,
|
||||||
|
});
|
||||||
|
if (ce) throw ce;
|
||||||
|
const { error: ve } = await supabase.auth.mfa.verify({
|
||||||
|
factorId: totpFactorId,
|
||||||
|
challengeId: ch.id,
|
||||||
|
code: code.trim(),
|
||||||
|
});
|
||||||
|
if (ve) throw ve;
|
||||||
|
done();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verifyPasskey() {
|
||||||
|
if (!passkeyFactorId) return;
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await stepUpWithPasskey(supabase, passkeyFactorId);
|
||||||
|
done();
|
||||||
|
} catch (e) {
|
||||||
|
setError(passkeyErrorMessage(e));
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function redeemRecovery(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/security/recovery/redeem', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ code: recovery.trim() }),
|
||||||
|
});
|
||||||
|
const json = (await res.json()) as { ok?: boolean; error?: string };
|
||||||
|
if (!res.ok || !json.ok) {
|
||||||
|
throw new Error(
|
||||||
|
json.error === 'invalid_code'
|
||||||
|
? 'That recovery code is invalid or already used.'
|
||||||
|
: 'Recovery failed. Please try again.',
|
||||||
|
);
|
||||||
|
}
|
||||||
|
// Deleting verified factors logs the user out everywhere; clear local
|
||||||
|
// cookies and return to login to re-enroll.
|
||||||
|
await supabase.auth.signOut().catch(() => {});
|
||||||
|
router.replace('/login?mfa_reset=1');
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
|
||||||
|
{passkeyFactorId && (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Passkey</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Verify with your device biometrics or security key.
|
||||||
|
</p>
|
||||||
|
<button type="button" onClick={verifyPasskey} disabled={busy}>
|
||||||
|
{busy ? 'Waiting…' : 'Use a passkey'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{totpFactorId && (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Authenticator app</h2>
|
||||||
|
<form onSubmit={verifyTotp}>
|
||||||
|
<label htmlFor="challenge-code">6-digit code</label>
|
||||||
|
<input
|
||||||
|
id="challenge-code"
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
maxLength={6}
|
||||||
|
required
|
||||||
|
value={code}
|
||||||
|
onChange={(e) => setCode(e.target.value)}
|
||||||
|
/>
|
||||||
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
|
<button type="submit" disabled={busy || code.trim().length < 6}>
|
||||||
|
{busy ? 'Verifying…' : 'Verify'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="card">
|
||||||
|
<h2>Lost access?</h2>
|
||||||
|
{showRecovery ? (
|
||||||
|
<form onSubmit={redeemRecovery}>
|
||||||
|
<p className="muted">
|
||||||
|
Enter a recovery code. This removes your current two-factor
|
||||||
|
methods so you can set up new ones after signing in again.
|
||||||
|
</p>
|
||||||
|
<label htmlFor="recovery-code">Recovery code</label>
|
||||||
|
<input
|
||||||
|
id="recovery-code"
|
||||||
|
type="text"
|
||||||
|
autoComplete="off"
|
||||||
|
placeholder="xxxx-xxxx-xxxx"
|
||||||
|
required
|
||||||
|
value={recovery}
|
||||||
|
onChange={(e) => setRecovery(e.target.value)}
|
||||||
|
/>
|
||||||
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
|
<button
|
||||||
|
type="submit"
|
||||||
|
className="btn-danger"
|
||||||
|
disabled={busy || recovery.trim().length === 0}
|
||||||
|
>
|
||||||
|
{busy ? 'Working…' : 'Use recovery code'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
) : (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="secondary"
|
||||||
|
onClick={() => setShowRecovery(true)}
|
||||||
|
disabled={busy}
|
||||||
|
>
|
||||||
|
Use a recovery code
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,47 @@
|
|||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
import { safeNextPath } from '@/lib/auth/mfa';
|
||||||
|
import { ChallengeClient } from './challenge-client';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* AAL2 step-up challenge. The middleware sends authenticated aal1 users here
|
||||||
|
* when they have verified factors. Users with no verified factors are sent to
|
||||||
|
* enrollment instead; users already at aal2 are forwarded to their target.
|
||||||
|
*/
|
||||||
|
export default async function ChallengePage({
|
||||||
|
searchParams,
|
||||||
|
}: {
|
||||||
|
searchParams: { next?: string };
|
||||||
|
}) {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
|
||||||
|
const next = safeNextPath(searchParams.next);
|
||||||
|
|
||||||
|
const { data: aal } = await supabase.auth.mfa.getAuthenticatorAssuranceLevel();
|
||||||
|
if (aal?.currentLevel === 'aal2') redirect(next);
|
||||||
|
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const verified = factors?.all.filter((f) => f.status === 'verified') ?? [];
|
||||||
|
if (verified.length === 0) redirect('/security/enroll');
|
||||||
|
|
||||||
|
const totp = verified.find((f) => f.factor_type === 'totp');
|
||||||
|
const passkey = verified.find((f) => f.factor_type === 'webauthn');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="container">
|
||||||
|
<h1>Verify it's you</h1>
|
||||||
|
<p className="muted">Complete two-factor authentication to continue.</p>
|
||||||
|
<ChallengeClient
|
||||||
|
totpFactorId={totp?.id ?? null}
|
||||||
|
passkeyFactorId={passkey?.id ?? null}
|
||||||
|
next={next}
|
||||||
|
/>
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,79 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
||||||
|
import {
|
||||||
|
PasskeyEnrollPanel,
|
||||||
|
RecoveryCodesPanel,
|
||||||
|
TotpEnrollPanel,
|
||||||
|
} from '../mfa-components';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Drives the mandatory first-factor enrollment: pick TOTP and/or passkey, then
|
||||||
|
* (once a factor is verified and the session is aal2) generate and display the
|
||||||
|
* one-time recovery codes before releasing the user to the dashboard.
|
||||||
|
*/
|
||||||
|
export function EnrollClient() {
|
||||||
|
const router = useRouter();
|
||||||
|
const supabase = useMemo(() => createSupabaseBrowserClient(), []);
|
||||||
|
const [phase, setPhase] = useState<'choose' | 'recovery'>('choose');
|
||||||
|
const [codes, setCodes] = useState<string[]>([]);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function handleVerified() {
|
||||||
|
setError(null);
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/security/recovery/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
const json = (await res.json()) as { codes?: string[]; error?: string };
|
||||||
|
if (!res.ok || !json.codes) {
|
||||||
|
throw new Error(json.error || 'Could not generate recovery codes.');
|
||||||
|
}
|
||||||
|
setCodes(json.codes);
|
||||||
|
} catch (e) {
|
||||||
|
// The factor is already enabled; surface the error but still let the
|
||||||
|
// user proceed (they can regenerate codes later in Security settings).
|
||||||
|
setError(
|
||||||
|
`${(e as Error).message} You can generate recovery codes later in Security settings.`,
|
||||||
|
);
|
||||||
|
setCodes([]);
|
||||||
|
} finally {
|
||||||
|
setPhase('recovery');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function finish() {
|
||||||
|
router.replace('/dashboard');
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
if (phase === 'recovery') {
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
{codes.length > 0 ? (
|
||||||
|
<RecoveryCodesPanel codes={codes} />
|
||||||
|
) : (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Two-factor authentication enabled</h2>
|
||||||
|
<p className="muted">Your account is now protected.</p>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
<div className="row">
|
||||||
|
<button type="button" onClick={finish}>
|
||||||
|
Continue to dashboard
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
<TotpEnrollPanel supabase={supabase} onVerified={handleVerified} />
|
||||||
|
<PasskeyEnrollPanel supabase={supabase} onVerified={handleVerified} />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
import { EnrollClient } from './enroll-client';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Mandatory MFA enrollment gate. Reachable only by authenticated users (the
|
||||||
|
* middleware sends users here when they have zero verified factors). If the
|
||||||
|
* user already has a verified factor, there is nothing to enroll, so we send
|
||||||
|
* them on to the dashboard.
|
||||||
|
*/
|
||||||
|
export default async function EnrollPage() {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const verified = factors?.all.filter((f) => f.status === 'verified') ?? [];
|
||||||
|
if (verified.length > 0) redirect('/dashboard');
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="container">
|
||||||
|
<h1>Secure your account</h1>
|
||||||
|
<p className="muted">
|
||||||
|
Two-factor authentication is required. Add at least one method below to
|
||||||
|
continue.
|
||||||
|
</p>
|
||||||
|
<EnrollClient />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useState } from 'react';
|
||||||
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
import {
|
||||||
|
enrollPasskey,
|
||||||
|
passkeyErrorMessage,
|
||||||
|
} from '@/lib/auth/webauthn-client';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Remove any leftover *unverified* factors of a given type before starting a
|
||||||
|
* fresh enrollment. GoTrue rejects a second enroll with a duplicate friendly
|
||||||
|
* name, and abandoned/unverified factors would otherwise block re-enrollment
|
||||||
|
* (e.g. after a refresh mid-flow). Unenrolling unverified factors does not
|
||||||
|
* require aal2.
|
||||||
|
*/
|
||||||
|
async function cleanupUnverified(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
factorType: 'totp' | 'webauthn',
|
||||||
|
): Promise<void> {
|
||||||
|
const { data } = await supabase.auth.mfa.listFactors();
|
||||||
|
const stale =
|
||||||
|
data?.all.filter(
|
||||||
|
(f) => f.factor_type === factorType && f.status === 'unverified',
|
||||||
|
) ?? [];
|
||||||
|
for (const f of stale) {
|
||||||
|
await supabase.auth.mfa.unenroll({ factorId: f.id });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/** TOTP authenticator-app enrollment: QR + manual secret, then code verify. */
|
||||||
|
export function TotpEnrollPanel({
|
||||||
|
supabase,
|
||||||
|
onVerified,
|
||||||
|
}: {
|
||||||
|
supabase: SupabaseClient;
|
||||||
|
onVerified: () => void;
|
||||||
|
}) {
|
||||||
|
const [stage, setStage] = useState<'idle' | 'pending'>('idle');
|
||||||
|
const [qr, setQr] = useState('');
|
||||||
|
const [secret, setSecret] = useState('');
|
||||||
|
const [factorId, setFactorId] = useState('');
|
||||||
|
const [code, setCode] = useState('');
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await cleanupUnverified(supabase, 'totp');
|
||||||
|
const { data, error } = await supabase.auth.mfa.enroll({
|
||||||
|
factorType: 'totp',
|
||||||
|
friendlyName: 'Authenticator app',
|
||||||
|
});
|
||||||
|
if (error) throw error;
|
||||||
|
if (!data || !('totp' in data)) {
|
||||||
|
throw new Error('Unexpected enrollment response.');
|
||||||
|
}
|
||||||
|
setFactorId(data.id);
|
||||||
|
setQr(data.totp.qr_code);
|
||||||
|
setSecret(data.totp.secret);
|
||||||
|
setStage('pending');
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function verify(e: React.FormEvent) {
|
||||||
|
e.preventDefault();
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
const { data: ch, error: ce } = await supabase.auth.mfa.challenge({
|
||||||
|
factorId,
|
||||||
|
});
|
||||||
|
if (ce) throw ce;
|
||||||
|
const { error: ve } = await supabase.auth.mfa.verify({
|
||||||
|
factorId,
|
||||||
|
challengeId: ch.id,
|
||||||
|
code: code.trim(),
|
||||||
|
});
|
||||||
|
if (ve) throw ve;
|
||||||
|
onVerified();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (stage === 'idle') {
|
||||||
|
return (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Authenticator app</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Use an app like Google Authenticator, 1Password, or Authy to generate
|
||||||
|
6-digit codes.
|
||||||
|
</p>
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
<button type="button" onClick={start} disabled={busy}>
|
||||||
|
{busy ? 'Preparing…' : 'Set up authenticator app'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Scan the QR code</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Scan this with your authenticator app, then enter the 6-digit code to
|
||||||
|
confirm.
|
||||||
|
</p>
|
||||||
|
{qr && (
|
||||||
|
// eslint-disable-next-line @next/next/no-img-element
|
||||||
|
<img
|
||||||
|
src={qr}
|
||||||
|
alt="TOTP QR code"
|
||||||
|
width={200}
|
||||||
|
height={200}
|
||||||
|
style={{ background: '#fff', padding: 8, borderRadius: 8 }}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
<p className="muted" style={{ marginTop: '0.75rem' }}>
|
||||||
|
Can't scan? Enter this secret manually:
|
||||||
|
</p>
|
||||||
|
<div className="token">{secret}</div>
|
||||||
|
<form onSubmit={verify}>
|
||||||
|
<label htmlFor="totp-code">6-digit code</label>
|
||||||
|
<input
|
||||||
|
id="totp-code"
|
||||||
|
type="text"
|
||||||
|
inputMode="numeric"
|
||||||
|
autoComplete="one-time-code"
|
||||||
|
pattern="[0-9]*"
|
||||||
|
maxLength={6}
|
||||||
|
required
|
||||||
|
value={code}
|
||||||
|
onChange={(e) => setCode(e.target.value)}
|
||||||
|
/>
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
|
<button type="submit" disabled={busy || code.trim().length < 6}>
|
||||||
|
{busy ? 'Verifying…' : 'Verify and enable'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Passkey (WebAuthn) enrollment via the simplewebauthn ceremony. */
|
||||||
|
export function PasskeyEnrollPanel({
|
||||||
|
supabase,
|
||||||
|
onVerified,
|
||||||
|
}: {
|
||||||
|
supabase: SupabaseClient;
|
||||||
|
onVerified: () => void;
|
||||||
|
}) {
|
||||||
|
const [busy, setBusy] = useState(false);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
async function start() {
|
||||||
|
setError(null);
|
||||||
|
setBusy(true);
|
||||||
|
try {
|
||||||
|
await cleanupUnverified(supabase, 'webauthn');
|
||||||
|
await enrollPasskey(supabase, 'Passkey');
|
||||||
|
onVerified();
|
||||||
|
} catch (e) {
|
||||||
|
setError(passkeyErrorMessage(e));
|
||||||
|
} finally {
|
||||||
|
setBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Passkey</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Use your device's biometrics, screen lock, or a hardware security
|
||||||
|
key.
|
||||||
|
</p>
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
<button type="button" onClick={start} disabled={busy}>
|
||||||
|
{busy ? 'Waiting for passkey…' : 'Set up a passkey'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** One-time display of freshly generated recovery codes. */
|
||||||
|
export function RecoveryCodesPanel({ codes }: { codes: string[] }) {
|
||||||
|
const [copied, setCopied] = useState(false);
|
||||||
|
|
||||||
|
function copy() {
|
||||||
|
navigator.clipboard
|
||||||
|
.writeText(codes.join('\n'))
|
||||||
|
.then(() => setCopied(true))
|
||||||
|
.catch(() => setCopied(false));
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Save your recovery codes</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Store these somewhere safe. Each code can be used once to recover access
|
||||||
|
if you lose your authenticator and passkeys. They will not be shown
|
||||||
|
again.
|
||||||
|
</p>
|
||||||
|
<div
|
||||||
|
className="token"
|
||||||
|
style={{ display: 'grid', gap: '0.25rem', lineHeight: 1.8 }}
|
||||||
|
>
|
||||||
|
{codes.map((c) => (
|
||||||
|
<span key={c}>{c}</span>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
|
<button type="button" className="secondary" onClick={copy}>
|
||||||
|
{copied ? 'Copied' : 'Copy codes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
import { redirect } from 'next/navigation';
|
||||||
|
import { createSupabaseServerClient } from '@/lib/supabase/server';
|
||||||
|
import { SecurityClient } from './security-client';
|
||||||
|
|
||||||
|
export const dynamic = 'force-dynamic';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Security settings: manage MFA factors and regenerate recovery codes. The
|
||||||
|
* middleware guarantees the visitor is authenticated and at aal2 (mandatory
|
||||||
|
* MFA), so factor mutations here always run with the required assurance level.
|
||||||
|
*/
|
||||||
|
export default async function SecurityPage() {
|
||||||
|
const supabase = createSupabaseServerClient();
|
||||||
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
if (!user) redirect('/login');
|
||||||
|
|
||||||
|
const { data: factors } = await supabase.auth.mfa.listFactors();
|
||||||
|
const verified =
|
||||||
|
factors?.all
|
||||||
|
.filter((f) => f.status === 'verified')
|
||||||
|
.map((f) => ({
|
||||||
|
id: f.id,
|
||||||
|
type: f.factor_type,
|
||||||
|
friendlyName: f.friendly_name ?? null,
|
||||||
|
createdAt: f.created_at,
|
||||||
|
})) ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<main className="container">
|
||||||
|
<h1>Security</h1>
|
||||||
|
<p className="muted">Manage two-factor authentication for your account.</p>
|
||||||
|
<SecurityClient initialFactors={verified} />
|
||||||
|
</main>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,182 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { useMemo, useState } from 'react';
|
||||||
|
import { useRouter } from 'next/navigation';
|
||||||
|
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
||||||
|
import {
|
||||||
|
PasskeyEnrollPanel,
|
||||||
|
RecoveryCodesPanel,
|
||||||
|
TotpEnrollPanel,
|
||||||
|
} from './mfa-components';
|
||||||
|
|
||||||
|
type FactorView = {
|
||||||
|
id: string;
|
||||||
|
type: string;
|
||||||
|
friendlyName: string | null;
|
||||||
|
createdAt: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
const TYPE_LABEL: Record<string, string> = {
|
||||||
|
totp: 'Authenticator app',
|
||||||
|
webauthn: 'Passkey',
|
||||||
|
phone: 'Phone',
|
||||||
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Security settings client: list verified factors, add new ones, remove
|
||||||
|
* factors (never the last one — mandatory MFA), and regenerate recovery codes.
|
||||||
|
*/
|
||||||
|
export function SecurityClient({
|
||||||
|
initialFactors,
|
||||||
|
}: {
|
||||||
|
initialFactors: FactorView[];
|
||||||
|
}) {
|
||||||
|
const router = useRouter();
|
||||||
|
const supabase = useMemo(() => createSupabaseBrowserClient(), []);
|
||||||
|
const [factors] = useState<FactorView[]>(initialFactors);
|
||||||
|
const [adding, setAdding] = useState<null | 'totp' | 'webauthn'>(null);
|
||||||
|
const [busyId, setBusyId] = useState<string | null>(null);
|
||||||
|
const [error, setError] = useState<string | null>(null);
|
||||||
|
const [notice, setNotice] = useState<string | null>(null);
|
||||||
|
const [codes, setCodes] = useState<string[] | null>(null);
|
||||||
|
const [regenBusy, setRegenBusy] = useState(false);
|
||||||
|
|
||||||
|
async function remove(id: string) {
|
||||||
|
if (factors.length <= 1) {
|
||||||
|
setError('You must keep at least one two-factor method enabled.');
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
setBusyId(id);
|
||||||
|
try {
|
||||||
|
const { error } = await supabase.auth.mfa.unenroll({ factorId: id });
|
||||||
|
if (error) throw error;
|
||||||
|
router.refresh();
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setBusyId(null);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function onAdded() {
|
||||||
|
setAdding(null);
|
||||||
|
setNotice('Two-factor method added.');
|
||||||
|
router.refresh();
|
||||||
|
}
|
||||||
|
|
||||||
|
async function regenerate() {
|
||||||
|
setError(null);
|
||||||
|
setNotice(null);
|
||||||
|
setCodes(null);
|
||||||
|
setRegenBusy(true);
|
||||||
|
try {
|
||||||
|
const res = await fetch('/api/security/recovery/generate', {
|
||||||
|
method: 'POST',
|
||||||
|
});
|
||||||
|
const json = (await res.json()) as { codes?: string[]; error?: string };
|
||||||
|
if (!res.ok || !json.codes) {
|
||||||
|
throw new Error(json.error || 'Could not generate recovery codes.');
|
||||||
|
}
|
||||||
|
setCodes(json.codes);
|
||||||
|
} catch (e) {
|
||||||
|
setError((e as Error).message);
|
||||||
|
} finally {
|
||||||
|
setRegenBusy(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="stack">
|
||||||
|
{error && <p className="error">{error}</p>}
|
||||||
|
{notice && <p className="success">{notice}</p>}
|
||||||
|
|
||||||
|
<div className="card">
|
||||||
|
<h2>Your two-factor methods</h2>
|
||||||
|
{factors.length === 0 ? (
|
||||||
|
<p className="muted">No methods enabled.</p>
|
||||||
|
) : (
|
||||||
|
<table className="admin-table">
|
||||||
|
<thead>
|
||||||
|
<tr>
|
||||||
|
<th>Method</th>
|
||||||
|
<th>Name</th>
|
||||||
|
<th>Added</th>
|
||||||
|
<th aria-label="actions" />
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody>
|
||||||
|
{factors.map((f) => (
|
||||||
|
<tr key={f.id}>
|
||||||
|
<td>{TYPE_LABEL[f.type] ?? f.type}</td>
|
||||||
|
<td>{f.friendlyName ?? '—'}</td>
|
||||||
|
<td>{new Date(f.createdAt).toLocaleDateString()}</td>
|
||||||
|
<td>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="btn-sm btn-danger"
|
||||||
|
onClick={() => remove(f.id)}
|
||||||
|
disabled={busyId === f.id || factors.length <= 1}
|
||||||
|
title={
|
||||||
|
factors.length <= 1
|
||||||
|
? 'At least one method is required'
|
||||||
|
: 'Remove this method'
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{busyId === f.id ? 'Removing…' : 'Remove'}
|
||||||
|
</button>
|
||||||
|
</td>
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{adding === 'totp' && (
|
||||||
|
<TotpEnrollPanel supabase={supabase} onVerified={onAdded} />
|
||||||
|
)}
|
||||||
|
{adding === 'webauthn' && (
|
||||||
|
<PasskeyEnrollPanel supabase={supabase} onVerified={onAdded} />
|
||||||
|
)}
|
||||||
|
|
||||||
|
{adding === null && (
|
||||||
|
<div className="card">
|
||||||
|
<h2>Add a method</h2>
|
||||||
|
<div className="row">
|
||||||
|
<button type="button" onClick={() => setAdding('totp')}>
|
||||||
|
Add authenticator app
|
||||||
|
</button>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="secondary"
|
||||||
|
onClick={() => setAdding('webauthn')}
|
||||||
|
>
|
||||||
|
Add passkey
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="card">
|
||||||
|
<h2>Recovery codes</h2>
|
||||||
|
<p className="muted">
|
||||||
|
Generate a new set of single-use recovery codes. This invalidates any
|
||||||
|
codes you were issued before.
|
||||||
|
</p>
|
||||||
|
{codes && <RecoveryCodesPanel codes={codes} />}
|
||||||
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
className="secondary"
|
||||||
|
onClick={regenerate}
|
||||||
|
disabled={regenBusy}
|
||||||
|
>
|
||||||
|
{regenBusy ? 'Generating…' : 'Regenerate recovery codes'}
|
||||||
|
</button>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
+74
-6
@@ -1,41 +1,110 @@
|
|||||||
'use client';
|
'use client';
|
||||||
|
|
||||||
import { useState, useTransition } from 'react';
|
import { useEffect, useState, useTransition } from 'react';
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from 'next/navigation';
|
||||||
import Link from 'next/link';
|
import Link from 'next/link';
|
||||||
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
import { createSupabaseBrowserClient } from '@/lib/supabase/browser';
|
||||||
|
|
||||||
|
const RESEND_COOLDOWN = 45;
|
||||||
|
|
||||||
export default function SignupPage() {
|
export default function SignupPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const [email, setEmail] = useState('');
|
const [email, setEmail] = useState('');
|
||||||
const [password, setPassword] = useState('');
|
const [password, setPassword] = useState('');
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [info, setInfo] = useState<string | null>(null);
|
const [submitted, setSubmitted] = useState(false);
|
||||||
|
const [resendInfo, setResendInfo] = useState<string | null>(null);
|
||||||
|
const [cooldown, setCooldown] = useState(0);
|
||||||
const [isPending, startTransition] = useTransition();
|
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) {
|
function onSubmit(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
setInfo(null);
|
setResendInfo(null);
|
||||||
const supabase = createSupabaseBrowserClient();
|
const supabase = createSupabaseBrowserClient();
|
||||||
startTransition(async () => {
|
startTransition(async () => {
|
||||||
const { data, error } = await supabase.auth.signUp({
|
const { data, error } = await supabase.auth.signUp({
|
||||||
email,
|
email,
|
||||||
password,
|
password,
|
||||||
|
options: {
|
||||||
|
emailRedirectTo: `${process.env.NEXT_PUBLIC_APP_URL ?? ''}/auth/confirm`,
|
||||||
|
},
|
||||||
});
|
});
|
||||||
if (error) {
|
if (error) {
|
||||||
setError(error.message);
|
setError(error.message);
|
||||||
return;
|
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) {
|
if (data.session) {
|
||||||
router.push('/dashboard');
|
router.push('/dashboard');
|
||||||
router.refresh();
|
router.refresh();
|
||||||
} else {
|
return;
|
||||||
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 (
|
return (
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<h1>Sign up</h1>
|
<h1>Sign up</h1>
|
||||||
@@ -60,7 +129,6 @@ export default function SignupPage() {
|
|||||||
onChange={(e) => setPassword(e.target.value)}
|
onChange={(e) => setPassword(e.target.value)}
|
||||||
/>
|
/>
|
||||||
{error && <p className="error">{error}</p>}
|
{error && <p className="error">{error}</p>}
|
||||||
{info && <p className="success">{info}</p>}
|
|
||||||
<div className="row" style={{ marginTop: '1rem' }}>
|
<div className="row" style={{ marginTop: '1rem' }}>
|
||||||
<button type="submit" disabled={isPending}>
|
<button type="submit" disabled={isPending}>
|
||||||
{isPending ? 'Creating…' : 'Create account'}
|
{isPending ? 'Creating…' : 'Create account'}
|
||||||
|
|||||||
+5
-1
@@ -20,12 +20,16 @@ services:
|
|||||||
restart: unless-stopped
|
restart: unless-stopped
|
||||||
security_opt:
|
security_opt:
|
||||||
- no-new-privileges:true
|
- no-new-privileges:true
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
env_file:
|
env_file:
|
||||||
- .env.production
|
- .env.production
|
||||||
expose:
|
expose:
|
||||||
- "3000"
|
- "3000"
|
||||||
networks:
|
networks:
|
||||||
- default
|
default:
|
||||||
|
aliases:
|
||||||
|
- web-prod
|
||||||
healthcheck:
|
healthcheck:
|
||||||
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/"]
|
test: ["CMD", "wget", "-qO-", "http://127.0.0.1:3000/"]
|
||||||
interval: 30s
|
interval: 30s
|
||||||
|
|||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* 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;
|
||||||
@@ -0,0 +1,372 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,83 @@
|
|||||||
|
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,
|
||||||
|
};
|
||||||
|
}
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,138 @@
|
|||||||
|
/**
|
||||||
|
* 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;
|
||||||
|
}
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
/**
|
||||||
|
* 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];
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
/**
|
||||||
|
* 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));
|
||||||
|
}
|
||||||
@@ -0,0 +1,49 @@
|
|||||||
|
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 };
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
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);
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
/**
|
||||||
|
* Shared MFA constants/helpers used by both server and client code.
|
||||||
|
*
|
||||||
|
* The WebAuthn Relying Party ID is fixed to the registrable suffix
|
||||||
|
* `linumiq.net` so the same passkey works across `app-dev.linumiq.net` and
|
||||||
|
* `app.linumiq.net`. The RP origin is derived from NEXT_PUBLIC_APP_URL so each
|
||||||
|
* environment supplies its own concrete origin at challenge time.
|
||||||
|
*/
|
||||||
|
export const MFA_RP_ID = 'linumiq.net';
|
||||||
|
|
||||||
|
/** Origin (scheme + host) of this environment's app, from NEXT_PUBLIC_APP_URL. */
|
||||||
|
export function getAppOrigin(): string {
|
||||||
|
const raw = process.env.NEXT_PUBLIC_APP_URL;
|
||||||
|
if (raw) {
|
||||||
|
try {
|
||||||
|
return new URL(raw).origin;
|
||||||
|
} catch {
|
||||||
|
// fall through to the localhost default
|
||||||
|
}
|
||||||
|
}
|
||||||
|
return 'http://localhost:3000';
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Whitelist a `next` redirect target to same-origin relative paths only
|
||||||
|
* (open-redirect guard). Anything else falls back to /dashboard.
|
||||||
|
*/
|
||||||
|
export function safeNextPath(raw: string | null | undefined): string {
|
||||||
|
if (!raw || !raw.startsWith('/') || raw.startsWith('//')) {
|
||||||
|
return '/dashboard';
|
||||||
|
}
|
||||||
|
return raw;
|
||||||
|
}
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
import { createHash, randomBytes } from 'crypto';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* MFA recovery codes.
|
||||||
|
*
|
||||||
|
* GoTrue has no native recovery-code support, so we manage them ourselves in
|
||||||
|
* the `mfa_recovery_codes` table (service-role only; see migration 0002). We
|
||||||
|
* only ever persist a SHA-256 hash of each code — the plaintext is shown to the
|
||||||
|
* user exactly once at generation time. Codes are high-entropy random values,
|
||||||
|
* so a fast hash is sufficient (no need for bcrypt/per-code salt).
|
||||||
|
*/
|
||||||
|
|
||||||
|
/** Normalise user input so hyphens / case / spacing don't matter on redeem. */
|
||||||
|
function normalize(code: string): string {
|
||||||
|
return code.replace(/[^a-z0-9]/gi, '').toLowerCase();
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Stable hash used both when storing and when redeeming a code. */
|
||||||
|
export function hashRecoveryCode(code: string): string {
|
||||||
|
return createHash('sha256').update(normalize(code)).digest('hex');
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Generate `n` formatted recovery codes (e.g. `a1b2-c3d4-e5f6`). */
|
||||||
|
export function generateRecoveryCodes(n = 10): string[] {
|
||||||
|
const codes: string[] = [];
|
||||||
|
for (let i = 0; i < n; i++) {
|
||||||
|
const raw = randomBytes(6).toString('hex'); // 12 hex chars
|
||||||
|
codes.push(`${raw.slice(0, 4)}-${raw.slice(4, 8)}-${raw.slice(8, 12)}`);
|
||||||
|
}
|
||||||
|
return codes;
|
||||||
|
}
|
||||||
@@ -0,0 +1,147 @@
|
|||||||
|
'use client';
|
||||||
|
|
||||||
|
import { startAuthentication, startRegistration } from '@simplewebauthn/browser';
|
||||||
|
import type { SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
import { MFA_RP_ID, getAppOrigin } from './mfa';
|
||||||
|
|
||||||
|
/**
|
||||||
|
* WebAuthn (passkey) MFA ceremonies.
|
||||||
|
*
|
||||||
|
* supabase-js 2.106 ships a native WebAuthn helper, but its verify step expects
|
||||||
|
* the raw browser `Credential` object, whereas we run the ceremony with
|
||||||
|
* `@simplewebauthn/browser` (which yields the W3C JSON form). So we drive the
|
||||||
|
* GoTrue REST endpoints directly with the user's bearer token and feed the JSON
|
||||||
|
* options to simplewebauthn, then persist the returned aal2 session via
|
||||||
|
* `setSession`. The RP id/origins are client-supplied (GoTrue v2.186 reads them
|
||||||
|
* from the challenge/verify body).
|
||||||
|
*/
|
||||||
|
|
||||||
|
const SUPABASE_URL = process.env.NEXT_PUBLIC_SUPABASE_URL!;
|
||||||
|
const ANON_KEY = process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY!;
|
||||||
|
|
||||||
|
type GoTrueJson = Record<string, unknown> & {
|
||||||
|
msg?: string;
|
||||||
|
error?: string;
|
||||||
|
error_description?: string;
|
||||||
|
};
|
||||||
|
|
||||||
|
async function getAccessToken(supabase: SupabaseClient): Promise<string> {
|
||||||
|
const { data } = await supabase.auth.getSession();
|
||||||
|
const token = data.session?.access_token;
|
||||||
|
if (!token) throw new Error('No active session.');
|
||||||
|
return token;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function gotrue(
|
||||||
|
token: string,
|
||||||
|
path: string,
|
||||||
|
body: unknown,
|
||||||
|
): Promise<GoTrueJson> {
|
||||||
|
const res = await fetch(`${SUPABASE_URL}/auth/v1/${path}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: {
|
||||||
|
'Content-Type': 'application/json',
|
||||||
|
apikey: ANON_KEY,
|
||||||
|
Authorization: `Bearer ${token}`,
|
||||||
|
},
|
||||||
|
body: JSON.stringify(body),
|
||||||
|
});
|
||||||
|
const json = (await res.json().catch(() => ({}))) as GoTrueJson;
|
||||||
|
if (!res.ok) {
|
||||||
|
throw new Error(
|
||||||
|
json.msg ||
|
||||||
|
json.error_description ||
|
||||||
|
json.error ||
|
||||||
|
`Request failed (${res.status})`,
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return json;
|
||||||
|
}
|
||||||
|
|
||||||
|
async function applyTokens(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
json: GoTrueJson,
|
||||||
|
): Promise<void> {
|
||||||
|
const access_token = json.access_token as string | undefined;
|
||||||
|
const refresh_token = json.refresh_token as string | undefined;
|
||||||
|
if (access_token && refresh_token) {
|
||||||
|
await supabase.auth.setSession({ access_token, refresh_token });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function webauthnBody(extra: Record<string, unknown> = {}) {
|
||||||
|
return { rpId: MFA_RP_ID, rpOrigins: [getAppOrigin()], ...extra };
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Enroll + verify a brand new passkey. Requires the browser to be online and a
|
||||||
|
* platform/cross-platform authenticator available. On success the session is
|
||||||
|
* upgraded to aal2.
|
||||||
|
*/
|
||||||
|
export async function enrollPasskey(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
friendlyName: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const token = await getAccessToken(supabase);
|
||||||
|
const factor = await gotrue(token, 'factors', {
|
||||||
|
factor_type: 'webauthn',
|
||||||
|
friendly_name: friendlyName,
|
||||||
|
});
|
||||||
|
const factorId = factor.id as string;
|
||||||
|
|
||||||
|
const challenge = await gotrue(token, `factors/${factorId}/challenge`, {
|
||||||
|
webauthn: webauthnBody(),
|
||||||
|
});
|
||||||
|
const webauthn = challenge.webauthn as {
|
||||||
|
credential_options: { publicKey: unknown };
|
||||||
|
};
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const attResp = await startRegistration({
|
||||||
|
optionsJSON: webauthn.credential_options.publicKey as any,
|
||||||
|
});
|
||||||
|
|
||||||
|
const verify = await gotrue(token, `factors/${factorId}/verify`, {
|
||||||
|
challenge_id: challenge.id,
|
||||||
|
webauthn: webauthnBody({ type: 'create', credential_response: attResp }),
|
||||||
|
});
|
||||||
|
await applyTokens(supabase, verify);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Run a passkey assertion against an already-verified factor to step the
|
||||||
|
* session up to aal2.
|
||||||
|
*/
|
||||||
|
export async function stepUpWithPasskey(
|
||||||
|
supabase: SupabaseClient,
|
||||||
|
factorId: string,
|
||||||
|
): Promise<void> {
|
||||||
|
const token = await getAccessToken(supabase);
|
||||||
|
|
||||||
|
const challenge = await gotrue(token, `factors/${factorId}/challenge`, {
|
||||||
|
webauthn: webauthnBody(),
|
||||||
|
});
|
||||||
|
const webauthn = challenge.webauthn as {
|
||||||
|
credential_options: { publicKey: unknown };
|
||||||
|
};
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
const asseResp = await startAuthentication({
|
||||||
|
optionsJSON: webauthn.credential_options.publicKey as any,
|
||||||
|
});
|
||||||
|
|
||||||
|
const verify = await gotrue(token, `factors/${factorId}/verify`, {
|
||||||
|
challenge_id: challenge.id,
|
||||||
|
webauthn: webauthnBody({ type: 'request', credential_response: asseResp }),
|
||||||
|
});
|
||||||
|
await applyTokens(supabase, verify);
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Human-friendly message for the common WebAuthn ceremony failures. */
|
||||||
|
export function passkeyErrorMessage(e: unknown): string {
|
||||||
|
const err = e as { name?: string; message?: string };
|
||||||
|
if (err?.name === 'NotAllowedError' || err?.name === 'AbortError') {
|
||||||
|
return 'Passkey prompt was dismissed or timed out. Please try again.';
|
||||||
|
}
|
||||||
|
return err?.message || 'Passkey operation failed.';
|
||||||
|
}
|
||||||
@@ -0,0 +1,44 @@
|
|||||||
|
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
@@ -0,0 +1,171 @@
|
|||||||
|
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;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1,7 +1,36 @@
|
|||||||
import { createClient, SupabaseClient } from '@supabase/supabase-js';
|
import { createClient, SupabaseClient } from '@supabase/supabase-js';
|
||||||
|
import { Agent } from 'undici';
|
||||||
|
|
||||||
let _admin: SupabaseClient | null = null;
|
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 {
|
export function getSupabaseAdmin(): SupabaseClient {
|
||||||
if (_admin) return _admin;
|
if (_admin) return _admin;
|
||||||
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
const url = process.env.NEXT_PUBLIC_SUPABASE_URL;
|
||||||
@@ -11,6 +40,18 @@ export function getSupabaseAdmin(): SupabaseClient {
|
|||||||
}
|
}
|
||||||
_admin = createClient(url, key, {
|
_admin = createClient(url, key, {
|
||||||
auth: { autoRefreshToken: false, persistSession: false },
|
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;
|
return _admin;
|
||||||
}
|
}
|
||||||
|
|||||||
+91
-2
@@ -1,6 +1,26 @@
|
|||||||
import { createServerClient } from '@supabase/ssr';
|
import { createServerClient } from '@supabase/ssr';
|
||||||
import { NextResponse, type NextRequest } from 'next/server';
|
import { NextResponse, type NextRequest } from 'next/server';
|
||||||
|
|
||||||
|
// Path prefixes that are reachable without a completed MFA step-up. These are
|
||||||
|
// the auth flow itself, the MFA enrollment/challenge surface, their supporting
|
||||||
|
// APIs, and public email templates. Everything else (including the root path)
|
||||||
|
// requires aal2 once the user is authenticated.
|
||||||
|
const MFA_ALLOWLIST = [
|
||||||
|
'/login',
|
||||||
|
'/signup',
|
||||||
|
'/auth',
|
||||||
|
'/security',
|
||||||
|
'/api/auth',
|
||||||
|
'/api/security',
|
||||||
|
'/email-templates',
|
||||||
|
];
|
||||||
|
|
||||||
|
function isMfaAllowlisted(path: string): boolean {
|
||||||
|
return MFA_ALLOWLIST.some(
|
||||||
|
(prefix) => path === prefix || path.startsWith(`${prefix}/`),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
export async function middleware(request: NextRequest) {
|
export async function middleware(request: NextRequest) {
|
||||||
let response = NextResponse.next({ request });
|
let response = NextResponse.next({ request });
|
||||||
|
|
||||||
@@ -23,10 +43,79 @@ export async function middleware(request: NextRequest) {
|
|||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
await supabase.auth.getUser();
|
const {
|
||||||
|
data: { user },
|
||||||
|
} = await supabase.auth.getUser();
|
||||||
|
|
||||||
|
const path = request.nextUrl.pathname;
|
||||||
|
|
||||||
|
// 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
|
||||||
|
// short-circuit responses 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;
|
||||||
|
};
|
||||||
|
|
||||||
|
const redirectTo = (pathname: string, search = ''): NextResponse => {
|
||||||
|
const url = request.nextUrl.clone();
|
||||||
|
url.pathname = pathname;
|
||||||
|
url.search = search;
|
||||||
|
return withCookies(NextResponse.redirect(url));
|
||||||
|
};
|
||||||
|
|
||||||
|
// Defense-in-depth: guard the admin surface here in addition to the
|
||||||
|
// per-route requireAdmin()/requireAdminApi() checks.
|
||||||
|
if (path.startsWith('/admin') || path.startsWith('/api/admin')) {
|
||||||
|
if (!user) {
|
||||||
|
if (path.startsWith('/api/admin')) {
|
||||||
|
return withCookies(
|
||||||
|
NextResponse.json({ error: 'unauthorized' }, { status: 401 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return redirectTo('/login');
|
||||||
|
}
|
||||||
|
if (user.app_metadata?.role !== 'admin') {
|
||||||
|
if (path.startsWith('/api/admin')) {
|
||||||
|
return withCookies(
|
||||||
|
NextResponse.json({ error: 'forbidden' }, { status: 403 }),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return redirectTo('/dashboard');
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Mandatory MFA gate for every authenticated request outside the allowlist.
|
||||||
|
if (user && !isMfaAllowlisted(path)) {
|
||||||
|
const [{ data: aal }, { data: factors }] = await Promise.all([
|
||||||
|
supabase.auth.mfa.getAuthenticatorAssuranceLevel(),
|
||||||
|
supabase.auth.mfa.listFactors(),
|
||||||
|
]);
|
||||||
|
const verifiedCount =
|
||||||
|
factors?.all.filter((f) => f.status === 'verified').length ?? 0;
|
||||||
|
|
||||||
|
if (verifiedCount === 0) {
|
||||||
|
// No second factor at all → force enrollment.
|
||||||
|
return redirectTo('/security/enroll');
|
||||||
|
}
|
||||||
|
if (aal?.nextLevel === 'aal2' && aal?.currentLevel === 'aal1') {
|
||||||
|
// Has a factor but session is only aal1 → force step-up, preserving the
|
||||||
|
// originally requested destination.
|
||||||
|
const next = encodeURIComponent(`${path}${request.nextUrl.search}`);
|
||||||
|
return redirectTo('/security/challenge', `?next=${next}`);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
return response;
|
return response;
|
||||||
}
|
}
|
||||||
|
|
||||||
export const config = {
|
export const config = {
|
||||||
matcher: ['/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)'],
|
matcher: [
|
||||||
|
'/((?!_next/static|_next/image|favicon.ico|api/tunnel/claim).*)',
|
||||||
|
'/admin/:path*',
|
||||||
|
'/api/admin/:path*',
|
||||||
|
],
|
||||||
};
|
};
|
||||||
|
|||||||
Generated
+632
@@ -0,0 +1,632 @@
|
|||||||
|
{
|
||||||
|
"name": "linumiq-web",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"lockfileVersion": 3,
|
||||||
|
"requires": true,
|
||||||
|
"packages": {
|
||||||
|
"": {
|
||||||
|
"name": "linumiq-web",
|
||||||
|
"version": "1.0.0",
|
||||||
|
"dependencies": {
|
||||||
|
"@simplewebauthn/browser": "13.3.0",
|
||||||
|
"@supabase/ssr": "0.10.3",
|
||||||
|
"@supabase/supabase-js": "2.106.2",
|
||||||
|
"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/@simplewebauthn/browser": {
|
||||||
|
"version": "13.3.0",
|
||||||
|
"resolved": "https://registry.npmjs.org/@simplewebauthn/browser/-/browser-13.3.0.tgz",
|
||||||
|
"integrity": "sha512-BE/UWv6FOToAdVk0EokzkqQQDOWtNydYlY6+OrmiZ5SCNmb41VehttboTetUM3T/fr6EAFYVXjz4My2wg230rQ==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/auth-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/auth-js/-/auth-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-VcAjUErkHkhC5Jaf+g/G1qbkQrFh8edaCdHa7pxJmHUjkWKjT7UnYCtPA89XV0N0GIYRkEqJZw5V62CtOxTmBQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.8.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/functions-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/functions-js/-/functions-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-oRnr0QrL8H+zTO1YyQ1QjiHZU/957jvubbxSJTUm2XLAgzoGGV9Tahfyd+uvLsBLRVmXLtpU3oyCjdQIvkGMOA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.8.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/phoenix": {
|
||||||
|
"version": "0.4.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/phoenix/-/phoenix-0.4.2.tgz",
|
||||||
|
"integrity": "sha512-YSAGnmDAfuleFCVt3CeurQZAhxRfXWeZIIkwp7NhYzQ1UwW6ePSnzsFAiUm/mbCkfoCf70QQHKW/K6RKh52a4A==",
|
||||||
|
"license": "MIT"
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/postgrest-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/postgrest-js/-/postgrest-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-tDOzyPgp9pIRMR2x6C9+uDSJrnXSzxLtt3d7nC+Lrsy3jnJDHYfdQC/xcRyhJE/TOBJ0heSqRKR3UmejDjZxsw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"tslib": "2.8.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/realtime-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/realtime-js/-/realtime-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-LdRGT7DNhyZkPjubUv5bSdAZ0jSEX8wTHvx7htj7+K59TOZRvz4TuQK7tL2RWxyIZVeFMRluL04SzWS61rKnUA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@supabase/phoenix": "^0.4.2",
|
||||||
|
"tslib": "2.8.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/ssr": {
|
||||||
|
"version": "0.10.3",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/ssr/-/ssr-0.10.3.tgz",
|
||||||
|
"integrity": "sha512-ux2CJgX89h0Fz2lY7ZNafNG2SkXpyRc5dz77K9eKeBLPdtywQixKwIuetDeIViAJBp/buOUVmgj8PVesOklNpw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"cookie": "^1.0.2"
|
||||||
|
},
|
||||||
|
"peerDependencies": {
|
||||||
|
"@supabase/supabase-js": "^2.105.3"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/storage-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/storage-js/-/storage-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-xgKCSYuev1YarV+iVqr+zlfgSyremnJtn8T0NCT8L4XmMv1CLtESc0Q6kNp8+mKWdX/8ND0nzm7OMKx08kwNAw==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"iceberg-js": "^0.8.1",
|
||||||
|
"tslib": "2.8.1"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"node_modules/@supabase/supabase-js": {
|
||||||
|
"version": "2.106.2",
|
||||||
|
"resolved": "https://registry.npmjs.org/@supabase/supabase-js/-/supabase-js-2.106.2.tgz",
|
||||||
|
"integrity": "sha512-2/RZ/1fmJx/MRSEDG2Xk8+J4JVk5clM9V0uSI6kUTrcS32KA89DtqI5RUOC9r6mzY3WBC9qexLjssIHjbLyVJA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"@supabase/auth-js": "2.106.2",
|
||||||
|
"@supabase/functions-js": "2.106.2",
|
||||||
|
"@supabase/postgrest-js": "2.106.2",
|
||||||
|
"@supabase/realtime-js": "2.106.2",
|
||||||
|
"@supabase/storage-js": "2.106.2"
|
||||||
|
},
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.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/node": {
|
||||||
|
"version": "20.16.10",
|
||||||
|
"resolved": "https://registry.npmjs.org/@types/node/-/node-20.16.10.tgz",
|
||||||
|
"integrity": "sha512-vQUKgWTjEIRFCvK6CyriPH3MZYiYlNy0fKiEYHWbcoWLEgs4opurGGKlebrTLqdSMIbXImH6XExNiIyNUv3WpA==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT",
|
||||||
|
"dependencies": {
|
||||||
|
"undici-types": "~6.19.2"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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/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": "1.1.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/cookie/-/cookie-1.1.1.tgz",
|
||||||
|
"integrity": "sha512-ei8Aos7ja0weRpFzJnEA9UHJ/7XQmqglbRwnf2ATjcB9Wq874VKH9kfjjirM6UhU2/E5fFYadylyhFldcqSidQ==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=18"
|
||||||
|
},
|
||||||
|
"funding": {
|
||||||
|
"type": "opencollective",
|
||||||
|
"url": "https://opencollective.com/express"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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/iceberg-js": {
|
||||||
|
"version": "0.8.1",
|
||||||
|
"resolved": "https://registry.npmjs.org/iceberg-js/-/iceberg-js-0.8.1.tgz",
|
||||||
|
"integrity": "sha512-1dhVQZXhcHje7798IVM+xoo/1ZdVfzOMIc8/rgVSijRK38EDqOJoGula9N/8ZI5RD8QTxNQtK/Gozpr+qUqRRA==",
|
||||||
|
"license": "MIT",
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20.0.0"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"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/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==",
|
||||||
|
"dev": true,
|
||||||
|
"license": "MIT"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
+8
-3
@@ -2,17 +2,22 @@
|
|||||||
"name": "linumiq-web",
|
"name": "linumiq-web",
|
||||||
"version": "1.0.0",
|
"version": "1.0.0",
|
||||||
"private": true,
|
"private": true,
|
||||||
|
"engines": {
|
||||||
|
"node": ">=20"
|
||||||
|
},
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"dev": "next dev",
|
"dev": "next dev",
|
||||||
"build": "next build",
|
"build": "next build",
|
||||||
"start": "next start"
|
"start": "next start"
|
||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@supabase/ssr": "0.5.2",
|
"@simplewebauthn/browser": "13.3.0",
|
||||||
"@supabase/supabase-js": "2.45.4",
|
"@supabase/ssr": "0.10.3",
|
||||||
|
"@supabase/supabase-js": "2.106.2",
|
||||||
"next": "14.2.15",
|
"next": "14.2.15",
|
||||||
"react": "18.3.1",
|
"react": "18.3.1",
|
||||||
"react-dom": "18.3.1"
|
"react-dom": "18.3.1",
|
||||||
|
"undici": "6.21.1"
|
||||||
},
|
},
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "20.16.10",
|
"@types/node": "20.16.10",
|
||||||
|
|||||||
@@ -0,0 +1,4 @@
|
|||||||
|
<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>
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
-- 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.';
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
-- 0002_mfa_recovery.sql
|
||||||
|
-- Additive, idempotent migration for mandatory-MFA recovery codes.
|
||||||
|
-- Safe to run multiple times.
|
||||||
|
|
||||||
|
-- 1. Recovery codes -------------------------------------------------------
|
||||||
|
-- One row per single-use recovery code. We only ever store a SHA-256 hash of
|
||||||
|
-- the code; the plaintext is shown to the user exactly once at generation.
|
||||||
|
create table if not exists public.mfa_recovery_codes (
|
||||||
|
id bigint generated always as identity primary key,
|
||||||
|
user_id uuid not null,
|
||||||
|
code_hash text not null,
|
||||||
|
used_at timestamptz,
|
||||||
|
created_at timestamptz not null default now()
|
||||||
|
);
|
||||||
|
|
||||||
|
create index if not exists mfa_recovery_codes_user_id_idx
|
||||||
|
on public.mfa_recovery_codes (user_id);
|
||||||
|
|
||||||
|
-- Cascade-delete recovery codes when the owning auth user is removed, so no
|
||||||
|
-- orphaned rows are left behind (e.g. on account deletion or MFA reset).
|
||||||
|
do $$
|
||||||
|
begin
|
||||||
|
if not exists (
|
||||||
|
select 1 from pg_constraint
|
||||||
|
where conname = 'mfa_recovery_codes_user_id_fkey'
|
||||||
|
and conrelid = 'public.mfa_recovery_codes'::regclass
|
||||||
|
) then
|
||||||
|
alter table public.mfa_recovery_codes
|
||||||
|
add constraint mfa_recovery_codes_user_id_fkey
|
||||||
|
foreign key (user_id) references auth.users (id) on delete cascade;
|
||||||
|
end if;
|
||||||
|
end $$;
|
||||||
|
|
||||||
|
-- Fast lookup of an unused code by (user, hash) during redemption.
|
||||||
|
create unique index if not exists mfa_recovery_codes_user_hash_uidx
|
||||||
|
on public.mfa_recovery_codes (user_id, code_hash);
|
||||||
|
|
||||||
|
-- 2. Lock down with RLS, NO policies ---------------------------------------
|
||||||
|
-- RLS enabled with NO policies so anon/authenticated roles cannot read or
|
||||||
|
-- write recovery codes at all. The application generates and redeems codes
|
||||||
|
-- exclusively through the service-role client, which bypasses RLS.
|
||||||
|
alter table public.mfa_recovery_codes enable row level security;
|
||||||
|
|
||||||
|
comment on table public.mfa_recovery_codes is
|
||||||
|
'Single-use MFA recovery codes (SHA-256 hashed). RLS enabled with no policies: service-role only.';
|
||||||
@@ -0,0 +1,53 @@
|
|||||||
|
# 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';"
|
||||||
|
```
|
||||||
Reference in New Issue
Block a user