codex-agent-hour-tracker 0.2.0__tar.gz → 0.2.2__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 (76) hide show
  1. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/.gitignore +3 -0
  2. codex_agent_hour_tracker-0.2.2/CHANGELOG.md +47 -0
  3. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/PKG-INFO +31 -4
  4. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/README.md +29 -3
  5. codex_agent_hour_tracker-0.2.2/SECURITY.md +41 -0
  6. codex_agent_hour_tracker-0.2.2/community/api.js +431 -0
  7. codex_agent_hour_tracker-0.2.2/community/auth.js +336 -0
  8. codex_agent_hour_tracker-0.2.2/community/cookies.js +34 -0
  9. codex_agent_hour_tracker-0.2.2/community/crypto.js +47 -0
  10. codex_agent_hour_tracker-0.2.2/community/db.js +233 -0
  11. codex_agent_hour_tracker-0.2.2/community/score.js +269 -0
  12. codex_agent_hour_tracker-0.2.2/community-env.d.ts +25 -0
  13. codex_agent_hour_tracker-0.2.2/docs/account-usage.md +23 -0
  14. codex_agent_hour_tracker-0.2.2/docs/community.md +111 -0
  15. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/docs/exports.md +9 -1
  16. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/docs/methodology.md +5 -1
  17. codex_agent_hour_tracker-0.2.2/functions/api/community/[[path]].js +7 -0
  18. codex_agent_hour_tracker-0.2.2/functions/community/_middleware.js +14 -0
  19. codex_agent_hour_tracker-0.2.2/migrations/0001_community.sql +79 -0
  20. codex_agent_hour_tracker-0.2.2/package-lock.json +1853 -0
  21. codex_agent_hour_tracker-0.2.2/package.json +20 -0
  22. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/pyproject.toml +9 -1
  23. codex_agent_hour_tracker-0.2.2/scripts/export_account_usage.py +14 -0
  24. codex_agent_hour_tracker-0.2.2/site/app.js +187 -0
  25. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/benchmarks/index.html +2 -2
  26. codex_agent_hour_tracker-0.2.2/site/community/index.html +170 -0
  27. codex_agent_hour_tracker-0.2.2/site/community.js +377 -0
  28. codex_agent_hour_tracker-0.2.2/site/favicon.png +0 -0
  29. codex_agent_hour_tracker-0.2.2/site/index.html +301 -0
  30. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/score.mjs +75 -0
  31. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/styles.css +235 -5
  32. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/skills/codex-agent-hour-tracker/SKILL.md +7 -0
  33. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/__init__.py +1 -1
  34. codex_agent_hour_tracker-0.2.2/src/agent_hour_tracker/account_usage.py +341 -0
  35. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/archive.py +10 -2
  36. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/cli.py +9 -0
  37. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/scanner.py +18 -2
  38. codex_agent_hour_tracker-0.2.2/src/agent_hour_tracker/session_io.py +47 -0
  39. codex_agent_hour_tracker-0.2.2/tests/community-api.mjs +260 -0
  40. codex_agent_hour_tracker-0.2.2/tests/community-auth.mjs +181 -0
  41. codex_agent_hour_tracker-0.2.2/tests/community-database.mjs +212 -0
  42. codex_agent_hour_tracker-0.2.2/tests/community-headers.mjs +32 -0
  43. codex_agent_hour_tracker-0.2.2/tests/community-runtime.mjs +121 -0
  44. codex_agent_hour_tracker-0.2.2/tests/community-score.mjs +78 -0
  45. codex_agent_hour_tracker-0.2.2/tests/community-security-auth.mjs +377 -0
  46. codex_agent_hour_tracker-0.2.2/tests/site-local.mjs +86 -0
  47. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/site-score.mjs +21 -0
  48. codex_agent_hour_tracker-0.2.2/tests/site-ui.mjs +373 -0
  49. codex_agent_hour_tracker-0.2.2/tests/test_account_usage_exporter.py +338 -0
  50. codex_agent_hour_tracker-0.2.2/tests/test_compressed_sessions.py +189 -0
  51. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_public_files.py +18 -3
  52. codex_agent_hour_tracker-0.2.2/wrangler.jsonc +31 -0
  53. codex_agent_hour_tracker-0.2.0/CHANGELOG.md +0 -24
  54. codex_agent_hour_tracker-0.2.0/SECURITY.md +0 -27
  55. codex_agent_hour_tracker-0.2.0/site/app.js +0 -200
  56. codex_agent_hour_tracker-0.2.0/site/index.html +0 -362
  57. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/LICENSE +0 -0
  58. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/scripts/sync_benchmarks.py +0 -0
  59. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/_headers +0 -0
  60. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/benchmarks-data.js +0 -0
  61. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/benchmarks.js +0 -0
  62. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/favicon.svg +0 -0
  63. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/site/social-card.png +0 -0
  64. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/skills/codex-agent-hour-tracker/agents/openai.yaml +0 -0
  65. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/__main__.py +0 -0
  66. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/benchmarks.json +0 -0
  67. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/benchmarks.py +0 -0
  68. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/metrics.py +0 -0
  69. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/report.py +0 -0
  70. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/src/agent_hour_tracker/share.py +0 -0
  71. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_archive.py +0 -0
  72. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_cli.py +0 -0
  73. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_metrics.py +0 -0
  74. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_report.py +0 -0
  75. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/tests/test_scanner.py +0 -0
  76. {codex_agent_hour_tracker-0.2.0 → codex_agent_hour_tracker-0.2.2}/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
