codex-agent-hour-tracker 0.2.0__tar.gz → 0.2.1__tar.gz

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.
Files changed (71) hide show
  1. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/.gitignore +3 -0
  2. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/CHANGELOG.md +17 -0
  3. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/PKG-INFO +21 -4
  4. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/README.md +19 -3
  5. codex_agent_hour_tracker-0.2.1/SECURITY.md +39 -0
  6. codex_agent_hour_tracker-0.2.1/community/api.js +431 -0
  7. codex_agent_hour_tracker-0.2.1/community/auth.js +336 -0
  8. codex_agent_hour_tracker-0.2.1/community/cookies.js +34 -0
  9. codex_agent_hour_tracker-0.2.1/community/crypto.js +47 -0
  10. codex_agent_hour_tracker-0.2.1/community/db.js +233 -0
  11. codex_agent_hour_tracker-0.2.1/community/score.js +269 -0
  12. codex_agent_hour_tracker-0.2.1/community-env.d.ts +25 -0
  13. codex_agent_hour_tracker-0.2.1/docs/community.md +111 -0
  14. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/docs/exports.md +5 -1
  15. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/docs/methodology.md +5 -1
  16. codex_agent_hour_tracker-0.2.1/functions/api/community/[[path]].js +7 -0
  17. codex_agent_hour_tracker-0.2.1/functions/community/_middleware.js +14 -0
  18. codex_agent_hour_tracker-0.2.1/migrations/0001_community.sql +79 -0
  19. codex_agent_hour_tracker-0.2.1/package-lock.json +1853 -0
  20. codex_agent_hour_tracker-0.2.1/package.json +20 -0
  21. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/pyproject.toml +9 -1
  22. codex_agent_hour_tracker-0.2.1/site/app.js +187 -0
  23. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/benchmarks/index.html +2 -2
  24. codex_agent_hour_tracker-0.2.1/site/community/index.html +170 -0
  25. codex_agent_hour_tracker-0.2.1/site/community.js +377 -0
  26. codex_agent_hour_tracker-0.2.1/site/favicon.png +0 -0
  27. codex_agent_hour_tracker-0.2.1/site/index.html +301 -0
  28. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/score.mjs +75 -0
  29. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/styles.css +235 -5
  30. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/__init__.py +1 -1
  31. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/archive.py +10 -2
  32. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/cli.py +2 -0
  33. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/scanner.py +18 -2
  34. codex_agent_hour_tracker-0.2.1/src/agent_hour_tracker/session_io.py +47 -0
  35. codex_agent_hour_tracker-0.2.1/tests/community-api.mjs +260 -0
  36. codex_agent_hour_tracker-0.2.1/tests/community-auth.mjs +181 -0
  37. codex_agent_hour_tracker-0.2.1/tests/community-database.mjs +212 -0
  38. codex_agent_hour_tracker-0.2.1/tests/community-headers.mjs +32 -0
  39. codex_agent_hour_tracker-0.2.1/tests/community-runtime.mjs +121 -0
  40. codex_agent_hour_tracker-0.2.1/tests/community-score.mjs +78 -0
  41. codex_agent_hour_tracker-0.2.1/tests/community-security-auth.mjs +377 -0
  42. codex_agent_hour_tracker-0.2.1/tests/site-local.mjs +86 -0
  43. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/site-score.mjs +21 -0
  44. codex_agent_hour_tracker-0.2.1/tests/site-ui.mjs +373 -0
  45. codex_agent_hour_tracker-0.2.1/tests/test_compressed_sessions.py +189 -0
  46. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_public_files.py +18 -3
  47. codex_agent_hour_tracker-0.2.1/wrangler.jsonc +31 -0
  48. codex_agent_hour_tracker-0.2.0/SECURITY.md +0 -27
  49. codex_agent_hour_tracker-0.2.0/site/app.js +0 -200
  50. codex_agent_hour_tracker-0.2.0/site/index.html +0 -362
  51. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/LICENSE +0 -0
  52. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/scripts/sync_benchmarks.py +0 -0
  53. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/_headers +0 -0
  54. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/benchmarks-data.js +0 -0
  55. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/benchmarks.js +0 -0
  56. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/favicon.svg +0 -0
  57. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/site/social-card.png +0 -0
  58. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/skills/codex-agent-hour-tracker/SKILL.md +0 -0
  59. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/skills/codex-agent-hour-tracker/agents/openai.yaml +0 -0
  60. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/__main__.py +0 -0
  61. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/benchmarks.json +0 -0
  62. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/benchmarks.py +0 -0
  63. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/metrics.py +0 -0
  64. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/report.py +0 -0
  65. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/src/agent_hour_tracker/share.py +0 -0
  66. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_archive.py +0 -0
  67. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_cli.py +0 -0
  68. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_metrics.py +0 -0
  69. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_report.py +0 -0
  70. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_scanner.py +0 -0
  71. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.1}/tests/test_v020_reports.py +0 -0
