Compare commits

..

10 Commits

Author SHA1 Message Date
igm
1b46fc0ecc delete unsued 2026-01-10 18:27:39 +08:00
igm
587d17c39c Update README with comprehensive project documentation
- Add tech stack overview (frontend, backend, shared packages)
- Document project structure with directory tree
- Expand setup instructions with manual development option
- Add scripts reference table
- Document features (auth, organizations, dashboard)
- Add frontend routes overview
- Document API structure and namespaces

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 18:25:22 +08:00
RevIQ
cca901a9b9 Merge branch 'whats-left' 2026-01-10 18:10:40 +08:00
RevIQ
42badf3c52 Add DBIP city database and improve geo test coverage
- Add dbip-city-lite package to devenv for GeoIP testing
- Set GEOIP_DATABASE_PATH env var to point to the MMDB database
- Add tests for initGeoReader double-init and error handling
- Add real database tests for IP lookups (US, AU, DE, GB)
- Make real database tests conditional with describe.skipIf
- Improve test coverage from ~97% to 98.82%

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 18:10:30 +08:00
RevIQ
bd53a60497 Merge branch 'more-testing-stuff' 2026-01-10 18:10:03 +08:00
RevIQ
d486e2444e Add org settings layout with responsive nav and member management
- Create SettingsLayout component with left sidebar nav (desktop) and
  horizontal scroll nav (mobile)
- Add settings gear icon to sidebar (Lucide icon, only in org context)
- Fix home icon highlighting to only match exact org home path
- Create /settings/members route with full member management
- Create /settings/sites placeholder route
- Update general settings to use new SettingsLayout

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 18:09:17 +08:00
RevIQ
319edf70db Fix IP address not being set on sessions from localhost
The extractClientIP() function only checked proxy headers (X-Forwarded-For,
CF-Connecting-IP, etc.) which don't exist when running locally without a proxy.

Changes:
- Add clientIP field to APIContext
- Use Bun's server.requestIP() to get client IP from direct socket connection
- Update getGeoInfo() to accept fallback IP parameter
- Pass context.clientIP to getGeoInfo() in auth procedures

Now sessions will have IP address set even for local development (::1 or 127.0.0.1).

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 18:08:21 +08:00
RevIQ
74b26818ca Add comprehensive e2e tests for all auth procedures
Tests cover all login scenarios from docs/initial-app.md:
- Signup with password and passkey
- Password login with trusted device (immediate completion)
- Password login with untrusted device (email confirmation)
- Full passkey authentication flow
- User with no auth methods (stays pending)
- Non-existent email (anti-enumeration with fake token)
- Email verification and resend flows
- Password reset with session revocation
- Logout

All auth procedures now have 100% function coverage.
127 tests passing across 3 e2e test files.

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 17:55:39 +08:00
RevIQ
b93f5e0b69 lint 2026-01-10 17:52:00 +08:00
RevIQ
fb68f341dd Reorganize layouts with dedicated admin sidebar (dark theme)
- Create admin layout with dark sidebar (zinc-900 background, light text)
- Move dashboard components to layout/dashboard/ subfolder
- Move admin components to layout/admin/ subfolder
- Admin sidebar has: Dashboard, Organizations, Users nav items
- Admin header shows "Admin" badge and "Exit Admin" link
- Update all route imports to use new barrel exports
- Add macOS sed syntax reference to CLAUDE.md

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
2026-01-10 17:45:17 +08:00
43 changed files with 3448 additions and 359 deletions

View File

@@ -6,3 +6,11 @@ Before starting the dev server, check if it's already running:
- Use `lsof -i :6827` or check for existing background tasks - Use `lsof -i :6827` or check for existing background tasks
- The dev server runs on port 6827 (may fall back to 6828 if port is in use) - The dev server runs on port 6827 (may fall back to 6828 if port is in use)
- Start with `bun run --cwd apps/publisher-dashboard dev` or `devenv up` - Start with `bun run --cwd apps/publisher-dashboard dev` or `devenv up`
## macOS sed Syntax
macOS uses BSD sed which differs from GNU sed:
- In-place edit requires empty string for backup: `sed -i '' 's/old/new/g' file`
- GNU sed (Linux): `sed -i 's/old/new/g' file`
- Use `|` as delimiter when patterns contain `/`: `sed -i '' 's|old/path|new/path|g' file`
- For multiple files: `for f in *.txt; do sed -i '' 's/old/new/g' "$f"; done`

121
README.md
View File

