Skip to content

Commit 7fd8a82

Browse files
SirDarcanosclaude
andcommitted
Add the Rollful dice API as a Cloudflare Worker
Rollful hosts the opendice npm package behind a public HTTP API. This is the first milestone: the Worker, its guards, and its OpenAPI document. The Worker needs no nodejs_compat. OpenDice has no dependencies and no Node built-ins, and takes its randomness from crypto.getRandomValues, so wrangler.jsonc carries no compatibility flags. The tests run inside workerd rather than Node so that this stays true. OpenDice already caps formula length, dice per roll, explosions per die and bonuses, and its parse errors are safe to return. The API adds what a public endpoint needs on top: body size, batch size, CORS, rate limiting, and a dice budget counted across a whole request. That last one matters because the Workers free plan allows 10ms of CPU per request: one 1000d2! roll costs about 1.7ms, but twenty would cost about 34ms. Parsing costs roughly 1% of rolling, so the handler parses every formula, sums the dice, and refuses before rolling anything. Requests are validated with the same Zod schemas that generate /openapi.json, so the document cannot drift from the endpoints it describes. Limits live in one file, which the site will read to document them. Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
0 parents  commit 7fd8a82

26 files changed

Lines changed: 4233 additions & 0 deletions

‎.github/workflows/ci.yml‎

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
# SPDX-License-Identifier: MIT
2+
# Typecheck, test and format-check on every push to main and every pull request.
3+
name: CI
4+
5+
on:
6+
push:
7+
branches: [main]
8+
pull_request:
9+
10+
# No GitHub API calls are made, so no token permissions are needed.
11+
permissions: {}
12+
13+
jobs:
14+
check:
15+
runs-on: ubuntu-latest
16+
timeout-minutes: 10
17+
steps:
18+
- uses: actions/checkout@v5
19+
- uses: actions/setup-node@v4
20+
with:
21+
node-version: 24
22+
cache: npm
23+
- run: npm ci
24+
- run: npm run typecheck
25+
- run: npm test
26+
- run: npm run format:check

‎.github/workflows/deploy-api.yml‎

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
# SPDX-License-Identifier: MIT
2+
# Deploys the Worker to api.rollful.dev when main changes.
3+
#
4+
# The checks run again here rather than trusting CI's result, so a deploy cannot ship code
5+
# that was never verified at the commit being deployed.
6+
#
7+
# Requires two repository secrets:
8+
# CLOUDFLARE_API_TOKEN a token with the Workers Scripts Edit permission
9+
# CLOUDFLARE_ACCOUNT_ID the account owning rollful.dev
10+
name: Deploy API
11+
12+
on:
13+
push:
14+
branches: [main]
15+
paths:
16+
- 'apps/api/**'
17+
- 'packages/schema/**'
18+
- 'package.json'
19+
- 'package-lock.json'
20+
- '.github/workflows/deploy-api.yml'
21+
workflow_dispatch:
22+
23+
permissions: {}
24+
25+
# One deploy at a time, and never cancel one part-way through.
26+
concurrency:
27+
group: deploy-api
28+
cancel-in-progress: false
29+
30+
jobs:
31+
deploy:
32+
runs-on: ubuntu-latest
33+
timeout-minutes: 10
34+
environment: production
35+
steps:
36+
- uses: actions/checkout@v5
37+
- uses: actions/setup-node@v4
38+
with:
39+
node-version: 24
40+
cache: npm
41+
- run: npm ci
42+
- run: npm run typecheck
43+
- run: npm test
44+
45+
- name: Deploy
46+
run: npx wrangler deploy
47+
working-directory: apps/api
48+
env:
49+
CLOUDFLARE_API_TOKEN: ${{ secrets.CLOUDFLARE_API_TOKEN }}
50+
CLOUDFLARE_ACCOUNT_ID: ${{ secrets.CLOUDFLARE_ACCOUNT_ID }}
51+
52+
- name: Check the deployed API answers
53+
run: |
54+
for attempt in 1 2 3 4 5; do
55+
if curl -sf 'https://api.rollful.dev/v1/health' | grep -q '"status":"ok"'; then
56+
echo "Health check passed"
57+
exit 0
58+
fi
59+
echo "Attempt $attempt failed, retrying"
60+
sleep 5
61+
done
62+
echo "::error::The deployed API did not answer /v1/health"
63+
exit 1

‎.gitignore‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
node_modules/
2+
dist/
3+
.wrangler/
4+
.astro/
5+
.dev.vars
6+
*.tgz
7+
.DS_Store
8+
9+
# Regenerated by `wrangler types`, which every typecheck runs first.
10+
worker-configuration.d.ts

‎.prettierrc.json‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
{
2+
"semi": false,
3+
"singleQuote": true,
4+
"printWidth": 100
5+
}

