Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 | 420x 12x 72x 12x 12x 12x 12x 329x 329x 329x 329x 329x 12x 12x 11x 11x 10x 10x 10x 12x 8x 8x 7x 7x 7x 5x 2x 2x 2x 12x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 12x 1x 1x 1x 1x 1x 1x 1x 12x 186x 186x 1x 185x 185x 185x 185x 185x 185x 185x 5x 180x 180x 6x 174x 174x 172x 174x 12x 6x 6x 3x 3x 12x 4x 4x 3x 3x 3x 2x 12x 4x 4x 4x 4x 4x 4x 1x 12x 3x 3x 2x 2x 2x 12x 11x 11x 11x 11x 12x 2x 2x 2x 2x 2x 2x 12x 12x | import { Hono } from 'hono';
import { describeRoute, openAPIRouteHandler, resolver, validator } from 'hono-openapi';
import { parseReplay, ReplayParseError, serializeReplay } from '@be-music/player-engine/replay';
import * as v from 'valibot';
import { loadAccount } from '../accounts.ts';
import { AVATAR_MAX_BYTES, putAvatar, removeAvatar } from '../avatars.ts';
import { CARD_HEIGHT, CARD_MAX_BYTES, CARD_WIDTH, cardURL, putScoreCard } from '../cards.ts';
import { updateProfile } from '../profiles.ts';
import type { AppEnv } from '../app.ts';
import { loadSession, passOnSetCookies } from '../auth.ts';
import { openDatabase } from '../db/client.ts';
import { readJSONBody, SUBMISSION_LIMITS } from '../http/body.ts';
import { loadMyRank, loadRanking, type RankingFilter } from '../ranking.ts';
import { refreshChartsetIfUnchecked, type ChartsetLookup } from '../chartsets/refresh.ts';
import { isOn } from '../http/query.ts';
import { afterResponse } from '../http/after-response.ts';
import { loadReplayAccess, loadScoreDetail, toScoreResponse } from '../scores/detail.ts';
import { submitScore } from '../scores/submit.ts';
import { mountCourseRoutes } from './v0-courses.ts';
import { canSeeScore, setScoreHidden } from '../scores/visibility.ts';
import {
accountResponse,
errorResponse,
myRankQuery,
myRankResponse,
profileUpdateBody,
rankingQuery,
rankingResponse,
scoreResponse,
scoreVisibilityBody,
scoreVisibilityResponse,
submissionBody,
submissionResponse,
} from './schemas.ts';
/** A JSON response of `schema` for the OpenAPI document. */
const json = (description: string, schema: Parameters<typeof resolver>[0]) => ({
description,
content: { 'application/json': { schema: resolver(schema) } },
});
const signInRequired = json('No session: sign in first (anonymously is enough).', errorResponse(['sign-in-required']));
const notFound = (what: string) => json(`${what} does not exist.`, errorResponse(['not-found']));
/** The OpenAPI document's header; the paths come from the routes' `describeRoute` and validators. */
export const OPENAPI_DOCUMENTATION = {
openapi: '3.1.0',
info: {
title: 'Be-Music Leaderboard API',
version: '0',
description:
'Version 0 is a Public Beta: it may still change incompatibly (docs/leaderboard.md section 8). Data may be ' +
'deleted without notice. Requests are authenticated with a host-only OIDC app session or a resource-bound ' +
'Accounts access token; reads are public.',
},
servers: [{ url: '/api/v0' }],
};
/**
* Version 0 of the Leaderboard API, mounted at `/api/v0` (docs/leaderboard.md section 8). Version 0 is a Public Beta:
* it may still change incompatibly, and data may be deleted without notice. Once stable it becomes `/api/v1`, and
* breaking changes after that go into a new version mounted next to the old one.
*/
export function createV0API(options: { now: () => number; newId: () => string; chartsetLookup: ChartsetLookup }) {
const { now, newId, chartsetLookup } = options;
const v0 = new Hono<AppEnv>();
v0.use('*', async (c, next) => {
c.set('db', openDatabase(c.env.DB));
// Signed-out reads (most of the API's traffic) carry no session cookie and skip the session lookup altogether.
const { session, setCookies } = await loadSession(c.env, c.req.raw);
c.set('userId', session?.user.id);
await next();
passOnSetCookies(c.res, setCookies);
});
v0.get(
'/openapi.json',
openAPIRouteHandler(v0, { documentation: OPENAPI_DOCUMENTATION, exclude: ['/openapi.json'] }),
);
v0.get(
'/me',
describeRoute({
tags: ['Account'],
summary: 'My account',
responses: {
200: json('The signed-in account.', accountResponse),
401: signInRequired,
404: notFound('The account'),
},
}),
async (c) => {
const userId = c.get('userId');
if (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
const account = await loadAccount(c.get('db'), userId);
Iif (account === undefined) return c.json({ error: 'not-found' }, 404);
return c.json(account);
},
);
v0.patch(
'/me',
describeRoute({
tags: ['Account'],
summary: 'Change my handle or display name',
description:
'Fields left out stay as they are. The old handle stays reserved for the player, and its pages redirect to the new one.',
responses: {
200: json('The account after the change.', accountResponse),
400: json(
'The handle or the display name breaks a rule (`detail`: format, reserved, empty, length, characters).',
errorResponse(['invalid-handle', 'invalid-display-name']),
),
401: signInRequired,
404: notFound('The account'),
409: json('Another player holds this handle, now or formerly.', errorResponse(['handle-taken'])),
},
requestBody: { required: true, content: { 'application/json': { schema: resolver(profileUpdateBody) } } },
}),
validator('json', profileUpdateBody),
async (c) => {
const userId = c.get('userId');
if (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
Iif (c.env.AUTH_ISSUER)
return c.json({ error: 'managed-by-accounts', manageURL: new URL('/account', c.env.AUTH_ISSUER).href }, 409);
const result = await updateProfile(c.get('db'), userId, c.req.valid('json'));
if (!result.ok) {
return result.status === 400
? c.json({ error: result.error, detail: result.detail }, 400)
: c.json({ error: result.error }, result.status);
}
const account = await loadAccount(c.get('db'), userId);
Iif (account === undefined) return c.json({ error: 'not-found' }, 404);
return c.json(account);
},
);
v0.put(
'/me/avatar',
describeRoute({
tags: ['Account'],
summary: 'Upload my icon',
description: `The image itself as the body: WebP, PNG or JPEG (recognized by its signature), at most ${AVATAR_MAX_BYTES / 1024} KB. Clients shrink it to a 256 px square first.`,
requestBody: {
required: true,
content: {
'image/webp': { schema: { type: 'string', format: 'binary' } },
'image/png': { schema: { type: 'string', format: 'binary' } },
'image/jpeg': { schema: { type: 'string', format: 'binary' } },
},
},
responses: {
200: json('The account with its new icon.', accountResponse),
400: json('No image was sent.', errorResponse(['empty-body'])),
401: signInRequired,
413: json('The image is too large.', errorResponse(['avatar-too-large'])),
415: json('Not a WebP, PNG or JPEG image.', errorResponse(['unsupported-image'])),
},
}),
async (c) => {
const userId = c.get('userId');
Iif (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
Iif (c.env.AUTH_ISSUER)
return c.json({ error: 'managed-by-accounts', manageURL: new URL('/account', c.env.AUTH_ISSUER).href }, 409);
const declared = Number(c.req.header('content-length') ?? '0');
Iif (declared > AVATAR_MAX_BYTES) return c.json({ error: 'avatar-too-large' }, 413);
const bytes = new Uint8Array(await c.req.arrayBuffer());
const result = await putAvatar(c.get('db'), c.env.BLOBS, userId, bytes);
if (!result.ok) return c.json({ error: result.error }, result.status);
const account = await loadAccount(c.get('db'), userId);
Iif (account === undefined) return c.json({ error: 'not-found' }, 404);
return c.json(account);
},
);
v0.delete(
'/me/avatar',
describeRoute({
tags: ['Account'],
summary: 'Remove my icon',
description: 'Goes back to the icon generated from the account.',
responses: { 200: json('The account with the generated icon.', accountResponse), 401: signInRequired },
}),
async (c) => {
const userId = c.get('userId');
Iif (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
Iif (c.env.AUTH_ISSUER)
return c.json({ error: 'managed-by-accounts', manageURL: new URL('/account', c.env.AUTH_ISSUER).href }, 409);
await removeAvatar(c.get('db'), c.env.BLOBS, userId);
const account = await loadAccount(c.get('db'), userId);
Iif (account === undefined) return c.json({ error: 'not-found' }, 404);
return c.json(account);
},
);
v0.post(
'/scores',
describeRoute({
tags: ['Scores'],
summary: 'Submit a play',
description:
'Submits a replay with its fingerprint documents. The body is JSON, gzip-compressed (`Content-Encoding: ' +
'gzip`). The server re-simulates the play under every ruleset and answers its figures and ranks. The same ' +
'play submitted again by the same account answers 200 with the stored result. A play at another tempo, or a ' +
'course stage sent on its own, is stored without ranking it (`unranked`): the Leaderboard decides what it ' +
'shows.',
requestBody: {
required: true,
content: { 'application/json': { schema: resolver(submissionBody) } },
},
responses: {
201: json('Accepted.', submissionResponse),
200: json('Already submitted by this account: the stored result.', submissionResponse),
400: json(
'The body is not a submission.',
errorResponse(['invalid-submission', 'empty-body', 'invalid-encoding', 'invalid-json']),
),
401: signInRequired,
409: json(
'`chart-document-required`: send `chartDocument` too. `play-already-submitted`: another account sent it.',
errorResponse(['chart-document-required', 'play-already-submitted']),
),
413: json('The body is too large.', errorResponse(['body-too-large'])),
415: json('Not gzip-compressed JSON.', errorResponse(['expected-json', 'unsupported-encoding'])),
422: json(
'The play cannot be stored: an auto play, a malformed replay, a replay without fingerprints, a ' +
'fingerprint document that does not hash to the replay’s fingerprint, or a replay whose chart gameplay ' +
'options are not the ones its chart runs.',
errorResponse([
'invalid-replay',
'auto-play',
'two-player',
'missing-fingerprint',
'play-document-not-a-document',
'play-document-fingerprint-mismatch',
'chart-document-not-a-document',
'chart-document-fingerprint-mismatch',
'chart-play-options-mismatch',
]),
),
429: json('Too many submissions; retry after `Retry-After` seconds.', errorResponse(['rate-limited'])),
},
}),
async (c) => {
const userId = c.get('userId');
if (userId === undefined) {
return c.json({ error: 'sign-in-required' }, 401);
}
Iif (c.env.SUBMIT_LIMITER !== undefined) {
const { success } = await c.env.SUBMIT_LIMITER.limit({ key: userId });
if (!success) return c.json({ error: 'rate-limited' }, 429, { 'Retry-After': '60' });
}
const body = await readJSONBody(c.req.raw, SUBMISSION_LIMITS);
Iif (!body.ok) {
return c.json({ error: body.reason }, body.status);
}
const parsedBody = v.safeParse(submissionBody, body.value);
Iif (!parsedBody.success) {
return c.json({ error: 'invalid-submission' }, 400);
}
let replay;
try {
replay = parseReplay(parsedBody.output.replay);
} catch (error) {
Eif (error instanceof ReplayParseError) return c.json({ error: 'invalid-replay', detail: error.message }, 422);
throw error;
}
const outcome = await submitScore(
{ db: c.get('db'), blobs: c.env.BLOBS, now, newId },
{
userId,
replay,
replayText: serializeReplay(replay),
playDocument: parsedBody.output.playDocument,
chartDocument: parsedBody.output.chartDocument,
submittedBy: c.req.header('be-music-client'),
},
);
if (outcome.status === 'rejected') {
return c.json({ error: outcome.reason }, outcome.httpStatus);
}
const { status, ...rest } = outcome;
// A chart seen for the first time is filed under its chartset after the response, without holding it up.
if (status === 'accepted') {
afterResponse(c, () => refreshChartsetIfUnchecked(c.get('db'), chartsetLookup, rest.chartFingerprint, now()));
}
return c.json(rest, status === 'accepted' ? 201 : 200);
},
);
v0.get(
'/scores/:id',
describeRoute({
tags: ['Scores'],
summary: 'A play',
description: 'A hidden play answers only its player; to anyone else it does not exist.',
responses: { 200: json('The play under every ruleset.', scoreResponse), 404: notFound('The score') },
}),
async (c) => {
const detail = await loadScoreDetail(c.get('db'), c.req.param('id'));
if (detail === undefined || !canSeeScore(detail.score, c.get('userId'))) {
return c.json({ error: 'not-found' }, 404);
}
return c.json(toScoreResponse(detail));
},
);
v0.patch(
'/scores/:id',
describeRoute({
tags: ['Scores'],
summary: 'Hide or show my play',
description:
'A hidden play is kept, but leaves the rankings, the personal bests, the figures and every list, and only its player can open it. The player’s bests on the chart are rebuilt from the plays still shown.',
responses: {
200: json('The play’s visibility after the change.', scoreVisibilityResponse),
401: signInRequired,
403: json('Someone else played it.', errorResponse(['not-your-score'])),
404: notFound('The score'),
},
}),
validator('json', scoreVisibilityBody),
async (c) => {
const userId = c.get('userId');
if (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
const id = c.req.param('id');
const result = await setScoreHidden(c.get('db'), id, userId, c.req.valid('json').hidden, now());
if (!result.ok) return c.json({ error: result.error }, result.status);
return c.json({ id, hidden: result.hidden });
},
);
v0.put(
'/scores/:id/card',
describeRoute({
tags: ['Scores'],
summary: 'Upload a play’s share card',
description: `The ${CARD_WIDTH} x ${CARD_HEIGHT} picture link previews of the score page show (og:image), drawn by the player’s browser: PNG, WebP or JPEG, at most ${CARD_MAX_BYTES / 1024} KB. Only the play’s player can upload it.`,
requestBody: {
required: true,
content: {
'image/png': { schema: { type: 'string', format: 'binary' } },
'image/webp': { schema: { type: 'string', format: 'binary' } },
'image/jpeg': { schema: { type: 'string', format: 'binary' } },
},
},
responses: {
200: json('Stored.', v.object({ cardUrl: v.string() })),
400: json('No image was sent.', errorResponse(['empty-body'])),
401: signInRequired,
403: json('Someone else played it.', errorResponse(['not-your-score'])),
404: notFound('The score'),
413: json('The image is too large.', errorResponse(['card-too-large'])),
415: json('Not a PNG, WebP or JPEG image.', errorResponse(['unsupported-image'])),
},
}),
async (c) => {
const userId = c.get('userId');
Iif (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
Iif (Number(c.req.header('content-length') ?? '0') > CARD_MAX_BYTES)
return c.json({ error: 'card-too-large' }, 413);
const bytes = new Uint8Array(await c.req.arrayBuffer());
const result = await putScoreCard(c.get('db'), c.env.BLOBS, c.req.param('id'), userId, bytes);
if (!result.ok) return c.json({ error: result.error }, result.status);
return c.json({ cardUrl: cardURL(c.req.param('id'), result.cardKey) });
},
);
v0.get(
'/scores/:id/replay',
describeRoute({
tags: ['Scores'],
summary: 'A play’s replay',
description: 'The stored replay, gzip-compressed. Only its player can read a private one.',
responses: {
200: { description: 'The replay (docs/replay.md).', content: { 'application/json': {} } },
404: notFound('The score or its replay'),
},
}),
async (c) => {
const access = await loadReplayAccess(c.get('db'), c.req.param('id'), c.get('userId'));
if (access === undefined) return c.json({ error: 'not-found' }, 404);
const object = await c.env.BLOBS.get(access.key);
Iif (object === null) return c.json({ error: 'not-found' }, 404);
return new Response(object.body, {
headers: {
'content-type': 'application/json',
'content-encoding': 'gzip',
'cache-control': access.public ? 'public, max-age=31536000, immutable' : 'private',
},
encodeBody: 'manual',
});
},
);
v0.get(
'/charts/:chartFingerprint/leaderboard',
describeRoute({
tags: ['Rankings'],
summary: 'A chart’s ranking',
description: 'Players by best EX-Score under one ruleset; ties share a rank.',
responses: { 200: json('A page of the ranking.', rankingResponse) },
}),
validator('query', rankingQuery),
async (c) => {
const query = c.req.valid('query');
const filter: RankingFilter = {
chartFingerprint: c.req.param('chartFingerprint'),
ruleset: query.ruleset,
assisted: isOn(query.assisted),
includeAnonymous: isOn(query.anonymous),
playedHereOnly: isOn(query.played),
};
const ranking = await loadRanking(c.get('db'), filter, { offset: query.offset, limit: query.limit });
return c.json({ ...ranking, offset: query.offset, limit: query.limit });
},
);
v0.get(
'/charts/:chartFingerprint/leaderboard/me',
describeRoute({
tags: ['Rankings'],
summary: 'My rank on a chart',
description: 'My best on the chart and my rank among every player, anonymous ones included.',
responses: {
200: json('My rank.', myRankResponse),
401: signInRequired,
404: json('I have not played the chart under these filters.', errorResponse(['not-played'])),
},
}),
validator('query', myRankQuery),
async (c) => {
const userId = c.get('userId');
Iif (userId === undefined) return c.json({ error: 'sign-in-required' }, 401);
const query = c.req.valid('query');
const mine = await loadMyRank(c.get('db'), {
userId,
chartFingerprint: c.req.param('chartFingerprint'),
ruleset: query.ruleset,
assisted: isOn(query.assisted),
});
Iif (mine === undefined) return c.json({ error: 'not-played' }, 404);
return c.json(mine);
},
);
mountCourseRoutes(v0, { now, newId });
return v0;
}
|