@@ -1,9 +1,52 @@
# Reviq Publisher Dashboard # Reviq Publisher Dashboard
A modern publisher dashboard for managing organizations, members, and sites. Built as a monorepo with SvelteKit frontend and oRPC API server.
## Tech Stack
### Frontend (`apps/publisher-dashboard`)
- **SvelteKit** with Svelte 5 (runes)
- **Tailwind CSS v4** for styling
- **TanStack Query** for data fetching
- **bits-ui** for accessible UI primitives
- **Lucide** for icons
- **WebAuthn/Passkeys** for passwordless authentication
### Backend (`apps/api-server`)
- **Bun** runtime
- **oRPC** for type-safe API (contract-first)
- **Kysely** for type-safe SQL queries
- **PostgreSQL** database
- **Postmark** for transactional emails
### Shared Packages
- `@reviq/api-contract` - Shared API contract (oRPC)
- `@reviq/db` - Database client and queries
- `@reviq/db-schema` - Database schema and codegen
- `@reviq/utils` - Shared utilities
## Project Structure
```
publisher-dashboard/
├── apps/
│ ├── api-server/ # Backend API server
│ ├── cli/ # CLI tools
│ └── publisher-dashboard/ # SvelteKit frontend
├── packages/
│ ├── api-contract/ # Shared oRPC contract
│ ├── db/ # Database client
│ ├── db-schema/ # DB schema & codegen
│ ├── testing/ # Test utilities
│ └── utils/ # Shared utilities
└── db/ # Database migrations
```
## Setup ## Setup
### Prerequisites ### Prerequisites
- [Bun](https://bun.sh/) v1.1.42+
- [devenv](https://devenv.sh/) for development environment management - [devenv](https://devenv.sh/) for development environment management
### Environment Variables ### Environment Variables
@@ -29,9 +72,87 @@ devenv up
This starts: This starts:
- PostgreSQL database - PostgreSQL database
- Publisher dashboard dev server (port 6827) - Publisher dashboard dev server (port 6827)
- API server
- Package build watcher - Package build watcher
The database is automatically initialized with: The database is automatically initialized with:
- Database: `reviq-dashboard` - Database: `reviq-dashboard`
- User: `reviq` - User: `reviq`
- Password: `reviq` - Password: `reviq`
### Manual Development
If not using devenv, start services individually:
```bash
# Install dependencies
bun install
# Build packages first
bun run build:packages
# Start dev server
bun run dev
```
## Scripts
| Script | Description |
|--------|-------------|
| `bun run dev` | Start all dev servers |
| `bun run build` | Build all packages and apps |
| `bun run typecheck` | Run TypeScript type checking |
| `bun run lint` | Run Biome and ESLint |
| `bun run lint:fix` | Fix linting issues |
| `bun run test` | Run tests |
| `bun run db:codegen` | Generate database types |
## Features
### Authentication
- Passwordless login with passkeys (WebAuthn)
- Email verification
- Session management with device tracking
### Organizations
- Create and manage organizations
- Member management with roles (owner, admin, member)
- Invite members via email
- Organization settings
### Dashboard
- Organization switcher
- Performance metrics
- Reports (coming soon)
- Site management (coming soon)
## Architecture
### Frontend Routes
```
/ # Landing page
/login # Login page
/dashboard # Organization list
/dashboard/[slug] # Organization home
/dashboard/[slug]/performance # Performance metrics
/dashboard/[slug]/reports # Reports (placeholder)
/dashboard/[slug]/settings # Organization settings
├── /members # Member management
└── /sites # Sites (placeholder)
/account # User account settings
├── /security # Security settings
└── /sessions # Active sessions
/admin # Admin panel
```
### API Structure
The API uses oRPC with a contract-first approach. Routes are defined in `@reviq/api-contract` and implemented in `apps/api-server`.
Key API namespaces:
- `auth` - Authentication (passkeys, sessions)
- `me` - Current user profile
- `orgs` - Organization management
- `orgs.members` - Member management
- `orgs.invites` - Invitation management

File diff suppressed because it is too large Load Diff

View File

@@ -21,6 +21,8 @@ export interface APIContext {
reqHeaders: Headers; reqHeaders: Headers;
/** Response headers (for setting cookies) */ /** Response headers (for setting cookies) */
resHeaders: Headers; resHeaders: Headers;
/** Client IP address from direct connection (fallback when no proxy headers) */
clientIP?: string | null;
} }
/** /**

View File

@@ -39,7 +39,7 @@ const rpName = Bun.env.RP_NAME ?? DEFAULT_RP_NAME;
Bun.serve({ Bun.serve({
port, port,
async fetch(request) { async fetch(request, server) {
const url = new URL(request.url); const url = new URL(request.url);
if (url.pathname.startsWith("/api/v1/rpc")) { if (url.pathname.startsWith("/api/v1/rpc")) {
@@ -50,6 +50,10 @@ Bun.serve({
// Create response headers for setting cookies // Create response headers for setting cookies
const resHeaders = new Headers(); const resHeaders = new Headers();
// Get client IP from Bun's server (fallback for when no proxy headers)
const socketInfo = server.requestIP(request);
const clientIP = socketInfo?.address ?? null;
const context: APIContext = { const context: APIContext = {
db, db,
origin, origin,
@@ -57,6 +61,7 @@ Bun.serve({
rpName, rpName,
reqHeaders: request.headers, reqHeaders: request.headers,
resHeaders, resHeaders,
clientIP,
}; };
const { response } = await handler.handle(request, { const { response } = await handler.handle(request, {

View File

@@ -102,7 +102,7 @@ export const createLoginRequest = os.auth.createLoginRequest.handler(
const hasPassword = user.password_hash !== null; const hasPassword = user.password_hash !== null;
// Get geo info and user agent // Get geo info and user agent
const geo = getGeoInfo(context.reqHeaders); const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders); const userAgent = getUserAgent(context.reqHeaders);
// Create login request with secure token // Create login request with secure token

View File

@@ -86,7 +86,7 @@ export const loginIfRequestIsCompleted =
} }
// Get current request info // Get current request info
const geo = getGeoInfo(context.reqHeaders); const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders); const userAgent = getUserAgent(context.reqHeaders);
// Upsert user device // Upsert user device

View File

@@ -225,7 +225,7 @@ export const signup = os.auth.signup.handler(async ({ input, context }) => {
} }
// Get geo info and user agent for session creation // Get geo info and user agent for session creation
const geo = getGeoInfo(context.reqHeaders); const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders); const userAgent = getUserAgent(context.reqHeaders);
let userId: number; let userId: number;

View File

@@ -1,10 +1,18 @@
import { beforeEach, describe, expect, test } from "bun:test"; import {
afterAll,
beforeAll,
beforeEach,
describe,
expect,
test,
} from "bun:test";
import { import {
_resetForTesting, _resetForTesting,
_setReaderForTesting, _setReaderForTesting,
extractClientIP, extractClientIP,
getGeoInfo, getGeoInfo,
getUserAgent, getUserAgent,
initGeoReader,
lookupGeoFromIP, lookupGeoFromIP,
} from "./geo.js"; } from "./geo.js";
@@ -220,3 +228,110 @@ describe("getUserAgent", () => {
expect(getUserAgent(createHeaders({}))).toBe("Unknown"); expect(getUserAgent(createHeaders({}))).toBe("Unknown");
}); });
}); });
describe("initGeoReader", () => {
beforeEach(() => {
_resetForTesting();
});
test("calling initGeoReader twice does not reinitialize", async () => {
// First call initializes
await initGeoReader();
// Second call should return early (covers the early return branch)
await initGeoReader();
// If we get here without error, the early return worked
expect(true).toBe(true);
});
test("handles missing database file gracefully", async () => {
// Save original env
const originalPath = Bun.env.GEOIP_DATABASE_PATH;
// Point to non-existent file
Bun.env.GEOIP_DATABASE_PATH = "/nonexistent/path/to/db.mmdb";
// Should not throw, just log a warning
await initGeoReader();
// Lookups should return nulls since reader failed to initialize
expect(lookupGeoFromIP("8.8.8.8")).toEqual({
city: null,
region: null,
country: null,
});
// Restore original env
if (originalPath) {
Bun.env.GEOIP_DATABASE_PATH = originalPath;
} else {
delete Bun.env.GEOIP_DATABASE_PATH;
}
});
});
// Only run real database tests if GEOIP_DATABASE_PATH is set
const hasGeoDatabase = !!Bun.env.GEOIP_DATABASE_PATH;
describe.skipIf(!hasGeoDatabase)("real GeoIP database", () => {
beforeAll(async () => {
_resetForTesting();
await initGeoReader();
});
afterAll(() => {
_resetForTesting();
});
test("looks up Google DNS (8.8.8.8) - US", () => {
const result = lookupGeoFromIP("8.8.8.8");
expect(result.country).toBe("US");
});
test("looks up Cloudflare DNS (1.1.1.1) - AU", () => {
const result = lookupGeoFromIP("1.1.1.1");
// Cloudflare's 1.1.1.1 is geolocated to Sydney, Australia
expect(result.country).toBe("AU");
});
test("looks up known German IP", () => {
// Deutsche Telekom IP range
const result = lookupGeoFromIP("80.150.6.143");
expect(result.country).toBe("DE");
});
test("looks up known UK IP", () => {
// BBC IP range
const result = lookupGeoFromIP("212.58.244.71");
expect(result.country).toBe("GB");
});
test("returns city data for major IPs", () => {
const result = lookupGeoFromIP("8.8.8.8");
// DBIP returns "Mountain View" for Google DNS
expect(result.city).toBe("Mountain View");
expect(result.region).toBe("California");
});
test("getGeoInfo uses real database when no CF headers", () => {
const headers = createHeaders({ "X-Real-IP": "8.8.8.8" });
const result = getGeoInfo(headers);
expect(result.ip).toBe("8.8.8.8");
expect(result.country).toBe("US");
expect(result.city).toBe("Mountain View");
});
test("returns nulls for private/reserved IPs", () => {
const result = lookupGeoFromIP("192.168.1.1");
expect(result.city).toBeNull();
expect(result.country).toBeNull();
});
test("returns nulls for localhost", () => {
const result = lookupGeoFromIP("127.0.0.1");
expect(result.city).toBeNull();
expect(result.country).toBeNull();
});
});

View File

@@ -126,9 +126,16 @@ export const lookupGeoFromIP = (
/** /**
* Extract geolocation info from request headers. * Extract geolocation info from request headers.
* Uses Cloudflare headers when available, falls back to GeoIP database lookup. * Uses Cloudflare headers when available, falls back to GeoIP database lookup.
*
* @param headers - Request headers to extract proxy IP headers from
* @param fallbackIP - Optional fallback IP from direct socket connection (e.g., from Bun's server.requestIP)
*/ */
export const getGeoInfo = (headers: Headers): GeoInfo => { export const getGeoInfo = (
const ip = extractClientIP(headers); headers: Headers,
fallbackIP?: string | null,
): GeoInfo => {
// Try proxy headers first, then fall back to direct connection IP
const ip = extractClientIP(headers) ?? fallbackIP ?? null;
// Try Cloudflare geo headers first // Try Cloudflare geo headers first
const cfCountry = headers.get("CF-IPCountry"); const cfCountry = headers.get("CF-IPCountry");

View File

@@ -0,0 +1,39 @@
<script lang="ts">
import { Badge } from "$lib/components/ui/badge";
import { cn } from "$lib/utils.js";
import AdminMobileNav from "./admin-mobile-nav.svelte";
interface Props {
title: string;
class?: string;
}
let { title, class: className }: Props = $props();
</script>
<header
class={cn(
"flex h-14 items-center justify-between border-b border-border bg-card px-4 lg:px-6",
className,
)}
>
<div class="flex items-center gap-3">
<!-- Mobile menu button -->
<AdminMobileNav class="lg:hidden" />
<h1 class="text-base font-semibold tracking-tight text-foreground lg:text-lg">{title}</h1>
<Badge variant="destructive" class="hidden sm:inline-flex">Admin</Badge>
</div>
<div class="flex items-center gap-2">
<a
href="/dashboard"
class="flex items-center gap-1.5 rounded-md px-3 py-1.5 text-sm text-muted-foreground transition-colors hover:bg-accent hover:text-foreground"
>
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M19 12H5M12 19l-7-7 7-7" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<span class="hidden sm:inline">Exit Admin</span>
</a>
</div>
</header>

View File

@@ -0,0 +1,32 @@
<script lang="ts">
import type { Snippet } from "svelte";
import { cn } from "$lib/utils.js";
import AdminHeader from "./admin-header.svelte";
import AdminMobileNav from "./admin-mobile-nav.svelte";
import AdminSidebar from "./admin-sidebar.svelte";
interface Props {
title: string;
children: Snippet;
class?: string;
}
let { title, children, class: className }: Props = $props();
</script>
<div class="flex h-screen overflow-hidden bg-background">
<!-- Desktop sidebar - hidden on mobile -->
<div class="hidden lg:block">
<AdminSidebar />
</div>
<div class="flex flex-1 flex-col overflow-hidden">
<AdminHeader {title} />
<main class="flex-1 overflow-auto p-4 lg:p-6">
<div class={cn("mx-auto max-w-7xl", className)}>
{@render children()}
</div>
</main>
</div>
</div>

View File

@@ -0,0 +1,193 @@
<script lang="ts">
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
import { api } from "$lib/api/client";
import { Button } from "$lib/components/ui/button";
import { Separator } from "$lib/components/ui/separator";
import * as Sheet from "$lib/components/ui/sheet";
import { cn } from "$lib/utils.js";
interface Props {
class?: string;
}
let { class: className }: Props = $props();
let open = $state(false);
// Fetch current user
const userQuery = createQuery(() => ({
queryKey: ["me"],
queryFn: () => api.me.get(),
}));
const user = $derived(userQuery.data);
// Generate initials from display name or email
const initials = $derived.by(() => {
if (!user) {
return "??";
}
if (user.displayName) {
const parts = user.displayName.split(" ");
if (parts.length >= 2) {
return (
parts[0].charAt(0) + parts[parts.length - 1].charAt(0)
).toUpperCase();
}
return user.displayName.slice(0, 2).toUpperCase();
}
return user.email.slice(0, 2).toUpperCase();
});
const queryClient = useQueryClient();
function handleNavClick() {
open = false;
}
async function handleSignOut() {
try {
await api.auth.logout();
queryClient.clear();
open = false;
goto("/login");
} catch (error) {
console.error("Failed to sign out:", error);
}
}
// Admin nav items
const navItems = [
{ icon: "dashboard", href: "/admin", label: "Dashboard" },
{ icon: "building", href: "/admin/orgs", label: "Organizations" },
{ icon: "users", href: "/admin/users", label: "Users" },
];
</script>
<Sheet.Root bind:open>
<Sheet.Trigger>
{#snippet child({ props })}
<Button variant="ghost" size="icon" class={cn("h-9 w-9 lg:hidden", className)} {...props}>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M3 12h18M3 6h18M3 18h18" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<span class="sr-only">Open menu</span>
</Button>
{/snippet}
</Sheet.Trigger>
<Sheet.Content side="left" class="w-72 border-zinc-800 bg-zinc-900 p-0">
<Sheet.Header class="border-b border-zinc-800 px-6 py-4">
<div class="flex items-center gap-3">
<div class="flex h-9 w-9 items-center justify-center rounded-lg bg-red-600">
<svg class="h-5 w-5 text-white" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5">
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</div>
<Sheet.Title class="text-lg font-semibold text-white">Admin Panel</Sheet.Title>
</div>
</Sheet.Header>
<nav class="flex flex-1 flex-col p-4">
<div class="space-y-1">
{#each navItems as item}
{@const isActive =
item.href === "/admin"
? $page.url.pathname === "/admin"
: $page.url.pathname.startsWith(item.href)}
<a
href={item.href}
onclick={handleNavClick}
class={cn(
"flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium transition-colors",
isActive
? "bg-zinc-800 text-white"
: "text-zinc-400 hover:bg-zinc-800/50 hover:text-zinc-200",
)}
>
{#if item.icon === "dashboard"}
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<rect x="3" y="3" width="7" height="9" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="14" y="3" width="7" height="5" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="14" y="12" width="7" height="9" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="3" y="16" width="7" height="5" rx="1" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{:else if item.icon === "building"}
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M3 21h18M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16" stroke-linecap="round" stroke-linejoin="round" />
<path d="M9 6.5h1.5M9 10h1.5M9 13.5h1.5M13.5 6.5H15M13.5 10H15M13.5 13.5H15M9 21v-4h6v4" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{:else if item.icon === "users"}
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke-linecap="round" stroke-linejoin="round" />
<circle cx="9" cy="7" r="4" />
<path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{/if}
{item.label}
</a>
{/each}
</div>
<!-- Separator and back to dashboard -->
<div class="mt-6">
<Separator class="bg-zinc-800" />
<a
href="/dashboard"
onclick={handleNavClick}
class="mt-4 flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-zinc-400 transition-colors hover:bg-zinc-800/50 hover:text-zinc-200"
>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M19 12H5M12 19l-7-7 7-7" stroke-linecap="round" stroke-linejoin="round" />
</svg>
Back to Dashboard
</a>
</div>
<!-- User section at bottom -->
<div class="mt-auto pt-4">
<Separator class="mb-4 bg-zinc-800" />
<div class="flex items-center gap-3 rounded-lg px-3 py-2">
{#if user?.avatarUrl}
<img src={user.avatarUrl} alt="" class="h-9 w-9 rounded-full object-cover" />
{:else}
<div class="flex h-9 w-9 items-center justify-center rounded-full bg-gradient-to-br from-red-500 to-red-700 text-xs font-semibold text-white">
{initials}
</div>
{/if}
<div class="flex-1">
<p class="text-sm font-medium text-white">{user?.displayName ?? user?.email ?? "Loading..."}</p>
<p class="text-xs text-zinc-400">Admin</p>
</div>
</div>
<div class="mt-2 space-y-1">
<a
href="/account"
onclick={handleNavClick}
class="flex items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-zinc-400 transition-colors hover:bg-zinc-800/50 hover:text-zinc-200"
>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" stroke-linecap="round" stroke-linejoin="round" />
<circle cx="12" cy="7" r="4" />
</svg>
Account Settings
</a>
<button
onclick={handleSignOut}
class="flex w-full items-center gap-3 rounded-lg px-3 py-2.5 text-sm font-medium text-red-400 transition-colors hover:bg-red-500/10"
>
<svg class="h-5 w-5" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4" stroke-linecap="round" stroke-linejoin="round" />
<polyline points="16,17 21,12 16,7" stroke-linecap="round" stroke-linejoin="round" />
<line x1="21" y1="12" x2="9" y2="12" stroke-linecap="round" stroke-linejoin="round" />
</svg>
Sign out
</button>
</div>
</div>
</nav>
</Sheet.Content>
</Sheet.Root>

View File

@@ -0,0 +1,232 @@
<script lang="ts">
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { goto } from "$app/navigation";
import { page } from "$app/stores";
import { api } from "$lib/api/client";
import * as DropdownMenu from "$lib/components/ui/dropdown-menu";
import { cn } from "$lib/utils.js";
interface Props {
class?: string;
}
let { class: className }: Props = $props();
// Fetch current user
const userQuery = createQuery(() => ({
queryKey: ["me"],
queryFn: () => api.me.get(),
}));
const user = $derived(userQuery.data);
// Generate initials from display name or email
const initials = $derived.by(() => {
if (!user) {
return "??";
}
if (user.displayName) {
const parts = user.displayName.split(" ");
if (parts.length >= 2) {
return (
parts[0].charAt(0) + parts[parts.length - 1].charAt(0)
).toUpperCase();
}
return user.displayName.slice(0, 2).toUpperCase();
}
return user.email.slice(0, 2).toUpperCase();
});
const queryClient = useQueryClient();
async function handleSignOut() {
try {
await api.auth.logout();
queryClient.clear();
goto("/login");
} catch (error) {
console.error("Failed to sign out:", error);
}
}
// Admin nav items
const navItems = [
{ icon: "dashboard", href: "/admin", label: "Dashboard" },
{ icon: "building", href: "/admin/orgs", label: "Organizations" },
{ icon: "users", href: "/admin/users", label: "Users" },
];
</script>
<aside
class={cn(
"flex h-screen w-[80px] flex-col items-center bg-zinc-900",
className,
)}
>
<!-- Admin Logo -->
<div class="flex h-[94px] items-center justify-center">
<a
href="/admin"
class="group flex h-8 w-8 items-center justify-center rounded-lg bg-red-600 shadow-sm transition-transform duration-200 hover:scale-105"
aria-label="Admin Home"
>
<svg
class="h-4 w-4 text-white transition-transform duration-200 group-hover:scale-110"
viewBox="0 0 24 24"
fill="none"
stroke="currentColor"
stroke-width="2.5"
>
<path d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" stroke-linecap="round" stroke-linejoin="round" />
</svg>
</a>
</div>
<!-- Main Navigation -->
<nav class="flex flex-1 flex-col items-center gap-3">
{#each navItems as item}
{@const isActive =
item.href === "/admin"
? $page.url.pathname === "/admin"
: $page.url.pathname.startsWith(item.href)}
<a
href={item.href}
class={cn(
"group relative flex h-8 w-8 items-center justify-center rounded-lg transition-all duration-150",
isActive
? "bg-zinc-700 text-white"
: "text-zinc-400 hover:bg-zinc-800 hover:text-zinc-200",
)}
aria-label={item.label}
aria-current={isActive ? "page" : undefined}
>
{#if item.icon === "dashboard"}
{#if isActive}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
<path d="M3 13h8V3H3v10zm0 8h8v-6H3v6zm10 0h8V11h-8v10zm0-18v6h8V3h-8z" />
</svg>
{:else}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<rect x="3" y="3" width="7" height="9" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="14" y="3" width="7" height="5" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="14" y="12" width="7" height="9" rx="1" stroke-linecap="round" stroke-linejoin="round" />
<rect x="3" y="16" width="7" height="5" rx="1" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{/if}
{:else if item.icon === "building"}
{#if isActive}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
<path
fill-rule="evenodd"
d="M4.5 2.25a.75.75 0 000 1.5v16.5h-.75a.75.75 0 000 1.5h16.5a.75.75 0 000-1.5h-.75V3.75a.75.75 0 000-1.5h-15zM9 6a.75.75 0 000 1.5h1.5a.75.75 0 000-1.5H9zm-.75 3.75A.75.75 0 019 9h1.5a.75.75 0 010 1.5H9a.75.75 0 01-.75-.75zM9 12a.75.75 0 000 1.5h1.5a.75.75 0 000-1.5H9zm3.75-5.25A.75.75 0 0113.5 6H15a.75.75 0 010 1.5h-1.5a.75.75 0 01-.75-.75zM13.5 9a.75.75 0 000 1.5H15A.75.75 0 0015 9h-1.5zm-.75 3.75a.75.75 0 01.75-.75H15a.75.75 0 010 1.5h-1.5a.75.75 0 01-.75-.75zM9 19.5v-2.25a.75.75 0 01.75-.75h4.5a.75.75 0 01.75.75v2.25H9z"
clip-rule="evenodd"
/>
</svg>
{:else}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M3 21h18M5 21V5a2 2 0 012-2h10a2 2 0 012 2v16" stroke-linecap="round" stroke-linejoin="round" />
<path d="M9 6.5h1.5M9 10h1.5M9 13.5h1.5M13.5 6.5H15M13.5 10H15M13.5 13.5H15M9 21v-4h6v4" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{/if}
{:else if item.icon === "users"}
{#if isActive}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="currentColor">
<path d="M8.25 6.75a3.75 3.75 0 117.5 0 3.75 3.75 0 01-7.5 0zM15.75 9.75a3 3 0 116 0 3 3 0 01-6 0zM2.25 9.75a3 3 0 116 0 3 3 0 01-6 0zM6.31 15.117A6.745 6.745 0 0112 12a6.745 6.745 0 016.709 7.498.75.75 0 01-.372.568A12.696 12.696 0 0112 21.75c-2.305 0-4.47-.612-6.337-1.684a.75.75 0 01-.372-.568 6.787 6.787 0 011.019-4.38z" />
<path d="M5.082 14.254a8.287 8.287 0 00-1.308 5.135 9.687 9.687 0 01-1.764-.44l-.115-.04a.563.563 0 01-.373-.487l-.01-.121a3.75 3.75 0 013.57-4.047zM20.226 19.389a8.287 8.287 0 00-1.308-5.135 3.75 3.75 0 013.57 4.047l-.01.121a.563.563 0 01-.373.486l-.115.04c-.567.2-1.156.349-1.764.441z" />
</svg>
{:else}
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M17 21v-2a4 4 0 00-4-4H5a4 4 0 00-4 4v2" stroke-linecap="round" stroke-linejoin="round" />
<circle cx="9" cy="7" r="4" />
<path d="M23 21v-2a4 4 0 00-3-3.87M16 3.13a4 4 0 010 7.75" stroke-linecap="round" stroke-linejoin="round" />
</svg>
{/if}
{/if}
<!-- Tooltip -->
<span
class="pointer-events-none absolute left-full ml-3 whitespace-nowrap rounded-md bg-zinc-700 px-2.5 py-1.5 text-xs font-medium text-white opacity-0 shadow-lg transition-all duration-150 group-hover:opacity-100"
>
{item.label}
</span>
</a>
{/each}
</nav>
<!-- Bottom section -->
<div class="flex flex-col items-center gap-3 pb-6">
<!-- Back to Dashboard link -->
<a
href="/dashboard"
class="group relative flex h-8 w-8 items-center justify-center rounded-lg text-zinc-400 transition-all duration-150 hover:bg-zinc-800 hover:text-zinc-200"
aria-label="Back to Dashboard"
>
<svg class="h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M19 12H5M12 19l-7-7 7-7" stroke-linecap="round" stroke-linejoin="round" />
</svg>
<span
class="pointer-events-none absolute left-full ml-3 whitespace-nowrap rounded-md bg-zinc-700 px-2.5 py-1.5 text-xs font-medium text-white opacity-0 shadow-lg transition-all duration-150 group-hover:opacity-100"
>
Back to Dashboard
</span>
</a>
<!-- User Menu -->
<DropdownMenu.Root>
<DropdownMenu.Trigger>
{#snippet child({ props })}
<button
{...props}
class="relative h-6 w-6 overflow-hidden rounded-full ring-1 ring-zinc-700 transition-transform duration-150 hover:scale-110"
aria-label="User menu"
>
{#if user?.avatarUrl}
<img src={user.avatarUrl} alt="" class="h-full w-full object-cover" />
{:else}
<div
class="flex h-full w-full items-center justify-center bg-gradient-to-br from-red-500 to-red-700 text-[10px] font-semibold text-white"
>
{initials}
</div>
{/if}
</button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content class="w-64" side="right" align="end" sideOffset={8}>
<!-- User info header -->
<div class="flex items-center gap-3 p-2">
{#if user?.avatarUrl}
<img src={user.avatarUrl} alt="" class="h-10 w-10 rounded-full object-cover" />
{:else}
<div
class="flex h-10 w-10 items-center justify-center rounded-full bg-gradient-to-br from-red-500 to-red-700 text-sm font-semibold text-white"
>
{initials}
</div>
{/if}
<div class="flex flex-col">
<span class="text-sm font-medium">{user?.displayName ?? user?.email ?? "Loading..."}</span>
<span class="text-xs text-muted-foreground">Admin</span>
</div>
</div>
<DropdownMenu.Separator />
<DropdownMenu.Item onSelect={() => goto("/account")}>
<svg class="mr-2 h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M20 21v-2a4 4 0 00-4-4H8a4 4 0 00-4 4v2" stroke-linecap="round" stroke-linejoin="round" />
<circle cx="12" cy="7" r="4" />
</svg>
Account Settings
</DropdownMenu.Item>
<DropdownMenu.Separator />
<DropdownMenu.Item onSelect={handleSignOut} variant="destructive">
<svg class="mr-2 h-4 w-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.75">
<path d="M9 21H5a2 2 0 01-2-2V5a2 2 0 012-2h4" stroke-linecap="round" stroke-linejoin="round" />
<polyline points="16,17 21,12 16,7" stroke-linecap="round" stroke-linejoin="round" />
<line x1="21" y1="12" x2="9" y2="12" stroke-linecap="round" stroke-linejoin="round" />
</svg>
Sign out
</DropdownMenu.Item>
</DropdownMenu.Content>
</DropdownMenu.Root>
</div>
</aside>

View File

@@ -0,0 +1,4 @@
export { default as AdminHeader } from "./admin-header.svelte";
export { default as AdminLayout } from "./admin-layout.svelte";
export { default as AdminMobileNav } from "./admin-mobile-nav.svelte";
export { default as AdminSidebar } from "./admin-sidebar.svelte";

View File

@@ -1,4 +1,5 @@
<script lang="ts"> <script lang="ts">
import { Settings } from "@lucide/svelte";
import { getContext } from "svelte"; import { getContext } from "svelte";
import { page } from "$app/stores"; import { page } from "$app/stores";
import { cn } from "$lib/utils.js"; import { cn } from "$lib/utils.js";
@@ -68,8 +69,10 @@ const navItems = $derived.by(() => {
<nav class="flex flex-1 flex-col items-center gap-3"> <nav class="flex flex-1 flex-col items-center gap-3">
{#each navItems as item} {#each navItems as item}
{@const isActive = {@const isActive =
$page.url.pathname === item.href || item.icon === "home"
(item.href !== "/" && $page.url.pathname.startsWith(item.href))} ? $page.url.pathname === item.href
: $page.url.pathname === item.href ||
$page.url.pathname.startsWith(item.href + "/")}
<a <a
href={item.href} href={item.href}
class={cn( class={cn(
@@ -153,8 +156,34 @@ const navItems = $derived.by(() => {
</nav> </nav>
<!-- User Menu --> <!-- Bottom section -->
<div class="flex h-[80px] items-center justify-center"> <div class="flex flex-col items-center gap-3 pb-6">
<!-- Settings (only in org context) -->
{#if currentSlug}
{@const isSettingsActive = $page.url.pathname.startsWith(`/dashboard/${currentSlug}/settings`)}
<a
href="/dashboard/{currentSlug}/settings"
class={cn(
"group relative flex h-8 w-8 items-center justify-center rounded-lg transition-all duration-150",
isSettingsActive
? "bg-sidebar-accent text-sidebar-foreground"
: "text-sidebar-muted hover:bg-sidebar-accent/50 hover:text-sidebar-foreground",
)}
aria-label="Settings"
aria-current={isSettingsActive ? "page" : undefined}
>
<Settings class="h-4 w-4" />
<!-- Tooltip -->
<span
class="pointer-events-none absolute left-full ml-3 whitespace-nowrap rounded-md bg-foreground px-2.5 py-1.5 text-xs font-medium text-background opacity-0 shadow-lg transition-all duration-150 group-hover:opacity-100"
>
Settings
</span>
</a>
{/if}
<!-- User Menu -->
<UserMenu /> <UserMenu />
</div> </div>
</aside> </aside>

View File

@@ -0,0 +1,7 @@
export { default as AppHeader } from "./app-header.svelte";
export { default as AppSidebar } from "./app-sidebar.svelte";
export { default as DashboardLayout } from "./dashboard-layout.svelte";
export { default as EmailVerificationBanner } from "./email-verification-banner.svelte";
export { default as MobileNav } from "./mobile-nav.svelte";
export { default as OrgSwitcher } from "./org-switcher.svelte";
export { default as UserMenu } from "./user-menu.svelte";

View File

@@ -1,5 +1,19 @@
export { default as AppHeader } from "./app-header.svelte"; // Admin layout components
export { default as AppSidebar } from "./app-sidebar.svelte"; export {
export { default as DashboardLayout } from "./dashboard-layout.svelte"; AdminHeader,
export { default as EmailVerificationBanner } from "./email-verification-banner.svelte"; AdminLayout,
export { default as MobileNav } from "./mobile-nav.svelte"; AdminMobileNav,
AdminSidebar,
} from "./admin/index.js";
export {
AppHeader,
AppSidebar,
DashboardLayout,
EmailVerificationBanner,
MobileNav,
OrgSwitcher,
UserMenu,
} from "./dashboard/index.js";
// Settings layout components
export { SettingsLayout } from "./settings/index.js";

View File

@@ -0,0 +1 @@
export { default as SettingsLayout } from "./settings-layout.svelte";

View File

@@ -0,0 +1,115 @@
<script lang="ts">
import type { Snippet } from "svelte";
import { Building2, Globe, Settings, Users } from "@lucide/svelte";
import { getContext } from "svelte";
import { page } from "$app/stores";
import { DashboardLayout } from "$lib/components/layout";
import { cn } from "$lib/utils.js";
interface Props {
title: string;
children: Snippet;
}
let { title, children }: Props = $props();
// Get org context from parent layout
const orgContext = getContext<{ slug: string }>("orgContext");
const slug = $derived(orgContext?.slug);
// Settings navigation items
const navItems = $derived.by(() => [
{
href: `/dashboard/${slug}/settings`,
icon: Settings,
label: "General",
description: "Organization name, logo, and preferences",
},
{
href: `/dashboard/${slug}/settings/members`,
icon: Users,
label: "Members",
description: "Manage team members and invitations",
},
{
href: `/dashboard/${slug}/settings/sites`,
icon: Globe,
label: "Sites",
description: "Connected websites and domains",
},
]);
// Determine active item
const activeHref = $derived($page.url.pathname);
function isActive(href: string): boolean {
// Exact match for base settings path
if (href === `/dashboard/${slug}/settings`) {
return activeHref === href;
}
// Prefix match for sub-pages
return activeHref.startsWith(href);
}
</script>
<DashboardLayout title={title}>
<div class="flex flex-col gap-6 lg:flex-row lg:gap-8">
<!-- Settings Navigation -->
<nav class="w-full shrink-0 lg:w-64">
<!-- Mobile: horizontal scroll -->
<div class="flex gap-2 overflow-x-auto pb-2 lg:hidden">
{#each navItems as item}
{@const active = isActive(item.href)}
<a
href={item.href}
class={cn(
"flex shrink-0 items-center gap-2 rounded-lg border px-3 py-2 text-sm font-medium transition-colors",
active
? "border-primary bg-primary/5 text-primary"
: "border-transparent bg-muted/50 text-muted-foreground hover:bg-muted hover:text-foreground",
)}
>
<item.icon class="h-4 w-4" />
{item.label}
</a>
{/each}
</div>
<!-- Desktop: vertical list -->
<div class="hidden space-y-1 lg:block">
{#each navItems as item}
{@const active = isActive(item.href)}
<a
href={item.href}
class={cn(
"group flex items-start gap-3 rounded-lg px-3 py-2.5 transition-colors",
active
? "bg-primary/5 text-foreground"
: "text-muted-foreground hover:bg-muted/50 hover:text-foreground",
)}
>
<div
class={cn(
"mt-0.5 flex h-8 w-8 shrink-0 items-center justify-center rounded-lg transition-colors",
active
? "bg-primary text-primary-foreground"
: "bg-muted text-muted-foreground group-hover:bg-muted-foreground/20",
)}
>
<item.icon class="h-4 w-4" />
</div>
<div class="flex-1 space-y-0.5">
<p class="text-sm font-medium">{item.label}</p>
<p class="text-xs text-muted-foreground">{item.description}</p>
</div>
</a>
{/each}
</div>
</nav>
<!-- Content -->
<div class="min-w-0 flex-1">
{@render children()}
</div>
</div>
</DashboardLayout>

View File

@@ -1,7 +1,7 @@
<script lang="ts"> <script lang="ts">
import type { Snippet } from "svelte"; import type { Snippet } from "svelte";
import { AccountNav } from "$lib/components/account"; import { AccountNav } from "$lib/components/account";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
interface Props { interface Props {
children: Snippet; children: Snippet;

View File

@@ -2,8 +2,7 @@
import { AlertCircle, Building, Loader2, Plus, Users } from "@lucide/svelte"; import { AlertCircle, Building, Loader2, Plus, Users } from "@lucide/svelte";
import { createQuery } from "@tanstack/svelte-query"; import { createQuery } from "@tanstack/svelte-query";
import { api } from "$lib/api/client.js"; import { api } from "$lib/api/client.js";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import { Badge } from "$lib/components/ui/badge/index.js";
import { Button } from "$lib/components/ui/button/index.js"; import { Button } from "$lib/components/ui/button/index.js";
import { import {
Card, Card,
@@ -36,13 +35,8 @@ const hasError = $derived(orgsQuery.error || usersQuery.error);
<title>Admin Dashboard | Publisher Dashboard</title> <title>Admin Dashboard | Publisher Dashboard</title>
</svelte:head> </svelte:head>
<DashboardLayout title="Admin Dashboard"> <AdminLayout title="Dashboard">
<div class="space-y-6"> <div class="space-y-6">
<!-- Admin badge -->
<div class="flex items-center gap-2">
<Badge variant="destructive">Admin</Badge>
</div>
{#if isLoading} {#if isLoading}
<!-- Loading state --> <!-- Loading state -->
<div class="flex flex-col items-center justify-center py-16"> <div class="flex flex-col items-center justify-center py-16">
@@ -109,4 +103,4 @@ const hasError = $derived(orgsQuery.error || usersQuery.error);
</Card> </Card>
{/if} {/if}
</div> </div>
</DashboardLayout> </AdminLayout>

View File

@@ -3,7 +3,7 @@ import { AlertCircle, Building, Eye, Plus, Trash2 } from "@lucide/svelte";
import { createQuery, useQueryClient } from "@tanstack/svelte-query"; import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { toast } from "svelte-sonner"; import { toast } from "svelte-sonner";
import { api } from "$lib/api/client.js"; import { api } from "$lib/api/client.js";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import ConfirmDialog from "$lib/components/org/confirm-dialog.svelte"; import ConfirmDialog from "$lib/components/org/confirm-dialog.svelte";
import { Button } from "$lib/components/ui/button/index.js"; import { Button } from "$lib/components/ui/button/index.js";
import { import {
@@ -80,7 +80,7 @@ async function executeConfirmAction() {
<title>Organizations | Admin | Publisher Dashboard</title> <title>Organizations | Admin | Publisher Dashboard</title>
</svelte:head> </svelte:head>
<DashboardLayout title="Organizations"> <AdminLayout title="Organizations">
<div class="space-y-6"> <div class="space-y-6">
{#if orgsQuery.isPending} {#if orgsQuery.isPending}
<!-- Loading skeleton --> <!-- Loading skeleton -->
@@ -229,7 +229,7 @@ async function executeConfirmAction() {
</div> </div>
{/if} {/if}
</div> </div>
</DashboardLayout> </AdminLayout>
<!-- Confirmation dialog --> <!-- Confirmation dialog -->
<ConfirmDialog <ConfirmDialog

View File

@@ -14,7 +14,7 @@ import { toast } from "svelte-sonner";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { page } from "$app/state"; import { page } from "$app/state";
import { api } from "$lib/api/client"; import { api } from "$lib/api/client";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import { ConfirmDialog } from "$lib/components/org"; import { ConfirmDialog } from "$lib/components/org";
import { Alert, AlertDescription } from "$lib/components/ui/alert"; import { Alert, AlertDescription } from "$lib/components/ui/alert";
import { Button } from "$lib/components/ui/button"; import { Button } from "$lib/components/ui/button";
@@ -220,7 +220,7 @@ async function executeConfirmAction() {
</title> </title>
</svelte:head> </svelte:head>
<DashboardLayout title="Organization Details"> <AdminLayout title="Organization Details">
{#if orgQuery.isPending} {#if orgQuery.isPending}
<div class="flex flex-col items-center justify-center py-16"> <div class="flex flex-col items-center justify-center py-16">
<Loader2 class="h-8 w-8 animate-spin text-muted-foreground" /> <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
@@ -456,7 +456,7 @@ async function executeConfirmAction() {
</Card> </Card>
</div> </div>
{/if} {/if}
</DashboardLayout> </AdminLayout>
<!-- Confirmation dialog --> <!-- Confirmation dialog -->
<ConfirmDialog <ConfirmDialog

View File

@@ -3,7 +3,7 @@ import { ArrowLeft, Loader2 } from "@lucide/svelte";
import { toast } from "svelte-sonner"; import { toast } from "svelte-sonner";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { api } from "$lib/api/client.js"; import { api } from "$lib/api/client.js";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import { Button } from "$lib/components/ui/button/index.js"; import { Button } from "$lib/components/ui/button/index.js";
import { import {
Card, Card,
@@ -74,7 +74,7 @@ function handleSlugInput(event: Event) {
<title>New Organization | Admin | Publisher Dashboard</title> <title>New Organization | Admin | Publisher Dashboard</title>
</svelte:head> </svelte:head>
<DashboardLayout title="New Organization"> <AdminLayout title="New Organization">
<div class="mx-auto max-w-2xl space-y-6"> <div class="mx-auto max-w-2xl space-y-6">
<!-- Back link --> <!-- Back link -->
<a <a
@@ -157,4 +157,4 @@ function handleSlugInput(event: Event) {
</CardContent> </CardContent>
</Card> </Card>
</div> </div>
</DashboardLayout> </AdminLayout>

View File

@@ -3,7 +3,7 @@ import { AlertCircle, Check, Eye, Users, X } from "@lucide/svelte";
import { createQuery } from "@tanstack/svelte-query"; import { createQuery } from "@tanstack/svelte-query";
import { api } from "$lib/api/client.js"; import { api } from "$lib/api/client.js";
import { SuperuserBadge } from "$lib/components/admin/index.js"; import { SuperuserBadge } from "$lib/components/admin/index.js";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import { Button } from "$lib/components/ui/button/index.js"; import { Button } from "$lib/components/ui/button/index.js";
import { import {
Card, Card,
@@ -37,7 +37,7 @@ const usersQuery = createQuery(() => ({
<title>Users | Admin | Publisher Dashboard</title> <title>Users | Admin | Publisher Dashboard</title>
</svelte:head> </svelte:head>
<DashboardLayout title="Users"> <AdminLayout title="Users">
{#if usersQuery.isPending} {#if usersQuery.isPending}
<div class="space-y-6"> <div class="space-y-6">
<Card> <Card>
@@ -141,4 +141,4 @@ const usersQuery = createQuery(() => ({
</Card> </Card>
</div> </div>
{/if} {/if}
</DashboardLayout> </AdminLayout>

View File

@@ -14,7 +14,7 @@ import { toast } from "svelte-sonner";
import { page } from "$app/state"; import { page } from "$app/state";
import { api } from "$lib/api/client.js"; import { api } from "$lib/api/client.js";
import { SuperuserBadge } from "$lib/components/admin/index.js"; import { SuperuserBadge } from "$lib/components/admin/index.js";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { AdminLayout } from "$lib/components/layout";
import { Alert, AlertDescription } from "$lib/components/ui/alert/index.js"; import { Alert, AlertDescription } from "$lib/components/ui/alert/index.js";
import { Button } from "$lib/components/ui/button/index.js"; import { Button } from "$lib/components/ui/button/index.js";
import { import {
@@ -147,7 +147,7 @@ async function handleConfirmEmail() {
<title>{userDetailsQuery.data?.displayName ?? email} | Users | Admin</title> <title>{userDetailsQuery.data?.displayName ?? email} | Users | Admin</title>
</svelte:head> </svelte:head>
<DashboardLayout title="User Details"> <AdminLayout title="User Details">
<!-- Back navigation --> <!-- Back navigation -->
<div class="mb-6"> <div class="mb-6">
<Button variant="ghost" size="sm" href="/admin/users" class="gap-1"> <Button variant="ghost" size="sm" href="/admin/users" class="gap-1">
@@ -345,4 +345,4 @@ async function handleConfirmEmail() {
{/if} {/if}
</div> </div>
{/if} {/if}
</DashboardLayout> </AdminLayout>

View File

@@ -9,7 +9,7 @@ import {
import { createQuery } from "@tanstack/svelte-query"; import { createQuery } from "@tanstack/svelte-query";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { api } from "$lib/api/client"; import { api } from "$lib/api/client";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
import { Badge } from "$lib/components/ui/badge"; import { Badge } from "$lib/components/ui/badge";
import { import {
Card, Card,

View File

@@ -11,7 +11,7 @@ import {
import { createQuery } from "@tanstack/svelte-query"; import { createQuery } from "@tanstack/svelte-query";
import { getContext } from "svelte"; import { getContext } from "svelte";
import { api } from "$lib/api/client"; import { api } from "$lib/api/client";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
import { RoleBadge } from "$lib/components/org"; import { RoleBadge } from "$lib/components/org";
import { Button } from "$lib/components/ui/button"; import { Button } from "$lib/components/ui/button";
import { import {

View File

@@ -11,7 +11,7 @@ import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getContext } from "svelte"; import { getContext } from "svelte";
import { toast } from "svelte-sonner"; import { toast } from "svelte-sonner";
import { api } from "$lib/api/client"; import { api } from "$lib/api/client";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
import { ConfirmDialog, RoleBadge } from "$lib/components/org"; import { ConfirmDialog, RoleBadge } from "$lib/components/org";
import { Button } from "$lib/components/ui/button"; import { Button } from "$lib/components/ui/button";
import { import {

View File

@@ -4,7 +4,7 @@ import FrequentFilters from "$lib/components/dashboard/frequent-filters.svelte";
import MetricCard from "$lib/components/dashboard/metric-card.svelte"; import MetricCard from "$lib/components/dashboard/metric-card.svelte";
import PeakTrafficChart from "$lib/components/dashboard/peak-traffic-chart.svelte"; import PeakTrafficChart from "$lib/components/dashboard/peak-traffic-chart.svelte";
import PerformanceTable from "$lib/components/dashboard/performance-table.svelte"; import PerformanceTable from "$lib/components/dashboard/performance-table.svelte";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
// Get org context (for future filtering by org) // Get org context (for future filtering by org)
const orgContext = getContext<{ slug: string }>("orgContext"); const orgContext = getContext<{ slug: string }>("orgContext");

View File

@@ -1,5 +1,5 @@
<script lang="ts"> <script lang="ts">
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { DashboardLayout } from "$lib/components/layout";
</script> </script>
<svelte:head> <svelte:head>

View File

@@ -12,7 +12,7 @@ import { getContext } from "svelte";
import { toast } from "svelte-sonner"; import { toast } from "svelte-sonner";
import { goto } from "$app/navigation"; import { goto } from "$app/navigation";
import { api } from "$lib/api/client"; import { api } from "$lib/api/client";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte"; import { SettingsLayout } from "$lib/components/layout";
import { ConfirmDialog } from "$lib/components/org"; import { ConfirmDialog } from "$lib/components/org";
import { Alert, AlertDescription } from "$lib/components/ui/alert"; import { Alert, AlertDescription } from "$lib/components/ui/alert";
import { Button } from "$lib/components/ui/button"; import { Button } from "$lib/components/ui/button";
@@ -175,7 +175,7 @@ async function executeConfirmAction() {
<title>Settings | Publisher Dashboard</title> <title>Settings | Publisher Dashboard</title>
</svelte:head> </svelte:head>
<DashboardLayout title="Organization Settings"> <SettingsLayout title="Settings">
{#if isLoading || orgQuery.isPending} {#if isLoading || orgQuery.isPending}
<div class="flex flex-col items-center justify-center py-16"> <div class="flex flex-col items-center justify-center py-16">
<Loader2 class="h-8 w-8 animate-spin text-muted-foreground" /> <Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
@@ -192,7 +192,7 @@ async function executeConfirmAction() {
</p> </p>
</div> </div>
{:else} {:else}
<div class="mx-auto max-w-2xl space-y-6"> <div class="space-y-6">
<!-- General Settings (admin+ only) --> <!-- General Settings (admin+ only) -->
{#if canManageOrg} {#if canManageOrg}
<Card> <Card>
@@ -295,18 +295,9 @@ async function executeConfirmAction() {
</Card> </Card>
{/if} {/if}
<!-- Back link -->
<div class="pt-4">
<a
href="/dashboard/{slug}"
class="text-sm text-muted-foreground hover:text-foreground"
>
&larr; Back to organization
</a>
</div>
</div> </div>
{/if} {/if}
</DashboardLayout> </SettingsLayout>
<!-- Confirmation dialog --> <!-- Confirmation dialog -->
<ConfirmDialog <ConfirmDialog

View File

@@ -0,0 +1,453 @@
<script lang="ts">
import {
AlertCircle,
Clock,
Loader2,
UserPlus,
Users,
X,
} from "@lucide/svelte";
import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getContext } from "svelte";
import { toast } from "svelte-sonner";
import { api } from "$lib/api/client";
import { SettingsLayout } from "$lib/components/layout";
import { ConfirmDialog, RoleBadge } from "$lib/components/org";
import { Button } from "$lib/components/ui/button";
import {
Card,
CardContent,
CardHeader,
CardTitle,
} from "$lib/components/ui/card";
import { Input } from "$lib/components/ui/input";
import { Label } from "$lib/components/ui/label";
import {
Select,
SelectContent,
SelectItem,
SelectTrigger,
} from "$lib/components/ui/select";
import {
Table,
TableBody,
TableCell,
TableHead,
TableHeader,
TableRow,
} from "$lib/components/ui/table";
/**
* Members management settings page
*/
// Types from API contract
type OrgMemberOutput = Awaited<
ReturnType<typeof api.orgs.members.list>
>[number];
type OrgInviteOutput = Awaited<
ReturnType<typeof api.orgs.invites.list>
>[number];
type UserProfile = Awaited<ReturnType<typeof api.me.get>>;
// Get org context from layout
const orgContext = getContext<{
slug: string;
userQuery: { data: UserProfile | undefined };
membersQuery: { data: OrgMemberOutput[] | undefined; isPending: boolean };
currentUserRole: "owner" | "admin" | "member" | null;
canManageOrg: boolean;
isOwner: boolean;
isLoading: boolean;
error: Error | null;
}>("orgContext");
const slug = $derived(orgContext.slug);
const userData = $derived(orgContext.userQuery.data);
const membersData = $derived(orgContext.membersQuery.data);
const currentUserRole = $derived(orgContext.currentUserRole);
const canManageOrg = $derived(orgContext.canManageOrg);
const isOwner = $derived(orgContext.isOwner);
const isLoading = $derived(orgContext.isLoading);
const error = $derived(orgContext.error);
const currentUserId = $derived(userData?.id);
const queryClient = useQueryClient();
// Fetch invites (only for admins+)
const invitesQuery = createQuery(() => ({
queryKey: ["org", slug, "invites"],
queryFn: () => api.orgs.invites.list({ slug }),
enabled: !!slug && canManageOrg,
}));
// Invite form state
let inviteEmail = $state("");
let inviteRole = $state<"member" | "admin" | "owner">("member");
let isInviting = $state(false);
// Confirmation dialog state
let confirmDialogOpen = $state(false);
let confirmDialogTitle = $state("");
let confirmDialogDescription = $state("");
let confirmDialogVariant = $state<"default" | "destructive">("destructive");
let confirmAction = $state<() => Promise<void>>(() => Promise.resolve());
let isConfirmLoading = $state(false);
/**
* Send invite to email
*/
async function handleInvite() {
if (!inviteEmail.trim()) {
toast.error("Please enter an email address");
return;
}
isInviting = true;
try {
await api.orgs.invites.create({
slug,
email: inviteEmail.trim(),
role: inviteRole,
});
toast.success("Invitation sent!");
inviteEmail = "";
inviteRole = "member";
await queryClient.invalidateQueries({ queryKey: ["org", slug, "invites"] });
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to send invitation");
} finally {
isInviting = false;
}
}
/**
* Cancel a pending invite
*/
async function handleCancelInvite(inviteId: number, email: string) {
confirmDialogTitle = "Cancel Invitation";
confirmDialogDescription = `Are you sure you want to cancel the invitation to ${email}?`;
confirmDialogVariant = "destructive";
confirmAction = async () => {
try {
await api.orgs.invites.cancel({ slug, inviteId });
toast.success("Invitation cancelled");
await queryClient.invalidateQueries({
queryKey: ["org", slug, "invites"],
});
} catch (e) {
toast.error(
e instanceof Error ? e.message : "Failed to cancel invitation",
);
}
};
confirmDialogOpen = true;
}
/**
* Update member role
*/
async function handleUpdateRole(
userId: number,
newRole: "owner" | "admin" | "member",
) {
try {
await api.orgs.members.updateRole({ slug, userId, role: newRole });
toast.success("Role updated");
await queryClient.invalidateQueries({ queryKey: ["org", slug, "members"] });
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to update role");
}
}
/**
* Remove member
*/
async function handleRemoveMember(
userId: number,
displayName: string | null,
email: string,
) {
confirmDialogTitle = "Remove Member";
confirmDialogDescription = `Are you sure you want to remove ${displayName || email} from this organization?`;
confirmDialogVariant = "destructive";
confirmAction = async () => {
try {
await api.orgs.members.remove({ slug, userId });
toast.success("Member removed");
await queryClient.invalidateQueries({
queryKey: ["org", slug, "members"],
});
} catch (e) {
toast.error(e instanceof Error ? e.message : "Failed to remove member");
}
};
confirmDialogOpen = true;
}
/**
* Execute confirm action
*/
async function executeConfirmAction() {
isConfirmLoading = true;
try {
await confirmAction();
confirmDialogOpen = false;
} finally {
isConfirmLoading = false;
}
}
/**
* Format relative time
*/
function formatRelativeTime(date: Date): string {
const now = new Date();
const diff = date.getTime() - now.getTime();
const days = Math.ceil(diff / (1000 * 60 * 60 * 24));
if (days < 0) return "Expired";
if (days === 0) return "Today";
if (days === 1) return "Tomorrow";
return `${days} days`;
}
/**
* Check if user can remove a member
*/
function canRemoveMember(memberRole: string, memberId: number): boolean {
if (memberId === currentUserId) return false;
if (isOwner) return true;
if (currentUserRole === "admin" && memberRole === "member") return true;
return false;
}
/**
* Get available roles for invite based on current user's role
*/
const availableInviteRoles = $derived.by(() => {
if (isOwner) return ["member", "admin", "owner"] as const;
if (currentUserRole === "admin") return ["member", "admin"] as const;
return ["member"] as const;
});
</script>
<svelte:head>
<title>Members | Publisher Dashboard</title>
</svelte:head>
<SettingsLayout title="Settings">
{#if isLoading}
<div class="flex flex-col items-center justify-center py-16">
<Loader2 class="h-8 w-8 animate-spin text-muted-foreground" />
<p class="mt-4 text-sm text-muted-foreground">Loading members...</p>
</div>
{:else if error}
<div class="flex flex-col items-center justify-center py-16">
<AlertCircle class="h-8 w-8 text-destructive" />
<p class="mt-4 text-sm text-destructive">
{error instanceof Error ? error.message : "Failed to load members"}
</p>
</div>
{:else}
<div class="space-y-6">
<!-- Invite form (admin+ only) -->
{#if canManageOrg}
<Card>
<CardHeader>
<CardTitle class="flex items-center gap-2 text-base">
<UserPlus class="h-4 w-4" />
Invite Member
</CardTitle>
</CardHeader>
<CardContent>
<form onsubmit={(e) => { e.preventDefault(); handleInvite(); }} class="flex flex-col gap-4 sm:flex-row sm:items-end">
<div class="flex-1 space-y-2">
<Label for="invite-email">Email address</Label>
<Input
id="invite-email"
type="email"
placeholder="colleague@example.com"
bind:value={inviteEmail}
disabled={isInviting}
/>
</div>
<div class="w-full space-y-2 sm:w-32">
<Label for="invite-role">Role</Label>
<Select
type="single"
value={inviteRole}
onValueChange={(v) => { if (v) inviteRole = v as typeof inviteRole; }}
disabled={isInviting}
>
<SelectTrigger id="invite-role" class="w-full">
{inviteRole.charAt(0).toUpperCase() + inviteRole.slice(1)}
</SelectTrigger>
<SelectContent>
{#each availableInviteRoles as role}
<SelectItem value={role} label={role.charAt(0).toUpperCase() + role.slice(1)} />
{/each}
</SelectContent>
</Select>
</div>
<Button type="submit" disabled={isInviting || !inviteEmail.trim()}>
{#if isInviting}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
{/if}
Send Invite
</Button>
</form>
</CardContent>
</Card>
{/if}
<!-- Pending invites (admin+ only) -->
{#if canManageOrg && invitesQuery.data && invitesQuery.data.length > 0}
<Card>
<CardHeader>
<CardTitle class="flex items-center gap-2 text-base">
<Clock class="h-4 w-4" />
Pending Invitations ({invitesQuery.data.length})
</CardTitle>
</CardHeader>
<CardContent>
<Table>
<TableHeader>
<TableRow>
<TableHead>Email</TableHead>
<TableHead>Role</TableHead>
<TableHead>Invited by</TableHead>
<TableHead>Expires</TableHead>
<TableHead class="w-[50px]"></TableHead>
</TableRow>
</TableHeader>
<TableBody>
{#each invitesQuery.data as invite (invite.id)}
<TableRow>
<TableCell class="font-medium">{invite.email}</TableCell>
<TableCell><RoleBadge role={invite.role} /></TableCell>
<TableCell class="text-muted-foreground">{invite.invitedBy}</TableCell>
<TableCell class="text-muted-foreground">
{formatRelativeTime(new Date(invite.expiresAt))}
</TableCell>
<TableCell>
<Button
variant="ghost"
size="icon"
onclick={() => handleCancelInvite(invite.id, invite.email)}
>
<X class="h-4 w-4" />
<span class="sr-only">Cancel</span>
</Button>
</TableCell>
</TableRow>
{/each}
</TableBody>
</Table>
</CardContent>
</Card>
{/if}
<!-- Members list -->
<Card>
<CardHeader>
<CardTitle class="flex items-center gap-2 text-base">
<Users class="h-4 w-4" />
Members ({membersData?.length ?? 0})
</CardTitle>
</CardHeader>
<CardContent>
{#if membersData && membersData.length > 0}
<Table>
<TableHeader>
<TableRow>
<TableHead>Member</TableHead>
<TableHead>Role</TableHead>
<TableHead>Joined</TableHead>
{#if canManageOrg}
<TableHead class="w-[100px]"></TableHead>
{/if}
</TableRow>
</TableHeader>
<TableBody>
{#each membersData as member (member.id)}
{@const isCurrentUser = member.userId === currentUserId}
<TableRow>
<TableCell>
<div class="flex items-center gap-3">
<div class="flex h-8 w-8 items-center justify-center rounded-full bg-gradient-to-br from-primary/20 to-primary/10 text-xs font-medium">
{(member.displayName || member.email).charAt(0).toUpperCase()}
</div>
<div>
<p class="font-medium">
{member.displayName || member.email}
{#if isCurrentUser}
<span class="ml-1 text-xs text-muted-foreground">(You)</span>
{/if}
</p>
{#if member.displayName}
<p class="text-xs text-muted-foreground">{member.email}</p>
{/if}
</div>
</div>
</TableCell>
<TableCell>
{#if isOwner && !isCurrentUser}
<Select
type="single"
value={member.role}
onValueChange={(v) => { if (v) handleUpdateRole(member.userId, v as "owner" | "admin" | "member"); }}
>
<SelectTrigger size="sm" class="h-7 w-24 text-xs">
{member.role.charAt(0).toUpperCase() + member.role.slice(1)}
</SelectTrigger>
<SelectContent>
<SelectItem value="member" label="Member" />
<SelectItem value="admin" label="Admin" />
<SelectItem value="owner" label="Owner" />
</SelectContent>
</Select>
{:else}
<RoleBadge role={member.role} />
{/if}
</TableCell>
<TableCell class="text-muted-foreground">
{new Date(member.createdAt).toLocaleDateString()}
</TableCell>
{#if canManageOrg}
<TableCell>
{#if canRemoveMember(member.role, member.userId)}
<Button
variant="ghost"
size="sm"
class="text-destructive hover:text-destructive"
onclick={() => handleRemoveMember(member.userId, member.displayName, member.email)}
>
Remove
</Button>
{/if}
</TableCell>
{/if}
</TableRow>
{/each}
</TableBody>
</Table>
{:else}
<p class="text-sm text-muted-foreground">No members yet</p>
{/if}
</CardContent>
</Card>
</div>
{/if}
</SettingsLayout>
<!-- Confirmation dialog -->
<ConfirmDialog
bind:open={confirmDialogOpen}
title={confirmDialogTitle}
description={confirmDialogDescription}
variant={confirmDialogVariant}
loading={isConfirmLoading}
onconfirm={executeConfirmAction}
oncancel={() => confirmDialogOpen = false}
/>

View File

@@ -0,0 +1,40 @@
<script lang="ts">
import { Globe } from "@lucide/svelte";
import { SettingsLayout } from "$lib/components/layout";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "$lib/components/ui/card";
</script>
<svelte:head>
<title>Sites | Publisher Dashboard</title>
</svelte:head>
<SettingsLayout title="Settings">
<Card class="border-dashed">
<CardHeader>
<CardTitle class="flex items-center gap-2">
<Globe class="h-5 w-5 text-muted-foreground" />
Sites
</CardTitle>
<CardDescription>
Manage your connected websites and domains.
</CardDescription>
</CardHeader>
<CardContent>
<div class="flex flex-col items-center justify-center py-8 text-center">
<div class="flex h-12 w-12 items-center justify-center rounded-full bg-muted">
<Globe class="h-6 w-6 text-muted-foreground" />
</div>
<h3 class="mt-4 text-sm font-medium">Coming Soon</h3>
<p class="mt-1 text-sm text-muted-foreground">
Site management features are currently in development.
</p>
</div>
</CardContent>
</Card>
</SettingsLayout>

View File

@@ -7,6 +7,7 @@
git git
dbmate dbmate
ast-grep ast-grep
dbip-city-lite
]; ];
dotenv.enable = true; dotenv.enable = true;
@@ -39,6 +40,7 @@
env = { env = {
DATABASE_URL = "postgres://reviq:reviq@localhost/reviq-dashboard?sslmode=disable"; DATABASE_URL = "postgres://reviq:reviq@localhost/reviq-dashboard?sslmode=disable";
TEST_DATABASE_URL = "postgres://reviq:reviq@localhost/reviq-dashboard_test?sslmode=disable"; TEST_DATABASE_URL = "postgres://reviq:reviq@localhost/reviq-dashboard_test?sslmode=disable";
GEOIP_DATABASE_PATH = "${pkgs.dbip-city-lite}/share/dbip/dbip-city-lite.mmdb";
}; };
scripts = { scripts = {

View File

@@ -1,300 +0,0 @@
import type {
AuthenticationResponseJSON,
PublicKeyCredentialCreationOptionsJSON,
PublicKeyCredentialRequestOptionsJSON,
RegistrationResponseJSON,
} from "@simplewebauthn/types";
import {
generateAuthenticationOptions,
generateRegistrationOptions,
verifyAuthenticationResponse,
verifyRegistrationResponse,
} from "@simplewebauthn/server";
import { TRPCError } from "@trpc/server";
import { uniq } from "lodash-es";
const KNOWN_AAGUIDS: Record<string, string> = {
"ea9b8d66-4d01-1d21-3ce4-b6b48cb575d4": "Google Password Manager",
"adce0002-35bc-c60a-648b-0b25f1f05503": "Chrome on Mac",
"08987058-cadc-4b81-b6e1-30de50dcbe96": "Windows Hello",
"9ddd1817-af5a-4672-a2b9-3e3dd95000a9": "Windows Hello",
"6028b017-b1d4-4c02-b4b3-afcdafc96bb2": "Windows Hello",
"dd4ec289-e01d-41c9-bb89-70fa845d4bf2": "iCloud Keychain (Managed)",
"531126d6-e717-415c-9320-3d9aa6981239": "Dashlane",
"bada5566-a7aa-401f-bd96-45619a55120d": "1Password",
"b84e4048-15dc-4dd0-8640-f4f60813c8af": "NordPass",
"0ea242b4-43c4-4a1b-8b17-dd6d0b6baec6": "Keeper",
"891494da-2c90-4d31-a9cd-4eab0aed1309": "Sésame",
"f3809540-7f14-49c1-a8b3-8f813b225541": "Enpass",
"b5397666-4885-aa6b-cebf-e52262a439a2": "Chromium Browser",
"771b48fd-d3d4-4f74-9232-fc157ab0507a": "Edge on Mac",
"39a5647e-1853-446c-a1f6-a79bae9f5bc7": "IDmelon",
"d548826e-79b4-db40-a3d8-11116f7e8349": "Bitwarden",
"fbfc3007-154e-4ecc-8c0b-6e020557d7bd": "iCloud Keychain",
"53414d53-554e-4700-0000-000000000000": "Samsung Pass",
"66a0ccb3-bd6a-191f-ee06-e375c50b9846": "Thales Bio iOS SDK",
"8836336a-f590-0921-301d-46427531eee6": "Thales Bio Android SDK",
"cd69adb5-3c7a-deb9-3177-6800ea6cb72a": "Thales PIN Android SDK",
"17290f1e-c212-34d0-1423-365d729f09d9": "Thales PIN iOS SDK",
"50726f74-6f6e-5061-7373-50726f746f6e": "Proton Pass",
"fdb141b2-5d84-443e-8a35-4698c205a502": "KeePassXC",
"cc45f64e-52a2-451b-831a-4edd8022a202": "ToothPic Passkey Provider",
"bfc748bb-3429-4faa-b9f9-7cfa9f3b76d0": "iPasswords",
"b35a26b2-8f6e-4697-ab1d-d44db4da28c6": "Zoho Vault",
"b78a0a55-6ef8-d246-a042-ba0f6d55050c": "LastPass",
"de503f9c-21a4-4f76-b4b7-558eb55c6f89": "Devolutions",
};
export const getRPInfo = (
ctx: APIContext,
): {
rpName: string;
rpID: string;
origins: string[];
} => {
// RP must always be the frontend URL.
const rpID = ctx.origin.includes("oval.ph")
? "oval.ph"
: new URL(ctx.origin).hostname;
const origins = uniq(
ctx.env.ALLOWED_WEBAUTHN_ORIGINS.split(",").map((o) => new URL(o).origin),
);
return {
rpName: `Oval Business${rpID !== "oval.ph" ? ` (${rpID})` : ""}`,
rpID,
origins,
};
};
export const getUserPasskeys = async (ctx: APIContext, userId: string) => {
const userPasskeys = await fetchPasskeyQuery(ctx.db)
.where("passkeys.user_id", "=", userId)
.execute();
return userPasskeys.map(parsePasskey);
};
export const createRegistrationOptions = async (
ctx: ProtectedAPIContext,
): Promise<{
options: PublicKeyCredentialCreationOptionsJSON;
challengeId: PublicId<"passkey_challenges">;
}> => {
const { rpID, rpName } = getRPInfo(ctx);
const userPasskeys = await getUserPasskeys(ctx, ctx.user.id);
const options: PublicKeyCredentialCreationOptionsJSON =
await generateRegistrationOptions({
rpName,
rpID,
userName: ctx.user.display_name,
// Don't prompt users for additional information about the authenticator
// (Recommended for smoother UX)
attestationType: "direct",
// Prevent users from re-registering existing authenticators
excludeCredentials: userPasskeys.map((passkey) => ({
id: passkey.credentialId,
// Optional
transports: passkey.transports ?? undefined,
})),
// See "Guiding use of authenticators via authenticatorSelection" below
authenticatorSelection: {
// Defaults
residentKey: "preferred",
userVerification: "preferred",
// Optional
authenticatorAttachment: "platform",
},
});
const { public_id } = await ctx.db
.insertInto("passkey_challenges")
.values({
options: JSON.stringify(options),
})
.returning("public_id")
.executeTakeFirstOrThrow();
return {
options,
challengeId: public_id,
};
};
export const verifyRegistration = async (
ctx: ProtectedAPIContext,
{
challengeId,
response,
}: {
challengeId: PublicId<"passkey_challenges">;
response: RegistrationResponseJSON;
},
): Promise<void> => {
const { rpID, origins } = getRPInfo(ctx);
const optionsRaw = await ctx.db
.selectFrom("passkey_challenges")
.where("public_id", "=", challengeId)
.select("options")
.executeTakeFirst();
if (!optionsRaw) {
throw new TRPCError({
code: "TIMEOUT",
message: "Registration timed out. Please try again.",
});
}
const options =
optionsRaw.options as unknown as PublicKeyCredentialCreationOptionsJSON;
let verification;
try {
verification = await verifyRegistrationResponse({
response,
expectedChallenge: options.challenge,
expectedOrigin: origins,
expectedRPID: rpID,
});
} catch (error) {
throw new TRPCError({
code: "BAD_REQUEST",
message: `Invalid registration response. Please try again. ${(error as { message?: string }).message ?? ""}`,
});
} finally {
await ctx.db
.deleteFrom("passkey_challenges")
.where("public_id", "=", challengeId)
.execute();
}
const { verified, registrationInfo } = verification;
if (!(verified && registrationInfo)) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Unable to verify your device.",
});
}
const { credential, credentialDeviceType, credentialBackedUp } =
registrationInfo;
const guidName = KNOWN_AAGUIDS[registrationInfo.aaguid];
const insert: PasskeyInsert = {
credentialId: credential.id,
webAuthnUserId: options.user.id,
counter: BigInt(credential.counter),
deviceType: credentialDeviceType,
backupStatus: credentialBackedUp,
transports: response.response.transports ?? null,
rpid: rpID,
name: `${guidName ?? "Key"} registered at ${formatDateTime(new Date())}`,
publicKey: credential.publicKey,
};
await ctx.db
.insertInto("passkeys")
.values(
passkeyToInsert(insert, {
rawUserId: ctx.user.id,
}),
)
.execute();
};
export const createAuthenticationOptions = async (
ctx: APIContext,
userId: string,
): Promise<{
options: PublicKeyCredentialRequestOptionsJSON;
challengeId: PublicId<"passkey_challenges">;
}> => {
const { rpID } = getRPInfo(ctx);
const userPasskeys = await getUserPasskeys(ctx, userId);
const options = await generateAuthenticationOptions({
rpID,
// Require users to use a previously-registered authenticator
allowCredentials: userPasskeys.map((passkey) => ({
id: passkey.credentialId,
transports: passkey.transports ?? undefined,
})),
});
const { public_id: challengeId } = await ctx.db
.insertInto("passkey_challenges")
.values({
options: JSON.stringify(options),
})
.returning("public_id")
.executeTakeFirstOrThrow();
return {
options,
challengeId: challengeId,
};
};
export const verifyAuthentication = async (
ctx: APIContext,
{
userId,
challengeId,
response,
}: {
userId: string;
challengeId: PublicId<"passkey_challenges">;
response: AuthenticationResponseJSON;
},
): Promise<boolean> => {
const { rpID, origins } = getRPInfo(ctx);
const optionsRaw = await ctx.db
.selectFrom("passkey_challenges")
.where("public_id", "=", challengeId)
.select("options")
.executeTakeFirst();
if (!optionsRaw) {
throw new TRPCError({
code: "TIMEOUT",
message: "Registration timed out. Please try again.",
});
}
const options =
optionsRaw.options as unknown as PublicKeyCredentialRequestOptionsJSON;
try {
const userPasskeys = await getUserPasskeys(ctx, userId);
const passkey = userPasskeys.find(
(passkey) => passkey.credentialId === response.id,
);
if (!passkey) {
throw new TRPCError({
code: "BAD_REQUEST",
message: "Unknown passkey.",
});
}
const verification = await verifyAuthenticationResponse({
response,
expectedChallenge: options.challenge,
expectedOrigin: origins,
expectedRPID: rpID,
credential: {
id: passkey.credentialId,
publicKey: passkey.publicKey,
counter: Number.parseInt(passkey.counter.toString(), 10),
transports: passkey.transports ?? undefined,
},
});
if (!verification.verified) {
return false;
}
await ctx.db
.updateTable("passkeys")
.set((eb) => ({
counter: verification.authenticationInfo.newCounter.toString(),
last_used_at: eb.fn("NOW"),
}))
.where("passkeys.id", "=", passkey.id)
.execute();
} finally {
await ctx.db
.deleteFrom("passkey_challenges")
.where("public_id", "=", challengeId)
.execute();
}
return true;
};