‎AGENTS.md‎

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
# Working in this repository
2+
3+
Rollful is a hosted dice-rolling API built on the `opendice` npm package. This file is the
4+
single source of agent guidance. Setup, style and tests are in
5+
[CONTRIBUTING.md](CONTRIBUTING.md).
6+
7+
## What this repository is, and is not
8+
9+
Rollful hosts OpenDice. It does not reimplement it. Parsing, rolling, keep rules,
10+
explosions and the randomness all live in the package, and the API is a thin layer that
11+
adds what a public endpoint needs: validation, limits, CORS, rate limiting and an OpenAPI
12+
document.
13+
14+
If you find yourself writing dice logic here, it belongs in `opendice` instead.
15+
16+
Rollful is not tied to any game system. It knows what `4d6kh3` means and nothing about what
17+
anyone uses it for. Do not add rules, character sheets, system presets or named rolls.
18+
19+
## The line that must not be crossed
20+
21+
`RollContext.rand` lets a caller supply their own random source. It is not exposed through
22+
the API and must never be. A roll result records what the dice showed, never where the
23+
numbers came from, so a rigged source produces a result indistinguishable from a fair one.
24+
Exposing it would let anyone choose their own results while the response still looked
25+
honest.
26+
27+
## Layout
28+
29+
| Path | Contents |
30+
| ---------------------- | ------------------------------------------------ |
31+
| `apps/api` | the Worker: routes, guards, error mapping |
32+
| `apps/api/src/dice.ts` | the only place that calls OpenDice |
33+
| `packages/schema` | Zod schemas and the limits, shared with the site |
34+
35+
`packages/schema` is consumed as TypeScript source, not built. Both the Worker bundler and
36+
Astro compile it, so it has no build step.
37+
38+
## Where limits live
39+
40+
Every limit the API adds is in `packages/schema/src/limits.ts`, and nowhere else. The site
41+
reads the same file to document them, so a number changed there changes the guard, the
42+
OpenAPI document and the docs together. Do not hardcode a limit in a route or a test.
43+
44+
The limits OpenDice enforces itself are not repeated here. It already caps formula length,
45+
dice per roll, explosions per die, bonuses and the total's precision, and its parse errors
46+
are already safe to return: `excerpt()` replaces any character a formula cannot contain
47+
before quoting input back.
48+
49+
## The CPU budget
50+
51+
The Workers free plan allows 10ms of CPU per request. The worst single roll OpenDice will
52+
accept, `1000d2!`, costs about 1.7ms, so single rolls are safe by a wide margin.
53+
54+
Batches are not, which is why `assertWithinDiceBudget` exists. Twenty rolls of `1000d2!`
55+
would cost about 34ms. Parsing costs roughly 1% of rolling, so the handler parses every
56+
formula first, sums the dice, and refuses the request before rolling anything. Any new
57+
endpoint that rolls more than once must go through the same function.
58+
59+
## Node APIs
60+
61+
OpenDice uses none, and `wrangler.jsonc` deliberately has no `compatibility_flags` and no
62+
`nodejs_compat`. Randomness is `crypto.getRandomValues`, which workerd provides. The test
63+
"the Worker runs OpenDice without Node APIs" exists to catch a regression at deploy rather
64+
than in production. Do not add `nodejs_compat` to make a dependency work — pick a
65+
dependency that does not need it.
66+
67+
## Traps
68+
69+
- `roll()` returns objects made with `Object.create(null)`. They serialise fine, but they
70+
have no `hasOwnProperty` and no prototype. `dice.ts` copies the fields it needs rather
71+
than passing the object straight through.
72+
- `parseFormula()` throws on a string bonus that contains no dice, such as `'3'`. Numeric
73+
bonuses must be sent as numbers. This matches what OpenDice does internally.
74+
- The rate limit binding is per Cloudflare location, and `period` accepts only 10 or 60.
75+
Do not document it as a global quota.
76+
- A trailing word in a formula is a parse error unless the request lists it in `tags`. That
77+
is deliberate: an unrecognised word is far more often a typo than a tag.
78+
79+
## Style
80+
81+
Prose is neutral and direct, readable at high school level. It documents the product; it
82+
does not narrate.
83+
84+
Comments are kept to a minimum. Code should be self-explanatory, and a comment is only worth
85+
adding where the code cannot express the point. If the code could express it, change the
86+
code instead.
87+
88+
## Before you finish
89+
90+
```bash
91+
npm run typecheck && npm test && npm run format:check
92+
```

‎CHANGELOG.md‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
# Changelog
2+
3+
All notable changes to this project are documented here.
4+
5+
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/), and this
6+
project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7+
8+
## [Unreleased]
9+
10+
### Added
11+
12+
- The dice-rolling API as a Cloudflare Worker, serving `api.rollful.dev`.
13+
- `GET /v1/roll` for a roll from a query string.
14+
- `POST /v1/roll` for a roll with bonuses and tags.
15+
- `POST /v1/roll/batch` for several rolls in one request.
16+
- `GET /v1/health` for a liveness check.
17+
- `GET /openapi.json` for the OpenAPI 3.1 document, generated from the same Zod schemas
18+
that validate requests.
19+
- Request guards on top of the limits OpenDice already enforces: an 8 KB body, a
20+
200-character formula, 20 bonuses per roll, 20 rolls per batch, 1000 dice counted across
21+
a whole request, and 60 requests every 60 seconds per address.
22+
- `@rollful/schema`, holding the request and response schemas and every limit the API adds,
23+
shared with the site.
24+
- Tests running inside workerd, covering the grammar, each guard, CORS, rate limiting and
25+
the OpenAPI document.