@@ -0,0 +1,47 @@
1
+ # Changelog
2
+
3
+ ## 0.2.2
4
+
5
+ - Add `agent-hours account-usage` for private, service-reported ChatGPT account usage JSON and daily CSV.
6
+ - Fingerprint account identity by default; require explicit flags for plaintext identity or stdout.
7
+ - Keep account usage separate from public share cards and the community scoreboard.
8
+
9
+ ## 0.2.1
10
+
11
+ - Read `.jsonl.zst` rollouts in local scans and private exports on Python 3.11–3.14.
12
+ - Prefer the plain file when matching plain and compressed rollouts exist together.
13
+ - Report invalid and truncated compressed streams without exposing transcript content.
14
+ - Preserve existing timing, source classification, and global turn deduplication rules.
15
+ - Require Agent Hours 0.2.1 or newer to merge new private exports. Older private exports remain readable.
16
+
17
+ ## Unreleased website update
18
+
19
+ - Put the local score card directly below the run command, with Upload and Preview tabs.
20
+ - Hide detailed explanations under Stats for Nerds by default.
21
+ - Add a separate, opt-in community scoreboard for self-reported scores.
22
+ - Add GitHub sign-in, bot checks, and five accepted posts per account in a rolling 30-day window.
23
+ - Keep local imports private until the user confirms a community post.
24
+ - Leave the Python package and timing methodology unchanged at 0.2.0.
25
+
26
+ ## 0.2.0
27
+
28
+ - Rename the public metric to Agent-Hour Score. Keep its exact 30-completed-calendar-day definition.
29
+ - Combine multiple session directories and private exports with global turn deduplication.
30
+ - Add explicit exec inclusion and show measurement scope on reports and cards.
31
+ - Calculate optional Agent Leverage from reported period hours or an estimated weekly schedule.
32
+ - Add monthly summaries with partial-period denominators.
33
+ - Export versioned sanitized score JSON for local browser share-card generation.
34
+ - Redesign agenthours.dev with an interactive parallel-runtime explanation, leverage calculator, share studio, and dated benchmarks.
35
+ - Keep the existing timing methodology and human-root duration statistics.
36
+
37
+ ## 0.1.2
38
+
39
+ - Document compaction compatibility and add regressions for retained timing metadata without conversation decoding.
40
+
41
+ ## 0.1.1
42
+
43
+ - Add human-initiated top-level turn count, mean, and median active duration.
44
+
45
+ ## 0.1.0
46
+
47
+ - Publish the local scanner, calendar-day reports, sanitized scorecard, optional skill, and static website.
@@ -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.2
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
@@ -60,6 +61,16 @@ codex-agent-hour-tracker --share
60
61
 
61
62
  Both command names invoke the same tool. Upgrade an existing uv installation with `uv tool upgrade codex-agent-hour-tracker`.
62
63
 
64
+ ## Private ChatGPT account usage
65
+
66
+ ```bash
67
+ agent-hours account-usage --label laptop
68
+ ```
69
+
70
+ Uses your existing ChatGPT-backed Codex login to request service-reported token summaries and daily buckets. API-key-only login is unsupported. It writes private JSON and daily CSV to `reports/account-usage/`, ignored in this repository, with no metrics printed. Choose `--output-dir` for another private location. Identity is fingerprinted by default; `--include-identity` explicitly includes plaintext identity. These exports must never enter share cards or the public scoreboard.
71
+
72
+ This is separate from archive-derived runtime. Daily history can be sparse; timezone, retention, and lifetime completeness are unknown. See [private account exports](docs/account-usage.md) for permissions, Windows, secure capture, and null values.
73
+
63
74
  ## Calculate Agent Leverage
64
75
 
65
76
  Supply your human hours for the entire report period:
@@ -82,10 +93,20 @@ Agent Leverage divides agent runtime by human hours over the same period. A week
82
93
  agent-hours --share --format json
