Merge origin/master into reviq-auth-login-command

Resolved conflicts:
- apps/api-server/src/router.ts: Use meRoutes from master
- packages/api-contract/src/contract.ts: Keep master's nested sessions/devices/invites structure, add apiTokens

Co-Authored-By: Claude Opus 4.5 <noreply@anthropic.com>
This commit is contained in:
igm
2026-01-10 19:03:37 +08:00
67 changed files with 5091 additions and 713 deletions

3
.gitignore vendored
View File

@@ -34,6 +34,9 @@ devenv.local.nix
# TypeScript
*.tsbuildinfo
# Test coverage
coverage/
# Debug
npm-debug.log*
yarn-debug.log*

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
- 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`
## 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
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
### Prerequisites
- [Bun](https://bun.sh/) v1.1.42+
- [devenv](https://devenv.sh/) for development environment management
### Environment Variables
@@ -29,9 +72,87 @@ devenv up
This starts:
- PostgreSQL database
- Publisher dashboard dev server (port 6827)
- API server
- Package build watcher
The database is automatically initialized with:
- Database: `reviq-dashboard`
- User: `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

View File

@@ -0,0 +1,9 @@
[test]
# Coverage reporters: text for console, lcov for CI/tooling integration
coverageReporter = ["text", "lcov"]
# Output directory for lcov.info file
coverageDir = "coverage"
# Don't count test files in coverage metrics
coverageSkipTestFiles = true

View File

@@ -13,4 +13,12 @@ export default [
"@typescript-eslint/require-await": "off",
},
},
{
// Disable certain rules for test files that have issues with expect().rejects
files: ["**/__tests__/**/*.ts"],
rules: {
"@typescript-eslint/await-thenable": "off",
"@typescript-eslint/no-confusing-void-expression": "off",
},
},
];

View File

