scorezilla 0.3.0-next.1 → 0.3.0-next.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/API.md +125 -7
- package/CHANGELOG.md +88 -0
- package/README.md +131 -0
- package/RECIPES.md +227 -0
- package/dist/{errors-B7hyC-C5.d.cts → errors-CWTmormh.d.cts} +1 -1
- package/dist/{errors-B7hyC-C5.d.ts → errors-CWTmormh.d.ts} +1 -1
- package/dist/identity.cjs +116 -4
- package/dist/identity.cjs.map +1 -1
- package/dist/identity.d.cts +53 -20
- package/dist/identity.d.ts +53 -20
- package/dist/identity.js +116 -4
- package/dist/identity.js.map +1 -1
- package/dist/index.cjs +2 -2
- package/dist/index.d.cts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +2 -2
- package/dist/server.cjs +344 -1
- package/dist/server.cjs.map +1 -1
- package/dist/server.d.cts +301 -3
- package/dist/server.d.ts +301 -3
- package/dist/server.js +338 -2
- package/dist/server.js.map +1 -1
- package/package.json +14 -3
package/API.md
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
# Scorezilla SDK — API Reference
|
|
2
2
|
|
|
3
|
-
> **Status:**
|
|
4
|
-
> (`scorezilla/server`
|
|
5
|
-
>
|
|
6
|
-
> [VERSIONING.md](./VERSIONING.md) for the
|
|
7
|
-
> guarantees.
|
|
3
|
+
> **Status:** The public-key client and the HMAC server adapter
|
|
4
|
+
> (`scorezilla/server` — incl. `createScoreSubmitHandler` + JWT verifiers) are
|
|
5
|
+
> stable; the `scorezilla/identity` presets ship in 0.3.0. See
|
|
6
|
+
> [CHANGELOG.md](./CHANGELOG.md) and [VERSIONING.md](./VERSIONING.md) for the
|
|
7
|
+
> release timeline and stability guarantees.
|
|
8
8
|
|
|
9
9
|
## Quick start
|
|
10
10
|
|
|
@@ -50,8 +50,9 @@ type ScorezillaConfig = PublicKeyConfig /* | SecretKeyConfig — v0.2.0 */;
|
|
|
50
50
|
|
|
51
51
|
- `publicKey`: `pk_<game-slug>_<base62-suffix>`. Issued by the operator
|
|
52
52
|
dashboard. Safe to embed in browser code.
|
|
53
|
-
- `secretKey
|
|
54
|
-
|
|
53
|
+
- `secretKey`: a single `sk_live_<keyId>_<random>` token (the keyId is embedded,
|
|
54
|
+
so you manage one value). Server-side only — used by the `scorezilla/server`
|
|
55
|
+
adapter to HMAC-sign the secure path. Never embed it in client code.
|
|
55
56
|
|
|
56
57
|
### Mutual exclusivity
|
|
57
58
|
|
|
@@ -255,6 +256,123 @@ try {
|
|
|
255
256
|
}
|
|
256
257
|
```
|
|
257
258
|
|
|
259
|
+
## Server adapter (`scorezilla/server`)
|
|
260
|
+
|
|
261
|
+
The public-key client is client-authoritative — any player can submit any score
|
|
262
|
+
from devtools. For ranking-sensitive boards, sign submissions server-side with a
|
|
263
|
+
`sk_live_*` secret. Full recipes are in the
|
|
264
|
+
[README](./README.md#server-side-hmac-scorezillaserver); the surface:
|
|
265
|
+
|
|
266
|
+
### `Scorezilla` (server client)
|
|
267
|
+
|
|
268
|
+
```ts
|
|
269
|
+
import { Scorezilla } from 'scorezilla/server';
|
|
270
|
+
|
|
271
|
+
const sz = new Scorezilla({
|
|
272
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!, // sk_live_<keyId>_<random>
|
|
273
|
+
});
|
|
274
|
+
await sz.submitScore({ boardId, playerId, score, metadata });
|
|
275
|
+
```
|
|
276
|
+
|
|
277
|
+
Same methods as the public-key client (`submitScore`, `getLeaderboard`,
|
|
278
|
+
`getPlayerRank`, `getWindowAround`); each request is HMAC-SHA256 signed and
|
|
279
|
+
verified server-side. Server-only — importing it in a browser throws.
|
|
280
|
+
|
|
281
|
+
### `createScoreSubmitHandler(config)`
|
|
282
|
+
|
|
283
|
+
A framework-agnostic factory returning a `(Request) => Promise<Response>`
|
|
284
|
+
handler (Cloudflare Workers, Next route handlers, Hono, Deno, Bun). You supply
|
|
285
|
+
your auth via `verify`; it owns parsing/validation, signing, and error → HTTP
|
|
286
|
+
mapping.
|
|
287
|
+
|
|
288
|
+
```ts
|
|
289
|
+
import { createScoreSubmitHandler, verifySupabaseJwt } from 'scorezilla/server';
|
|
290
|
+
|
|
291
|
+
export const POST = createScoreSubmitHandler({
|
|
292
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
293
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
294
|
+
verify: verifySupabaseJwt({ supabaseUrl: process.env.SUPABASE_URL! }),
|
|
295
|
+
});
|
|
296
|
+
```
|
|
297
|
+
|
|
298
|
+
| Option | Type | Notes |
|
|
299
|
+
| ---------------------------------------------------- | ------------------------------------------------ | ----------------------------------------------------------------------------------- |
|
|
300
|
+
| `secretKey` | `string` | `sk_live_*`. Required. |
|
|
301
|
+
| `boardId` | `string` | Required. |
|
|
302
|
+
| `verify` | `(req) => { playerId, metadata? } \| null` | Required. The submitted `playerId` always comes from here — never the request body. |
|
|
303
|
+
| `parseSubmission?` | `(req) => { score, metadata? } \| null` | Defaults to JSON `{ score, metadata? }`. |
|
|
304
|
+
| `rateLimit?` | `(req) => { ok, retryAfterSeconds? }` | Runs **before** `verify`. |
|
|
305
|
+
| `cors?` | `{ origin, methods?, headers?, maxAgeSeconds? }` | OPTIONS preflight + reflected `Access-Control-Allow-Origin`. |
|
|
306
|
+
| `baseUrl?` · `fetch?` · `maxRetries?` · `timeoutMs?` | | Pass-through to the server client. |
|
|
307
|
+
|
|
308
|
+
### JWT verifiers
|
|
309
|
+
|
|
310
|
+
Built-in `verify` helpers — each returns `(req) => Promise<{ playerId } | null>`.
|
|
311
|
+
They require the optional peer dependency `jose` (loaded lazily; only consumers
|
|
312
|
+
of a verifier install it).
|
|
313
|
+
|
|
314
|
+
```ts
|
|
315
|
+
import {
|
|
316
|
+
verifyJwt, // generic JWKS: { jwksUrl, issuer, audience, claim? }
|
|
317
|
+
verifySupabaseJwt, // { supabaseUrl }
|
|
318
|
+
verifyClerkJwt, // { issuer }
|
|
319
|
+
verifyAuth0Jwt, // { domain, audience }
|
|
320
|
+
verifyFirebaseIdToken, // { projectId }
|
|
321
|
+
} from 'scorezilla/server';
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
For non-JWKS auth (Auth.js JWE sessions, opaque sessions, provider backend
|
|
325
|
+
SDKs), write your own `verify` — anything returning `{ playerId }` works. See
|
|
326
|
+
[RECIPES.md](./RECIPES.md) for worked recipes.
|
|
327
|
+
|
|
328
|
+
### `createGitHubOAuthHandler(config)`
|
|
329
|
+
|
|
330
|
+
The server half of `useAuthProvider({ provider: 'github' })` (see the
|
|
331
|
+
identity section below): a `(Request) => Promise<Response>` callback endpoint
|
|
332
|
+
that exchanges GitHub's OAuth `code` (the client secret stays server-side),
|
|
333
|
+
resolves the user id, and hands `{ id }` back to the sign-in popup via a
|
|
334
|
+
`postMessage` pinned to your game's origin. Deploy it anywhere that speaks
|
|
335
|
+
web `Request`/`Response`, and register its URL as the OAuth app's callback
|
|
336
|
+
URL on GitHub.
|
|
337
|
+
|
|
338
|
+
| Option | Type | Notes |
|
|
339
|
+
| --------------- | -------- | ------------------------------------------------------------------- |
|
|
340
|
+
| `clientId` | `string` | Your GitHub OAuth app client ID. Required. |
|
|
341
|
+
| `clientSecret` | `string` | Server-only. Required. |
|
|
342
|
+
| `allowedOrigin` | `string` | Exact origin of the game page (the `postMessage` target). Required. |
|
|
343
|
+
| `fetch?` | | Inject a fetch (testing / custom transport). |
|
|
344
|
+
|
|
345
|
+
## Identity presets (`scorezilla/identity`)
|
|
346
|
+
|
|
347
|
+
Browser-side helpers producing the `playerId` for `submitScore`. All of them
|
|
348
|
+
are **client-authoritative** — see the trust-boundary note in the
|
|
349
|
+
[README](./README.md#player-identity-scorezillaidentity); for spoof-proof
|
|
350
|
+
identity use the secure path above.
|
|
351
|
+
|
|
352
|
+
```ts
|
|
353
|
+
import {
|
|
354
|
+
useAnonymousPlayer, // { storageKey } → PlayerHandle (UUID, persisted)
|
|
355
|
+
usePromptedPlayer, // { storageKey, prompt } → Promise<PlayerHandle>
|
|
356
|
+
useServerAuthoritative, // () → marker; playerId comes from your server
|
|
357
|
+
useAuthProvider, // OAuth sign-in → Promise<AuthPlayerHandle | null>
|
|
358
|
+
} from 'scorezilla/identity';
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
### `useAuthProvider(options)`
|
|
362
|
+
|
|
363
|
+
Discriminated on `provider`:
|
|
364
|
+
|
|
365
|
+
| Provider | Options | Flow |
|
|
366
|
+
| ---------- | --------------------------------------- | --------------------------------------------------------------------- |
|
|
367
|
+
| `'google'` | `clientId`, `storageKey`, `autoSelect?` | Google Identity Services One Tap, client-only |
|
|
368
|
+
| `'github'` | `clientId`, `exchangeUrl`, `storageKey` | Popup → your deployed `createGitHubOAuthHandler` endpoint (see above) |
|
|
369
|
+
|
|
370
|
+
Resolves an `AuthPlayerHandle` (`{ id, provider, source, signOut() }`) — or
|
|
371
|
+
`null` when the player **declines** (dismissed One Tap, cancelled on GitHub,
|
|
372
|
+
closed the popup). Throws only on genuine failures (invalid arguments, popup
|
|
373
|
+
blocked, exchange endpoint failure). `source: 'restored'` means the id was
|
|
374
|
+
rehydrated from `localStorage` without a fresh provider interaction.
|
|
375
|
+
|
|
258
376
|
## Advanced
|
|
259
377
|
|
|
260
378
|
### Custom fetch / polyfills
|
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,93 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.3.0-next.3
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- [#45](https://github.com/isco-tec/scorezilla-js/pull/45) [`1a1e625`](https://github.com/isco-tec/scorezilla-js/commit/1a1e625cc6aff058071f922c7c5a619efa80ddc8) Thanks [@isco-tec](https://github.com/isco-tec)! - feat(identity): ship the GitHub provider for `useAuthProvider` (scorezilla#194)
|
|
8
|
+
|
|
9
|
+
The GitHub option is real (and final, per ADR 0009): a popup OAuth web flow
|
|
10
|
+
on the client plus a turnkey server-side token exchange.
|
|
11
|
+
- `useAuthProvider({ provider: 'github', clientId, exchangeUrl, storageKey })`
|
|
12
|
+
— opens the GitHub sign-in popup, validates the callback by origin + state,
|
|
13
|
+
resolves `github:<id>` (or `null` on decline). The provisional option shape
|
|
14
|
+
is finalized: `clientId`, `exchangeUrl`, and `storageKey` are all required.
|
|
15
|
+
- `createGitHubOAuthHandler({ clientId, clientSecret, allowedOrigin })` (new
|
|
16
|
+
in `scorezilla/server`) — the deployable callback endpoint: exchanges the
|
|
17
|
+
code (secret stays server-side), resolves the user id, posts it back to the
|
|
18
|
+
game's origin, closes the popup. The access token never reaches the browser.
|
|
19
|
+
- size-limit: server caps 7 → 8 KB (documented); new tree-shaking proof pins
|
|
20
|
+
that adapter-only consumers pay for neither factory.
|
|
21
|
+
|
|
22
|
+
### Patch Changes
|
|
23
|
+
|
|
24
|
+
- [#44](https://github.com/isco-tec/scorezilla-js/pull/44) [`e7fcc42`](https://github.com/isco-tec/scorezilla-js/commit/e7fcc4262b5d0a706d29f05333335f746307cb47) Thanks [@isco-tec](https://github.com/isco-tec)! - docs: make the `useAuthProvider` trust boundary explicit (scorezilla#213)
|
|
25
|
+
|
|
26
|
+
Client OAuth identity is sign-in convenience, not anti-forgery — the derived
|
|
27
|
+
id is computed client-side and submitted with the public key. New
|
|
28
|
+
trust-boundary notes on the `useAuthProvider` JSDoc and `AuthPlayerHandle`, a
|
|
29
|
+
"Player identity" section in the README, and a RECIPES.md recipe ("OAuth
|
|
30
|
+
identity and the secure path") routing ranking-sensitive boards to
|
|
31
|
+
`createScoreSubmitHandler` with a server-verified identity.
|
|
32
|
+
|
|
33
|
+
## 0.3.0-next.2
|
|
34
|
+
|
|
35
|
+
### Minor Changes
|
|
36
|
+
|
|
37
|
+
- [#41](https://github.com/isco-tec/scorezilla-js/pull/41) [`e48a5a2`](https://github.com/isco-tec/scorezilla-js/commit/e48a5a2f09cd0f098e8466b51586bd4108bb5678) Thanks [@isco-tec](https://github.com/isco-tec)! - feat(server): `createScoreSubmitHandler()` — turnkey secure score submissions
|
|
38
|
+
|
|
39
|
+
A framework-agnostic factory in `scorezilla/server` that collapses the secure
|
|
40
|
+
(HMAC-signed) submission path from ~150 lines of boilerplate into a few. It
|
|
41
|
+
returns a standard `(Request) => Promise<Response>` handler — drop it into a
|
|
42
|
+
Cloudflare Worker, a Next.js route handler, Hono, Deno, or Bun.
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
import { createScoreSubmitHandler } from 'scorezilla/server';
|
|
46
|
+
|
|
47
|
+
export const POST = createScoreSubmitHandler({
|
|
48
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
49
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
50
|
+
verify: async (req) => {
|
|
51
|
+
// your auth — any provider; return the trusted playerId
|
|
52
|
+
const user = await myAuth(req);
|
|
53
|
+
return user ? { playerId: user.id } : null;
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
```
|
|
57
|
+
|
|
58
|
+
- The submitted `playerId` always comes from `verify` (the verified request),
|
|
59
|
+
never the request body — so ranking-sensitive boards aren't subject to the
|
|
60
|
+
client-authoritative submission of the public-key path.
|
|
61
|
+
- Owns body parsing/validation, HMAC signing, and `ScorezillaError` → HTTP
|
|
62
|
+
status mapping. Optional `cors` (OPTIONS preflight + reflected origin) and a
|
|
63
|
+
pre-verify `rateLimit` gate.
|
|
64
|
+
- Works with **any** auth via the `verify` callback (Supabase / Clerk / Auth0 /
|
|
65
|
+
Firebase JWTs, Lucia / opaque sessions, or a provider backend SDK). First-class
|
|
66
|
+
one-line verifiers (`verifySupabaseJwt`, `verifyJwt`) follow.
|
|
67
|
+
|
|
68
|
+
- [#42](https://github.com/isco-tec/scorezilla-js/pull/42) [`7ca5976`](https://github.com/isco-tec/scorezilla-js/commit/7ca5976857cfff44cc3a3c155181cd9f6276aea0) Thanks [@isco-tec](https://github.com/isco-tec)! - feat(server): built-in `verifyJwt` + `verifySupabaseJwt` for `createScoreSubmitHandler`
|
|
69
|
+
|
|
70
|
+
Turn the common "verify a JWT, derive the player id" step into a one-liner.
|
|
71
|
+
Both return a `verify` function you drop straight into `createScoreSubmitHandler`.
|
|
72
|
+
|
|
73
|
+
```ts
|
|
74
|
+
import { createScoreSubmitHandler, verifySupabaseJwt } from 'scorezilla/server';
|
|
75
|
+
|
|
76
|
+
export const POST = createScoreSubmitHandler({
|
|
77
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
78
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
79
|
+
verify: verifySupabaseJwt({ supabaseUrl: process.env.SUPABASE_URL! }),
|
|
80
|
+
});
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
- `verifyJwt({ jwksUrl, issuer, audience, claim? })` — generic JWKS verifier,
|
|
84
|
+
plus first-class presets for the popular providers: `verifySupabaseJwt({
|
|
85
|
+
supabaseUrl })`, `verifyClerkJwt({ issuer })`, `verifyAuth0Jwt({ domain,
|
|
86
|
+
audience })`, and `verifyFirebaseIdToken({ projectId })`.
|
|
87
|
+
- **`jose` is an optional peer dependency**, loaded lazily via dynamic
|
|
88
|
+
`import()` — consumers who use the public-key client, the factory with their
|
|
89
|
+
own `verify`, or a provider backend SDK never install or load it.
|
|
90
|
+
|
|
3
91
|
## 0.3.0-next.1
|
|
4
92
|
|
|
5
93
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -92,6 +92,60 @@ await sz.getWindowAround({ boardId, playerId, before?, after? });
|
|
|
92
92
|
See [**API.md**](./API.md) for the full reference, including every response
|
|
93
93
|
field, every error code, and advanced patterns.
|
|
94
94
|
|
|
95
|
+
## Player identity (`scorezilla/identity`)
|
|
96
|
+
|
|
97
|
+
Browser-side helpers that produce the `playerId` you pass to `submitScore`:
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
import {
|
|
101
|
+
useAnonymousPlayer, // mints a UUID, persists in localStorage — no prompt
|
|
102
|
+
usePromptedPlayer, // asks once for a nickname, saves it, silent thereafter
|
|
103
|
+
useAuthProvider, // OAuth sign-in (Google + GitHub)
|
|
104
|
+
} from 'scorezilla/identity';
|
|
105
|
+
|
|
106
|
+
const player = await useAuthProvider({
|
|
107
|
+
provider: 'google',
|
|
108
|
+
clientId: 'YOUR_GOOGLE_CLIENT_ID.apps.googleusercontent.com',
|
|
109
|
+
storageKey: 'mygame:player',
|
|
110
|
+
});
|
|
111
|
+
if (player) await sz.submitScore({ boardId, playerId: player.id, score: 9001 });
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
**GitHub** needs one extra ingredient: GitHub's token exchange requires your
|
|
115
|
+
OAuth app's client secret, so you deploy a one-line exchange endpoint
|
|
116
|
+
(`createGitHubOAuthHandler` from `scorezilla/server`) and point the client at
|
|
117
|
+
it:
|
|
118
|
+
|
|
119
|
+
```ts
|
|
120
|
+
// Client — opens a GitHub sign-in popup; resolves github:<id> (or null on decline).
|
|
121
|
+
const player = await useAuthProvider({
|
|
122
|
+
provider: 'github',
|
|
123
|
+
clientId: 'YOUR_GITHUB_OAUTH_CLIENT_ID',
|
|
124
|
+
exchangeUrl: '/api/github-oauth',
|
|
125
|
+
storageKey: 'mygame:player',
|
|
126
|
+
});
|
|
127
|
+
|
|
128
|
+
// Server — deploy at /api/github-oauth and register that URL as the OAuth
|
|
129
|
+
// app's callback URL on GitHub. The secret + access token never reach the browser.
|
|
130
|
+
import { createGitHubOAuthHandler } from 'scorezilla/server';
|
|
131
|
+
|
|
132
|
+
export const GET = createGitHubOAuthHandler({
|
|
133
|
+
clientId: process.env.GITHUB_CLIENT_ID!,
|
|
134
|
+
clientSecret: process.env.GITHUB_CLIENT_SECRET!,
|
|
135
|
+
allowedOrigin: 'https://mygame.example', // your game page's origin
|
|
136
|
+
});
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
> **Trust boundary — all of these are client-authoritative.** `useAuthProvider`
|
|
140
|
+
> proves the player's identity _to the browser_, not to the leaderboard: the
|
|
141
|
+
> derived id is computed client-side and submitted with the public key, so it
|
|
142
|
+
> is exactly as forgeable as any other public-key write. OAuth identity is
|
|
143
|
+
> sign-in convenience for casual/vanity boards — **not anti-forgery**. For
|
|
144
|
+
> competitive or ranking-sensitive boards, submit through the secure path
|
|
145
|
+
> below (`createScoreSubmitHandler` + a server-verified identity); see
|
|
146
|
+
> [RECIPES.md](./RECIPES.md) for the combined "OAuth identity + secure
|
|
147
|
+
> submission" recipe.
|
|
148
|
+
|
|
95
149
|
## Server-side HMAC (`scorezilla/server`)
|
|
96
150
|
|
|
97
151
|
Public-key submissions are client-authoritative — anyone with your `pk_` can
|
|
@@ -122,6 +176,83 @@ browser throws at module evaluation. Use environment variables (or your
|
|
|
122
176
|
secret manager) to load the `sk_live_*` value; never embed it in a build
|
|
123
177
|
that ships to clients.
|
|
124
178
|
|
|
179
|
+
### Turnkey endpoint: `createScoreSubmitHandler`
|
|
180
|
+
|
|
181
|
+
Wiring the secure path by hand means verifying your auth, deriving the player
|
|
182
|
+
id from it, validating the body, signing, and mapping errors.
|
|
183
|
+
`createScoreSubmitHandler` does all of that — you supply only your auth. It
|
|
184
|
+
returns a standard `(Request) => Promise<Response>`, so it drops into a
|
|
185
|
+
Cloudflare Worker, a Next.js route handler, Hono, Deno, or Bun.
|
|
186
|
+
|
|
187
|
+
```ts
|
|
188
|
+
import { createScoreSubmitHandler } from 'scorezilla/server';
|
|
189
|
+
|
|
190
|
+
export const POST = createScoreSubmitHandler({
|
|
191
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
192
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
193
|
+
// The one app-specific bit: prove identity, return the TRUSTED playerId.
|
|
194
|
+
// The submitted playerId comes from here — never from the request body.
|
|
195
|
+
verify: async (req) => {
|
|
196
|
+
const user = await myAuth(req);
|
|
197
|
+
return user ? { playerId: user.id } : null;
|
|
198
|
+
},
|
|
199
|
+
cors: { origin: 'https://mygame.example' }, // omit for same-origin
|
|
200
|
+
});
|
|
201
|
+
```
|
|
202
|
+
|
|
203
|
+
Your client just POSTs `{ score, metadata? }` (plus its auth header) to the
|
|
204
|
+
endpoint; the handler signs and forwards it.
|
|
205
|
+
|
|
206
|
+
**Supabase? One line.** Built-in verifiers do the JWKS verification for you.
|
|
207
|
+
(`jose` is an optional peer dependency, loaded only when you use a built-in
|
|
208
|
+
verifier — `npm i jose`.)
|
|
209
|
+
|
|
210
|
+
```ts
|
|
211
|
+
import { createScoreSubmitHandler, verifySupabaseJwt } from 'scorezilla/server';
|
|
212
|
+
|
|
213
|
+
export const POST = createScoreSubmitHandler({
|
|
214
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
215
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
216
|
+
verify: verifySupabaseJwt({ supabaseUrl: process.env.SUPABASE_URL! }),
|
|
217
|
+
});
|
|
218
|
+
```
|
|
219
|
+
|
|
220
|
+
**Clerk, Auth0, and Firebase have presets too:**
|
|
221
|
+
|
|
222
|
+
```ts
|
|
223
|
+
import { verifyClerkJwt, verifyAuth0Jwt, verifyFirebaseIdToken } from 'scorezilla/server';
|
|
224
|
+
|
|
225
|
+
verify: verifyClerkJwt({ issuer: 'https://clerk.your-app.com' });
|
|
226
|
+
verify: verifyAuth0Jwt({ domain: 'you.us.auth0.com', audience: 'your-api' });
|
|
227
|
+
verify: verifyFirebaseIdToken({ projectId: 'your-firebase-project' });
|
|
228
|
+
```
|
|
229
|
+
|
|
230
|
+
**Any other JWKS provider** uses the generic `verifyJwt`:
|
|
231
|
+
|
|
232
|
+
```ts
|
|
233
|
+
import { verifyJwt } from 'scorezilla/server';
|
|
234
|
+
|
|
235
|
+
verify: verifyJwt({
|
|
236
|
+
jwksUrl: 'https://your-issuer/.well-known/jwks.json',
|
|
237
|
+
issuer: 'https://your-issuer',
|
|
238
|
+
audience: 'your-api', // claim: 'sub' (default) → playerId
|
|
239
|
+
});
|
|
240
|
+
```
|
|
241
|
+
|
|
242
|
+
**Anything else** — the `verify` callback is the universal seam. For
|
|
243
|
+
Auth.js/NextAuth (encrypted JWE sessions), Better Auth, opaque session
|
|
244
|
+
cookies, or a provider backend SDK, anything that returns `{ playerId }`
|
|
245
|
+
works:
|
|
246
|
+
|
|
247
|
+
```ts
|
|
248
|
+
verify: async (req) => {
|
|
249
|
+
const session = await validateSession(req); // your DB / SDK
|
|
250
|
+
return session ? { playerId: session.userId } : null;
|
|
251
|
+
};
|
|
252
|
+
```
|
|
253
|
+
|
|
254
|
+
Worked recipes for each of those live in [RECIPES.md](./RECIPES.md).
|
|
255
|
+
|
|
125
256
|
## Error handling
|
|
126
257
|
|
|
127
258
|
Every failure path — HTTP non-2xx, network error, timeout, abort, JSON parse
|
package/RECIPES.md
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
# Auth recipes — `createScoreSubmitHandler`
|
|
2
|
+
|
|
3
|
+
The built-in verifiers ([README](./README.md#turnkey-endpoint-createscoresubmithandler))
|
|
4
|
+
cover auth systems that issue **JWKS-verifiable bearer tokens** — Supabase,
|
|
5
|
+
Clerk, Auth0, Firebase, and any other provider via the generic `verifyJwt`.
|
|
6
|
+
|
|
7
|
+
This doc covers everything else: sessions that **cannot** be verified against a
|
|
8
|
+
public key set — encrypted session cookies (Auth.js), database-backed sessions
|
|
9
|
+
(Better Auth, roll-your-own), and provider backend SDKs. They all plug into the
|
|
10
|
+
same seam: the `verify` callback.
|
|
11
|
+
|
|
12
|
+
## The `verify` contract
|
|
13
|
+
|
|
14
|
+
```ts
|
|
15
|
+
verify: (req: Request) => Promise<{ playerId: string; metadata?: object } | null>;
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
- Return `{ playerId }` on success. The submitted `playerId` **always** comes
|
|
19
|
+
from `verify` — a `playerId` in the request body is ignored.
|
|
20
|
+
- Return `null` to reject (→ `401 unauthorized`). Throwing also rejects with
|
|
21
|
+
401; the error message is never surfaced to the client (it may carry token
|
|
22
|
+
internals), so prefer returning `null` explicitly.
|
|
23
|
+
- Read identity from **headers/cookies only**. The request body is reserved for
|
|
24
|
+
the score payload (`parseSubmission` consumes it).
|
|
25
|
+
- Optional `metadata` you return is trusted and **wins over** body metadata on
|
|
26
|
+
key conflicts — use it for server-verified fields like a display name.
|
|
27
|
+
- The optional `rateLimit` gate runs **before** `verify`, so unauthenticated
|
|
28
|
+
spam can't drive your auth/crypto work. Per-user limits belong inside
|
|
29
|
+
`verify` (after you know who the user is).
|
|
30
|
+
|
|
31
|
+
## Auth.js / NextAuth — encrypted JWE sessions
|
|
32
|
+
|
|
33
|
+
Auth.js does not expose a JWKS: its session cookie is a **JWE** — encrypted
|
|
34
|
+
with a key derived from `AUTH_SECRET` — so only your server can read it. Two
|
|
35
|
+
ways to wire it:
|
|
36
|
+
|
|
37
|
+
### In a Next.js App Router route handler
|
|
38
|
+
|
|
39
|
+
Call your Auth.js instance's `auth()` inside `verify` — it reads the session
|
|
40
|
+
from the ambient request context:
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
// app/api/submit-score/route.ts
|
|
44
|
+
import { createScoreSubmitHandler } from 'scorezilla/server';
|
|
45
|
+
import { auth } from '@/auth'; // your Auth.js config
|
|
46
|
+
|
|
47
|
+
export const POST = createScoreSubmitHandler({
|
|
48
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
49
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
50
|
+
verify: async () => {
|
|
51
|
+
const session = await auth();
|
|
52
|
+
return session?.user?.id ? { playerId: session.user.id } : null;
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
> **Note:** `session.user.id` is not populated by default with the JWT session
|
|
58
|
+
> strategy — expose it in your Auth.js config's `session` callback
|
|
59
|
+
> (`session.user.id = token.sub`), or use the `getToken` recipe below, where
|
|
60
|
+
> `sub` is always present.
|
|
61
|
+
|
|
62
|
+
### Anywhere else (framework-agnostic)
|
|
63
|
+
|
|
64
|
+
`getToken` decrypts the session cookie (or `Authorization` header) directly
|
|
65
|
+
from the `Request` — no Next context needed, so it works in the handler's
|
|
66
|
+
`verify` on any runtime:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { createScoreSubmitHandler } from 'scorezilla/server';
|
|
70
|
+
import { getToken } from 'next-auth/jwt'; // or '@auth/core/jwt' outside Next
|
|
71
|
+
|
|
72
|
+
export const handler = createScoreSubmitHandler({
|
|
73
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
74
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
75
|
+
verify: async (req) => {
|
|
76
|
+
const token = await getToken({
|
|
77
|
+
req,
|
|
78
|
+
secret: process.env.AUTH_SECRET!,
|
|
79
|
+
// The cookie name carries a __Secure- prefix on https. Auth.js infers
|
|
80
|
+
// this from AUTH_URL; set it explicitly where AUTH_URL isn't available.
|
|
81
|
+
secureCookie: true,
|
|
82
|
+
});
|
|
83
|
+
return token?.sub ? { playerId: token.sub } : null;
|
|
84
|
+
},
|
|
85
|
+
});
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
NextAuth **v4** uses a different default cookie name — add
|
|
89
|
+
`cookieName: 'next-auth.session-token'` (or its `__Secure-` variant) to the
|
|
90
|
+
`getToken` call.
|
|
91
|
+
|
|
92
|
+
## Better Auth — database-backed sessions
|
|
93
|
+
|
|
94
|
+
Better Auth sessions are opaque tokens looked up server-side. Its server API
|
|
95
|
+
takes the request headers directly:
|
|
96
|
+
|
|
97
|
+
```ts
|
|
98
|
+
import { createScoreSubmitHandler } from 'scorezilla/server';
|
|
99
|
+
import { auth } from './auth'; // your Better Auth instance
|
|
100
|
+
|
|
101
|
+
export const handler = createScoreSubmitHandler({
|
|
102
|
+
secretKey: process.env.SCOREZILLA_SECRET_KEY!,
|
|
103
|
+
boardId: process.env.SCOREZILLA_BOARD_ID!,
|
|
104
|
+
verify: async (req) => {
|
|
105
|
+
const session = await auth.api.getSession({ headers: req.headers });
|
|
106
|
+
return session ? { playerId: session.user.id } : null;
|
|
107
|
+
},
|
|
108
|
+
});
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
## Any opaque session cookie
|
|
112
|
+
|
|
113
|
+
For roll-your-own sessions (or anything storing a session id in a cookie and
|
|
114
|
+
the session itself in a DB/KV/Redis), `verify` is a cookie parse + store
|
|
115
|
+
lookup:
|
|
116
|
+
|
|
117
|
+
```ts
|
|
118
|
+
const SESSION_COOKIE = 'sid';
|
|
119
|
+
|
|
120
|
+
verify: async (req) => {
|
|
121
|
+
const cookies = req.headers.get('cookie') ?? '';
|
|
122
|
+
const match = new RegExp(`(?:^|;\\s*)${SESSION_COOKIE}=([^;]+)`).exec(cookies);
|
|
123
|
+
if (!match) return null;
|
|
124
|
+
|
|
125
|
+
const session = await sessionStore.get(match[1]); // your DB / KV / Redis
|
|
126
|
+
if (!session || session.expiresAt < now()) return null;
|
|
127
|
+
|
|
128
|
+
return { playerId: session.userId };
|
|
129
|
+
},
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
Encrypted-cookie systems (e.g. iron-session) are the same shape — replace the
|
|
133
|
+
store lookup with the library's unseal/decrypt call and read the user id from
|
|
134
|
+
the decrypted payload.
|
|
135
|
+
|
|
136
|
+
## Provider backend SDKs
|
|
137
|
+
|
|
138
|
+
Already shipping a provider's admin SDK? Wrap it instead of re-verifying
|
|
139
|
+
tokens yourself. For example, Firebase Admin (alternative to the
|
|
140
|
+
`verifyFirebaseIdToken` JWKS preset):
|
|
141
|
+
|
|
142
|
+
```ts
|
|
143
|
+
import { getAuth } from 'firebase-admin/auth';
|
|
144
|
+
|
|
145
|
+
verify: async (req) => {
|
|
146
|
+
const token = req.headers.get('authorization')?.replace(/^Bearer\s+/i, '');
|
|
147
|
+
if (!token) return null;
|
|
148
|
+
try {
|
|
149
|
+
const decoded = await getAuth().verifyIdToken(token);
|
|
150
|
+
return { playerId: decoded.uid };
|
|
151
|
+
} catch {
|
|
152
|
+
return null; // bad signature / expired / wrong project
|
|
153
|
+
}
|
|
154
|
+
},
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
The same pattern fits any backend SDK that authenticates a request or token
|
|
158
|
+
and hands back a stable user id.
|
|
159
|
+
|
|
160
|
+
## Returning trusted metadata
|
|
161
|
+
|
|
162
|
+
Anything your session already proves can ride along as trusted metadata — it
|
|
163
|
+
overrides whatever the client put in the body for the same keys:
|
|
164
|
+
|
|
165
|
+
```ts
|
|
166
|
+
verify: async (req) => {
|
|
167
|
+
const session = await auth.api.getSession({ headers: req.headers });
|
|
168
|
+
if (!session) return null;
|
|
169
|
+
return {
|
|
170
|
+
playerId: session.user.id,
|
|
171
|
+
metadata: { displayName: session.user.name }, // server-verified, wins over body
|
|
172
|
+
};
|
|
173
|
+
},
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
## OAuth identity and the secure path
|
|
177
|
+
|
|
178
|
+
`useAuthProvider` (from `scorezilla/identity`) is **client-authoritative**: it
|
|
179
|
+
proves the player's identity to the browser, not to your endpoint — the
|
|
180
|
+
`google:<sub>` / `github:<id>` ids arrive at your endpoint from the client,
|
|
181
|
+
with no credential attached for `verify` to check. (Yes, the GitHub flow's
|
|
182
|
+
exchange endpoint verifies identity — but only inside the sign-in popup; at
|
|
183
|
+
score-submit time the id is still client-asserted.) Combining `useAuthProvider`
|
|
184
|
+
with the secure path looks like one of these:
|
|
185
|
+
|
|
186
|
+
**Your app has real auth (recommended).** Trust comes from your auth platform;
|
|
187
|
+
the OAuth handle is just sign-in UX. Verify the platform session as usual —
|
|
188
|
+
the verified user id is the `playerId`:
|
|
189
|
+
|
|
190
|
+
```ts
|
|
191
|
+
// Identity for TRUST: the verified Supabase/Clerk/Auth0/Firebase session.
|
|
192
|
+
verify: verifySupabaseJwt({ supabaseUrl: process.env.SUPABASE_URL! }),
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
If you want the OAuth display identity alongside, send it in the request
|
|
196
|
+
body's `metadata` — it's treated as untrusted client data, which is exactly
|
|
197
|
+
what it is.
|
|
198
|
+
|
|
199
|
+
**OAuth-only, no backend auth.** You can still route submissions through
|
|
200
|
+
`createScoreSubmitHandler` to keep `sk_*` off the client and gain payload
|
|
201
|
+
validation + rate limiting — but identity stays client-asserted, and the
|
|
202
|
+
endpoint should say so:
|
|
203
|
+
|
|
204
|
+
```ts
|
|
205
|
+
// ⚠️ Client-asserted: any client can claim any id. Acceptable for casual
|
|
206
|
+
// boards; NOT for ranking-sensitive ones — add real auth for that.
|
|
207
|
+
verify: async (req) => {
|
|
208
|
+
const playerId = req.headers.get('x-player-id'); // e.g. the google:<sub> id
|
|
209
|
+
return playerId ? { playerId } : null;
|
|
210
|
+
},
|
|
211
|
+
```
|
|
212
|
+
|
|
213
|
+
There is no middle option: an id that arrives from the browser without a
|
|
214
|
+
verifiable credential cannot be promoted to trusted server-side, no matter
|
|
215
|
+
which OAuth provider produced it.
|
|
216
|
+
|
|
217
|
+
## Hardening checklist
|
|
218
|
+
|
|
219
|
+
- **Never** derive `playerId` from the request body or an unverified header —
|
|
220
|
+
only from the verified session/token. (The handler enforces the body half of
|
|
221
|
+
this for you.)
|
|
222
|
+
- Use a stable, non-PII user id as `playerId` (auth user id, not an email).
|
|
223
|
+
- Add a cheap per-IP `rateLimit` gate; do per-user limits inside `verify`.
|
|
224
|
+
- Keep secrets (`SCOREZILLA_SECRET_KEY`, `AUTH_SECRET`, session-store
|
|
225
|
+
credentials) in env vars or a secret manager — never in client builds.
|
|
226
|
+
- Set `cors` only if the game is served from a different origin than the
|
|
227
|
+
endpoint; omit it for same-origin.
|
|
@@ -363,4 +363,4 @@ declare class ScorezillaError extends Error {
|
|
|
363
363
|
static timeout(timeoutMs: number): ScorezillaError;
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
-
export { type ApiSuccess as A, type BaseConfig as B, type LeaderboardResponse as L, type OutOfBoundsReason as O, type PlayerRankResponse as P, type RankedEntry as R, type
|
|
366
|
+
export { type ApiSuccess as A, type BaseConfig as B, type FetchImpl as F, type LeaderboardResponse as L, type OutOfBoundsReason as O, type PlayerRankResponse as P, type RankedEntry as R, type ScorezillaConfig as S, type WindowAroundResponse as W, type SubmitScoreResponse as a, type ApiError as b, type ApiResponse as c, type PublicKeyConfig as d, ScorezillaError as e, type ScorezillaErrorCode as f, type SecretKeyConfig as g };
|
|
@@ -363,4 +363,4 @@ declare class ScorezillaError extends Error {
|
|
|
363
363
|
static timeout(timeoutMs: number): ScorezillaError;
|
|
364
364
|
}
|
|
365
365
|
|
|
366
|
-
export { type ApiSuccess as A, type BaseConfig as B, type LeaderboardResponse as L, type OutOfBoundsReason as O, type PlayerRankResponse as P, type RankedEntry as R, type
|
|
366
|
+
export { type ApiSuccess as A, type BaseConfig as B, type FetchImpl as F, type LeaderboardResponse as L, type OutOfBoundsReason as O, type PlayerRankResponse as P, type RankedEntry as R, type ScorezillaConfig as S, type WindowAroundResponse as W, type SubmitScoreResponse as a, type ApiError as b, type ApiResponse as c, type PublicKeyConfig as d, ScorezillaError as e, type ScorezillaErrorCode as f, type SecretKeyConfig as g };
|