83
94
  ```
84
95
 
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.
96
+ 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
97
 
87
98
  `--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
99
 
100
+ ## Join the community scoreboard
101
+
102
+ 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.
103
+
104
+ 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.
105
+
106
+ 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.
107
+
108
+ The local card tool works without an account or community access. Hosting and privacy details are in the [community guide](docs/community.md).
109
+
89
110
  ## Profiles and machines
90
111
 
91
112
  Repeat `--sessions-dir` to combine local profile directories:
@@ -132,15 +153,21 @@ Agent-hours measure runtime, not useful output, human-equivalent labor, or time
132
153
 
133
154
  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
155
 
156
+ 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.
157
+
135
158
  ## Development
136
159
 
137
160
  ```bash
138
161
  uv run python -m unittest discover -s tests -v
139
- node --test tests/site*.mjs
162
+ npm ci --ignore-scripts
163
+ npm test
164
+ npm run build:check
140
165
  python3 scripts/sync_benchmarks.py --check
141
166
  ```
142
167
 
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`.
168
+ 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.
169
+
170
+ 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
171
 
145
172
  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
173
 
@@ -34,6 +34,16 @@ codex-agent-hour-tracker --share
34
34
 
35
35
  Both command names invoke the same tool. Upgrade an existing uv installation with `uv tool upgrade codex-agent-hour-tracker`.
36
36
 
37
+ ## Private ChatGPT account usage
38
+
39
+ ```bash
40
+ agent-hours account-usage --label laptop
41
+ ```
42
+
43
+ Uses your existing ChatGPT-backed Codex login to request service-reported token summaries and daily buckets. API-key-only login is unsupported. It writes private JSON and daily CSV to `reports/account-usage/`, ignored in this repository, with no metrics printed. Choose `--output-dir` for another private location. Identity is fingerprinted by default; `--include-identity` explicitly includes plaintext identity. These exports must never enter share cards or the public scoreboard.
44
+
45
+ This is separate from archive-derived runtime. Daily history can be sparse; timezone, retention, and lifetime completeness are unknown. See [private account exports](docs/account-usage.md) for permissions, Windows, secure capture, and null values.
46
+
37
47
  ## Calculate Agent Leverage
38
48
 
39
49
  Supply your human hours for the entire report period:
@@ -56,10 +66,20 @@ Agent Leverage divides agent runtime by human hours over the same period. A week
56
66
  agent-hours --share --format json
57
67
  ```
58
68
 
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.
69
+ 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
70
 
61
71
  `--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
72
 
73
+ ## Join the community scoreboard
74
+
75
+ 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.
76
+
77
+ 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.
78
+
79
+ 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.
80
+
81
+ The local card tool works without an account or community access. Hosting and privacy details are in the [community guide](docs/community.md).
82
+
63
83
  ## Profiles and machines
64
84
 
65
85
  Repeat `--sessions-dir` to combine local profile directories:
@@ -106,15 +126,21 @@ Agent-hours measure runtime, not useful output, human-equivalent labor, or time
106
126
 
107
127
  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
128
 
129
+ 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.
130
+
109
131
  ## Development
110
132
 
111
133
  ```bash
112
134
  uv run python -m unittest discover -s tests -v
113
- node --test tests/site*.mjs
135
+ npm ci --ignore-scripts
136
+ npm test
137
+ npm run build:check
114
138
  python3 scripts/sync_benchmarks.py --check
115
139
  ```
116
140
 
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`.
141
+ 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.
142
+
143
+ 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
144
 
119
145
  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
146
 
@@ -0,0 +1,41 @@
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 archive scanner does not send session data over the network. The separate `account-usage` command queries OpenAI account services through the installed Codex app-server using an existing ChatGPT-backed login; it uploads no exports.
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
+ Account usage exports contain token metrics and daily activity. They use fingerprinted identity by default; fingerprints permit correlation and are not anonymization. Plaintext identity requires `--include-identity`. Default output is under ignored `reports/account-usage/`; other destinations require your own Git exclusions. Files are created exclusively as mode 0600 inside a mode 0700 output directory on POSIX. Direct Windows file output fails closed because private ACLs are not verified. `--stdout` is an explicit private-data disclosure to the caller; capture it securely. Account exports never enter the share schema or scoreboard. See [account export details](docs/account-usage.md).
24
+
25
+ ## Optional community scoreboard
26
+
27
+ 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.
28
+
29
+ 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.
30
+
31
+ 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.
32
+
33
+ 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.
34
+
35
+ 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.
36
+
37
+ All imported data is untrusted. A share card is self-reported and provides no cryptographic proof of runtime, identity, or productivity.
38
+
39
+ ## Reproduction details
40
+
41
+ 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 };