@@ -9,7 +9,8 @@
"typecheck": "tsc --noEmit",
"lint": "eslint . --cache",
"clean": "rm -rf dist .eslintcache",
"test:e2e": "bun test src/__tests__/e2e --no-parallel",
"test:e2e": "bun test src/__tests__/e2e --no-parallel --coverage",
"test:unit": "bun test src/__tests__/unit",
"test": "bun test --coverage src/utils"
},
"dependencies": {

File diff suppressed because it is too large Load Diff

View File

@@ -8,6 +8,14 @@
* - me.updateProfile - update profile fields
* - me.setPassword - set/change password
* - me.delete - delete account
* - me.sessions.list - list all sessions
* - me.sessions.revoke - revoke a session
* - me.sessions.revokeAll - revoke all sessions except current
* - me.devices.getInfo - get current device info
* - me.devices.trust - trust current device
* - me.devices.listTrusted - list trusted devices
* - me.devices.untrust - untrust a device
* - me.devices.revokeAll - revoke all trusted devices
*/
import type { Database } from "@reviq/db-schema";
@@ -59,14 +67,22 @@ function getDb(): Kysely<Database> {
function createAPIContext(options?: {
sessionToken?: string;
apiKey?: string;
deviceFingerprint?: string;
}): APIContext {
const reqHeaders = new Headers();
const cookies: string[] = [];
if (options?.sessionToken) {
reqHeaders.set(
"cookie",
`${COOKIE_NAMES.SESSION_TOKEN}=${options.sessionToken}`,
cookies.push(`${COOKIE_NAMES.SESSION_TOKEN}=${options.sessionToken}`);
}
if (options?.deviceFingerprint) {
cookies.push(
`${COOKIE_NAMES.DEVICE_FINGERPRINT}=${options.deviceFingerprint}`,
);
}
if (cookies.length > 0) {
reqHeaders.set("cookie", cookies.join("; "));
}
if (options?.apiKey) {
reqHeaders.set("x-api-key", options.apiKey);
}
@@ -82,26 +98,81 @@ function createAPIContext(options?: {
}
/**
* Create a real session in the database and return the token
* Create a real session in the database and return the token and session ID
*/
async function createSession(userId: number): Promise<string> {
async function createSession(
userId: number,
options?: { ipAddress?: string; userAgent?: string },
): Promise<{ token: string; sessionId: number }> {
const token = `test-session-${String(Date.now())}${String(Math.random())}`;
const tokenHashValue = await hashToken(token);
const expiresAt = new Date(Date.now() + SESSION_EXPIRY_MS);
await getDb()
const result = await getDb()
.insertInto("sessions")
.values({
user_id: userId,
token_hash: tokenHashValue,
ip_address: "127.0.0.1",
user_agent: "test-agent",
ip_address: options?.ipAddress ?? "127.0.0.1",
user_agent: options?.userAgent ?? "test-agent",
expires_at: expiresAt,
trusted_mode: false,
})
.execute();
.returning("id")
.executeTakeFirstOrThrow();
return token;
return { token, sessionId: Number(result.id) };
}
/**
* Create an authenticated API context for a user (creates session + context)
*/
async function createUserAPIContext(
userId: number,
options?: { deviceFingerprint?: string },
): Promise<{ context: APIContext; token: string }> {
const { token } = await createSession(userId);
const context = createAPIContext({
sessionToken: token,
deviceFingerprint: options?.deviceFingerprint,
});
return { context, token };
}
// Export to suppress unused warning - helper available for future tests
void createUserAPIContext;
/**
* Create a device in the database and return the fingerprint
*/
async function createDevice(
userId: number,
options?: {
fingerprint?: string;
isTrusted?: boolean;
name?: string;
userAgent?: string;
},
): Promise<{ fingerprint: string; deviceId: number }> {
const fingerprint =
options?.fingerprint ??
`test-fp-${String(Date.now())}${String(Math.random())}`;
const result = await getDb()
.insertInto("user_devices")
.values({
user_id: userId,
device_fingerprint: fingerprint,
is_trusted: options?.isTrusted ?? false,
name: options?.name ?? null,
user_agent: options?.userAgent ?? "Mozilla/5.0 Test Browser",
ip_address: "127.0.0.1",
last_used_at: new Date(),
})
.returning("id")
.executeTakeFirstOrThrow();
return { fingerprint, deviceId: Number(result.id) };
}
/**
@@ -158,7 +229,7 @@ describe("me.get", () => {
.where("id", "=", user.id)
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const result = await call(router.me.get, undefined, { context });
@@ -187,7 +258,7 @@ describe("me.get", () => {
.where("id", "=", user.id)
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const result = await call(router.me.get, undefined, { context });
@@ -203,7 +274,7 @@ describe("me.get", () => {
passwordHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const result = await call(router.me.get, undefined, { context });
@@ -217,7 +288,7 @@ describe("me.get", () => {
isSuperuser: true,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const result = await call(router.me.get, undefined, { context });
@@ -233,7 +304,7 @@ describe("me.authStatus", () => {
displayName: "Session User",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const result = await call(router.me.authStatus, undefined, { context });
@@ -279,7 +350,7 @@ describe("me.setupProfile", () => {
.where("id", "=", user.id)
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -315,7 +386,7 @@ describe("me.setupProfile", () => {
.where("id", "=", user.id)
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -345,7 +416,7 @@ describe("me.updateProfile", () => {
displayName: "Original Name",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -371,7 +442,7 @@ describe("me.updateProfile", () => {
displayName: "Original",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -410,7 +481,7 @@ describe("me.updateProfile", () => {
.where("id", "=", user.id)
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -441,7 +512,7 @@ describe("me.updateProfile", () => {
displayName: "Stay Same",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(router.me.updateProfile, {}, { context });
@@ -462,7 +533,7 @@ describe("me.setPassword", () => {
email: "nopass@example.com",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// Use a strong password
@@ -491,7 +562,7 @@ describe("me.setPassword", () => {
passwordHash: oldHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(
@@ -519,10 +590,9 @@ describe("me.setPassword", () => {
passwordHash: oldHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression
await expect(
call(
router.me.setPassword,
@@ -541,10 +611,9 @@ describe("me.setPassword", () => {
passwordHash: oldHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression
await expect(
call(
router.me.setPassword,
@@ -562,13 +631,13 @@ describe("me.setPassword", () => {
email: "weak@example.com",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// Password must be at least 8 chars to pass schema validation
// "password" passes length check but fails zxcvbn strength check
// zxcvbn provides feedback like "This is a top-10 common password"
// eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression
await expect(
call(
router.me.setPassword,
@@ -590,7 +659,7 @@ describe("me.delete", () => {
passwordHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(router.me.delete, { password }, { context });
@@ -610,10 +679,9 @@ describe("me.delete", () => {
email: "nopassdelete@example.com",
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression
await expect(
call(router.me.delete, { password: "anything" }, { context }),
).rejects.toThrow("Cannot delete account without a password");
@@ -626,10 +694,9 @@ describe("me.delete", () => {
passwordHash,
});
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// eslint-disable-next-line @typescript-eslint/await-thenable, @typescript-eslint/no-confusing-void-expression
await expect(
call(router.me.delete, { password: "WrongPassword123!" }, { context }),
).rejects.toThrow("Incorrect password");
@@ -654,7 +721,7 @@ describe("me.delete", () => {
})
.execute();
const sessionToken = await createSession(user.id);
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(router.me.delete, { password }, { context });
@@ -669,3 +736,573 @@ describe("me.delete", () => {
expect(tokens).toHaveLength(0);
});
});
// ===== Session Management Tests =====
describe("me.sessions.list", () => {
test("returns all sessions for user", async () => {
const user = await createTestUser(getDb(), {
email: "sessions@example.com",
});
// Create multiple sessions
const { token: sessionToken1 } = await createSession(user.id, {
ipAddress: "192.168.1.1",
userAgent: "Chrome/1.0",
});
await createSession(user.id, {
ipAddress: "192.168.1.2",
userAgent: "Firefox/1.0",
});
await createSession(user.id, {
ipAddress: "192.168.1.3",
userAgent: "Safari/1.0",
});
const context = createAPIContext({ sessionToken: sessionToken1 });
const sessions = await call(router.me.sessions.list, undefined, {
context,
});
expect(sessions).toHaveLength(3);
// Sessions should be ordered by created_at desc
expect(sessions[0]?.userAgent).toBe("Safari/1.0");
expect(sessions[1]?.userAgent).toBe("Firefox/1.0");
expect(sessions[2]?.userAgent).toBe("Chrome/1.0");
});
test("marks current session with isCurrent flag", async () => {
const user = await createTestUser(getDb(), {
email: "current@example.com",
});
const { token: sessionToken1, sessionId: id1 } = await createSession(
user.id,
);
const { sessionId: id2 } = await createSession(user.id);
const context = createAPIContext({ sessionToken: sessionToken1 });
const sessions = await call(router.me.sessions.list, undefined, {
context,
});
expect(sessions).toHaveLength(2);
const current = sessions.find((s) => s.id === id1);
const other = sessions.find((s) => s.id === id2);
expect(current?.isCurrent).toBe(true);
expect(other?.isCurrent).toBe(false);
});
test("returns session metadata correctly", async () => {
const user = await createTestUser(getDb(), {
email: "metadata@example.com",
});
// Create session and update with location data
const { token: sessionToken, sessionId } = await createSession(user.id, {
ipAddress: "8.8.8.8",
userAgent: "TestAgent/1.0",
});
await getDb()
.updateTable("sessions")
.set({
city: "San Francisco",
region: "CA",
country: "US",
trusted_mode: true,
})
.where("id", "=", String(sessionId))
.execute();
const context = createAPIContext({ sessionToken });
const sessions = await call(router.me.sessions.list, undefined, {
context,
});
expect(sessions).toHaveLength(1);
const session = sessions[0];
expect(session?.ip).toBe("8.8.8.8");
expect(session?.userAgent).toBe("TestAgent/1.0");
expect(session?.city).toBe("San Francisco");
expect(session?.region).toBe("CA");
expect(session?.country).toBe("US");
expect(session?.trustedMode).toBe(true);
expect(session?.createdAt).toBeInstanceOf(Date);
expect(session?.revokedAt).toBeNull();
});
});
describe("me.sessions.revoke", () => {
test("revokes another session successfully", async () => {
const user = await createTestUser(getDb(), {
email: "revoke@example.com",
});
const { token: sessionToken1 } = await createSession(user.id);
const { sessionId: sessionId2 } = await createSession(user.id);
const context = createAPIContext({ sessionToken: sessionToken1 });
await call(
router.me.sessions.revoke,
{ sessionId: sessionId2 },
{ context },
);
// Verify session is revoked
const session = await getDb()
.selectFrom("sessions")
.select(["revoked_at"])
.where("id", "=", String(sessionId2))
.executeTakeFirstOrThrow();
expect(session.revoked_at).not.toBeNull();
});
test("fails to revoke current session", async () => {
const user = await createTestUser(getDb(), {
email: "revokecurrent@example.com",
});
const { token: sessionToken, sessionId } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.sessions.revoke, { sessionId }, { context }),
).rejects.toThrow("Cannot revoke current session");
});
test("fails to revoke non-existent session", async () => {
const user = await createTestUser(getDb(), {
email: "revokenotfound@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.sessions.revoke, { sessionId: 999999 }, { context }),
).rejects.toThrow("Session not found");
});
test("fails to revoke already revoked session", async () => {
const user = await createTestUser(getDb(), {
email: "revokeagain@example.com",
});
const { token: sessionToken1 } = await createSession(user.id);
const { sessionId: sessionId2 } = await createSession(user.id);
// Revoke the session directly
await getDb()
.updateTable("sessions")
.set({ revoked_at: new Date() })
.where("id", "=", String(sessionId2))
.execute();
const context = createAPIContext({ sessionToken: sessionToken1 });
await expect(
call(router.me.sessions.revoke, { sessionId: sessionId2 }, { context }),
).rejects.toThrow("Session not found");
});
test("fails to revoke another user's session", async () => {
const user1 = await createTestUser(getDb(), {
email: "user1@example.com",
});
const user2 = await createTestUser(getDb(), {
email: "user2@example.com",
});
const { token: sessionToken1 } = await createSession(user1.id);
const { sessionId: sessionId2 } = await createSession(user2.id);
const context = createAPIContext({ sessionToken: sessionToken1 });
await expect(
call(router.me.sessions.revoke, { sessionId: sessionId2 }, { context }),
).rejects.toThrow("Session not found");
});
});
describe("me.sessions.revokeAll", () => {
test("revokes all sessions except current", async () => {
const user = await createTestUser(getDb(), {
email: "revokeall@example.com",
});
const { token: sessionToken1, sessionId: id1 } = await createSession(
user.id,
);
const { sessionId: id2 } = await createSession(user.id);
const { sessionId: id3 } = await createSession(user.id);
const context = createAPIContext({ sessionToken: sessionToken1 });
await call(router.me.sessions.revokeAll, undefined, { context });
// Verify current session is NOT revoked
const currentSession = await getDb()
.selectFrom("sessions")
.select(["revoked_at"])
.where("id", "=", String(id1))
.executeTakeFirstOrThrow();
expect(currentSession.revoked_at).toBeNull();
// Verify other sessions ARE revoked
const otherSessions = await getDb()
.selectFrom("sessions")
.select(["id", "revoked_at"])
.where("id", "in", [String(id2), String(id3)])
.execute();
for (const session of otherSessions) {
expect(session.revoked_at).not.toBeNull();
}
});
test("does nothing when only current session exists", async () => {
const user = await createTestUser(getDb(), {
email: "onlyone@example.com",
});
const { token: sessionToken, sessionId } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// Should not throw
await call(router.me.sessions.revokeAll, undefined, { context });
// Current session should still be valid
const session = await getDb()
.selectFrom("sessions")
.select(["revoked_at"])
.where("id", "=", String(sessionId))
.executeTakeFirstOrThrow();
expect(session.revoked_at).toBeNull();
});
});
// ===== Device Management Tests =====
describe("me.devices.getInfo", () => {
test("returns device info for current device", async () => {
const user = await createTestUser(getDb(), {
email: "deviceinfo@example.com",
});
const { fingerprint, deviceId } = await createDevice(user.id, {
name: "My MacBook",
isTrusted: true,
userAgent: "Safari/17.0",
});
// Update with location data
await getDb()
.updateTable("user_devices")
.set({
ip_address: "1.2.3.4",
city: "New York",
region: "NY",
country: "US",
})
.where("id", "=", String(deviceId))
.execute();
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({
sessionToken,
deviceFingerprint: fingerprint,
});
const info = await call(router.me.devices.getInfo, undefined, { context });
expect(info.id).toBe(deviceId);
expect(info.name).toBe("My MacBook");
expect(info.ip).toBe("1.2.3.4");
expect(info.city).toBe("New York");
expect(info.region).toBe("NY");
expect(info.country).toBe("US");
expect(info.isTrusted).toBe(true);
expect(info.lastUsedAt).toBeInstanceOf(Date);
});
test("returns default name from user agent when name is null", async () => {
const user = await createTestUser(getDb(), {
email: "defaultname@example.com",
});
const { fingerprint } = await createDevice(user.id, {
userAgent: "Mozilla/5.0 (Macintosh)",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({
sessionToken,
deviceFingerprint: fingerprint,
});
const info = await call(router.me.devices.getInfo, undefined, { context });
expect(info.name).toBe("Mozilla device");
});
test("fails without device fingerprint", async () => {
const user = await createTestUser(getDb(), {
email: "nofingerprint@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.devices.getInfo, undefined, { context }),
).rejects.toThrow("No device fingerprint found");
});
test("fails when device does not exist", async () => {
const user = await createTestUser(getDb(), {
email: "nodevice@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({
sessionToken,
deviceFingerprint: "nonexistent-fingerprint",
});
await expect(
call(router.me.devices.getInfo, undefined, { context }),
).rejects.toThrow("Device not found");
});
});
describe("me.devices.trust", () => {
test("trusts current device with name", async () => {
const user = await createTestUser(getDb(), {
email: "trustdevice@example.com",
});
const { fingerprint, deviceId } = await createDevice(user.id, {
isTrusted: false,
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({
sessionToken,
deviceFingerprint: fingerprint,
});
await call(
router.me.devices.trust,
{ name: "My Work Laptop" },
{ context },
);
// Verify device is trusted with the new name
const device = await getDb()
.selectFrom("user_devices")
.select(["is_trusted", "name"])
.where("id", "=", String(deviceId))
.executeTakeFirstOrThrow();
expect(device.is_trusted).toBe(true);
expect(device.name).toBe("My Work Laptop");
});
test("fails without device fingerprint", async () => {
const user = await createTestUser(getDb(), {
email: "trustnofp@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.devices.trust, { name: "Test" }, { context }),
).rejects.toThrow("No device fingerprint found");
});
test("fails when device does not exist", async () => {
const user = await createTestUser(getDb(), {
email: "trustnodevice@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({
sessionToken,
deviceFingerprint: "nonexistent",
});
await expect(
call(router.me.devices.trust, { name: "Test" }, { context }),
).rejects.toThrow("Device not found");
});
});
describe("me.devices.listTrusted", () => {
test("returns only trusted devices", async () => {
const user = await createTestUser(getDb(), {
email: "listtrusted@example.com",
});
// Create trusted and untrusted devices
await createDevice(user.id, { isTrusted: true, name: "Trusted 1" });
await createDevice(user.id, { isTrusted: true, name: "Trusted 2" });
await createDevice(user.id, { isTrusted: false, name: "Untrusted" });
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const devices = await call(router.me.devices.listTrusted, undefined, {
context,
});
expect(devices).toHaveLength(2);
expect(devices.map((d) => d.name).sort()).toEqual([
"Trusted 1",
"Trusted 2",
]);
expect(devices.every((d) => d.isTrusted)).toBe(true);
});
test("returns empty list when no trusted devices", async () => {
const user = await createTestUser(getDb(), {
email: "notrusted@example.com",
});
await createDevice(user.id, { isTrusted: false });
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const devices = await call(router.me.devices.listTrusted, undefined, {
context,
});
expect(devices).toHaveLength(0);
});
test("returns default name when device name is null", async () => {
const user = await createTestUser(getDb(), {
email: "defaulttrusted@example.com",
});
await createDevice(user.id, {
isTrusted: true,
name: undefined,
userAgent: "Chrome/120",
});
// Set name to null explicitly
await getDb()
.updateTable("user_devices")
.set({ name: null })
.where("user_id", "=", user.id)
.execute();
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
const devices = await call(router.me.devices.listTrusted, undefined, {
context,
});
expect(devices).toHaveLength(1);
expect(devices[0]?.name).toBe("Unknown device");
});
});
describe("me.devices.untrust", () => {
test("untrusts device by ID", async () => {
const user = await createTestUser(getDb(), {
email: "untrust@example.com",
});
const { deviceId } = await createDevice(user.id, {
isTrusted: true,
name: "Trusted Device",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(router.me.devices.untrust, { deviceId }, { context });
// Verify device is untrusted
const device = await getDb()
.selectFrom("user_devices")
.select(["is_trusted"])
.where("id", "=", String(deviceId))
.executeTakeFirstOrThrow();
expect(device.is_trusted).toBe(false);
});
test("fails to untrust non-existent device", async () => {
const user = await createTestUser(getDb(), {
email: "untrustnotfound@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.devices.untrust, { deviceId: 999999 }, { context }),
).rejects.toThrow("Device not found");
});
test("fails to untrust another user's device", async () => {
const user1 = await createTestUser(getDb(), {
email: "untrustuser1@example.com",
});
const user2 = await createTestUser(getDb(), {
email: "untrustuser2@example.com",
});
const { deviceId } = await createDevice(user2.id, { isTrusted: true });
const { token: sessionToken } = await createSession(user1.id);
const context = createAPIContext({ sessionToken });
await expect(
call(router.me.devices.untrust, { deviceId }, { context }),
).rejects.toThrow("Device not found");
});
});
describe("me.devices.revokeAll", () => {
test("untrusts all devices", async () => {
const user = await createTestUser(getDb(), {
email: "revokealldevices@example.com",
});
await createDevice(user.id, { isTrusted: true });
await createDevice(user.id, { isTrusted: true });
await createDevice(user.id, { isTrusted: false });
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
await call(router.me.devices.revokeAll, undefined, { context });
// All devices should be untrusted
const devices = await getDb()
.selectFrom("user_devices")
.select(["id", "is_trusted"])
.where("user_id", "=", user.id)
.execute();
expect(devices).toHaveLength(3);
expect(devices.every((d) => !d.is_trusted)).toBe(true);
});
test("works when no devices exist", async () => {
const user = await createTestUser(getDb(), {
email: "revokenodevices@example.com",
});
const { token: sessionToken } = await createSession(user.id);
const context = createAPIContext({ sessionToken });
// Should not throw
await call(router.me.devices.revokeAll, undefined, { context });
});
});

View File

@@ -9,15 +9,13 @@
import type { Database } from "@reviq/db-schema";
import type { Kysely } from "kysely";
import type {
APIContext,
AuthenticatedContext,
LoginRequestContext,
} from "../../context.js";
import type { APIContext } from "../../context.js";
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { call } from "@orpc/server";
import { VirtualAuthenticator } from "@reviq/virtual-authenticator";
import { router } from "../../router.js";
import { COOKIE_NAMES } from "../../utils/cookies.js";
import { hashToken } from "../../utils/crypto.js";
import { getUserPasskeys } from "../../utils/webauthn.js";
import { KNOWN_AAGUIDS, TEST_RP } from "../helpers/test-constants.js";
import {
@@ -28,6 +26,9 @@ import {
truncateAllTables,
} from "../helpers/test-db.js";
/** Session expiry duration: 24 hours in milliseconds */
const SESSION_EXPIRY_MS = 24 * 60 * 60 * 1000;
let db: Kysely<Database> | undefined;
/**
@@ -41,67 +42,93 @@ function getDb(): Kysely<Database> {
}
/**
* Create an API context (for public endpoints)
* Create an API context with optional session token
*/
function createAPIContext(): APIContext {
function createAPIContext(sessionToken?: string): APIContext {
const reqHeaders = new Headers();
if (sessionToken) {
reqHeaders.set("cookie", `${COOKIE_NAMES.SESSION_TOKEN}=${sessionToken}`);
}
return {
db: getDb(),
origin: TEST_RP.origin,
allowedOrigins: [...TEST_RP.allowedOrigins],
rpName: TEST_RP.rpName,
reqHeaders: new Headers(),
reqHeaders,
resHeaders: new Headers(),
};
}
/**
* Create an authenticated context (for protected endpoints)
* Create a real session in the database and return the token
*/
function createAuthenticatedContext(
userId: number,
email: string,
): AuthenticatedContext {
const now = new Date();
return {
...createAPIContext(),
user: {
id: userId,
email,
displayName: null,
emailVerifiedAt: null,
isSuperuser: false,
},
session: {
id: "1",
trustedMode: false,
createdAt: now,
},
auth: {
method: "session",
sessionId: "1",
expiresAt: new Date(now.getTime() + 24 * 60 * 60 * 1000),
createdAt: now,
},
};
async function createSession(userId: number): Promise<string> {
const token = `test-session-${String(Date.now())}${String(Math.random())}`;
const tokenHashValue = await hashToken(token);
const expiresAt = new Date(Date.now() + SESSION_EXPIRY_MS);
await getDb()
.insertInto("sessions")
.values({
user_id: userId,
token_hash: tokenHashValue,
ip_address: "127.0.0.1",
user_agent: "test-agent",
expires_at: expiresAt,
trusted_mode: false,
})
.execute();
return token;
}
/**
* Create a login request context (for login flow endpoints)
* Create a login request in the database and return ID and token
*/
function createLoginRequestContext(
async function createLoginRequest(
userId: number,
email: string,
): LoginRequestContext {
return {
...createAPIContext(),
loginRequestId: 1,
user: {
id: userId,
): Promise<{ id: number; token: string }> {
const token = `test-login-${String(Date.now())}${String(Math.random())}`;
const expiresAt = new Date(Date.now() + 10 * 60 * 1000); // 10 minutes
const result = await getDb()
.insertInto("login_requests")
.values({
user_id: userId,
email,
displayName: null,
emailVerifiedAt: null,
isSuperuser: false,
},
token,
expires_at: expiresAt,
})
.returning("id")
.executeTakeFirstOrThrow();
return { id: Number(result.id), token };
}
/**
* Create an authenticated API context for a user (creates session + context)
*/
async function createUserAPIContext(userId: number): Promise<APIContext> {
const sessionToken = await createSession(userId);
return createAPIContext(sessionToken);
}
/**
* Create an API context with login request cookie
*/
function createLoginRequestContext(loginToken: string): APIContext {
const reqHeaders = new Headers();
reqHeaders.set("cookie", `${COOKIE_NAMES.LOGIN_REQUEST_TOKEN}=${loginToken}`);
return {
db: getDb(),
origin: TEST_RP.origin,
allowedOrigins: [...TEST_RP.allowedOrigins],
rpName: TEST_RP.rpName,
reqHeaders,
resHeaders: new Headers(),
};
}
@@ -127,7 +154,7 @@ async function registerPasskey(
authenticator: VirtualAuthenticator,
) {
const apiCtx = createAPIContext();
const authCtx = createAuthenticatedContext(userId, email);
const authCtx = await createUserAPIContext(userId);
const { options, challengeId } = await call(
router.auth.webauthn.createRegistrationOptions,
@@ -152,7 +179,8 @@ async function authenticate(
email: string,
authenticator: VirtualAuthenticator,
) {
const loginCtx = createLoginRequestContext(userId, email);
const { token: loginToken } = await createLoginRequest(userId, email);
const loginCtx = createLoginRequestContext(loginToken);
const { options, challengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
@@ -234,8 +262,8 @@ describe("registration flow", () => {
// Create credential with virtual authenticator
const response = authenticator.createCredential(options);
// Verify registration via router
const authCtx = createAuthenticatedContext(user.id, user.email);
// Verify registration via router (requires authenticated session)
const authCtx = await createUserAPIContext(user.id);
await call(
router.auth.webauthn.verifyRegistration,
{ challengeId, response },
@@ -256,7 +284,7 @@ describe("registration flow", () => {
});
const authenticator = new VirtualAuthenticator({ origin: TEST_RP.origin });
const apiCtx = createAPIContext();
const authCtx = createAuthenticatedContext(user.id, user.email);
const authCtx = await createUserAPIContext(user.id);
// Register first passkey via router
const { options: options1, challengeId: challengeId1 } = await call(
@@ -299,7 +327,7 @@ describe("registration flow", () => {
});
const apiCtx = createAPIContext();
const authCtx = createAuthenticatedContext(user.id, user.email);
const authCtx = await createUserAPIContext(user.id);
const { options, challengeId } = await call(
router.auth.webauthn.createRegistrationOptions,
@@ -325,7 +353,7 @@ describe("registration flow", () => {
});
const authenticator = new VirtualAuthenticator({ origin: TEST_RP.origin });
const apiCtx = createAPIContext();
const authCtx = createAuthenticatedContext(user.id, user.email);
const authCtx = await createUserAPIContext(user.id);
const { options, challengeId } = await call(
router.auth.webauthn.createRegistrationOptions,
@@ -355,7 +383,7 @@ describe("registration flow", () => {
});
const authenticator = new VirtualAuthenticator({ origin: TEST_RP.origin });
const apiCtx = createAPIContext();
const authCtx = createAuthenticatedContext(user.id, user.email);
const authCtx = await createUserAPIContext(user.id);
// Create options via router
const { options } = await call(
@@ -399,7 +427,8 @@ describe("authentication flow", () => {
);
// Create authentication options via router
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options, challengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -427,7 +456,8 @@ describe("authentication flow", () => {
await registerPasskey(user.id, user.email, authenticator);
// Authenticate via router
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options: authOptions, challengeId: authChallengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -460,7 +490,8 @@ describe("authentication flow", () => {
expect(firstPasskey.lastUsedAt).toBeNull();
// Authenticate via router
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options: authOptions, challengeId: authChallengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -489,7 +520,8 @@ describe("authentication flow", () => {
await registerPasskey(user.id, user.email, authenticator);
// Authenticate via router
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options: authOptions, challengeId: authChallengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -522,7 +554,8 @@ describe("authentication flow", () => {
await registerPasskey(user.id, user.email, authenticator);
// Create auth options via router
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options: authOptions } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -585,7 +618,8 @@ describe("security tests", () => {
authenticator.setSignCount(regResponse.id, 0);
// Create a new authentication challenge
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options, challengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -624,7 +658,8 @@ describe("security tests", () => {
await registerPasskey(user.id, user.email, authenticator);
// Create authentication challenge
const loginCtx = createLoginRequestContext(user.id, user.email);
const { token: loginToken } = await createLoginRequest(user.id, user.email);
const loginCtx = createLoginRequestContext(loginToken);
const { options, challengeId } = await call(
router.auth.webauthn.createAuthenticationOptions,
undefined,
@@ -755,7 +790,7 @@ describe("passkey management", () => {
await registerPasskey(user.id, user.email, authenticator2);
// List passkeys via router handler
const ctx = createAuthenticatedContext(user.id, user.email);
const ctx = await createUserAPIContext(user.id);
const passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx,
});
@@ -806,7 +841,7 @@ describe("passkey management", () => {
await registerPasskey(user.id, user.email, authenticator);
const ctx = createAuthenticatedContext(user.id, user.email);
const ctx = await createUserAPIContext(user.id);
let passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx,
});
@@ -842,8 +877,8 @@ describe("passkey management", () => {
await registerPasskey(user1.id, user1.email, auth1);
await registerPasskey(user2.id, user2.email, auth2);
const ctx1 = createAuthenticatedContext(user1.id, user1.email);
const ctx2 = createAuthenticatedContext(user2.id, user2.email);
const ctx1 = await createUserAPIContext(user1.id);
const ctx2 = await createUserAPIContext(user2.id);
const user2Passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx2,
@@ -853,12 +888,18 @@ describe("passkey management", () => {
throw new Error("Expected user2 passkey to exist");
}
// Try to rename user2's passkey using user1's context (should not work)
await call(
router.me.passkeys.rename,
{ passkeyId: user2FirstPasskey.id, name: "Hacked Name" },
{ context: ctx1 },
);
// Try to rename user2's passkey using user1's context (should throw NOT_FOUND)
try {
await call(
router.me.passkeys.rename,
{ passkeyId: user2FirstPasskey.id, name: "Hacked Name" },
{ context: ctx1 },
);
throw new Error("Expected rename to fail with NOT_FOUND");
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toContain("Passkey not found");
}
// User2's passkey should be unchanged
const user2PasskeysAfter = await call(router.me.passkeys.list, undefined, {
@@ -880,7 +921,7 @@ describe("passkey management", () => {
await registerPasskey(user.id, user.email, authenticator);
const ctx = createAuthenticatedContext(user.id, user.email);
const ctx = await createUserAPIContext(user.id);
let passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx,
});
@@ -906,7 +947,7 @@ describe("passkey management", () => {
await registerPasskey(user.id, user.email, auth1);
await registerPasskey(user.id, user.email, auth2);
const ctx = createAuthenticatedContext(user.id, user.email);
const ctx = await createUserAPIContext(user.id);
let passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx,
});
@@ -937,7 +978,7 @@ describe("passkey management", () => {
await registerPasskey(user.id, user.email, authenticator);
const ctx = createAuthenticatedContext(user.id, user.email);
const ctx = await createUserAPIContext(user.id);
const passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx,
});
@@ -978,8 +1019,8 @@ describe("passkey management", () => {
await registerPasskey(user1.id, user1.email, auth1);
await registerPasskey(user2.id, user2.email, auth2);
const ctx1 = createAuthenticatedContext(user1.id, user1.email);
const ctx2 = createAuthenticatedContext(user2.id, user2.email);
const ctx1 = await createUserAPIContext(user1.id);
const ctx2 = await createUserAPIContext(user2.id);
const user2Passkeys = await call(router.me.passkeys.list, undefined, {
context: ctx2,
@@ -989,12 +1030,18 @@ describe("passkey management", () => {
throw new Error("Expected user2 passkey to exist");
}
// Try to delete user2's passkey using user1's context (should not affect user2)
await call(
router.me.passkeys.delete,
{ passkeyId: user2FirstPasskey.id },
{ context: ctx1 },
);
// Try to delete user2's passkey using user1's context (should throw NOT_FOUND)
try {
await call(
router.me.passkeys.delete,
{ passkeyId: user2FirstPasskey.id },
{ context: ctx1 },
);
throw new Error("Expected delete to fail with NOT_FOUND");
} catch (error) {
expect(error).toBeInstanceOf(Error);
expect((error as Error).message).toContain("Passkey not found");
}
// User2's passkey should still exist
const user2PasskeysAfter = await call(router.me.passkeys.list, undefined, {

View File

@@ -4,6 +4,7 @@
import type { Database } from "@reviq/db-schema";
import type { Kysely } from "kysely";
import { existsSync } from "node:fs";
import { join } from "node:path";
import { createDb } from "@reviq/db";
import { sql } from "kysely";
@@ -134,13 +135,13 @@ async function ensureTestDatabaseExists(): Promise<void> {
*
* @throws Error if repo root cannot be found
*/
async function findRepoRoot(): Promise<string> {
function findRepoRoot(): string {
let current = import.meta.dir;
// Walk up to 10 levels to find the repo root
for (let i = 0; i < 10; i++) {
const migrationsPath = join(current, "db", "migrations");
if (await Bun.file(migrationsPath).exists()) {
if (existsSync(migrationsPath)) {
return current;
}
const parent = join(current, "..");
@@ -166,7 +167,7 @@ export async function runMigrations(): Promise<void> {
// Ensure the database exists first
await ensureTestDatabaseExists();
const repoRoot = await findRepoRoot();
const repoRoot = findRepoRoot();
const proc = Bun.spawn(["dbmate", "up"], {
env: { ...process.env, DATABASE_URL: testDbUrl },

View File

@@ -21,6 +21,8 @@ export interface APIContext {
reqHeaders: Headers;
/** Response headers (for setting cookies) */
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({
port,
async fetch(request) {
async fetch(request, server) {
const url = new URL(request.url);
if (url.pathname.startsWith("/api/v1/rpc")) {
@@ -50,6 +50,10 @@ Bun.serve({
// Create response headers for setting cookies
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 = {
db,
origin,
@@ -57,6 +61,7 @@ Bun.serve({
rpName,
reqHeaders: request.headers,
resHeaders,
clientIP,
};
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;
// Get geo info and user agent
const geo = getGeoInfo(context.reqHeaders);
const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders);
// Create login request with secure token

View File

@@ -86,7 +86,7 @@ export const loginIfRequestIsCompleted =
}
// Get current request info
const geo = getGeoInfo(context.reqHeaders);
const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders);
// 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
const geo = getGeoInfo(context.reqHeaders);
const geo = getGeoInfo(context.reqHeaders, context.clientIP);
const userAgent = getUserAgent(context.reqHeaders);
let userId: number;

View File

@@ -0,0 +1,63 @@
/**
* Me routes - consolidated exports for os.router()
*/
import { createApiToken, deleteApiToken, listApiTokens } from "./api-tokens.js";
import { meAuthStatus } from "./auth-status.js";
import { meDelete } from "./delete.js";
import {
getDeviceInfo,
listTrustedDevices,
revokeAllTrustedDevices,
trustDevice,
untrustDevice,
} from "./devices.js";
import { meGet } from "./get.js";
import {
acceptInvite,
declineInvite,
getInvite,
listInvites,
} from "./invites.js";
import { deletePasskey, listPasskeys, renamePasskey } from "./passkeys.js";
import { listSessions, revokeAllSessions, revokeSession } from "./sessions.js";
import { setPassword } from "./set-password.js";
import { setupProfile } from "./setup-profile.js";
import { updateProfile } from "./update-profile.js";
export const meRoutes = {
get: meGet,
authStatus: meAuthStatus,
setupProfile,
updateProfile,
delete: meDelete,
setPassword,
passkeys: {
list: listPasskeys,
rename: renamePasskey,
delete: deletePasskey,
},
invites: {
list: listInvites,
get: getInvite,
accept: acceptInvite,
decline: declineInvite,
},
sessions: {
list: listSessions,
revoke: revokeSession,
revokeAll: revokeAllSessions,
},
devices: {
getInfo: getDeviceInfo,
trust: trustDevice,
listTrusted: listTrustedDevices,
untrust: untrustDevice,
revokeAll: revokeAllTrustedDevices,
},
apiTokens: {
list: listApiTokens,
create: createApiToken,
delete: deleteApiToken,
},
};

View File

@@ -0,0 +1,41 @@
/**
* Get current user auth status
*/
import { authMiddleware, os } from "../base.js";
export const meAuthStatus = os.me.authStatus
.use(authMiddleware)
.handler(async ({ context }) => {
const user = await context.db
.selectFrom("users")
.select([
"id",
"email",
"display_name",
"full_name",
"phone_number",
"avatar_url",
"email_verified_at",
"is_superuser",
"password_hash",
])
.where("id", "=", context.user.id)
.executeTakeFirstOrThrow();
return {
user: {
id: user.id,
email: user.email,
displayName: user.display_name,
fullName: user.full_name,
phoneNumber: user.phone_number,
avatarUrl: user.avatar_url,
emailVerified: user.email_verified_at !== null,
needsSetup: user.display_name === null,
isSuperuser: user.is_superuser,
hasPassword: user.password_hash !== null,
},
auth: context.auth,
};
});

View File

@@ -13,7 +13,7 @@ import { defaultDeviceName, requireDeviceFingerprint } from "./helpers.js";
* @throws BAD_REQUEST if no device fingerprint found
* @throws NOT_FOUND if device doesn't exist
*/
export const getDeviceInfo = os.me.getDeviceInfo
export const getDeviceInfo = os.me.devices.getInfo
.use(authMiddleware)
.handler(async ({ context }) => {
const fingerprint = requireDeviceFingerprint(context.reqHeaders);
@@ -48,7 +48,7 @@ export const getDeviceInfo = os.me.getDeviceInfo
* @throws BAD_REQUEST if no device fingerprint found
* @throws NOT_FOUND if device doesn't exist
*/
export const trustDevice = os.me.trustDevice
export const trustDevice = os.me.devices.trust
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { name } = input;
@@ -73,7 +73,7 @@ export const trustDevice = os.me.trustDevice
* - Requires authentication
* - Returns all trusted devices for the current user
*/
export const listTrustedDevices = os.me.listTrustedDevices
export const listTrustedDevices = os.me.devices.listTrusted
.use(authMiddleware)
.handler(async ({ context }) => {
const devices = await context.db
@@ -102,7 +102,7 @@ export const listTrustedDevices = os.me.listTrustedDevices
* - Marks device as untrusted by ID
* @throws NOT_FOUND if device doesn't exist
*/
export const untrustDevice = os.me.untrustDevice
export const untrustDevice = os.me.devices.untrust
.use(authMiddleware)
.handler(async ({ input, context }) => {
const result = await context.db
@@ -124,7 +124,7 @@ export const untrustDevice = os.me.untrustDevice
* - Requires authentication
* - Marks all devices as untrusted
*/
export const revokeAllTrustedDevices = os.me.revokeAllTrustedDevices
export const revokeAllTrustedDevices = os.me.devices.revokeAll
.use(authMiddleware)
.handler(async ({ context }) => {
await context.db

View File

@@ -0,0 +1,38 @@
/**
* Get current user profile
*/
import { authMiddleware, os } from "../base.js";
export const meGet = os.me.get
.use(authMiddleware)
.handler(async ({ context }) => {
const user = await context.db
.selectFrom("users")
.select([
"id",
"email",
"display_name",
"full_name",
"phone_number",
"avatar_url",
"email_verified_at",
"is_superuser",
"password_hash",
])
.where("id", "=", context.user.id)
.executeTakeFirstOrThrow();
return {
id: user.id,
email: user.email,
displayName: user.display_name,
fullName: user.full_name,
phoneNumber: user.phone_number,
avatarUrl: user.avatar_url,
emailVerified: user.email_verified_at !== null,
needsSetup: user.display_name === null,
isSuperuser: user.is_superuser,
hasPassword: user.password_hash !== null,
};
});

View File

@@ -10,6 +10,12 @@ export {
trustDevice,
untrustDevice,
} from "./devices.js";
export {
acceptInvite,
declineInvite,
getInvite,
listInvites,
} from "./invites.js";
export { deletePasskey, listPasskeys, renamePasskey } from "./passkeys.js";
export {
listSessions,

View File

@@ -0,0 +1,211 @@
/**
* User invite procedures - list, get, decline invites for the current user
*/
import { ORPCError } from "@orpc/server";
import { authMiddleware, os } from "../base.js";
/**
* List pending invites for the current user
* Only returns invites where the user's email matches and email is verified
*/
export const listInvites = os.me.invites.list
.use(authMiddleware)
.handler(async ({ context }) => {
// Only show invites if email is verified
if (!context.user.emailVerifiedAt) {
return [];
}
// Get non-expired invites matching user's email
const invites = await context.db
.selectFrom("org_invites")
.innerJoin("orgs", "orgs.id", "org_invites.org_id")
.innerJoin("users", "users.id", "org_invites.invited_by")
.where("org_invites.email", "=", context.user.email.toLowerCase())
.where("org_invites.expires_at", ">", new Date())
.select([
"org_invites.id",
"org_invites.role",
"org_invites.created_at",
"org_invites.expires_at",
"orgs.id as org_id",
"orgs.slug as org_slug",
"orgs.display_name as org_display_name",
"orgs.logo_url as org_logo_url",
"users.display_name as inviter_name",
"users.email as inviter_email",
])
.orderBy("org_invites.created_at", "desc")
.execute();
return invites.map((i) => ({
id: i.id,
org: {
id: i.org_id,
slug: i.org_slug,
displayName: i.org_display_name,
logoUrl: i.org_logo_url,
},
role: i.role,
invitedBy: i.inviter_name ?? i.inviter_email,
createdAt: i.created_at,
expiresAt: i.expires_at,
}));
});
/**
* Get a specific invite by ID
* Only returns if the invite belongs to the current user's email
*/
export const getInvite = os.me.invites.get
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { inviteId } = input;
// Only show invite if email is verified
if (!context.user.emailVerifiedAt) {
throw new ORPCError("FORBIDDEN", {
message: "Please verify your email to view invitations",
});
}
// Get the invite matching user's email
const invite = await context.db
.selectFrom("org_invites")
.innerJoin("orgs", "orgs.id", "org_invites.org_id")
.innerJoin("users", "users.id", "org_invites.invited_by")
.where("org_invites.id", "=", inviteId)
.where("org_invites.email", "=", context.user.email.toLowerCase())
.where("org_invites.expires_at", ">", new Date())
.select([
"org_invites.id",
"org_invites.role",
"org_invites.created_at",
"org_invites.expires_at",
"orgs.id as org_id",
"orgs.slug as org_slug",
"orgs.display_name as org_display_name",
"orgs.logo_url as org_logo_url",
"users.display_name as inviter_name",
"users.email as inviter_email",
])
.executeTakeFirst();
if (!invite) {
throw new ORPCError("NOT_FOUND", {
message: "Invitation not found or expired",
});
}
return {
id: invite.id,
org: {
id: invite.org_id,
slug: invite.org_slug,
displayName: invite.org_display_name,
logoUrl: invite.org_logo_url,
},
role: invite.role,
invitedBy: invite.inviter_name ?? invite.inviter_email,
createdAt: invite.created_at,
expiresAt: invite.expires_at,
};
});
/**
* Accept an invite by ID
* Adds user to org and deletes the invite
*/
export const acceptInvite = os.me.invites.accept
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { inviteId } = input;
// Only allow accepting if email is verified
if (!context.user.emailVerifiedAt) {
throw new ORPCError("FORBIDDEN", {
message: "Please verify your email to accept invitations",
});
}
// Get the invite matching user's email
const invite = await context.db
.selectFrom("org_invites")
.where("id", "=", inviteId)
.where("email", "=", context.user.email.toLowerCase())
.where("expires_at", ">", new Date())
.select(["id", "org_id", "role"])
.executeTakeFirst();
if (!invite) {
throw new ORPCError("NOT_FOUND", {
message: "Invitation not found or expired",
});
}
try {
// Accept the invite in a transaction
await context.db.transaction().execute(async (trx) => {
// Add user as a member
await trx
.insertInto("org_members")
.values({
org_id: invite.org_id,
user_id: context.user.id,
role: invite.role,
})
.execute();
// Delete the invite
await trx
.deleteFrom("org_invites")
.where("id", "=", invite.id)
.execute();
});
} catch (error) {
// Handle unique constraint violation (user is already a member)
if (
error instanceof Error &&
error.message.includes("org_members_org_id_user_id_key")
) {
// Clean up the invite since user is already a member
await context.db
.deleteFrom("org_invites")
.where("id", "=", invite.id)
.execute();
throw new ORPCError("CONFLICT", {
message: "You are already a member of this organization",
});
}
throw error;
}
return { success: true };
});
/**
* Decline an invite
* Deletes the invite if it belongs to the current user's email
*/
export const declineInvite = os.me.invites.decline
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { inviteId } = input;
// Delete the invite only if it matches user's email
const result = await context.db
.deleteFrom("org_invites")
.where("id", "=", inviteId)
.where("email", "=", context.user.email.toLowerCase())
.executeTakeFirst();
if (!result.numDeletedRows || result.numDeletedRows === 0n) {
throw new ORPCError("NOT_FOUND", {
message: "Invitation not found",
});
}
return { success: true };
});

View File

@@ -11,7 +11,7 @@ import { authMiddleware, os } from "../base.js";
* - Returns all sessions for the current user
* - Includes isCurrent flag to identify active session
*/
export const listSessions = os.me.listSessions
export const listSessions = os.me.sessions.list
.use(authMiddleware)
.handler(async ({ context }) => {
const sessions = await context.db
@@ -42,7 +42,7 @@ export const listSessions = os.me.listSessions
* @throws NOT_FOUND if session doesn't exist
* @throws BAD_REQUEST if trying to revoke current session
*/
export const revokeSession = os.me.revokeSession
export const revokeSession = os.me.sessions.revoke
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { sessionId } = input;
@@ -74,7 +74,7 @@ export const revokeSession = os.me.revokeSession
* - Requires authentication
* - Revokes all sessions except current
*/
export const revokeAllSessions = os.me.revokeAllSessions
export const revokeAllSessions = os.me.sessions.revokeAll
.use(authMiddleware)
.handler(async ({ context }) => {
// Revoke all sessions except current

View File

@@ -0,0 +1,24 @@
/**
* Setup user profile (initial setup after signup)
*/
import { authMiddleware, os } from "../base.js";
export const setupProfile = os.me.setupProfile
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { displayName, fullName, phoneNumber } = input;
await context.db
.updateTable("users")
.set({
display_name: displayName,
full_name: fullName ?? null,
phone_number: phoneNumber ?? null,
updated_at: new Date(),
})
.where("id", "=", context.user.id)
.execute();
return { success: true };
});

View File

@@ -15,31 +15,7 @@ import {
loginRequestMiddleware,
os,
} from "./procedures/base.js";
import {
createApiToken,
deleteApiToken,
listApiTokens,
} from "./procedures/me/api-tokens.js";
import { meDelete } from "./procedures/me/delete.js";
import {
getDeviceInfo,
listTrustedDevices,
revokeAllTrustedDevices,
trustDevice,
untrustDevice,
} from "./procedures/me/devices.js";
import {
deletePasskey,
listPasskeys,
renamePasskey,
} from "./procedures/me/passkeys.js";
import {
listSessions,
revokeAllSessions,
revokeSession,
} from "./procedures/me/sessions.js";
import { setPassword } from "./procedures/me/set-password.js";
import { updateProfile } from "./procedures/me/update-profile.js";
import { meRoutes } from "./procedures/me/_routes.js";
import {
invitesAccept,
invitesCancel,
@@ -169,105 +145,6 @@ const verifyAuthentication = os.auth.webauthn.verifyAuthentication
return { success: true };
});
// Me procedures
const meGet = os.me.get.use(authMiddleware).handler(async ({ context }) => {
const user = await context.db
.selectFrom("users")
.select([
"id",
"email",
"display_name",
"full_name",
"phone_number",
"avatar_url",
"email_verified_at",
"is_superuser",
"password_hash",
])
.where("id", "=", context.user.id)
.executeTakeFirstOrThrow();
return {
id: user.id,
email: user.email,
displayName: user.display_name,
fullName: user.full_name,
phoneNumber: user.phone_number,
avatarUrl: user.avatar_url,
emailVerified: user.email_verified_at !== null,
needsSetup: user.display_name === null,
isSuperuser: user.is_superuser,
hasPassword: user.password_hash !== null,
};
});
const meAuthStatus = os.me.authStatus
.use(authMiddleware)
.handler(async ({ context }) => {
const user = await context.db
.selectFrom("users")
.select([
"id",
"email",
"display_name",
"full_name",
"phone_number",
"avatar_url",
"email_verified_at",
"is_superuser",
"password_hash",
])
.where("id", "=", context.user.id)
.executeTakeFirstOrThrow();
return {
user: {
id: user.id,
email: user.email,
displayName: user.display_name,
fullName: user.full_name,
phoneNumber: user.phone_number,
avatarUrl: user.avatar_url,
emailVerified: user.email_verified_at !== null,
needsSetup: user.display_name === null,
isSuperuser: user.is_superuser,
hasPassword: user.password_hash !== null,
},
auth: context.auth,
};
});
const setupProfile = os.me.setupProfile
.use(authMiddleware)
.handler(async ({ input, context }) => {
const { displayName, fullName, phoneNumber } = input;
await context.db
.updateTable("users")
.set({
display_name: displayName,
full_name: fullName ?? null,
phone_number: phoneNumber ?? null,
updated_at: new Date(),
})
.where("id", "=", context.user.id)
.execute();
return { success: true };
});
// Me procedures imported from ./procedures/me/*
// - updateProfile, setPassword, meDelete
// - listPasskeys, renamePasskey, deletePasskey
// - listSessions, revokeSession, revokeAllSessions
// - getDeviceInfo, trustDevice, listTrustedDevices, untrustDevice, revokeAllTrustedDevices
// Orgs procedures - imported from ./procedures/orgs/index.js
// - orgsList, orgsCreate, orgsGet, orgsUpdate, orgsDelete, orgsLeave
// - membersList, membersUpdateRole, membersRemove
// - invitesList, invitesCreate, invitesCancel, invitesAccept
// - sitesList
// Build the router
export const router = os.router({
auth: {
@@ -288,32 +165,7 @@ export const router = os.router({
verifyAuthentication,
},
},
me: {
get: meGet,
authStatus: meAuthStatus,
setupProfile,
updateProfile,
delete: meDelete,
setPassword,
passkeys: {
list: listPasskeys,
rename: renamePasskey,
delete: deletePasskey,
},
listSessions,
revokeSession,
revokeAllSessions,
getDeviceInfo,
trustDevice,
listTrustedDevices,
untrustDevice,
revokeAllTrustedDevices,
apiTokens: {
list: listApiTokens,
create: createApiToken,
delete: deleteApiToken,
},
},
me: meRoutes,
orgs: {
list: orgsList,
create: orgsCreate,

View File

@@ -126,9 +126,16 @@ export const lookupGeoFromIP = (
/**
* Extract geolocation info from request headers.
* 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 => {
const ip = extractClientIP(headers);
export const getGeoInfo = (
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
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

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

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">
import { Settings } from "@lucide/svelte";
import { getContext } from "svelte";
import { page } from "$app/stores";
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">
{#each navItems as item}
{@const isActive =
$page.url.pathname === item.href ||
(item.href !== "/" && $page.url.pathname.startsWith(item.href))}
item.icon === "home"
? $page.url.pathname === item.href
: $page.url.pathname === item.href ||
$page.url.pathname.startsWith(item.href + "/")}
<a
href={item.href}
class={cn(
@@ -153,8 +156,34 @@ const navItems = $derived.by(() => {
</nav>
<!-- User Menu -->
<div class="flex h-[80px] items-center justify-center">
<!-- Bottom section -->
<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 />
</div>
</aside>

View File

@@ -0,0 +1,42 @@
<script lang="ts">
import type { Snippet } from "svelte";
import { createQuery } from "@tanstack/svelte-query";
import { api } from "$lib/api/client";
import { cn } from "$lib/utils.js";
import AppHeader from "./app-header.svelte";
import AppSidebar from "./app-sidebar.svelte";
import EmailVerificationBanner from "./email-verification-banner.svelte";
interface Props {
title: string;
children: Snippet;
class?: string;
}
let { title, children, class: className }: Props = $props();
const userQuery = createQuery(() => ({
queryKey: ["me"],
queryFn: () => api.me.get(),
}));
</script>
<div class="flex h-screen overflow-hidden bg-background">
<!-- Desktop sidebar - hidden on mobile -->
<div class="hidden lg:block">
<AppSidebar />
</div>
<div class="flex flex-1 flex-col overflow-hidden">
{#if userQuery.data && !userQuery.data.emailVerified}
<EmailVerificationBanner email={userQuery.data.email} />
{/if}
<AppHeader {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,69 @@
<script lang="ts">
import { Loader2, Mail, RefreshCw } from "@lucide/svelte";
import { toast } from "svelte-sonner";
import { api } from "$lib/api/client";
import { Button } from "$lib/components/ui/button";
interface Props {
email: string;
}
let { email }: Props = $props();
let resendCooldown = $state(0);
let isResending = $state(false);
// Handle cooldown timer
$effect(() => {
if (resendCooldown > 0) {
const timer = setTimeout(() => {
resendCooldown -= 1;
}, 1000);
return () => clearTimeout(timer);
}
});
async function handleResend() {
isResending = true;
try {
await api.auth.resendVerificationEmail();
resendCooldown = 60;
toast.success("Verification email sent!");
} catch (err) {
toast.error(err instanceof Error ? err.message : "Failed to send email");
} finally {
isResending = false;
}
}
</script>
<div
class="flex items-center justify-between gap-4 border-b border-amber-500/30 bg-amber-500/10 px-4 py-3"
>
<div class="flex items-center gap-3">
<Mail class="h-4 w-4 shrink-0 text-amber-600 dark:text-amber-400" />
<p class="text-sm text-amber-700 dark:text-amber-300">
Please verify your email address at
<span class="font-medium">{email}</span>
</p>
</div>
<Button
variant="outline"
size="sm"
disabled={resendCooldown > 0 || isResending}
onclick={handleResend}
class="shrink-0 border-amber-500/50 text-amber-700 hover:bg-amber-500/20 dark:text-amber-300"
>
{#if isResending}
<Loader2 class="h-4 w-4 animate-spin" />
Sending...
{:else if resendCooldown > 0}
<RefreshCw class="h-4 w-4" />
Resend ({resendCooldown}s)
{:else}
<RefreshCw class="h-4 w-4" />
Resend verification email
{/if}
</Button>
</div>

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

@@ -43,7 +43,7 @@ function handleOrgSelect(slug: string) {
</button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content class="w-56" side="right" sideOffset={8}>
<DropdownMenu.Content class="w-56" side="right" align="start" sideOffset={8}>
<DropdownMenu.Label>Organizations</DropdownMenu.Label>
<DropdownMenu.Separator />
{#if orgsQuery.isPending}

View File

@@ -70,7 +70,7 @@ async function handleSignOut() {
</button>
{/snippet}
</DropdownMenu.Trigger>
<DropdownMenu.Content class="w-64" side="right" sideOffset={8}>
<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}

View File

@@ -1,4 +1,18 @@
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 MobileNav } from "./mobile-nav.svelte";
// Admin layout components
export {
AdminHeader,
AdminLayout,
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">
import type { Snippet } from "svelte";
import { AccountNav } from "$lib/components/account";
import DashboardLayout from "$lib/components/layout/dashboard-layout.svelte";
import { DashboardLayout } from "$lib/components/layout";
interface Props {
children: Snippet;

View File

@@ -28,12 +28,12 @@ const queryClient = useQueryClient();
const devicesQuery = createQuery(() => ({
queryKey: ["trustedDevices"],
queryFn: () => api.me.listTrustedDevices(),
queryFn: () => api.me.devices.listTrusted(),
}));
const currentDeviceQuery = createQuery(() => ({
queryKey: ["deviceInfo"],
queryFn: () => api.me.getDeviceInfo(),
queryFn: () => api.me.devices.getInfo(),
}));
// Get current device fingerprint from comparison
@@ -106,7 +106,7 @@ async function handleRemoveTrust() {
isRemoving = true;
try {
await api.me.untrustDevice({ deviceId: selectedDeviceId });
await api.me.devices.untrust({ deviceId: selectedDeviceId });
await queryClient.invalidateQueries({ queryKey: ["trustedDevices"] });
toast.success("Device trust removed");
confirmDialogOpen = false;
@@ -125,7 +125,7 @@ async function handleRemoveAllTrust() {
isRemovingAll = true;
try {
await api.me.revokeAllTrustedDevices();
await api.me.devices.revokeAll();
await queryClient.invalidateQueries({ queryKey: ["trustedDevices"] });
toast.success("All trusted devices removed");
confirmAllDialogOpen = false;

View File

@@ -0,0 +1,243 @@
<script lang="ts">
import {
AlertCircle,
ArrowLeft,
Building2,
Calendar,
CheckCircle2,
Clock,
Loader2,
User,
XCircle,
} from "@lucide/svelte";
import {
createMutation,
createQuery,
useQueryClient,
} from "@tanstack/svelte-query";
import { toast } from "svelte-sonner";
import { goto } from "$app/navigation";
import { page } from "$app/state";
import { api } from "$lib/api/client";
import { Alert, AlertDescription } from "$lib/components/ui/alert";
import { Button } from "$lib/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "$lib/components/ui/card";
import { LoadingButton } from "$lib/components/ui/loading-button";
import { Separator } from "$lib/components/ui/separator";
const inviteId = $derived(Number(page.params.inviteId));
const queryClient = useQueryClient();
// Fetch the invite details
const inviteQuery = createQuery(() => ({
queryKey: ["me", "invites", inviteId],
queryFn: () => api.me.invites.get({ inviteId }),
enabled: !Number.isNaN(inviteId),
}));
// Accept mutation
const acceptMutation = createMutation(() => ({
mutationFn: () => api.me.invites.accept({ inviteId }),
onSuccess: () => {
toast.success("You've joined the organization!");
// Invalidate queries
queryClient.invalidateQueries({ queryKey: ["me", "invites"] });
queryClient.invalidateQueries({ queryKey: ["orgs"] });
// Redirect to the org dashboard
if (inviteQuery.data) {
goto(`/dashboard/${inviteQuery.data.org.slug}`);
} else {
goto("/dashboard");
}
},
onError: (error) => {
toast.error(
error instanceof Error ? error.message : "Failed to accept invitation",
);
},
}));
// Decline mutation
const declineMutation = createMutation(() => ({
mutationFn: () => api.me.invites.decline({ inviteId }),
onSuccess: () => {
toast.success("Invitation declined");
// Invalidate queries
queryClient.invalidateQueries({ queryKey: ["me", "invites"] });
goto("/dashboard");
},
onError: (error) => {
toast.error(
error instanceof Error ? error.message : "Failed to decline invitation",
);
},
}));
/**
* Format role for display
*/
function formatRole(role: string): string {
return role.charAt(0).toUpperCase() + role.slice(1);
}
/**
* Format date for display
*/
function formatDate(date: Date): string {
return date.toLocaleDateString("en-US", {
month: "long",
day: "numeric",
year: "numeric",
});
}
/**
* Check if invite is expiring soon (within 3 days)
*/
function isExpiringSoon(expiresAt: Date): boolean {
const threeDaysFromNow = new Date();
threeDaysFromNow.setDate(threeDaysFromNow.getDate() + 3);
return expiresAt < threeDaysFromNow;
}
</script>
<svelte:head>
<title>Organization Invitation | Publisher Dashboard</title>
</svelte:head>
<div class="space-y-6">
<!-- Back link -->
<Button variant="ghost" size="sm" href="/dashboard" class="-ml-2">
<ArrowLeft class="mr-2 h-4 w-4" />
Back to Dashboard
</Button>
{#if inviteQuery.isPending}
<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 invitation...</p>
</div>
{:else if inviteQuery.error}
<Alert variant="destructive">
<AlertCircle class="h-4 w-4" />
<AlertDescription>
{inviteQuery.error instanceof Error ? inviteQuery.error.message : "Failed to load invitation"}
</AlertDescription>
</Alert>
<Button variant="outline" href="/dashboard">
Go to Dashboard
</Button>
{:else if inviteQuery.data}
{@const invite = inviteQuery.data}
<Card>
<CardHeader>
<div class="flex items-start gap-4">
{#if invite.org.logoUrl}
<img
src={invite.org.logoUrl}
alt="{invite.org.displayName} logo"
class="h-16 w-16 rounded-xl object-cover"
/>
{:else}
<div class="flex h-16 w-16 items-center justify-center rounded-xl bg-gradient-to-br from-primary/20 to-primary/10">
<Building2 class="h-8 w-8 text-primary" />
</div>
{/if}
<div class="flex-1">
<CardTitle class="text-xl">{invite.org.displayName}</CardTitle>
<CardDescription class="mt-1">
You've been invited to join this organization
</CardDescription>
</div>
</div>
</CardHeader>
<CardContent class="space-y-6">
<!-- Invite details -->
<div class="grid gap-4 sm:grid-cols-2">
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
<User class="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p class="text-sm font-medium">Role</p>
<p class="text-sm text-muted-foreground">{formatRole(invite.role)}</p>
</div>
</div>
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
<User class="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p class="text-sm font-medium">Invited by</p>
<p class="text-sm text-muted-foreground">{invite.invitedBy}</p>
</div>
</div>
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-muted">
<Calendar class="h-5 w-5 text-muted-foreground" />
</div>
<div>
<p class="text-sm font-medium">Sent on</p>
<p class="text-sm text-muted-foreground">{formatDate(new Date(invite.createdAt))}</p>
</div>
</div>
<div class="flex items-center gap-3">
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-muted {isExpiringSoon(new Date(invite.expiresAt)) ? 'bg-warning/10' : ''}">
<Clock class="h-5 w-5 {isExpiringSoon(new Date(invite.expiresAt)) ? 'text-warning' : 'text-muted-foreground'}" />
</div>
<div>
<p class="text-sm font-medium">Expires on</p>
<p class="text-sm {isExpiringSoon(new Date(invite.expiresAt)) ? 'text-warning' : 'text-muted-foreground'}">
{formatDate(new Date(invite.expiresAt))}
</p>
</div>
</div>
</div>
{#if isExpiringSoon(new Date(invite.expiresAt))}
<Alert>
<Clock class="h-4 w-4" />
<AlertDescription>
This invitation will expire soon. Accept it before {formatDate(new Date(invite.expiresAt))} to join the organization.
</AlertDescription>
</Alert>
{/if}
<Separator />
<!-- Actions -->
<div class="flex flex-col gap-3 sm:flex-row sm:justify-end">
<Button
variant="outline"
disabled={acceptMutation.isPending || declineMutation.isPending}
onclick={() => declineMutation.mutate()}
>
{#if declineMutation.isPending}
<Loader2 class="mr-2 h-4 w-4 animate-spin" />
Declining...
{:else}
<XCircle class="mr-2 h-4 w-4" />
Decline
{/if}
</Button>
<LoadingButton
loading={acceptMutation.isPending}
disabled={declineMutation.isPending}
loadingText="Joining..."
onclick={() => acceptMutation.mutate()}
>
<CheckCircle2 class="mr-2 h-4 w-4" />
Accept & Join
</LoadingButton>
</div>
</CardContent>
</Card>
{/if}
</div>

View File

@@ -30,7 +30,7 @@ const queryClient = useQueryClient();
const sessionsQuery = createQuery(() => ({
queryKey: ["sessions"],
queryFn: () => api.me.listSessions(),
queryFn: () => api.me.sessions.list(),
}));
let confirmDialogOpen = $state(false);
@@ -121,7 +121,7 @@ async function handleRevoke() {
isRevoking = true;
try {
await api.me.revokeSession({ sessionId: selectedSessionId });
await api.me.sessions.revoke({ sessionId: selectedSessionId });
await queryClient.invalidateQueries({ queryKey: ["sessions"] });
toast.success("Session revoked");
confirmDialogOpen = false;
@@ -140,7 +140,7 @@ async function handleRevokeAll() {
isRevokingAll = true;
try {
await api.me.revokeAllSessions();
await api.me.sessions.revokeAll();
await queryClient.invalidateQueries({ queryKey: ["sessions"] });
toast.success("All other sessions revoked");
confirmAllDialogOpen = false;

View File

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

View File

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

View File

@@ -3,7 +3,7 @@ import { ArrowLeft, Loader2 } from "@lucide/svelte";
import { toast } from "svelte-sonner";
import { goto } from "$app/navigation";
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 {
Card,
@@ -74,7 +74,7 @@ function handleSlugInput(event: Event) {
<title>New Organization | Admin | Publisher Dashboard</title>
</svelte:head>
<DashboardLayout title="New Organization">
<AdminLayout title="New Organization">
<div class="mx-auto max-w-2xl space-y-6">
<!-- Back link -->
<a
@@ -157,4 +157,4 @@ function handleSlugInput(event: Event) {
</CardContent>
</Card>
</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 { api } from "$lib/api/client.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 {
Card,
@@ -37,7 +37,7 @@ const usersQuery = createQuery(() => ({
<title>Users | Admin | Publisher Dashboard</title>
</svelte:head>
<DashboardLayout title="Users">
<AdminLayout title="Users">
{#if usersQuery.isPending}
<div class="space-y-6">
<Card>
@@ -141,4 +141,4 @@ const usersQuery = createQuery(() => ({
</Card>
</div>
{/if}
</DashboardLayout>
</AdminLayout>

View File

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

View File

@@ -58,7 +58,7 @@ const statusQuery = createQuery(() => ({
$effect(() => {
if (statusQuery.data?.status === "completed") {
clearLoginFlowState();
goto(statusQuery.data.redirectTo || "/performance");
goto(statusQuery.data.redirectTo || "/");
}
});

View File

@@ -22,7 +22,7 @@ const userQuery = createQuery(() => ({
// Redirect if user doesn't need setup
$effect(() => {
if (userQuery.data && !userQuery.data.needsSetup) {
goto("/performance");
goto("/");
}
});
@@ -68,7 +68,7 @@ async function handleSubmit(e: Event) {
});
toast.success("Profile setup complete!");
goto("/performance");
goto("/");
} catch (e) {
error = e instanceof Error ? e.message : "Failed to save profile";
} finally {

View File

@@ -15,7 +15,7 @@ import { LoadingButton } from "$lib/components/ui/loading-button";
// TanStack Query v6 with Svelte 5: options passed as thunk, results accessed directly
const deviceQuery = createQuery(() => ({
queryKey: ["deviceInfo"],
queryFn: () => api.me.getDeviceInfo(),
queryFn: () => api.me.devices.getInfo(),
}));
// Parse user agent for suggested device name
@@ -50,9 +50,9 @@ async function handleTrust() {
error = "";
try {
await api.me.trustDevice({ name: deviceName.trim() });
await api.me.devices.trust({ name: deviceName.trim() });
toast.success("Device trusted successfully!");
goto("/performance");
goto("/");
} catch (e) {
error = e instanceof Error ? e.message : "Failed to trust device";
} finally {

View File

@@ -31,7 +31,7 @@ async function verifyEmail(): Promise<void> {
try {
await api.auth.verifyEmail({ token });
toast.success("Email verified successfully!");
goto("/performance");
goto("/");
} catch (e) {
error = e instanceof Error ? e.message : "Verification failed";
} finally {

View File

@@ -1,18 +1,27 @@
<script lang="ts">
import { AlertCircle, Building2, Loader2 } from "@lucide/svelte";
import {
AlertCircle,
Building2,
ChevronRight,
Loader2,
Mail,
} from "@lucide/svelte";
import { createQuery } from "@tanstack/svelte-query";
import { goto } from "$app/navigation";
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 {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "$lib/components/ui/card";
/**
* Dashboard page - lists all organizations the user is a member of
* Also shows pending invites at the top
*/
// Fetch user's organizations
@@ -21,6 +30,12 @@ const orgsQuery = createQuery(() => ({
queryFn: () => api.orgs.list(),
}));
// Fetch user's pending invites
const invitesQuery = createQuery(() => ({
queryKey: ["me", "invites"],
queryFn: () => api.me.invites.list(),
}));
// Redirect to login on auth error
$effect(() => {
if (orgsQuery.error) {
@@ -57,6 +72,13 @@ function formatDate(date: Date): string {
year: date.getFullYear() !== now.getFullYear() ? "numeric" : undefined,
});
}
/**
* Format role for display
*/
function formatRole(role: string): string {
return role.charAt(0).toUpperCase() + role.slice(1);
}
</script>
<svelte:head>
@@ -64,7 +86,61 @@ function formatDate(date: Date): string {
</svelte:head>
<DashboardLayout title="Organizations">
<div class="space-y-6">
<div class="space-y-8">
<!-- Pending Invites Section -->
{#if invitesQuery.data && invitesQuery.data.length > 0}
<div class="space-y-4">
<div class="flex items-center gap-2">
<Mail class="h-5 w-5 text-primary" />
<h2 class="text-lg font-semibold">Pending Invitations</h2>
<Badge variant="secondary">{invitesQuery.data.length}</Badge>
</div>
<div class="grid grid-cols-1 gap-3 sm:grid-cols-2 lg:grid-cols-3">
{#each invitesQuery.data as invite (invite.id)}
<a
href="/account/org-invites/{invite.id}"
class="group block"
>
<Card class="h-full border-primary/30 bg-primary/5 transition-colors group-hover:border-primary/50">
<CardHeader class="pb-2">
<div class="flex items-start justify-between gap-2">
<div class="flex items-center gap-3">
{#if invite.org.logoUrl}
<img
src={invite.org.logoUrl}
alt="{invite.org.displayName} logo"
class="h-10 w-10 rounded-lg object-cover"
/>
{:else}
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-primary/20">
<Building2 class="h-5 w-5 text-primary" />
</div>
{/if}
<div class="min-w-0 flex-1">
<CardTitle class="truncate text-base">
{invite.org.displayName}
</CardTitle>
<CardDescription class="truncate text-xs">
Invited as {formatRole(invite.role)}
</CardDescription>
</div>
</div>
<ChevronRight class="h-5 w-5 text-muted-foreground group-hover:text-primary" />
</div>
</CardHeader>
<CardContent class="pt-0">
<p class="text-xs text-muted-foreground">
From {invite.invitedBy} &middot; {formatDate(new Date(invite.createdAt))}
</p>
</CardContent>
</Card>
</a>
{/each}
</div>
</div>
{/if}
<!-- Organizations Section -->
{#if orgsQuery.isPending}
<!-- Loading state -->
<div class="flex flex-col items-center justify-center py-16">
@@ -79,8 +155,8 @@ function formatDate(date: Date): string {
{orgsQuery.error instanceof Error ? orgsQuery.error.message : "Failed to load organizations"}
</p>
</div>
{:else if orgsQuery.data && orgsQuery.data.length === 0}
<!-- Empty state -->
{:else if orgsQuery.data && orgsQuery.data.length === 0 && (!invitesQuery.data || invitesQuery.data.length === 0)}
<!-- Empty state (no orgs and no invites) -->
<Card class="border-dashed">
<CardContent class="flex flex-col items-center justify-center py-16">
<div class="flex h-16 w-16 items-center justify-center rounded-full bg-muted">
@@ -93,47 +169,57 @@ function formatDate(date: Date): string {
</p>
</CardContent>
</Card>
{:else if orgsQuery.data && orgsQuery.data.length === 0 && invitesQuery.data && invitesQuery.data.length > 0}
<!-- No orgs but has invites -->
<div class="text-center text-sm text-muted-foreground py-4">
Accept an invitation above to join an organization.
</div>
{:else if orgsQuery.data}
<!-- Org grid -->
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{#each orgsQuery.data as org (org.id)}
<a
href="/dashboard/{org.slug}"
class="group block transition-transform hover:scale-[1.02]"
>
<Card class="h-full transition-colors group-hover:border-primary/50">
<CardHeader class="pb-3">
<div class="flex items-start gap-3">
<!-- Logo or placeholder -->
{#if org.logoUrl}
<img
src={org.logoUrl}
alt="{org.displayName} logo"
class="h-10 w-10 rounded-lg object-cover"
/>
{:else}
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-primary/20 to-primary/10">
<Building2 class="h-5 w-5 text-primary" />
<div class="space-y-4">
{#if invitesQuery.data && invitesQuery.data.length > 0}
<h2 class="text-lg font-semibold">Your Organizations</h2>
{/if}
<div class="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3">
{#each orgsQuery.data as org (org.id)}
<a
href="/dashboard/{org.slug}"
class="group block transition-transform hover:scale-[1.02]"
>
<Card class="h-full transition-colors group-hover:border-primary/50">
<CardHeader class="pb-3">
<div class="flex items-start gap-3">
<!-- Logo or placeholder -->
{#if org.logoUrl}
<img
src={org.logoUrl}
alt="{org.displayName} logo"
class="h-10 w-10 rounded-lg object-cover"
/>
{:else}
<div class="flex h-10 w-10 items-center justify-center rounded-lg bg-gradient-to-br from-primary/20 to-primary/10">
<Building2 class="h-5 w-5 text-primary" />
</div>
{/if}
<div class="min-w-0 flex-1">
<CardTitle class="truncate text-base">
{org.displayName}
</CardTitle>
<p class="truncate text-xs text-muted-foreground">
{org.slug}
</p>
</div>
{/if}
<div class="min-w-0 flex-1">
<CardTitle class="truncate text-base">
{org.displayName}
</CardTitle>
<p class="truncate text-xs text-muted-foreground">
{org.slug}
</p>
</div>
</div>
</CardHeader>
<CardContent class="pt-0">
<p class="text-xs text-muted-foreground">
Created {formatDate(new Date(org.createdAt))}
</p>
</CardContent>
</Card>
</a>
{/each}
</CardHeader>
<CardContent class="pt-0">
<p class="text-xs text-muted-foreground">
Created {formatDate(new Date(org.createdAt))}
</p>
</CardContent>
</Card>
</a>
{/each}
</div>
</div>
{/if}
</div>

View File

@@ -11,7 +11,7 @@ import {
import { createQuery } from "@tanstack/svelte-query";
import { getContext } from "svelte";
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 { Button } from "$lib/components/ui/button";
import {

View File

@@ -11,7 +11,7 @@ import { createQuery, useQueryClient } from "@tanstack/svelte-query";
import { getContext } from "svelte";
import { toast } from "svelte-sonner";
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 { Button } from "$lib/components/ui/button";
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 PeakTrafficChart from "$lib/components/dashboard/peak-traffic-chart.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)
const orgContext = getContext<{ slug: string }>("orgContext");

View File

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

View File

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

View File

@@ -0,0 +1,469 @@
<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

@@ -1,4 +1,4 @@
\restrict NwR9NcSOK9D25dGgvUNdLvsNphDACAXsvkQ5NSmhpf6sLcFR570yQ96lhgCbCXf
\restrict CIj4ub2A9kD8NQM2nKa1cg31hNutT3jXdOch0DnJ2bT48qpQKbe9XxNtViPwfYR
-- Dumped from database version 17.7
-- Dumped by pg_dump version 17.7
@@ -1084,7 +1084,7 @@ ALTER TABLE ONLY public.user_devices
-- PostgreSQL database dump complete
--
\unrestrict NwR9NcSOK9D25dGgvUNdLvsNphDACAXsvkQ5NSmhpf6sLcFR570yQ96lhgCbCXf
\unrestrict CIj4ub2A9kD8NQM2nKa1cg31hNutT3jXdOch0DnJ2bT48qpQKbe9XxNtViPwfYR
--

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;
};

View File

@@ -48,6 +48,7 @@ import {
setupProfileInputSchema,
trustDeviceInputSchema,
updateProfileInputSchema,
userInviteOutputSchema,
userProfileSchema,
} from "./schemas/user.js";
@@ -150,19 +151,39 @@ export const contract = oc.router({
.output(successResponseSchema),
}),
// Sessions & devices
listSessions: oc.output(z.array(sessionOutputSchema)),
revokeSession: oc
.input(z.object({ sessionId: z.number() }))
.output(successResponseSchema),
revokeAllSessions: oc.output(successResponseSchema),
getDeviceInfo: oc.output(deviceOutputSchema),
trustDevice: oc.input(trustDeviceInputSchema).output(successResponseSchema),
listTrustedDevices: oc.output(z.array(deviceOutputSchema)),
untrustDevice: oc
.input(z.object({ deviceId: z.number() }))
.output(successResponseSchema),
revokeAllTrustedDevices: oc.output(successResponseSchema),
// Org invites for the current user
invites: oc.router({
list: oc.output(z.array(userInviteOutputSchema)),
get: oc
.input(z.object({ inviteId: z.number() }))
.output(userInviteOutputSchema),
accept: oc
.input(z.object({ inviteId: z.number() }))
.output(successResponseSchema),
decline: oc
.input(z.object({ inviteId: z.number() }))
.output(successResponseSchema),
}),
// Sessions
sessions: oc.router({
list: oc.output(z.array(sessionOutputSchema)),
revoke: oc
.input(z.object({ sessionId: z.number() }))
.output(successResponseSchema),
revokeAll: oc.output(successResponseSchema),
}),
// Devices
devices: oc.router({
getInfo: oc.output(deviceOutputSchema),
trust: oc.input(trustDeviceInputSchema).output(successResponseSchema),
listTrusted: oc.output(z.array(deviceOutputSchema)),
untrust: oc
.input(z.object({ deviceId: z.number() }))
.output(successResponseSchema),
revokeAll: oc.output(successResponseSchema),
}),
// API tokens for CLI/programmatic access
apiTokens: oc.router({

View File

@@ -1,5 +1,6 @@
import * as z from "zod";
import { nonEmptyString, optionalString, phoneSchema } from "./common.js";
import { orgRoleSchema } from "./org.js";
/**
* User profile schema
@@ -132,3 +133,21 @@ export const authStatusOutputSchema = z.object({
sessionAuthStatusSchema,
]),
});
/**
* User invite output schema
* Returned by me.invites.list - includes org info for the user's pending invites
*/
export const userInviteOutputSchema = z.object({
id: z.number(),
org: z.object({
id: z.number(),
slug: z.string(),
displayName: z.string(),
logoUrl: z.string().nullable(),
}),
role: orgRoleSchema,
invitedBy: z.string(),
createdAt: z.date(),
expiresAt: z.date(),
});