@@ -15,3 +15,6 @@ __pycache__/
15
15
  !.env.example
16
16
  .dev.vars
17
17
  .wrangler/
18
+ node_modules/
19
+ .dev.vars.*
20
+ !.dev.vars.example
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.2.1
4
+
5
+ - Read `.jsonl.zst` rollouts in local scans and private exports on Python 3.11–3.14.
6
+ - Prefer the plain file when matching plain and compressed rollouts exist together.
7
+ - Report invalid and truncated compressed streams without exposing transcript content.
8
+ - Preserve existing timing, source classification, and global turn deduplication rules.
9
+ - Require Agent Hours 0.2.1 or newer to merge new private exports. Older private exports remain readable.
10
+
11
+ ## Unreleased website update
12
+
13
+ - Put the local score card directly below the run command, with Upload and Preview tabs.
14
+ - Hide detailed explanations under Stats for Nerds by default.
15
+ - Add a separate, opt-in community scoreboard for self-reported scores.
16
+ - Add GitHub sign-in, bot checks, and five accepted posts per account in a rolling 30-day window.
17
+ - Keep local imports private until the user confirms a community post.
18
+ - Leave the Python package and timing methodology unchanged at 0.2.0.
19
+
3
20
  ## 0.2.0
4
21
 
5
22
  - Rename the public metric to Agent-Hour Score. Keep its exact 30-completed-calendar-day definition.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.5
2
2
  Name: codex-agent-hour-tracker
3
- Version: 0.2.0
3
+ Version: 0.2.1
4
4
  Summary: Measure cumulative Codex agent runtime without decoding conversation content.
5
5
  Project-URL: Homepage, https://agenthours.dev
6
6
  Project-URL: Repository, https://github.com/tim-osterhus/codex-agent-hour-tracker
@@ -20,6 +20,7 @@ Classifier: Programming Language :: Python :: 3.14
20
20
  Classifier: Programming Language :: Python :: Implementation :: CPython
21
21
  Classifier: Programming Language :: Python :: Implementation :: PyPy
22
22
  Requires-Python: >=3.11
23
+ Requires-Dist: backports-zstd<2,>=1.0; python_version < '3.14'
23
24
  Requires-Dist: tzdata>=2025.2; platform_system == 'Windows'
24
25
  Requires-Dist: tzlocal<6,>=5.3
25
26
  Description-Content-Type: text/markdown
@@ -82,10 +83,20 @@ Agent Leverage divides agent runtime by human hours over the same period. A week
82
83
  agent-hours --share --format json
83
84
  ```
84
85
 
85
- Paste this sanitized aggregate JSON into the [share studio](https://agenthours.dev/#share). Preview and download a square or landscape PNG/SVG in your browser. Calculation and image generation run locally. The website accepts only the public score schema.
86
+ Upload or paste this sanitized aggregate JSON into the [share studio](https://agenthours.dev/#share). Preview and download a square or landscape PNG/SVG in your browser. Importing a score and making a card run locally. The website accepts only the public score schema.
86
87
 
87
88
  `--share` is the safe default for sharing, but dates, counts, durations, timezone, and optional human-hours assumptions remain a deliberate aggregate disclosure. Review the card before posting it.
88
89
 
90
+ ## Join the community scoreboard
91
+
92
+ The separate [community page](https://agenthours.dev/community/) shows self-reported scores. GitHub sign-in identifies the person posting, but does not verify their runtime. Scores can be edited or inflated.
93
+
94
+ After importing your score, choose **Share to community**. Review the public fields, sign in with GitHub, and confirm the post. Importing a file never posts it. The community score omits Agent Leverage and human-hours assumptions.
95
+
96
+ Each GitHub account can make five successful posts in a rolling 30-day window. Updating a score counts as a post. Deleting it does not refund a slot. The page warns you after your fourth post and shows when a slot opens.
97
+
98
+ The local card tool works without an account or community access. Hosting and privacy details are in the [community guide](docs/community.md).
99
+
89
100
  ## Profiles and machines
90
101
 
91
102
  Repeat `--sessions-dir` to combine local profile directories:
@@ -132,15 +143,21 @@ Agent-hours measure runtime, not useful output, human-equivalent labor, or time
132
143
 
133
144
  The scanner retains compact timing metadata without decoding conversation, reasoning, or tool payloads. No session data leaves the machine through the CLI. Compacted records remain supported while completed-turn metadata survives.
134
145
 
146
+ Scans and private exports read both `.jsonl` and `.jsonl.zst` rollouts. When both forms exist beside each other, the plain file takes precedence. Compressed input streams through the same metadata parser. Invalid or truncated compressed streams produce aggregate decompression diagnostics.
147
+
135
148
  ## Development
136
149
 
137
150
  ```bash
