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
7 changes: 7 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,7 @@
"qrcode": "^1.5.0",
"qs": "^6.14.2",
"rate-limiter-flexible": "^7.3.0",
"sqids": "^0.3.0",
"stripe": "^18.0.0",
"uuid": "^9.0.0",
"ws": "^8.18.0",
Expand Down
6 changes: 4 additions & 2 deletions src/config/public-routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@ import { demoRouter } from '../routes/public/demo'
import { documentationRouter } from '../routes/public/documentation'
import { healthCheckRouter } from '../routes/public/health-check'
import { invitePublicRouter } from '../routes/public/invite-public'
import { playerPublicRouter } from '../routes/public/player-public'
import { userPublicRouter } from '../routes/public/user-public'
import { webhookRouter } from '../routes/public/webhook'

export function configurePublicRoutes(app: Koa) {
app.use(demoRouter().routes())
app.use(documentationRouter().routes())
app.use(healthCheckRouter().routes())
app.use(userPublicRouter().routes())
app.use(demoRouter().routes())
app.use(invitePublicRouter().routes())
app.use(playerPublicRouter().routes())
app.use(userPublicRouter().routes())
app.use(webhookRouter().routes())
}
16 changes: 16 additions & 0 deletions src/entities/game.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@ import {
Collection,
Embedded,
Entity,
EntityManager,
ManyToOne,
OneToMany,
OneToOne,
PrimaryKey,
Property,
} from '@mikro-orm/mysql'
import Sqids from 'sqids'
import GameSecret from './game-secret'
import Organisation from './organisation'
import Player from './player'
Expand Down Expand Up @@ -61,6 +63,20 @@ export default class Game {
this.organisation = organisation
}

getToken() {
return new Sqids({ minLength: 8 }).encode([this.id])
}

static async fromToken(token: string, em: EntityManager) {
const ids = new Sqids({ minLength: 8 }).decode(token)

if (ids.length !== 1) {
return null
}

return em.repo(Game).findOne({ id: ids[0] })
}

static getLiveConfigCacheKey(game: Game) {
return `live-config-${game.id}`
}
Expand Down
16 changes: 12 additions & 4 deletions src/lib/auth/jwt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,24 @@ export function sign<T extends object>(
): Promise<string> {
return new Promise((resolve, reject) => {
jwt.sign(payload, secret, options, (err, token) => {
if (err) reject(err)
if (err) {
return reject(err)
}
resolve(token as string)
})
})
}

