Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,4 @@ test-results
outputs/*
work/*
packages/rage-cli/dist
.vercel
1 change: 1 addition & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ Rage AI is a local-first frustration leaderboard for Claude Code and Codex. It s
- Better Auth with GitHub OAuth and API-key publish tokens
- Neon Postgres via Drizzle ORM and `pg`
- Upstash Redis for product rate limits
- Copy-ready X and LinkedIn share drafts from public aggregate scores
- Biome, Vitest, Playwright, and `@wiseiodev/guardrails`

## Development
Expand Down
1 change: 1 addition & 0 deletions apps/web/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
"type": "module",
"scripts": {
"dev": "next dev",
"env:dev": "cd ../.. && pnpm dlx vercel@latest env pull apps/web/.env --yes",
"build": "next build",
"start": "next start",
"check": "biome check .",
Expand Down
56 changes: 39 additions & 17 deletions apps/web/src/app/api/auth/device/approve/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,16 +14,28 @@ const approveSchema = z.object({
.trim()
.min(2)
.max(32)
.regex(/^[a-zA-Z0-9_-]+$/),
.regex(/^[a-zA-Z0-9_-]+$/)
.optional()
.or(z.literal(''))
.transform((value) => (value ? value : undefined)),
})

async function parseBody(request: Request) {
async function parseBody(request: Request): Promise<{ body: unknown; isForm: boolean }> {
const contentType = request.headers.get('content-type') ?? ''
if (contentType.includes('application/json')) {
return request.json()
return { body: await request.json(), isForm: false }
}
const formData = await request.formData()
return Object.fromEntries(formData.entries())
return { body: Object.fromEntries(formData.entries()), isForm: true }
}

function redirectToDevicePage(request: Request, userCode: string, approved = false) {
const url = new URL('/auth/device', request.url)
url.searchParams.set('code', userCode)
if (approved) {
url.searchParams.set('approved', '1')
}
return Response.redirect(url, 303)
}

export async function POST(request: Request) {
Expand All @@ -32,7 +44,8 @@ export async function POST(request: Request) {
return Response.json({ ok: false, message: 'Sign in with GitHub first' }, { status: 401 })
}

const body = approveSchema.safeParse(await parseBody(request).catch(() => null))
const parsedBody = await parseBody(request).catch(() => null)
const body = approveSchema.safeParse(parsedBody?.body)
if (!body.success) {
return Response.json({ ok: false, message: 'Invalid approval request' }, { status: 400 })
}
Expand All @@ -51,25 +64,30 @@ export async function POST(request: Request) {
.limit(1)

if (!pending) {
if (parsedBody?.isForm) {
return redirectToDevicePage(request, body.data.userCode)
}
return Response.json(
{ ok: false, message: 'Device code not found or expired' },
{ status: 404 },
)
}

await db
.insert(rageProfile)
.values({
userId: session.user.id,
handle: body.data.handle,
})
.onConflictDoUpdate({
target: rageProfile.userId,
set: {
if (body.data.handle) {
await db
.insert(rageProfile)
.values({
userId: session.user.id,
handle: body.data.handle,
updatedAt: new Date(),
},
})
})
.onConflictDoUpdate({
target: rageProfile.userId,
set: {
handle: body.data.handle,
updatedAt: new Date(),
},
})
}

await db
.update(deviceAuthRequest)
Expand All @@ -80,6 +98,10 @@ export async function POST(request: Request) {
})
.where(eq(deviceAuthRequest.id, pending.id))

if (parsedBody?.isForm) {
return redirectToDevicePage(request, body.data.userCode, true)
}

const isAdmin = adminLogins().has(session.user.name?.toLowerCase() ?? '')
return Response.json({
ok: true,
Expand Down
26 changes: 18 additions & 8 deletions apps/web/src/app/api/auth/device/complete/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,35 +19,45 @@ export async function POST(request: Request) {

const db = getDb()
const installIdHash = hmacIdentifier(body.data.installId)
const [approved] = await db
const [requestRecord] = await db
.select()
.from(deviceAuthRequest)
.where(
and(
eq(deviceAuthRequest.deviceCodeHash, hmacIdentifier(body.data.deviceCode)),
eq(deviceAuthRequest.installIdHash, installIdHash),
eq(deviceAuthRequest.status, 'approved'),
isNull(deviceAuthRequest.apiKeyId),
gt(deviceAuthRequest.expiresAt, new Date()),
),
)
.limit(1)

if (!approved?.userId) {
if (!requestRecord) {
return Response.json(
{ ok: false, message: 'Device is not approved or has expired' },
{ ok: false, message: 'Device auth request has expired or was already completed' },
{ status: 404 },
)
}

if (requestRecord.status !== 'approved' || !requestRecord.userId) {
return Response.json(
{
ok: false,
message: 'Device is waiting for browser approval',
status: requestRecord.status,
},
{ status: 202 },
)
}

const token = randomToken('rage_sk')
const apiKeyId = randomUUID()
await db.insert(apiKeyTable).values({
id: apiKeyId,
name: approved.deviceLabel,
name: requestRecord.deviceLabel,
prefix: 'rage_sk',
key: hmacIdentifier(token),
userId: approved.userId,
userId: requestRecord.userId,
metadata: {
installIdHash,
scope: 'publish',
Expand All @@ -60,12 +70,12 @@ export async function POST(request: Request) {
apiKeyId,
updatedAt: new Date(),
})
.where(eq(deviceAuthRequest.id, approved.id))
.where(eq(deviceAuthRequest.id, requestRecord.id))

const [profile] = await db
.select({ handle: rageProfile.handle })
.from(rageProfile)
.where(eq(rageProfile.userId, approved.userId))
.where(eq(rageProfile.userId, requestRecord.userId))
.limit(1)

return Response.json({
Expand Down
26 changes: 26 additions & 0 deletions apps/web/src/app/api/publish/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import {
type PublishBatchRequest,
publishBatchRequestSchema,
publishRequestSchema,
type ShareUrl,
type WindowKind,
} from '@rageai/core'
import { apiKey as apiKeyTable, getDb, leaderboardRow, rageProfile, submission } from '@rageai/db'
import { and, eq } from 'drizzle-orm'
Expand Down Expand Up @@ -181,11 +183,35 @@ export async function POST(request: Request) {
}
})

const shareUrls: ShareUrl[] = []
const shareWindows = new Set<WindowKind>(firstPayload.windows.map((window) => window.window))
for (const window of shareWindows) {
const [row] = await db
.select({ id: leaderboardRow.id })
.from(leaderboardRow)
.where(
and(
eq(leaderboardRow.userId, keyRecord.userId),
eq(leaderboardRow.installIdHash, installIdHash),
eq(leaderboardRow.hostApp, firstPayload.hostApp),
eq(leaderboardRow.window, window),
),
)
.limit(1)
if (row) {
shareUrls.push({
window,
url: `${appUrl()}/share/${row.id}`,
})
}
}

return Response.json({
ok: true,
message:
parsed.publicPayloads.length === 1 ? 'Rage score published.' : 'Rage scores published.',
leaderboardUrl: `${appUrl()}/leaderboard`,
published: parsed.publicPayloads.map((payload) => payload.hostApp),
shareUrls,
})
}
26 changes: 14 additions & 12 deletions apps/web/src/app/auth/device/page.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,24 @@ export const dynamic = 'force-dynamic'
export default async function DevicePage({
searchParams,
}: {
searchParams: Promise<{ code?: string }>
searchParams: Promise<{ approved?: string; code?: string }>
}) {
const params = await searchParams
const callbackURL = params.code
? `/auth/device?code=${encodeURIComponent(params.code)}`
: '/auth/device'
const session = await getAuth()
.api.getSession({ headers: await headers() })
.catch(() => null)

return (
<article className="mx-auto grid max-w-md gap-5 px-4 py-8">
<h1 className="font-semibold text-3xl">Approve Rage CLI</h1>
{params.approved ? (
<div className="rounded-md border border-emerald-200 bg-emerald-50 p-4 text-emerald-950 text-sm">
Device approved. You can return to the terminal.
</div>
) : null}
{session ? (
<form action="/api/auth/device/approve" className="grid gap-3" method="post">
<label className="grid gap-1 text-sm">
Expand All @@ -28,16 +36,10 @@ export default async function DevicePage({
required
/>
</label>
<label className="grid gap-1 text-sm">
Public handle
<input
className="rounded-md border border-zinc-300 px-3 py-2"
name="handle"
pattern="[a-zA-Z0-9_-]{2,32}"
placeholder="wise"
required
/>
</label>
<p className="text-sm text-zinc-600">
This stores a local publish token for this device. You can choose your public handle
when publishing.
</p>
<button
className="rounded-md bg-zinc-950 px-3 py-2 font-medium text-sm text-white"
type="submit"
Expand All @@ -48,7 +50,7 @@ export default async function DevicePage({
) : (
<div className="grid gap-3">
<p className="text-zinc-600">Sign in with GitHub before approving a device.</p>
<SignInWithGitHub />
<SignInWithGitHub callbackURL={callbackURL} />
</div>
)}
</article>
Expand Down
11 changes: 11 additions & 0 deletions apps/web/src/app/leaderboard/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
import type { Route } from 'next'
import Link from 'next/link'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
import { Table, Td, Th } from '@/components/ui/table'
import { getLeaderboardRows } from '@/lib/leaderboard'
Expand Down Expand Up @@ -38,6 +40,7 @@ export default async function LeaderboardPage() {
<Th className="text-right">Swears</Th>
<Th className="text-right">Words</Th>
<Th>Top</Th>
<Th className="text-right">Share</Th>
</tr>
</thead>
<tbody>
Expand All @@ -50,6 +53,14 @@ export default async function LeaderboardPage() {
<Td className="text-right">{row.scoredProfanityCount}</Td>
<Td className="text-right">{row.userWordCount}</Td>
<Td>{row.topIntensity ?? '-'}</Td>
<Td className="text-right">
<Link
className="text-zinc-600 underline"
href={`/share/${row.id}` as Route}
>
Open
</Link>
</Td>
</tr>
))}
</tbody>
Expand Down
10 changes: 10 additions & 0 deletions apps/web/src/app/page.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import type { Route } from 'next'
import Link from 'next/link'
import { Badge } from '@/components/ui/badge'
import { Card, CardContent, CardHeader } from '@/components/ui/card'
Expand Down Expand Up @@ -48,6 +49,7 @@ export default async function HomePage() {
<Th>Host</Th>
<Th className="text-right">Rage/1k</Th>
<Th className="text-right">Words</Th>
<Th className="text-right">Share</Th>
</tr>
</thead>
<tbody>
Expand All @@ -58,6 +60,14 @@ export default async function HomePage() {
<Td>{row.hostApp}</Td>
<Td className="text-right">{row.ratePerThousandWords}</Td>
<Td className="text-right">{row.userWordCount}</Td>
<Td className="text-right">
<Link
className="text-zinc-600 underline"
href={`/share/${row.id}` as Route}
>
Open
</Link>
</Td>
</tr>
))}
</tbody>
Expand Down
Loading