mirror of
https://github.com/djdevin/recflare.git
synced 2026-09-08 14:41:28 -07:00
authentication improvements
This commit is contained in:
@@ -5,6 +5,10 @@ import type { SharedHonoEnv, SharedHonoVariables } from '@repo/hono-helpers/src/
|
||||
import type { NotificationsHub } from '../../notify/src/notifications-hub'
|
||||
|
||||
export type Env = SharedHonoEnv & {
|
||||
// Shared Secrets Store binding for the HS256 JWT signing key. Resolve the value
|
||||
// with `await env.JWT_SECRET.get()`; all workers bind the same store so tokens
|
||||
// signed by `auth` verify here.
|
||||
JWT_SECRET: SecretsStoreSecret
|
||||
// D1 database holding rooms (JSON blob + generated columns). See rooms-db.ts.
|
||||
DB: D1Database
|
||||
// Shared player-presence KV (owned by the `match` worker). Read here to resolve
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/**
|
||||
* Minimal HS256 JWT validation.
|
||||
*
|
||||
* 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.
|
||||
* The signing key is supplied by the caller from the shared `JWT_SECRET` Secrets
|
||||
* Store binding (see context.ts) - the same key the `auth` worker signs with.
|
||||
*/
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
|
||||
function base64urlToBytes(input: string): Uint8Array {
|
||||
const padded = input.replace(/-/g, '+').replace(/_/g, '/')
|
||||
@@ -22,7 +21,7 @@ function base64urlToBytes(input: string): Uint8Array {
|
||||
*/
|
||||
export async function validateAndGetAccountId(
|
||||
token: string,
|
||||
secret: string = DEV_SECRET
|
||||
secret: string
|
||||
): Promise<string | null> {
|
||||
const parts = token.split('.')
|
||||
if (parts.length !== 3) return null
|
||||
|
||||
@@ -19,9 +19,9 @@ import {
|
||||
getRoomsByCreator,
|
||||
getRoomsByIds,
|
||||
getSimilarRooms,
|
||||
getVisitedRooms,
|
||||
removeCheer,
|
||||
removeFavorite,
|
||||
getVisitedRooms,
|
||||
saveSubRoomData,
|
||||
searchRooms,
|
||||
setRoomDescription,
|
||||
@@ -132,7 +132,10 @@ async function handlePhotonAccessToken(c: Context<App>) {
|
||||
async function authedAccountId(c: Context<App>): Promise<number | null> {
|
||||
const authHeader = c.req.header('Authorization') ?? ''
|
||||
if (!authHeader.toLowerCase().startsWith('bearer ')) return null
|
||||
const sub = await validateAndGetAccountId(authHeader.slice('Bearer '.length))
|
||||
const sub = await validateAndGetAccountId(
|
||||
authHeader.slice('Bearer '.length),
|
||||
await c.env.JWT_SECRET.get()
|
||||
)
|
||||
const id = sub ? Number.parseInt(sub, 10) : Number.NaN
|
||||
return Number.isNaN(id) ? null : id
|
||||
}
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { env, SELF } from 'cloudflare:test'
|
||||
import { adminSecretsStore, env, SELF } from 'cloudflare:test'
|
||||
import { beforeAll, describe, expect, it } from 'vitest'
|
||||
|
||||
import '../../rooms.app'
|
||||
@@ -19,8 +19,8 @@ declare module 'cloudflare:test' {
|
||||
|
||||
const ORIGIN = 'https://example.com'
|
||||
|
||||
// Mint a token the way the `auth` worker does, using the same dev secret.
|
||||
const DEV_SECRET = 'dev-insecure-signing-key-change-me'
|
||||
// Mint a token the way the `auth` worker does, signing with the shared test key seeded into the JWT_SECRET store.
|
||||
const TEST_SECRET = 'test-signing-key'
|
||||
function b64url(input: ArrayBuffer | string): string {
|
||||
const bytes = typeof input === 'string' ? new TextEncoder().encode(input) : new Uint8Array(input)
|
||||
let binary = ''
|
||||
@@ -34,7 +34,7 @@ async function bearer(sub: string): Promise<Record<string, string>> {
|
||||
)}`
|
||||
const key = await crypto.subtle.importKey(
|
||||
'raw',
|
||||
new TextEncoder().encode(DEV_SECRET),
|
||||
new TextEncoder().encode(TEST_SECRET),
|
||||
{ name: 'HMAC', hash: 'SHA-256' },
|
||||
false,
|
||||
['sign']
|
||||
@@ -45,6 +45,8 @@ async function bearer(sub: string): Promise<Record<string, string>> {
|
||||
|
||||
// Apply the schema + seed the imported rooms into the test D1 (mirrors the migrations).
|
||||
beforeAll(async () => {
|
||||
// Seed the shared JWT signing key into the local Secrets Store so .get() resolves.
|
||||
await adminSecretsStore(env.JWT_SECRET).create('test-signing-key')
|
||||
for (const stmt of SCHEMA_DDL) await env.DB.prepare(stmt).run()
|
||||
for (const stmt of ROOM_INSTANCE_SCHEMA_DDL) await env.DB.prepare(stmt).run()
|
||||
const insert = env.DB.prepare('INSERT OR IGNORE INTO rooms (data) VALUES (?1)')
|
||||
@@ -317,9 +319,7 @@ describe('rooms endpoints', () => {
|
||||
})
|
||||
|
||||
it('GET /rooms/recommendations returns a bare array of public rooms (split-test params ignored)', async () => {
|
||||
const res = await SELF.fetch(
|
||||
`${ORIGIN}/rooms/recommendations?splitTestId=1&splitTestValue=5`
|
||||
)
|
||||
const res = await SELF.fetch(`${ORIGIN}/rooms/recommendations?splitTestId=1&splitTestValue=5`)
|
||||
expect(res.status).toBe(200)
|
||||
const body = (await res.json()) as Array<{ RoomId: number; IsDorm?: boolean }>
|
||||
expect(Array.isArray(body)).toBe(true)
|
||||
@@ -328,9 +328,9 @@ describe('rooms endpoints', () => {
|
||||
expect(body.some((r) => r.RoomId === 1 || r.IsDorm === true)).toBe(false)
|
||||
|
||||
// The split-test params don't change the result.
|
||||
const plain = (await (
|
||||
await SELF.fetch(`${ORIGIN}/rooms/recommendations`)
|
||||
).json()) as Array<{ RoomId: number }>
|
||||
const plain = (await (await SELF.fetch(`${ORIGIN}/rooms/recommendations`)).json()) as Array<{
|
||||
RoomId: number
|
||||
}>
|
||||
expect(plain.map((r) => r.RoomId)).toEqual(body.map((r) => r.RoomId))
|
||||
})
|
||||
|
||||
@@ -664,9 +664,11 @@ describe('rooms endpoints', () => {
|
||||
Success: true,
|
||||
})
|
||||
const tagsOf = async () =>
|
||||
((await (await SELF.fetch(`${ORIGIN}/rooms/2`)).json()) as {
|
||||
Tags: Array<{ Tag: string; Type: number }>
|
||||
}).Tags
|
||||
(
|
||||
(await (await SELF.fetch(`${ORIGIN}/rooms/2`)).json()) as {
|
||||
Tags: Array<{ Tag: string; Type: number }>
|
||||
}
|
||||
).Tags
|
||||
expect(await tagsOf()).toContainEqual({ Tag: 'quest', Type: 0 })
|
||||
|
||||
// Adding the same tag again (different case) is a no-op — no duplicate.
|
||||
@@ -866,7 +868,8 @@ describe('rooms endpoints', () => {
|
||||
|
||||
// No token → 401.
|
||||
expect(
|
||||
(await SELF.fetch(`${ORIGIN}/rooms/12/interactionby/me/favorite`, { method: 'DELETE' })).status
|
||||
(await SELF.fetch(`${ORIGIN}/rooms/12/interactionby/me/favorite`, { method: 'DELETE' }))
|
||||
.status
|
||||
).toBe(401)
|
||||
|
||||
// Favorite + cheer on, then DELETE clears only the favorite (cheer untouched).
|
||||
|
||||
@@ -38,6 +38,16 @@
|
||||
}
|
||||
]
|
||||
},
|
||||
// Shared Secrets Store holding the HS256 JWT signing key. Every worker binds the
|
||||
// same store as JWT_SECRET so tokens signed by `auth` verify here. The "local"
|
||||
// store_id placeholder is replaced with RECFLARE_SECRETS_STORE at deploy time.
|
||||
"secrets_store_secrets": [
|
||||
{
|
||||
"binding": "JWT_SECRET",
|
||||
"store_id": "local",
|
||||
"secret_name": "JWT_SECRET"
|
||||
}
|
||||
],
|
||||
"upload_source_maps": true,
|
||||
"observability": {
|
||||
"logs": {
|
||||
|
||||
Reference in New Issue
Block a user