‎CLAUDE.md‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
This project keeps a single source of truth for agent guidance in **`AGENTS.md`**.
2+
3+
👉 **Read [`AGENTS.md`](./AGENTS.md) before working in this codebase.** It covers what this
4+
repository is, the line that must not be crossed, where the limits live, why the CPU budget
5+
shapes the API, and the traps that have already caught someone.
6+
7+
Setup, code style and tests live in [`CONTRIBUTING.md`](./CONTRIBUTING.md).
8+
9+
Do not add separate guidance here — update `AGENTS.md` instead, so the two never drift
10+
apart.

‎CONTRIBUTING.md‎

Lines changed: 103 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
# Contributing
2+
3+
## Setup
4+
5+
Node 22 or later.
6+
7+
```bash
8+
npm install
9+
```
10+
11+
The repository uses npm workspaces. Install once at the root; do not install inside a
12+
workspace.
13+
14+
Two packages have install scripts that fetch platform binaries, `esbuild` and `workerd`.
15+
They are approved explicitly in the root `package.json` under `allowScripts`, so a new
16+
dependency that wants to run install scripts has to be approved deliberately.
17+
18+
## Running the API
19+
20+
```bash
21+
npm run dev
22+
```
23+
24+
This starts `wrangler dev` on `http://localhost:8787` with the same bindings as production,
25+
including the rate limiter.
26+
27+
```bash
28+
curl 'http://localhost:8787/v1/roll?formula=4d6kh3'
29+
curl 'http://localhost:8787/openapi.json'
30+
```
31+
32+
## Checks
33+
34+
```bash
35+
npm run typecheck
36+
npm test
37+
npm run format:check
38+
```
39+
40+
`npm run typecheck` regenerates `apps/api/worker-configuration.d.ts` with `wrangler types`
41+
before compiling, so binding types always match `wrangler.jsonc`. That file is generated and
42+
is not committed.
43+
44+
## Tests
45+
46+
Tests run inside workerd through `@cloudflare/vitest-pool-workers`, not in Node. This is
47+
deliberate: the API's whole premise is that OpenDice needs no Node compatibility layer, and
48+
a test running in Node would not prove it.
49+
50+
```bash
51+
npm test --workspace @rollful/api
52+
cd apps/api && npx vitest # watch mode
53+
```
54+
55+
Tests drive the Worker over HTTP through `SELF`, so middleware, validation, error mapping
56+
and CORS are all covered rather than bypassed. Each request sends its own
57+
`cf-connecting-ip`, because the rate limiter is real in local tests too and a shared address
58+
would make one test spend another's budget.
59+
60+
Read limits from `@rollful/schema` in tests rather than repeating the numbers.
61+
62+
## Style
63+
64+
Prettier settings are in `.prettierrc.json`: no semicolons, single quotes, 100 columns.
65+
66+
```bash
67+
npm run format
68+
```
69+
70+
Prose is neutral and direct, readable at high school level. Comments are kept to a minimum;
71+
code should explain itself, and a comment is only worth adding where the code cannot express
72+
the point.
73+
74+
Every source file starts with the SPDX header:
75+
76+
```ts
77+
// SPDX-License-Identifier: MIT
78+
// Copyright (C) 2026 Nicola Mustone
79+
```
80+
81+
## Deploying
82+
83+
Pushes to `main` deploy the Worker through GitHub Actions. It needs two repository secrets:
84+
85+
| Secret | Value |
86+
| ----------------------- | ------------------------------------------------------------- |
87+
| `CLOUDFLARE_API_TOKEN` | a token created from the **Edit Cloudflare Workers** template |
88+
| `CLOUDFLARE_ACCOUNT_ID` | the account owning `rollful.dev`, from `npx wrangler whoami` |
89+
90+
To deploy by hand:
91+
92+
```bash
93+
npm run deploy
94+
```
95+
96+
`api.rollful.dev` is a Worker Custom Domain, so Cloudflare creates the DNS record and issues
97+
the certificate on the first deploy. There is no DNS record to add by hand, and none to keep
98+
in step afterwards. The `rollful.dev` zone must already exist in the account.
99+
100+
## Changes
101+
102+
Add an entry to [CHANGELOG.md](CHANGELOG.md) under `Unreleased` for anything that changes
103+
the API's behaviour, its limits, or its response shapes.

‎LICENSE‎

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,21 @@
1+
MIT License
2+
3+
Copyright (c) 2026 Nicola Mustone
4+
5+
Permission is hereby granted, free of charge, to any person obtaining a copy
6+
of this software and associated documentation files (the "Software"), to deal
7+
in the Software without restriction, including without limitation the rights
8+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9+
copies of the Software, and to permit persons to whom the Software is
10+
furnished to do so, subject to the following conditions:
11+
12+
The above copyright notice and this permission notice shall be included in all
13+
copies or substantial portions of the Software.
14+
15+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
SOFTWARE.

0 commit comments

Comments
 (0)