138
151
  uv run python -m unittest discover -s tests -v
139
- node --test tests/site*.mjs
152
+ npm ci --ignore-scripts
153
+ npm test
154
+ npm run build:check
140
155
  python3 scripts/sync_benchmarks.py --check
141
156
  ```
142
157
 
143
- The repository has a Python package in `src/agent_hour_tracker/`, synthetic tests in `tests/`, and a static website in `site/`. The [export contracts](docs/exports.md) define private merge data and public score data separately. The package benchmark registry generates the website copy through `scripts/sync_benchmarks.py`.
158
+ The repository has a Python package in `src/agent_hour_tracker/`, synthetic tests in `tests/`, and browser assets in `site/`. The optional community API uses Pages Functions in `functions/`, application code in `community/`, and D1 migrations in `migrations/`. Node.js 24 runs the website development tools. Installing the Python CLI does not install or run the website backend.
159
+
160
+ The [export contracts](docs/exports.md) define private merge data and public score data separately. The package benchmark registry generates the website copy through `scripts/sync_benchmarks.py`.
144
161
 
145
162
  The [optional Codex skill](https://github.com/tim-osterhus/codex-agent-hour-tracker/tree/main/skills/codex-agent-hour-tracker/) guides collection and sharing workflows. It is not required to install or run the tool.
146
163
 
@@ -56,10 +56,20 @@ Agent Leverage divides agent runtime by human hours over the same period. A week
56
56
  agent-hours --share --format json
57
57
  ```
58
58
 
