mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 14:41:28 -07:00
almost into a room
This commit is contained in:
@@ -0,0 +1,190 @@
|
||||
import { Hono } from 'hono'
|
||||
import { useWorkersLogger } from 'workers-tagged-logger'
|
||||
|
||||
import { withNotFound, withOnError } from '@repo/hono-helpers'
|
||||
|
||||
import type { App } from './context'
|
||||
import type { Context } from 'hono'
|
||||
import { validateAndGetAccountId } from './jwt'
|
||||
|
||||
/**
|
||||
* Ported from the C# `AccountsController`. Endpoints that the C# backs with EF
|
||||
* Core (`AppDbContext`) are stubbed here — there's no DB binding yet, so reads
|
||||
* return synthesized defaults (the C# fills every field with a fallback anyway)
|
||||
* and writes accept-and-ack without persisting. Each stub is marked `TODO`.
|
||||
*
|
||||
* Auth-gated routes still validate the Bearer JWT issued by the `auth` worker.
|
||||
*/
|
||||
|
||||
/** Account shape returned by the public lookup endpoints. */
|
||||
interface Account {
|
||||
AccountId: number
|
||||
ProfileImage: string
|
||||
IsJunior: boolean
|
||||
Platforms: number
|
||||
PersonalPronouns: number
|
||||
IdentityFlags: number
|
||||
Username: string
|
||||
DisplayName: string
|
||||
CreatedAt: string
|
||||
}
|
||||
|
||||
/**
|
||||
* Resolve the account id from a Bearer token, mirroring the repeated
|
||||
* auth-header check in the C#. Returns `null` when the header is missing,
|
||||
* the token is invalid, or the `sub` claim isn't an integer.
|
||||
*/
|
||||
async function authedId(c: Context<App>): Promise<number | null> {
|
||||
const authHeader = c.req.header('Authorization') ?? ''
|
||||
console.log(authHeader);
|
||||
if (!authHeader.toLowerCase().startsWith('bearer ')) return null
|
||||
|
||||
const token = authHeader.slice('Bearer '.length)
|
||||
const accountId = await validateAndGetAccountId(token)
|
||||
if (!accountId) return null
|
||||
|
||||
const id = Number.parseInt(accountId, 10)
|
||||
return Number.isNaN(id) ? null : id
|
||||
}
|
||||
|
||||
/** Results.Unauthorized() equivalent — 401 with empty body. */
|
||||
function unauthorized(c: Context<App>) {
|
||||
return c.body(null, 401)
|
||||
}
|
||||
|
||||
/** Read a single string field from a form-urlencoded / multipart body. */
|
||||
async function formField(c: Context<App>, name: string): Promise<string> {
|
||||
const body = await c.req.parseBody().catch(() => ({}) as Record<string, unknown>)
|
||||
const value = body[name]
|
||||
return typeof value === 'string' ? value : ''
|
||||
}
|
||||
|
||||
/**
|
||||
* Synthesize an `Account` from an id using the same fallbacks the C# applies
|
||||
* when a column is null. Stands in for `db.Accounts.FindAsync(id)`.
|
||||
*/
|
||||
function defaultAccount(id: number): Account {
|
||||
return {
|
||||
AccountId: id,
|
||||
ProfileImage: 'DefaultProfileImage.jpg',
|
||||
IsJunior: false,
|
||||
Platforms: 0,
|
||||
PersonalPronouns: 0,
|
||||
IdentityFlags: 0,
|
||||
Username: `Player${id}`,
|
||||
DisplayName: `Player${id}`,
|
||||
CreatedAt: new Date().toISOString(),
|
||||
}
|
||||
}
|
||||
|
||||
const app = new Hono<App>()
|
||||
.use(
|
||||
'*',
|
||||
// middleware
|
||||
(c, next) =>
|
||||
useWorkersLogger(c.env.NAME, {
|
||||
environment: c.env.ENVIRONMENT,
|
||||
release: c.env.SENTRY_RELEASE,
|
||||
})(c, next)
|
||||
)
|
||||
|
||||
.onError(withOnError())
|
||||
.notFound(withNotFound())
|
||||
|
||||
// Root health check (the C# source returned a placeholder string here).
|
||||
.get('/', (c) => c.json({ service: 'accounts', status: 'ok' }))
|
||||
|
||||
// ---- Self account --------------------------------------------------------
|
||||
.get('/account/me', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
// TODO: load the real account; the C# 404s when the row is missing.
|
||||
const account = defaultAccount(id)
|
||||
return c.json({
|
||||
...account,
|
||||
ProfileImage: 'hdqeamlcmatc6qzoi2ybgf0ddijjcf.jpg',
|
||||
Email: null,
|
||||
Phone: null,
|
||||
JuniorState: null,
|
||||
Birthday: null,
|
||||
ParentAccountId: null,
|
||||
AvailableUsernameChanges: 1,
|
||||
})
|
||||
})
|
||||
|
||||
// ---- Bulk / single lookup ------------------------------------------------
|
||||
// Register the static `bulk` path before the `/account/:id` param route.
|
||||
.get('/account/bulk', (c) => {
|
||||
// C# reads repeated `id` query params; also accept a comma-separated list.
|
||||
const ids = c.req
|
||||
.queries('id')
|
||||
?.flatMap((v) => v.split(','))
|
||||
.map((s) => Number.parseInt(s.trim(), 10))
|
||||
.filter((n) => !Number.isNaN(n))
|
||||
// TODO: query Accounts for these ids instead of synthesizing.
|
||||
return c.json((ids ?? []).map(defaultAccount))
|
||||
})
|
||||
|
||||
.get('/account/:id/bio', (c) => {
|
||||
const accountId = Number.parseInt(c.req.param('id'), 10)
|
||||
if (Number.isNaN(accountId)) return c.body(null, 400)
|
||||
// TODO: query PlayerBios; no binding yet so the bio is always empty.
|
||||
return c.json({ accountId, bio: '' })
|
||||
})
|
||||
|
||||
.get('/account/:id', (c) => {
|
||||
const accountId = Number.parseInt(c.req.param('id'), 10)
|
||||
if (Number.isNaN(accountId)) return c.body(null, 400)
|
||||
// TODO: load the real account; the C# 404s when the row is missing.
|
||||
return c.json(defaultAccount(accountId))
|
||||
})
|
||||
|
||||
// ---- Create --------------------------------------------------------------
|
||||
.post('/account/create', async (c) => {
|
||||
// Parsed for fidelity; unused until there's a DB to persist CachedLogins.
|
||||
await formField(c, 'platform')
|
||||
await formField(c, 'platformId')
|
||||
|
||||
const accountId = Math.floor(Math.random() * (99999 - 10000 + 1)) + 10000
|
||||
const account = defaultAccount(accountId)
|
||||
// TODO: persist the account + a dorm Room/SubRoom once a DB binding exists.
|
||||
return c.json({ success: true, value: account })
|
||||
})
|
||||
|
||||
// ---- Parental control ----------------------------------------------------
|
||||
.get('/parentalcontrol/me', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
return c.json({ accountId: id, disallowInAppPurchases: false })
|
||||
})
|
||||
|
||||
// ---- Profile mutations ---------------------------------------------------
|
||||
.put('/account/me/displayname', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
await formField(c, 'displayName') // TODO: persist on the account row.
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
.put('/account/me/username', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
await formField(c, 'username') // TODO: persist on the account row.
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
.put('/account/me/bio', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
await formField(c, 'bio') // TODO: upsert into PlayerBios.
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
.put('/account/me/profileimage', async (c) => {
|
||||
const id = await authedId(c)
|
||||
if (id === null) return unauthorized(c)
|
||||
await formField(c, 'imageName') // TODO: persist on the account row.
|
||||
return c.json({ success: true })
|
||||
})
|
||||
|
||||
export default app
|
||||
@@ -0,0 +1,14 @@
|
||||
import type { HonoApp } from '@repo/hono-helpers'
|
||||
import type { SharedHonoEnv, SharedHonoVariables } from '@repo/hono-helpers/src/types'
|
||||
|
||||
export type Env = SharedHonoEnv & {
|
||||
// add additional Bindings here
|
||||
}
|
||||
|
||||
/** Variables can be extended */
|
||||
export type Variables = SharedHonoVariables
|
||||
|
||||
export interface App extends HonoApp {
|
||||
Bindings: Env
|
||||
Variables: Variables
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
/**
|
||||
* Minimal HS256 JWT validation, mirroring the C# `JwtTokenService.ValidateAndGetAccountId`.
|
||||
*
|
||||
* Uses the same placeholder dev secret as the `auth` worker (`apps/auth/src/jwt.ts`).
|
||||
* Swap both for a shared secret binding before this is used for anything real.
|
||||
*/
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
|
||||
function base64urlToBytes(input: string): Uint8Array {
|
||||
const padded = input.replace(/-/g, '+').replace(/_/g, '/')
|
||||
const binary = atob(padded + '='.repeat((4 - (padded.length % 4)) % 4))
|
||||
const bytes = new Uint8Array(binary.length)
|
||||
for (let i = 0; i < binary.length; i++) {
|
||||
bytes[i] = binary.charCodeAt(i)
|
||||
}
|
||||
return bytes
|
||||
}
|
||||
|
||||
/**
|
||||
* Validate an HS256 token and return its `sub` (account id) claim, or `null`
|
||||
* when the token is malformed, has a bad signature, or is expired.
|
||||
*/
|
||||
export async function validateAndGetAccountId(
|
||||
token: string,
|
||||
secret: string = DEV_SECRET
|
||||
): Promise<string | null> {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
const [header, payload, signature] = parts
|
||||
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(secret),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['verify']
|
||||
)
|
||||
const valid = await crypto.subtle.verify(
|
||||
'HMAC',
|
||||
key,
|
||||
base64urlToBytes(signature),
|
||||
new TextEncoder().encode(`${header}.${payload}`)
|
||||
)
|
||||
if (!valid) return null
|
||||
|
||||
let claims: { sub?: string; exp?: number }
|
||||
try {
|
||||
claims = JSON.parse(new TextDecoder().decode(base64urlToBytes(payload)))
|
||||
} catch {
|
||||
return null
|
||||
}
|
||||
|
||||
if (typeof claims.exp === 'number' && claims.exp < Math.floor(Date.now() / 1000)) {
|
||||
return null
|
||||
}
|
||||
|
||||
return claims.sub ?? null
|
||||
}
|
||||
@@ -0,0 +1,133 @@
|
||||
import { exports } from 'cloudflare:workers'
|
||||
import { describe, expect, test } from 'vitest'
|
||||
|
||||
import '../../accounts.app'
|
||||
|
||||
const ORIGIN = 'https://accounts.rec.djdevin.net'
|
||||
|
||||
// Mint a token the way the `auth` worker does, using the same dev secret, so the
|
||||
// accounts worker's validation accepts it. Kept inline to avoid a cross-package
|
||||
// import.
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
|
||||
function b64url(input: ArrayBuffer | string): string {
|
||||
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input)
|
||||
let binary = ''
|
||||
for (const byte of bytes) binary += String.fromCharCode(byte)
|
||||
return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '')
|
||||
}
|
||||
|
||||
async function bearer(sub = '42'): Promise<Record<string, string>> {
|
||||
const now = Math.floor(Date.now() / 1000)
|
||||
const signingInput = `${b64url(JSON.stringify({ alg: 'HS256', typ: 'JWT' }))}.${b64url(
|
||||
JSON.stringify({ sub, exp: now + 3600 })
|
||||
)}`
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(DEV_SECRET),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
)
|
||||
const sig = await crypto.subtle.sign('HMAC', key, new TextEncoder().encode(signingInput))
|
||||
return { Authorization: `Bearer ${signingInput}.${b64url(sig)}` }
|
||||
}
|
||||
|
||||
const form = (fields: Record<string, string>): RequestInit => ({
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body: new URLSearchParams(fields).toString(),
|
||||
})
|
||||
|
||||
describe('public endpoints', () => {
|
||||
test('GET / returns a health response', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/`)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ service: 'accounts', status: 'ok' })
|
||||
})
|
||||
|
||||
test('GET /account/:id returns a default account', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/123`)
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toMatchObject({
|
||||
AccountId: 123,
|
||||
Username: 'Player123',
|
||||
DisplayName: 'Player123',
|
||||
ProfileImage: 'DefaultProfileImage.jpg',
|
||||
})
|
||||
})
|
||||
|
||||
test('GET /account/:id rejects a non-numeric id', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/abc`)
|
||||
expect(res.status).toBe(400)
|
||||
})
|
||||
|
||||
test('GET /account/bulk returns one account per id', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/bulk?id=1&id=2,3`)
|
||||
expect(res.status).toBe(200)
|
||||
const accounts = (await res.json()) as Array<{ AccountId: number }>
|
||||
expect(accounts.map((a) => a.AccountId)).toEqual([1, 2, 3])
|
||||
})
|
||||
|
||||
test('GET /account/:id/bio returns an empty bio', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/7/bio`)
|
||||
expect(await res.json()).toEqual({ accountId: 7, bio: '' })
|
||||
})
|
||||
|
||||
test('POST /account/create returns a wrapped account', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/create`, { method: 'POST' })
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as { success: boolean; value: { AccountId: number } }
|
||||
expect(body.success).toBe(true)
|
||||
expect(body.value.AccountId).toBeGreaterThanOrEqual(10000)
|
||||
expect(body.value.AccountId).toBeLessThanOrEqual(99999)
|
||||
})
|
||||
})
|
||||
|
||||
describe('auth-gated endpoints', () => {
|
||||
test('GET /account/me 401s without a token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/me`)
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('GET /account/me 401s with a garbage token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/me`, {
|
||||
headers: { Authorization: 'Bearer not-a-real-token' },
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('GET /account/me returns the self account with a valid token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/me`, { headers: await bearer() })
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toMatchObject({
|
||||
AccountId: 42,
|
||||
Username: 'Player42',
|
||||
AvailableUsernameChanges: 1,
|
||||
ParentAccountId: null,
|
||||
})
|
||||
})
|
||||
|
||||
test('GET /parentalcontrol/me returns the flags', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/parentalcontrol/me`, {
|
||||
headers: await bearer(),
|
||||
})
|
||||
expect(await res.json()).toEqual({ accountId: 42, disallowInAppPurchases: false })
|
||||
})
|
||||
|
||||
test('PUT /account/me/displayname 401s without a token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/me/displayname`, {
|
||||
...form({ displayName: 'Bob' }),
|
||||
})
|
||||
expect(res.status).toBe(401)
|
||||
})
|
||||
|
||||
test('PUT /account/me/displayname acks with a valid token', async () => {
|
||||
const res = await exports.default.fetch(`${ORIGIN}/account/me/displayname`, {
|
||||
...form({ displayName: 'Bob' }),
|
||||
headers: { ...(await bearer()), 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
})
|
||||
expect(res.status).toBe(200)
|
||||
expect(await res.json()).toEqual({ success: true })
|
||||
})
|
||||
})
|
||||
Reference in New Issue
Block a user