export function verify<T extends object>(token: string, secret: string): Promise<T> {
export function verify<T extends object>(
token: string,
secret: string,
options: jwt.VerifyOptions = {},
): Promise<T> {
return new Promise((resolve, reject) => {
jwt.verify(token, secret, (err, decoded) => {
if (err) reject(err)
jwt.verify(token, secret, options, (err, decoded) => {
if (err) {
return reject(err)
}
resolve(decoded as T)
})
})
Expand Down
31 changes: 31 additions & 0 deletions src/lib/logging/buildPlayerAuthActivity.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
import { EntityManager } from '@mikro-orm/mysql'
import Player from '../../entities/player'
import PlayerAuthActivity, { PlayerAuthActivityType } from '../../entities/player-auth-activity'

export function buildPlayerAuthActivity({
em,
player,
type,
ip,
userAgent,
extra,
}: {
em: EntityManager
player: Player
type: PlayerAuthActivityType
ip: string
userAgent?: string
extra?: Record<string, unknown>
}) {
const activity = new PlayerAuthActivity(player)
activity.type = type
activity.extra = {
...extra,
userAgent,
ip: type === PlayerAuthActivityType.DELETED_AUTH ? undefined : ip,
}

em.persist(activity)

return activity
}
2 changes: 1 addition & 1 deletion src/lib/routing/state.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import type APIKey from '../../entities/api-key'
import type Game from '../../entities/game'
import type User from '../../entities/user'

export type PublicRouteState = Record<string, never>
export type PublicRouteState = Record<string, unknown>

export type ProtectedRouteState = {
jwt: {
Expand Down
16 changes: 10 additions & 6 deletions src/middleware/limiter-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,11 @@ import { isAPIRoute } from '../lib/routing/route-info'
const limitMap = {
default: Number(process.env.API_RATE_LIMIT) || 100,
auth: Number(process.env.API_RATE_LIMIT_AUTH) || 20,
playerPublic: Number(process.env.PUBLIC_RATE_LIMIT_PLAYERS) || 10,
} as const

const rateLimitOverrides = new Map<string, keyof typeof limitMap>([
['/public/players', 'playerPublic'],
['/v1/players/auth', 'auth'],
['/v1/players/identify', 'auth'],
['/v1/players/socket-token', 'auth'],
Expand All @@ -25,12 +27,14 @@ export function getMaxRequestsForPath(requestPath: string) {
}
}

export async function limiterMiddleware(ctx: Context, next: Next): Promise<void> {
if (
isAPIRoute(ctx) &&
process.env.NODE_ENV !== 'test' &&
!rateLimitBypass.has(ctx.request.path)
) {
function isPlayerPublicRoute(ctx: Context) {
return ctx.path.match(/^\/(public\/players)\//) !== null
}

export async function limiterMiddleware(ctx: Context, next: Next) {
const routeMatches = isPlayerPublicRoute(ctx) || isAPIRoute(ctx)

if (routeMatches && process.env.NODE_ENV !== 'test' && !rateLimitBypass.has(ctx.request.path)) {
const { limitMapKey, maxRequests } = getMaxRequestsForPath(ctx.request.path)
const userId = ctx.state.jwt?.sub || 'anonymous'
const redisKey = `requests:${userId}:${ctx.request.ip}:${limitMapKey}`
Expand Down
37 changes: 16 additions & 21 deletions src/routes/api/player-auth/common.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import type { Next } from 'koa'
import assert from 'node:assert'
import type { APIRouteContext } from '../../../lib/routing/context'
import APIKey from '../../../entities/api-key'
import Player from '../../../entities/player'
import PlayerAlias from '../../../entities/player-alias'
import PlayerAuthActivity, { PlayerAuthActivityType } from '../../../entities/player-auth-activity'
import { buildPlayerAuthActivity } from '../../../lib/logging/buildPlayerAuthActivity'

export type PlayerAuthRouteState = {
alias: PlayerAlias
Expand All @@ -27,37 +29,30 @@ export async function loadAliasWithAuth(ctx: APIRouteContext<PlayerAuthRouteStat
await next()
}

export function getRedisAuthKey(key: APIKey, alias: PlayerAlias): string {
return `player-auth:${key.game.id}:verification:${alias.id}`
export function getRedisAuthKey(alias: PlayerAlias) {
return `player-auth:${alias.player.game.id}:verification:${alias.id}`
}

export function getRedisPasswordResetKey(key: APIKey, code: string): string {
export function getRedisPasswordResetKey(key: APIKey, code: string) {
return `player-auth:${key.game.id}:password-reset:${code}`
}

export function handleFailedLogin(ctx: APIRouteContext): never {
return ctx.throw(401, {
message: 'Incorrect identifier or password',
errorCode: 'INVALID_CREDENTIALS',
})
}

export function createPlayerAuthActivity(
ctx: APIRouteContext,
player: Player,
data: { type: PlayerAuthActivityType; extra?: Record<string, unknown> },
): PlayerAuthActivity {
const ip = ctx.request.ip

const activity = new PlayerAuthActivity(player)
activity.type = data.type
activity.extra = {
...data.extra,
return buildPlayerAuthActivity({
em: ctx.em,
player,
type: data.type,
ip: ctx.request.ip,
userAgent: ctx.request.headers['user-agent'],
ip: data.type === PlayerAuthActivityType.DELETED_AUTH ? undefined : ip,
}

ctx.em.persist(activity)
extra: data.extra,
})
}

return activity
export function sessionBuilder(alias: PlayerAlias) {
assert(alias.player.auth)
return alias.player.auth.createSession(alias)
}
Loading