59
- Paste this sanitized aggregate JSON into the [share studio](https://agenthours.dev/#share). Preview and download a square or landscape PNG/SVG in your browser. Calculation and image generation run locally. The website accepts only the public score schema.
59
+ Upload or paste this sanitized aggregate JSON into the [share studio](https://agenthours.dev/#share). Preview and download a square or landscape PNG/SVG in your browser. Importing a score and making a card run locally. The website accepts only the public score schema.
60
60
 
61
61
  `--share` is the safe default for sharing, but dates, counts, durations, timezone, and optional human-hours assumptions remain a deliberate aggregate disclosure. Review the card before posting it.
62
62
 
63
+ ## Join the community scoreboard
64
+
65
+ The separate [community page](https://agenthours.dev/community/) shows self-reported scores. GitHub sign-in identifies the person posting, but does not verify their runtime. Scores can be edited or inflated.
66
+
67
+ After importing your score, choose **Share to community**. Review the public fields, sign in with GitHub, and confirm the post. Importing a file never posts it. The community score omits Agent Leverage and human-hours assumptions.
68
+
69
+ Each GitHub account can make five successful posts in a rolling 30-day window. Updating a score counts as a post. Deleting it does not refund a slot. The page warns you after your fourth post and shows when a slot opens.
70
+
71
+ The local card tool works without an account or community access. Hosting and privacy details are in the [community guide](docs/community.md).
72
+
63
73
  ## Profiles and machines
64
74
 
65
75
  Repeat `--sessions-dir` to combine local profile directories:
@@ -106,15 +116,21 @@ Agent-hours measure runtime, not useful output, human-equivalent labor, or time
106
116
 
107
117
  The scanner retains compact timing metadata without decoding conversation, reasoning, or tool payloads. No session data leaves the machine through the CLI. Compacted records remain supported while completed-turn metadata survives.
108
118
 
119
+ Scans and private exports read both `.jsonl` and `.jsonl.zst` rollouts. When both forms exist beside each other, the plain file takes precedence. Compressed input streams through the same metadata parser. Invalid or truncated compressed streams produce aggregate decompression diagnostics.
120
+
109
121
  ## Development
110
122
 
111
123
  ```bash
112
124
  uv run python -m unittest discover -s tests -v
113
- node --test tests/site*.mjs
125
+ npm ci --ignore-scripts
126
+ npm test
127
+ npm run build:check
114
128
  python3 scripts/sync_benchmarks.py --check
115
129
  ```
116
130
 
117
- The repository has a Python package in `src/agent_hour_tracker/`, synthetic tests in `tests/`, and a static website in `site/`. The [export contracts](docs/exports.md) define private merge data and public score data separately. The package benchmark registry generates the website copy through `scripts/sync_benchmarks.py`.
131
+ The repository has a Python package in `src/agent_hour_tracker/`, synthetic tests in `tests/`, and browser assets in `site/`. The optional community API uses Pages Functions in `functions/`, application code in `community/`, and D1 migrations in `migrations/`. Node.js 24 runs the website development tools. Installing the Python CLI does not install or run the website backend.
132
+
133
+ The [export contracts](docs/exports.md) define private merge data and public score data separately. The package benchmark registry generates the website copy through `scripts/sync_benchmarks.py`.
118
134
 
119
135
  The [optional Codex skill](https://github.com/tim-osterhus/codex-agent-hour-tracker/tree/main/skills/codex-agent-hour-tracker/) guides collection and sharing workflows. It is not required to install or run the tool.
120
136
 
@@ -0,0 +1,39 @@
1
+ # Security
2
+
3
+ ## Supported versions
4
+
5
+ The latest version is the supported version. Update to the latest published version before investigating or reporting a security issue. Older versions may not contain current fixes.
6
+
7
+ ## Private reports
8
+
9
+ Report vulnerabilities privately through [GitHub Security Advisories](https://github.com/tim-osterhus/codex-agent-hour-tracker/security/advisories) and GitHub's private vulnerability reporting workflow. Do not use a public issue for undisclosed vulnerabilities.
10
+
11
+ Never attach Codex session files, transcripts, or full generated reports to a public issue. Those files can contain sensitive activity data even when the report looks operational.
12
+
13
+ The `--share` command emits a bounded aggregate designed for sharing. Sharing its dates, counts, or durations is still an intentional disclosure. Review the card before publishing it.
14
+
15
+ ## Data boundaries
16
+
17
+ The scanner reads local plain or Zstandard-compressed archive bytes and decodes only bounded timing and source metadata. It does not decode conversation, reasoning, or tool payloads. The CLI does not send session data over the network.
18
+
19
+ Private merge exports retain exact start timestamps, durations, source classes, and persistent hashed turn identifiers. Hashes permit correlation and do not anonymize activity. Keep these exports private. Full text and CSV reports also reveal activity patterns.
20
+
21
+ Public share exports use a separate allowlist of aggregate fields. The website validates that schema, rejects private archives, and renders images locally. Importing a score does not submit it. Downloaded cards still disclose their displayed aggregates and optional human-hours assumptions.
22
+
23
+ ## Optional community scoreboard
24
+
25
+ Publishing requires a separate confirmation on the community page. A post links your GitHub login to aggregate runtime, dates, timezone, scope, and software versions. It excludes daily rows, machine labels, turn identifiers, and human-hours assumptions. Public scores are visible to anyone and can be copied.
26
+
27
+ Choosing **Share to community** temporarily puts an allowlisted score in browser tab storage for the page handoff. It does not store the raw file or private archive. This is separate from posting to the server.
28
+
29
+ GitHub login requests no repository or email scopes. The service uses a Secure, HttpOnly, SameSite login cookie and checks the request origin and CSRF token for changes. GitHub access tokens are discarded after identity lookup. The site has no analytics scripts. Cloudflare Turnstile loads when you choose to post, and contacts Cloudflare for a bot check.
30
+
31
+ The database stores a stable GitHub account ID, login, session records, current public scores, and a short-lived posting ledger. Five accepted posts are allowed per account in a rolling 30-day window. A separate short-burst limit uses time-bucketed keyed IP fingerprints, not raw IP addresses. Fingerprints are private and are not a guarantee of anonymity.
32
+
33
+ Deleting a score removes its current public entry. It does not refund posting slots or erase copies others made. Expired private records are pruned during service use. Provider backups and operational logs can have separate retention. Hosting providers still receive normal connection metadata, including IP addresses. See the [community guide](docs/community.md) for retention and operator controls.
34
+
35
+ All imported data is untrusted. A share card is self-reported and provides no cryptographic proof of runtime, identity, or productivity.
36
+
37
+ ## Reproduction details
38
+
39
+ Describe the affected version, the command or input shape involved, and the observed impact. Provide a minimal reproduction that contains synthetic data. Do not include private session content.
@@ -0,0 +1,431 @@
1
+ import {
2
+ AuthError,
3
+ beginGitHubLogin,
4
+ finishGitHubLogin,
5
+ getSiteOrigin,
6
+ getSubmissionConfig,
7
+ loadSession,
8
+ revokeSession,
9
+ validateCsrf,
10
+ } from "./auth.js";
11
+ import { clearCookie, SESSION_COOKIE } from "./cookies.js";
12
+ import { hmacSha256 } from "./crypto.js";
13
+ import {
14
+ consumeRateBucket,
15
+ deleteOwnScore,
16
+ findAcceptedRequest,
17
+ getPublicScores,
18
+ getUserScores,
19
+ pruneRateBuckets,
20
+ pruneSessions,
21
+ quotaForUser,
22
+ recordAcceptedScore,
23
+ } from "./db.js";
24
+ import { parseScore, scoreDigest, ScoreValidationError } from "./score.js";
25
+
26
+ const MAX_BODY_BYTES = 64 * 1024;
27
+ const MAX_TURNSTILE_RESPONSE_BYTES = 16 * 1024;
28
+ const UUID_V4 = /^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
29
+
30
+ class ApiError extends Error {
31
+ constructor(code, status, message) {
32
+ super(message);
33
+ this.name = "ApiError";
34
+ this.code = code;
35
+ this.status = status;
36
+ }
37
+ }
38
+
39
+ const dbRequired = (env) => {
40
+ if (!env?.COMMUNITY_DB || typeof env.COMMUNITY_DB.prepare !== "function") {
41
+ throw new ApiError("community_unavailable", 503, "Community service is unavailable.");
42
+ }
43
+ return env.COMMUNITY_DB;
44
+ };
45
+
46
+ function responseJson(value, status = 200, { cache = "no-store", cookies = [] } = {}) {
47
+ const headers = new Headers({
48
+ "Content-Type": "application/json; charset=utf-8",
49
+ "X-Content-Type-Options": "nosniff",
50
+ "X-Frame-Options": "DENY",
51
+ "Referrer-Policy": "no-referrer",
52
+ "Content-Security-Policy": "default-src 'none'; frame-ancestors 'none'; base-uri 'none'",
53
+ "Cache-Control": cache,
54
+ });
55
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
56
+ return new Response(JSON.stringify(value), { status, headers });
57
+ }
58
+
59
+ function redirectResponse(location, cookies = []) {
60
+ const headers = new Headers({ Location: location, "Cache-Control": "no-store" });
61
+ for (const cookie of cookies) headers.append("Set-Cookie", cookie);
62
+ return new Response(null, { status: 302, headers });
63
+ }
64
+
65
+ function error(code, status, message) {
66
+ return new ApiError(code, status, message);
67
+ }
68
+
69
+ function enabledOrThrow(env) {
70
+ const config = getSubmissionConfig(env);
71
+ if (!config.enabled) throw error("submissions_disabled", 503, "Community submissions are disabled.");
72
+ return config;
73
+ }
74
+
75
+ function configuredOrThrow(env) {
76
+ const config = getSubmissionConfig(env);
77
+ if (!config.configured) {
78
+ throw error("community_unavailable", 503, "Community service is unavailable.");
79
+ }
80
+ return config;
81
+ }
82
+
83
+ function assertOrigin(request, env) {
84
+ const origin = getSiteOrigin(env);
85
+ if (!origin || request.headers.get("Origin") !== origin) {
86
+ throw error("origin_invalid", 403, "The request origin is not allowed.");
87
+ }
88
+ }
89
+
90
+ async function requireSession(request, env, now) {
91
+ configuredOrThrow(env);
92
+ const session = await loadSession(request, dbRequired(env), { now });
93
+ if (!session) throw error("authentication_required", 401, "GitHub sign-in is required.");
94
+ return session;
95
+ }
96
+
97
+ async function requireMutationSession(request, env, now) {
98
+ assertOrigin(request, env);
99
+ const session = await requireSession(request, env, now);
100
+ if (!(await validateCsrf(request, session))) {
101
+ throw error("csrf_invalid", 403, "The CSRF token is invalid.");
102
+ }
103
+ return session;
104
+ }
105
+
106
+ async function boundedRequestText(request, maxBytes = MAX_BODY_BYTES) {
107
+ const contentLength = Number(request.headers.get("Content-Length") ?? 0);
108
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
109
+ throw error("request_too_large", 413, "The request body is too large.");
110
+ }
111
+ const reader = request.body?.getReader();
112
+ if (!reader) {
113
+ const text = await request.text();
114
+ if (new TextEncoder().encode(text).byteLength > maxBytes) {
115
+ throw error("request_too_large", 413, "The request body is too large.");
116
+ }
117
+ return text;
118
+ }
119
+ const chunks = [];
120
+ let total = 0;
121
+ let oversized = false;
122
+ try {
123
+ while (true) {
124
+ const { done, value } = await reader.read();
125
+ if (done) break;
126
+ total += value.byteLength;
127
+ if (total > maxBytes) {
128
+ oversized = true;
129
+ throw error("request_too_large", 413, "The request body is too large.");
130
+ }
131
+ chunks.push(value);
132
+ }
133
+ } finally {
134
+ if (oversized) await reader.cancel().catch(() => {});
135
+ reader.releaseLock();
136
+ }
137
+ const bytes = new Uint8Array(total);
138
+ let offset = 0;
139
+ for (const chunk of chunks) {
140
+ bytes.set(chunk, offset);
141
+ offset += chunk.byteLength;
142
+ }
143
+ try {
144
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
145
+ } catch {
146
+ throw error("request_invalid", 400, "The request body is invalid JSON.");
147
+ }
148
+ }
149
+
150
+ async function readJsonBody(request, expectedKeys) {
151
+ const contentType = request.headers.get("Content-Type") ?? "";
152
+ if (!/^application\/json(?:\s*;|$)/i.test(contentType)) {
153
+ throw error("request_invalid", 400, "The request must use JSON.");
154
+ }
155
+ let body;
156
+ try {
157
+ body = JSON.parse(await boundedRequestText(request));
158
+ } catch (caught) {
159
+ if (caught instanceof ApiError) throw caught;
160
+ throw error("request_invalid", 400, "The request body is invalid JSON.");
161
+ }
162
+ if (
163
+ body === null ||
164
+ typeof body !== "object" ||
165
+ Array.isArray(body) ||
166
+ Object.keys(body).length !== expectedKeys.length ||
167
+ expectedKeys.some((key) => !Object.hasOwn(body, key))
168
+ ) {
169
+ throw error("request_invalid", 400, "The request fields are invalid.");
170
+ }
171
+ return body;
172
+ }
173
+
174
+ async function boundedResponseText(response, maxBytes) {
175
+ const contentLength = Number(response.headers.get("Content-Length") ?? 0);
176
+ if (Number.isFinite(contentLength) && contentLength > maxBytes) {
177
+ if (response.body) await response.body.cancel().catch(() => {});
178
+ return null;
179
+ }
180
+ const reader = response.body?.getReader();
181
+ if (!reader) {
182
+ const text = await response.text();
183
+ return new TextEncoder().encode(text).byteLength <= maxBytes ? text : null;
184
+ }
185
+ const chunks = [];
186
+ let total = 0;
187
+ let oversized = false;
188
+ try {
189
+ while (true) {
190
+ const { done, value } = await reader.read();
191
+ if (done) break;
192
+ total += value.byteLength;
193
+ if (total > maxBytes) {
194
+ oversized = true;
195
+ return null;
196
+ }
197
+ chunks.push(value);
198
+ }
199
+ } finally {
200
+ if (oversized) await reader.cancel().catch(() => {});
201
+ reader.releaseLock();
202
+ }
203
+ const bytes = new Uint8Array(total);
204
+ let offset = 0;
205
+ for (const chunk of chunks) {
206
+ bytes.set(chunk, offset);
207
+ offset += chunk.byteLength;
208
+ }
209
+ try {
210
+ return new TextDecoder("utf-8", { fatal: true }).decode(bytes);
211
+ } catch {
212
+ return null;
213
+ }
214
+ }
215
+
216
+ async function verifyTurnstile(env, request, token, requestId, fetchImpl) {
217
+ const ip = request.headers.get("CF-Connecting-IP");
218
+ const payload = {
219
+ secret: env.TURNSTILE_SECRET_KEY,
220
+ response: token,
221
+ idempotency_key: requestId,
222
+ };
223
+ if (ip && ip.length <= 64) payload.remoteip = ip;
224
+ let result;
225
+ try {
226
+ const response = await fetchImpl("https://challenges.cloudflare.com/turnstile/v0/siteverify", {
227
+ method: "POST",
228
+ // Never forward the secret to a redirect target; non-OK responses fail below.
229
+ redirect: "manual",
230
+ signal: AbortSignal.timeout(10_000),
231
+ headers: { "Content-Type": "application/json" },
232
+ body: JSON.stringify(payload),
233
+ });
234
+ const text = await boundedResponseText(response, MAX_TURNSTILE_RESPONSE_BYTES);
235
+ if (!response.ok || text === null) return false;
236
+ result = JSON.parse(text);
237
+ } catch {
238
+ return false;
239
+ }
240
+ const hostname = getSubmissionConfig(env).hostname;
241
+ return Boolean(
242
+ result &&
243
+ result.success === true &&
244
+ result.hostname === hostname &&
245
+ result.action === "community_post",
246
+ );
247
+ }
248
+
249
+ async function consumeWriteRateLimit(db, env, request, now) {
250
+ const suppliedIp = request.headers.get("CF-Connecting-IP");
251
+ const ip = suppliedIp && suppliedIp.length <= 64 ? suppliedIp : "unknown";
252
+ const bucketStart = Math.floor(now / 60_000) * 60_000;
253
+ const bucketHash = await hmacSha256(env.SESSION_SECRET, `${ip}\u0000${bucketStart}`);
254
+ await pruneRateBuckets(db, now);
255
+ return consumeRateBucket(db, bucketHash, bucketStart);
256
+ }
257
+
258
+ function requestIdValue(value) {
259
+ if (typeof value !== "string" || !UUID_V4.test(value)) {
260
+ throw error("request_invalid", 400, "The request ID must be a UUID.");
261
+ }
262
+ return value.toLowerCase();
263
+ }
264
+
265
+ async function postScore(request, env, { now, fetchImpl }) {
266
+ enabledOrThrow(env);
267
+ const session = await requireMutationSession(request, env, now);
268
+ const db = dbRequired(env);
269
+ const body = await readJsonBody(request, ["score", "turnstile_token", "request_id"]);
270
+ const requestId = requestIdValue(body.request_id);
271
+ if (typeof body.turnstile_token !== "string" || body.turnstile_token.length === 0 || body.turnstile_token.length > 2048) {
272
+ throw error("request_invalid", 400, "The Turnstile token is invalid.");
273
+ }
274
+ let score;
275
+ try {
276
+ score = parseScore(body.score, { now });
277
+ } catch (caught) {
278
+ if (caught instanceof ScoreValidationError) throw error("score_invalid", 400, "The public score is invalid.");
279
+ throw caught;
280
+ }
281
+ const digest = await scoreDigest(score);
282
+ const existing = await findAcceptedRequest(db, requestId);
283
+ if (existing) {
284
+ if (
285
+ Number(existing.github_id) !== session.githubId ||
286
+ existing.scope !== score.scope ||
287
+ existing.score_digest !== digest
288
+ ) {
289
+ throw error("request_id_conflict", 409, "The request ID was already used for another score.");
290
+ }
291
+ return responseJson({
292
+ ok: true,
293
+ quota: await quotaForUser(db, session.githubId, now),
294
+ });
295
+ }
296
+ if (!(await consumeWriteRateLimit(db, env, request, now))) {
297
+ throw error("rate_limited", 429, "Too many community submissions. Try again shortly.");
298
+ }
299
+ if (!(await verifyTurnstile(env, request, body.turnstile_token, requestId, fetchImpl))) {
300
+ throw error("turnstile_invalid", 400, "Turnstile verification failed.");
301
+ }
302
+ const result = await recordAcceptedScore(db, {
303
+ githubId: session.githubId,
304
+ login: session.login,
305
+ requestId,
306
+ score,
307
+ now,
308
+ });
309
+ if (result.status === "request_conflict") throw error("request_id_conflict", 409, "The request ID was already used for another score.");
310
+ if (result.status === "quota_exceeded") throw error("quota_exceeded", 429, "The rolling community posting quota has been reached.");
311
+ return responseJson({ ok: true, quota: result.quota });
312
+ }
313
+
314
+ async function deleteScore(request, env, { now }) {
315
+ const session = await requireMutationSession(request, env, now);
316
+ const body = await readJsonBody(request, ["scope"]);
317
+ if (body.scope !== "interactive-only" && body.scope !== "including-exec") {
318
+ throw error("request_invalid", 400, "The score scope is invalid.");
319
+ }
320
+ if (!(await consumeWriteRateLimit(dbRequired(env), env, request, now))) {
321
+ throw error("rate_limited", 429, "Too many community requests. Try again shortly.");
322
+ }
323
+ await deleteOwnScore(dbRequired(env), { githubId: session.githubId, scope: body.scope });
324
+ return responseJson({ ok: true });
325
+ }
326
+
327
+ async function logout(request, env, { now }) {
328
+ const session = await requireMutationSession(request, env, now);
329
+ const db = dbRequired(env);
330
+ if (!(await consumeWriteRateLimit(db, env, request, now))) {
331
+ throw error("rate_limited", 429, "Too many community requests. Try again shortly.");
332
+ }
333
+ await revokeSession(db, session, now);
334
+ return responseJson({ ok: true }, 200, { cookies: [clearCookie(SESSION_COOKIE)] });
335
+ }
336
+
337
+ async function session(request, env, now) {
338
+ const config = getSubmissionConfig(env);
339
+ if (!config.configured) {
340
+ return responseJson({ authenticated: false, user: null, csrf_token: null, quota: null, scores: [] });
341
+ }
342
+ const db = dbRequired(env);
343
+ const current = await loadSession(request, db, { now });
344
+ if (!current) {
345
+ return responseJson({ authenticated: false, user: null, csrf_token: null, quota: null, scores: [] });
346
+ }
347
+ return responseJson({
348
+ authenticated: true,
349
+ user: { login: current.login },
350
+ csrf_token: current.csrfToken,
351
+ quota: await quotaForUser(db, current.githubId, now),
352
+ scores: await getUserScores(db, current.githubId),
353
+ });
354
+ }
355
+
356
+ async function board(url, env, now) {
357
+ const db = dbRequired(env);
358
+ if (url.searchParams.getAll("scope").length !== 1 || [...url.searchParams.keys()].some((key) => key !== "scope")) {
359
+ throw error("request_invalid", 400, "A score scope is required.");
360
+ }
361
+ const scope = url.searchParams.get("scope");
362
+ if (scope !== "interactive-only" && scope !== "including-exec") {
363
+ throw error("request_invalid", 400, "The score scope is invalid.");
364
+ }
365
+ return responseJson({ scores: await getPublicScores(db, scope, { now, limit: 50 }) }, 200, { cache: "public, max-age=60" });
366
+ }
367
+
368
+ const AUTH_MESSAGES = Object.freeze({
369
+ community_unavailable: "Community service is unavailable.",
370
+ oauth_state_invalid: "The sign-in state is invalid or expired.",
371
+ oauth_failed: "GitHub sign-in could not be completed.",
372
+ submissions_disabled: "Community submissions are disabled.",
373
+ server_unavailable: "Community service is unavailable.",
374
+ });
375
+
376
+ function mapError(caught) {
377
+ if (caught instanceof ApiError) return responseJson({ error: caught.code, message: caught.message }, caught.status);
378
+ if (caught instanceof AuthError) {
379
+ return responseJson(
380
+ { error: caught.code, message: AUTH_MESSAGES[caught.code] ?? "GitHub sign-in could not be completed." },
381
+ caught.status,
382
+ );
383
+ }
384
+ if (caught instanceof ScoreValidationError) return responseJson({ error: "score_invalid", message: "The public score is invalid." }, 400);
385
+ return responseJson({ error: "server_error", message: "Community service is unavailable." }, 500);
386
+ }
387
+
388
+ /** Main route used by the Pages catch-all Function and direct integration tests. */
389
+ export async function routeCommunity(request, env, { now = Date.now(), fetchImpl = globalThis.fetch } = {}) {
390
+ const url = new URL(request.url);
391
+ const path = url.pathname.replace(/^\/api\/community\/?/, "");
392
+ try {
393
+ if (request.method === "GET" && path === "config") {
394
+ const config = getSubmissionConfig(env);
395
+ return responseJson(
396
+ { enabled: config.enabled, turnstile_site_key: config.turnstile_site_key },
397
+ 200,
398
+ { cache: "public, max-age=60" },
399
+ );
400
+ }
401
+ if (request.method === "GET" && path === "session") return await session(request, env, now);
402
+ if (request.method === "GET" && path === "scores") return await board(url, env, now);
403
+ if (request.method === "GET" && path === "auth/login") {
404
+ configuredOrThrow(env);
405
+ const db = dbRequired(env);
406
+ if (!(await consumeWriteRateLimit(db, env, request, now))) {
407
+ throw error("rate_limited", 429, "Too many community requests. Try again shortly.");
408
+ }
409
+ await pruneSessions(db, now);
410
+ return await beginGitHubLogin(env, { now });
411
+ }
412
+ if (request.method === "GET" && path === "auth/callback") {
413
+ configuredOrThrow(env);
414
+ const db = dbRequired(env);
415
+ if (!(await consumeWriteRateLimit(db, env, request, now))) {
416
+ throw error("rate_limited", 429, "Too many community requests. Try again shortly.");
417
+ }
418
+ await pruneSessions(db, now);
419
+ return await finishGitHubLogin(env, request, { now, fetchImpl });
420
+ }
421
+ if (request.method === "POST" && path === "scores") return await postScore(request, env, { now, fetchImpl });
422
+ if (request.method === "DELETE" && path === "scores") return await deleteScore(request, env, { now });
423
+ if (request.method === "POST" && path === "logout") return await logout(request, env, { now });
424
+ throw error("not_found", 404, "Community route not found.");
425
+ } catch (caught) {
426
+ if (caught instanceof Error && caught.code && caught.status) return mapError(caught);
427
+ return mapError(caught);
428
+ }
429
+ }
430
+
431
+ export { ApiError, MAX_BODY_BYTES };