Compare commits

..
Author SHA1 Message Date
CodeWhale Bot 6ec8176f97 chore(changelog): document maintainer and cron secret rules 2026-11-13 05:34:06 -08:00
CodeWhale Bot d544046fb3 web: refuse periodic repeated patterns in maintainer and cron secrets
Update secretStrongEnough to reject values that repeat a pattern with a period up to half the secret length, closing repeated short strings that pass the 8-distinct-character floor while leaving random hex, UUID and base64 secrets accepted. Update the 503 unavailability messages, operator docs and weak-secret test cases accordingly.

Checks: web npm test (7 node + 1316 vitest in 92 files), npx tsc --noEmit, npm run lint, npm run check:docs and npm run check pass.
2026-11-13 05:34:05 -08:00
CodeWhale BotandClaude Sonnet 5.5 06a5f9bbe1 web: accept hex and UUID secrets, and refuse secrets that contain lone surrogates
The distinct-character floor for the maintainer token and the cron secret is now 8
instead of 16, so a random hex secret (16 possible symbols) or a UUID is accepted.
A secret containing an unpaired UTF-16 surrogate is refused, since such a value is
encoded as the replacement character when it is compared. The documentation states
the new floor and gives a command for generating a secret.

Checks: web npm test 7 node + 1316 vitest in 92 files, tsc, lint and check:docs pass.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-13 05:34:03 -08:00
CodeWhale BotandClaude Sonnet 5.5 bed977ba04 web: bind admin sessions to the maintainer token and apply one strength rule to both secrets
A session now records a SHA-256 fingerprint of the MAINTAINER_TOKEN it was
issued under, and validation requires that fingerprint to match the token
currently configured. Changing the token therefore ends every open admin
session, sessions stored without a fingerprint are no longer accepted, and
a session is only issued when the configured token meets the minimum. The
draft post route, merch operator route, merch interest list and admin page
pass the configured token to validation; the extra length checks added at
those gates are dropped because validation now covers them.

The minimum is one rule shared by MAINTAINER_TOKEN and CRON_SECRET: 32 to
512 characters, counted by code point, with at least 16 distinct
characters. 512 matches the sign-in form's submit limit. A CRON_SECRET that
does not meet it leaves the manual cron trigger answering 503 with the
requirement, before the limiter or the comparison. The admin page logs the
requirement when the configured token is too weak, so operators can find it
in the Worker logs.

Tests: session binding and legacy records (community-agent), rotation at
login and at the merch interest list, weak token and weak cron secret
patterns, and the exact minimum. Web suite 1314 passed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-13 05:34:02 -08:00
CodeWhale BotandClaude Sonnet 5.5 b6b3013e7e web: rate limit the manual cron trigger and require a 32-character maintainer token
The manual /api/cron trigger now consults the shared rate limiter under its
own key before comparing the submitted secret, answers 429 with Retry-After
when the budget is spent, and answers 503 when the limiter is missing or
fails, so the secret is never compared without a bound on attempts.

Maintainer sign-in treats a MAINTAINER_TOKEN shorter than 32 characters as
unavailable: the login route answers 503 with a message naming the minimum,
and the admin page, the draft post route, the merch operator route and the
merch interest list apply the same check so an existing session stops being
honoured while the configured token is too short.

Tests: cron route (5), admin login (6, two new), merch interest (one new);
existing fixtures that used short tokens now use 32+ characters.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-13 05:34:00 -08:00
CodeWhale Bot 0002f88ca2 fix(api): keep repeated hook labels distinct in plugin index
Use the existing per-event ordinal for hook row identity. Hook names are optional labels and validation deliberately retains repeated names. The route regression covers repeated explicit labels and a label matching the unnamed fallback.

Validation: plugin-index route tests: 2 passed, 0 failed, 844 filtered out; cargo fmt --all -- --check and git diff --check passed; scripts/preflight.sh --check passed. macOS linker reported the existing __eh_frame size warning. Refs CW-7875.
2026-11-12 23:01:25 -08:00
CodeWhale BotandClaude Sonnet 5.5 fb43ff028a fix(config): show the telemetry setting default as on, matching the runtime
The settings schema declared telemetry default false while the resolver
(telemetry_consent_from_env) treats an unset value as on, so the settings
API reported default false for a default-on policy.

Landed in Engine push 18 (CW-7875) with the CHANGELOG line the review wrote
(CW-7987 REVIEW.md finding 2; the packet's line was not used). This is the
committed part only: CW-7987 stays open for the active-version readback and
the ingest bundle rebuilt from the frozen candidate. Review: farm runs
20261112T110021Z-gtelrev-config-37102e (codewhale-config, 21 run, 21 passed,
823 skipped) and 20261112T110024Z-gtelrev-telem-751b20 (codewhale-telemetry,
53 run, 53 passed).

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 23:01:24 -08:00
CodeWhale BotandClaude Sonnet 5.5 f8c3a015a4 feat(router): preserve explicit per-question decision abstention
An explicit abstained:true on a System One answer now survives decoding and the
routing receipt, and can never authorize Auto (tier), the thinking effort, a
shadow noul read or a shadow chat intent, even at a zero confidence floor. A
non-boolean abstained value fails answer decoding and is refused like any other
malformed answer. Provider usage evidence and the declared fallback are
unchanged. The custom decision endpoint half of the original change is not
included.

Receipt field abstained_questions touches crates/models, cost_status and the
tui activity_detail fixture outside the slice owner list; it is additive with a
serde default.

Landed in Engine push 18 (CW-7875) with the CHANGELOG line from the review (CW-7992 REVIEW.md finding 1). Review: farm run 20261112T112213Z-leg01review-tip-faf9ea, 42 run, 42 passed, 7181 skipped; counterfactual run 20261112T112313Z-leg01review-cf-032c60 fails 2 of 3 with the guards removed.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-12 23:01:23 -08:00
CodeWhale BotandClaude Sonnet 5.5 973d48e35c test(engine): expire the dropped-dispatch deadline only after the client call is entered (CW-8127)
The dropped-dispatch test gave the nested call a real 100 ms deadline. On a
slow runner that deadline could expire before bind_dispatch settled the
unknown-usage record, so the biased wall-clock select won with zero records
(left: 0, right: 1). Give the call a 600 s deadline, wait until the fixture
client is entered (the record is settled before the client is called), then
pause tokio time and advance 601 s so the deadline always fires after dispatch.
The wait selects on entered against the dispatch with a panic if the dispatch
ends first, inside a 10 s real-time timeout, so a regression that stops the
dispatch before the client fails at once instead of hanging. Every assertion is
unchanged. Product code is unchanged.

nextest stress 40/40 passed, 6 tests per iteration, target test 40/40 (farm run
20261112T113538Z-cw8127r1-new-33edc8); the old test under the same stress failed
1 of 20 at left: 0 (farm run 20261112T104528Z-cw8127-old-7569e0).
clippy -p codewhale-engine --all-targets --all-features -D warnings clean (farm
run 20261112T113538Z-cw8127r1-clippy-373b1e); cargo fmt --check and
scripts/preflight.sh --check OK.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 23:01:22 -08:00
CodeWhale BotandClaude Sonnet 5.5 5be2da2a69 fix(app-server): plugin index names plugins by id, labels tools, signals cut name lists (CW-8049 PL-02 repair 1)
/v1/commands rows carry plugin_id (not the name) and workspace_sourced; the
index projects an active plugin's commands from those rows, labels native and
language-server plugins as tool, sources project commands as project, and
reports a cut or control-character name list under problems. Doc comment
removed.

Checks (Boat farm, Linux x86_64, at c3bc310042): nextest -p codewhale-app-server
-p codewhale-tui -E 'test(/plugin_index|command_catalog|get_v1_commands|user_registry|commands::discovery/)':
51 run, 51 passed, 6713 skipped (run 20261112T080110Z-plidx4-test-26f07e);
clippy -D warnings for engine, app-server and tui: clean
(run 20261112T080110Z-plidx4-clippy-124ba8). fmt, runtime-routes and facts
were the worker's local checks; preflight was not run on that tip.

Landing (push 18): rebased onto push 17; agent-docs.generated.json conflicted
with push 17's regeneration and was regenerated with derive-facts at each of
the two picks. docs/RUNTIME_ROUTES.md: check-runtime-routes PASS, no change.
CHANGELOG line from the round-2 review wording.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 23:01:20 -08:00
CodeWhale BotandClaude Sonnet 5.5 9ca1c1c076 feat(app-server): one read route lists every plugin kind (CW-8049 PL-02)
GET /v1/apps/plugin-index projects the plugin registry, the built-in
switch catalog, skills, connectors, hooks and hand-written commands into
one list with kind, source and state. Each item embeds the row its owner's
route returns by calling that owner's handler, so a field an owner adds
appears here without a second edit; an owner that fails is named under
unavailable and the rest still list. A plugin item carries the names of the
skills, connectors, hooks, commands and profiles it adds, and those are
not listed again as items. Replaces nothing; the owners keep their routes.

A user command row now says which plugin added it (UserCommand.plugin,
CommandCatalogEntry.plugin, filled from the registry's plugin authority),
so a plugin's markdown command is not shown as hand-written. The wiring
in runtime_api.rs (mod line, route line, that field) and the
command_catalog and tui hunks are separable from plugin_index.rs.

Checks: farm nextest 6 run, 6 passed; farm clippy -D warnings clean for
engine, app-server, tui; preflight OK.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 23:01:19 -08:00
CodeWhale BotandClaude Fable 5.2 7179ae8d17 refactor(catalog): one model listing for both commands, and the inventory stops judging windows by name
With the readings proved equal on one captured catalog, the second copies
go:

- `route_preferences::list_models` no longer assembles its own roster
  (catalog rows, saved default, sort, dedup). It calls
  `provider_lake::listed_models_for_route`, the same function `models`
  prints.
- The routing inventory no longer asks the bundled catalog whether a model
  name has a context window to decide if a number is verified. The
  resolved route's own source decides; a route that does not resolve is
  unverified.

Farm (Linux x86_64), this commit: catalog_parity 1 test run: 1 passed;
config and engine lib tests filtered
`catalog model pricing cost_status route`: 1316 passed, 0 failed; clippy
-D warnings for config and engine (all targets, all features) and for cli
and app-server (all targets): clean.

Landing (push 18): CHANGELOG line for the pair (REF-05, CW-7971) from the
round-2 review, added in this commit.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
2026-11-12 23:01:18 -08:00
CodeWhale BotandClaude Fable 5.2 117a1fa6ff fix(catalog): both model commands, the Runtime API, routing and cost read one captured catalog the same way
The new check loads one captured Models.dev catalog (the bundled seed,
sha256 7c48830c…d256) and an id-only Anthropic roster into a sealed home,
then reads three routes through `model list` / `model resolve`, `models`,
`GET /v1/providers/{id}/models`, the routing inventory and the cost
envelope: the official Anthropic route, a custom endpoint serving a
same-named model, and the Z.ai plan endpoint. It prints every reading and
fails on any disagreement.

On the previous source it found three:

- `model list` skipped a custom endpoint unless its table was literally
  named `custom`. It now lists every configured custom route under the
  route's own name.
- `model resolve` refused a custom endpoint's saved model ("no registered
  model") because the legacy registry was asked about an endpoint that owns
  its own roster. The registry is no longer consulted for those routes; the
  route resolver and a fetched roster still decide.
- The routing inventory gave a custom endpoint the context window and
  output limit of a same-named model and marked the window verified. It
  now takes the window, its source and the output limit from the resolved
  route, so a borrowed number is marked unverified and an unpublished
  output limit stays unknown.

`provider_lake::listed_models_for_route` is the list body of `models`
moved out unchanged so the check can read it.

One spelling difference is left and reported, not asserted: the inventory
normalises a listed `glm-5.1` to `GLM-5.1`.

One disagreement is also named, not hidden: a custom endpoint has no
published window, so routing still reports 200,000 for a saved model whose
name matches a known one (the router's long-context tag reads it), marked
unverified, while the Runtime API reports unknown. The check records the
Runtime reading as unknown and allows exactly that pair as a known
difference; any other window disagreement fails.

The check also pins the charge side: a custom endpoint gets no charge
(`UnknownBillingBasis`); the Z.ai plan route gets no charge
(`NotMoneyMetered`) even for a model that has a list rate, and both
surfaces show that same list rate; an id-only first-party model with no
price row reads unknown on both surfaces and produces no charge.

Farm (Linux x86_64): config, engine and app-server lib tests filtered
`catalog_parity catalog model pricing cost_status route`: 1444 passed,
0 failed; clippy -D warnings for config, engine, cli and app-server (all
targets, all features): clean.

Co-Authored-By: Claude Fable 5.2 <[email protected]>
Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 23:01:16 -08:00
CodeWhale BotandClaude Sonnet 5.5 7e225f05ef fix(acp): a plugin tool's nested approval reaches the editor as a permission request that names the nested tool (CW-8050)
When a plugin tool asks the core to run a tool that needs approval, the ACP
projection resolves the nested execution id to the admitted plugin call and
shows the request on it. The request is built from the approval.required
payload (nested tool name, input, summary) so title, kind and rawInput show
what is being approved, and it carries no status so the running plugin call is
not reset to pending. The gates test and journey test live in acp_journey and
assert the second request names write and carries nested.txt.

Docs (RUNTIME_API, EXTENSIONS, zh_hans) and web/data/agent-docs.generated.json
updated.

Checks: nextest -p codewhale-app-server -E 'test(acp)' on the build farm,
48 run, 48 passed, 815 skipped; cargo fmt --check clean; preflight --check OK.

Landing (push 18): rebased onto push 17. The zh_hans EXTENSIONS and
RUNTIME_API paragraphs conflicted with push 17's CW-8071 wording of the same
ACP paragraph; kept push 17's text and added this change's sentences where
the English copies have them. agent-docs.generated.json regenerated with
derive-facts. CHANGELOG line from the round-2 review.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-11-12 23:01:15 -08:00
CodeWhale Bot 9ddd373849 test(ci): validate bounded macOS artifact timeout branches
The release workflow now has a platform-specific bound, but three existing helper checks accepted numeric literals only. Parse only a numeric cap or the supported macOS conditional, require both branches to stay within 1–360 minutes, and assert macOS 360 versus other platforms 210. Keep nightly at 210 and verify compiler-cache installation and activation remain Linux-only.

Validation: full Node workflow contract passed (211 consumed inputs, 11 wrapper event cases with 12 steps each, 13 hermetic invocation checks). Independent review repeated it, rejected eight in-memory workflow regressions and checked eight parser edge cases. Prior Version drift CI failures were this stale contract, not a version mismatch. Exact new-SHA CI/RC are still required before landing.
2026-11-12 22:58:22 -08:00
CodeWhale Bot dc56a2c3be ci: give macOS artifact builds room to finish without sccache
Both macOS builds in RC 43354633748 on cbc255813d exhausted the
210-minute job limit. Their logs recorded repeated sccache server
shutdowns and local fallback without a Rust compiler diagnostic.
The cache failure is observed; its share of the elapsed time is unknown.

Restrict the optional compiler cache to Linux and allow macOS artifact
jobs 360 minutes. Other platforms keep 210 minutes. Preserve the dist
profile, source SHA pinning, import checks and downstream artifact gates.
Remove the obsolete timeout comment.

Validation: actionlint with ShellCheck disabled and git diff --check
passed, independently repeated by the reviewer. No Rust source changed.
The prior full CI passed at cbc255813d; exact new-SHA CI and RC remain
required before landing. No release or publication was performed.
2026-11-12 22:27:51 -08:00
23 changed files with 339 additions and 81 deletions

No files matched your search

+47 -17
View File
@@ -810,6 +810,20 @@ assert.doesNotMatch(
// A job that calls a reusable workflow (`uses:`) cannot carry the key at all —
// GitHub rejects it — so the callee owns its own caps. That is why the artifact
// bounds live in release-artifacts.yml rather than in its callers.
function timeoutMinutes(value) {
const literal = /^\d+$/.test(value);
const conditional = value.match(
/^\$\{\{\s*startsWith\(matrix\.os,\s*'macos-'\)\s*&&\s*(\d+)\s*\|\|\s*(\d+)\s*\}\}$/,
);
if (!literal && !conditional) return null;
const macos = Number(literal ? value : conditional[1]);
const other = Number(literal ? value : conditional[2]);
if (![macos, other].every((cap) => Number.isInteger(cap) && cap > 0 && cap <= 360)) {
return null;
}
return { macos, other };
}
function jobsWithoutTimeout(source) {
const lines = source.split("\n");
const jobsAt = lines.findIndex((line) => /^jobs:\s*$/.test(line));
@@ -823,7 +837,8 @@ function jobsWithoutTimeout(source) {
for (let j = i + 1; j < lines.length; j += 1) {
if (/^ [A-Za-z0-9_-]+:\s*$/.test(lines[j])) break;
if (/^ uses:/.test(lines[j])) reusable = true;
if (/^ timeout-minutes:\s*\d+\s*$/.test(lines[j])) capped = true;
const timeout = lines[j].match(/^ timeout-minutes:\s*(.+?)\s*$/);
if (timeout && timeoutMinutes(timeout[1])) capped = true;
}
if (!reusable && !capped) offenders.push(header[1]);
}
@@ -862,26 +877,41 @@ for (const [name, source] of [
);
}
// The Windows artifact build historically runs 40-45 minutes, so its cap has to
// keep real margin — a tight bound here fails healthy releases.
const buildTimeout = artifacts.match(/^ build:\n(?:.*\n)*? timeout-minutes: (\d+)$/m);
assert.ok(buildTimeout, "release-artifacts build job must be capped");
assert.ok(
Number(buildTimeout[1]) >= 60,
`artifact build cap ${buildTimeout[1]}m leaves no margin over a healthy 40-45m Windows build`,
);
function jobTimeout(source, job) {
function jobTimeout(source, job, platform = "other") {
const match = source.match(
new RegExp(`^ ${job}:\\n(?:.*\\n)*? timeout-minutes: (\\d+)$`, "m"),
new RegExp(`^ ${job}:\\n(?:.*\\n)*? timeout-minutes: (.+)$`, "m"),
);
assert.ok(match, `${job} must declare timeout-minutes`);
return Number(match[1]);
const caps = timeoutMinutes(match[1].trim());
assert.ok(caps, `${job} must declare a bounded timeout`);
return caps[platform];
}
// Fast setup and packaging fail quickly. Native builds need the same finite
// cold-build allowance as full CI: both 0.10.1 macOS artifacts hit the old
// 90m compilation cap before reaching their launch and inventory checks.
const macosTimeout = "${{ startsWith(matrix.os, 'macos-') && 360 || 210 }}";
assert.deepEqual(timeoutMinutes(macosTimeout), { macos: 360, other: 210 });
for (const invalid of [
"0", "361", "Infinity", "${{ matrix.timeout }}",
"${{ startsWith(matrix.os, 'macos-') && 361 || 210 }}",
"${{ startsWith(matrix.os, 'macos-') && 360 || 0 }}",
]) {
assert.equal(timeoutMinutes(invalid), null, `${invalid} must not count as a bounded cap`);
}
assert.deepEqual(
jobsWithoutTimeout(`jobs:\n capped:\n timeout-minutes: ${macosTimeout}\n`),
[],
);
assert.equal(jobTimeout(artifacts, "build", "macos"), 360);
assert.equal(jobTimeout(artifacts, "build"), 210);
const artifactCacheSetup = artifacts.match(
/ - uses: mozilla-actions\/sccache-action@[^\n]+\n(?:(?! - ).*\n)*/,
);
assert.ok(artifactCacheSetup, "artifact compiler cache setup must be explicit");
assert.match(artifactCacheSetup[0], /^ if: runner\.os == 'Linux'$/m);
assert.match(
namedStep(artifacts, "Enable sccache"),
/^ if: steps\.sccache\.outcome == 'success' && runner\.os == 'Linux'$/m,
);
assert.equal(jobTimeout(candidate, "resolve"), 10);
assert.equal(jobTimeout(candidate, "web"), 15);
assert.equal(jobTimeout(artifacts, "pin"), 10);
@@ -894,7 +924,7 @@ for (const job of ["bundle", "windows-installer", "assemble", "smoke"]) {
}
assert.equal(
jobTimeout(nightly, "build"), jobTimeout(artifacts, "build"),
"nightly and release must share the native cold-build allowance",
"nightly and non-macOS release builds must share the cold-build allowance",
);
assert.equal(jobTimeout(release, "resolve"), 10);
// The 0.10.1 cold parity build exhausted 45 minutes before tests started.
+3 -4
View File
@@ -88,9 +88,7 @@ jobs:
build:
name: Build ${{ matrix.platform }}
# Both cold macOS artifact builds on 0.10.1 exhausted 90 minutes inside
# compilation. Keep the full CI build budget; packaging stays capped below.
timeout-minutes: 210
timeout-minutes: ${{ startsWith(matrix.os, 'macos-') && 360 || 210 }}
# FreeBSD is a source-build target with no prebuilt asset, no npm binary and no CI check
# (see packaging/freebsd/README.md and docs/INSTALL.md#freebsd).
strategy:
@@ -175,10 +173,11 @@ jobs:
toolchain: stable
targets: ${{ matrix.target }}
- uses: mozilla-actions/sccache-action@fc920bf0ec8de6ee65d409111f7ec508035751ba # v0.0.11
if: runner.os == 'Linux'
id: sccache
continue-on-error: true
- name: Enable sccache
if: steps.sccache.outcome == 'success' && runner.os != 'Windows'
if: steps.sccache.outcome == 'success' && runner.os == 'Linux'
shell: bash
run: |
{
+1
View File
@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Plugin index (Runtime API):** a new `GET /v1/apps/plugin-index` route lists plugins, skills, connectors, hooks and hand-written commands with kind, source and state, and `/v1/commands` rows say which plugin (`plugin_id`) added a command and whether a command came from the project (`workspace_sourced`) (CW-8092).
- **Model commands and routing:** `codewhale model list` now lists every custom endpoint you have configured, under its own name. `codewhale model resolve` no longer refuses a model on a custom endpoint, router or local server whose model list has not been fetched yet; once a list is fetched, a model missing from it is still refused. Automatic routing marks a context window as verified only when the route itself supplies it, and no longer reports a guessed output limit.
- **ACP:** when a plugin tool asks the core to run a tool that needs approval, the editor now gets a `session/request_permission` on the plugin tool's call that names the nested tool and its input; before, the prompt ended with an internal error (CW-8050).
- **Website maintainer and cron secrets:** the manual cron trigger is rate limited, admin sign-in and the cron secret require a 32 to 512 character secret with at least 8 distinct characters that is not a repeated pattern, and changing the maintainer token signs out existing admin sessions.
- **README and contributor credit:** the repository front page now opens the way the website does: the line "The model can be anyone's. The agent should be yours.", one sentence on what Codewhale is, the install command and one picture, with reference detail moved into the linked guides; the 18 translated READMEs follow the same structure and say they are machine-drafted. The contributor wall and the website now count the same 433 people (407 GitHub accounts and the commit authors whose email is not linked to an account), where the website had counted accounts only. `DEPENDENCY_SECURITY.md` moved into `docs/dependency-maintenance.md`, and `.github/SUPPORT.md` says where to ask for help.
- **Website Plugins page:** The website's Plugins page now describes what the released version does, and a labelled section says what 0.10.3 adds: one Plugins place, Standard and Creator mode, and the Permissions control.
- **First-time guide on the website:** a new docs page, "Use Codewhale for the first time" (`/docs/first-time`, English and Simplified Chinese), walks someone who has never used a terminal through opening one, installing, choosing the folder Codewhale works in and when that choice matters, opening a terminal in a folder from Finder or File Explorer, connecting a model, a first task, and stopping, undoing and quitting. The install page gains a short "New to the terminal?" block for macOS and Windows that links to it, and `llms.txt` carries the same steps.
+1
View File
@@ -21,6 +21,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
- **Plugin index (Runtime API):** a new `GET /v1/apps/plugin-index` route lists plugins, skills, connectors, hooks and hand-written commands with kind, source and state, and `/v1/commands` rows say which plugin (`plugin_id`) added a command and whether a command came from the project (`workspace_sourced`) (CW-8092).
- **Model commands and routing:** `codewhale model list` now lists every custom endpoint you have configured, under its own name. `codewhale model resolve` no longer refuses a model on a custom endpoint, router or local server whose model list has not been fetched yet; once a list is fetched, a model missing from it is still refused. Automatic routing marks a context window as verified only when the route itself supplies it, and no longer reports a guessed output limit.
- **ACP:** when a plugin tool asks the core to run a tool that needs approval, the editor now gets a `session/request_permission` on the plugin tool's call that names the nested tool and its input; before, the prompt ended with an internal error (CW-8050).
- **Website maintainer and cron secrets:** the manual cron trigger is rate limited, admin sign-in and the cron secret require a 32 to 512 character secret with at least 8 distinct characters that is not a repeated pattern, and changing the maintainer token signs out existing admin sessions.
- **README and contributor credit:** the repository front page now opens the way the website does: the line "The model can be anyone's. The agent should be yours.", one sentence on what Codewhale is, the install command and one picture, with reference detail moved into the linked guides; the 18 translated READMEs follow the same structure and say they are machine-drafted. The contributor wall and the website now count the same 433 people (407 GitHub accounts and the commit authors whose email is not linked to an account), where the website had counted accounts only. `DEPENDENCY_SECURITY.md` moved into `docs/dependency-maintenance.md`, and `.github/SUPPORT.md` says where to ask for help.
- **Website Plugins page:** The website's Plugins page now describes what the released version does, and a labelled section says what 0.10.3 adds: one Plugins place, Standard and Creator mode, and the Permissions control.
- **First-time guide on the website:** a new docs page, "Use Codewhale for the first time" (`/docs/first-time`, English and Simplified Chinese), walks someone who has never used a terminal through opening one, installing, choosing the folder Codewhale works in and when that choice matters, opening a terminal in a folder from Finder or File Explorer, connecting a model, a first task, and stopping, undoing and quitting. The install page gains a short "New to the terminal?" block for macOS and Windows that links to it, and `llms.txt` carries the same steps.
+9 -2
View File
@@ -9,14 +9,21 @@ GITHUB_TOKEN=
GITHUB_REPO=codewhale-hq/CodeWhale
# Optional — required to manually invoke /api/cron
# (cloudflare cron triggers don't need this; they set cf-cron).
# (cloudflare cron triggers don't need this; they set cf-cron). When set it must
# be 32 to 512 characters with at least 8 distinct, and a shorter value repeated
# is refused; otherwise the trigger stays disabled.
# Generate one with: openssl rand -base64 33
CRON_SECRET=
# Optional — defaults to deepseek-flash.
DEEPSEEK_MODEL=deepseek-flash
DEEPSEEK_BASE_URL=https://api.deepseek.com
# Admin panel auth. Set to a random secret; enter it in the /admin login form.
# Admin panel auth. Set to a random secret of 32 to 512 characters with at
# least 8 distinct characters, and a shorter value repeated is refused (anything
# else leaves admin sign-in disabled); enter it in the /admin login form.
# Changing it signs out open admin sessions.
# Generate one with: openssl rand -base64 33
MAINTAINER_TOKEN=
# GitHub PAT for posting comments via /admin. Needs issues:write scope.
+5 -3
View File
@@ -87,8 +87,8 @@ form. The form posts to `/api/admin/login`; the token never goes in the URL.
|---|---|---|
| `DEEPSEEK_API_KEY` | Yes | DeepSeek API key for the community agent |
| `GITHUB_TOKEN` | Optional | Fine-grained PAT for GitHub API (raises rate limit) |
| `CRON_SECRET` | Optional | Shared secret for manual cron invocation |
| `MAINTAINER_TOKEN` | Optional | Auth token for /admin panel |
| `CRON_SECRET` | Optional | Shared secret for manual cron invocation (32 to 512 characters, at least 8 distinct, and a shorter value repeated is refused; otherwise the trigger stays disabled); attempts are rate limited (5 per minute per location) |
| `MAINTAINER_TOKEN` | Optional | Auth token for /admin panel; 32 to 512 characters with at least 8 distinct, and a shorter value repeated is refused (otherwise sign-in stays disabled); changing it signs out open sessions |
| `MAINTAINER_GITHUB_PAT` | Optional | GitHub PAT with `issues:write` scope for posting comments |
## Initial deployment
@@ -103,7 +103,9 @@ One-time setup before the first `npm run deploy`:
Copy the returned `id` values into the matching `CURATED_KV` and
`NEXT_INC_CACHE_KV` bindings in `cloudflare.config.ts`.
2. **Set secrets:**
2. **Set secrets:** generate `MAINTAINER_TOKEN` and `CRON_SECRET` with
`openssl rand -base64 33` (any random value of 32 to 512 characters with at
least 8 distinct and not a shorter value repeated works; `openssl rand -hex 32` is fine).
```bash
npx wrangler secret put DEEPSEEK_API_KEY
npx wrangler secret put MAINTAINER_TOKEN
+2 -2
View File
@@ -20,10 +20,10 @@ Env (mirrors `.env.example`):
| `DEEPSEEK_API_KEY` | DeepSeek platform key (`sk-...`) | only for the `/api/cron` tasks (summarization + community agent) |
| `GITHUB_TOKEN` | Fine-grained PAT, public-repo read scope | optional (raises rate limit 60 → 5000 req/h) |
| `GITHUB_REPO` | Defaults to `codewhale-hq/CodeWhale` | optional |
| `CRON_SECRET` | Shared secret for manual `/api/cron` invocation | optional (Cloudflare cron triggers don't need it) |
| `CRON_SECRET` | Shared secret for manual `/api/cron` invocation (32-512 characters, 8+ distinct; a shorter value repeated is refused)| optional (Cloudflare cron triggers don't need it) |
| `DEEPSEEK_MODEL` | Defaults to `deepseek-flash` | optional |
| `DEEPSEEK_BASE_URL` | Defaults to `https://api.deepseek.com` | optional |
| `MAINTAINER_TOKEN` | Admin panel auth; enter it in the `/admin` login form | only for `/admin` |
| `MAINTAINER_TOKEN` | Admin panel auth (32-512 characters, 8+ distinct; a shorter value repeated is refused; changing it signs out sessions); enter it in the `/admin` login form | only for `/admin` |
| `MAINTAINER_GITHUB_PAT` | PAT with `issues:write`, for posting comments via `/admin` | only for `/admin` posting |
| `NEXT_PUBLIC_GITEE_ENABLED` | Set to `1` once the Gitee mirror exists; blank hides Gitee links | optional |
+4 -2
View File
@@ -4,6 +4,7 @@ import { ConnectionBanner } from "@/components/connection-banner";
import { EmptyState, ErrorState } from "@/components/surface-state";
import { WhalePose } from "@/components/whale-pose";
import { getAgentEnv, listDrafts, validateSession, type AgentDraft } from "@/lib/community-agent";
import { MAINTAINER_TOKEN_UNAVAILABLE, maintainerTokenUsable } from "@/lib/maintainer-token";
import { AdminClient } from "./admin-client";
export const dynamic = "force-dynamic";
@@ -77,7 +78,8 @@ export default async function AdminPage({
const env = await getAgentEnv();
if (!env.MAINTAINER_TOKEN) {
if (!maintainerTokenUsable(env.MAINTAINER_TOKEN)) {
if (env.MAINTAINER_TOKEN) console.warn(MAINTAINER_TOKEN_UNAVAILABLE);
return (
<div className="route-state">
<ConnectionBanner locale={locale} />
@@ -98,7 +100,7 @@ export default async function AdminPage({
const cookieStore = await cookies();
const sid = cookieStore.get("mt_sid")?.value;
const authed = await validateSession(env.CURATED_KV, sid);
const authed = await validateSession(env.CURATED_KV, sid, env.MAINTAINER_TOKEN);
if (!authed) {
return <LoginForm locale={locale} error={err === "1"} />;
+5 -5
View File
@@ -1,12 +1,12 @@
import { NextResponse } from "next/server";
import { getAgentEnv, safeEqual, createSession } from "@/lib/community-agent";
import { MAINTAINER_TOKEN_UNAVAILABLE, MAX_SECRET_CHARS, maintainerTokenUsable } from "@/lib/maintainer-token";
import { FormBodyError, readBoundedUrlEncodedForm } from "@/lib/bounded-form";
export const dynamic = "force-dynamic";
const ALLOWED_LOCALES = new Set(["en", "zh"]);
const MAX_LOGIN_BODY_BYTES = 4_096;
const MAX_TOKEN_CHARS = 512;
function pickLocale(value: string | null | undefined): string {
if (!value) return "en";
@@ -18,8 +18,8 @@ export async function POST(req: Request) {
const url = new URL(req.url);
const localeFromQuery = pickLocale(url.searchParams.get("locale"));
if (!env.MAINTAINER_TOKEN) {
return new NextResponse("Not configured", {
if (!maintainerTokenUsable(env.MAINTAINER_TOKEN)) {
return new NextResponse(MAINTAINER_TOKEN_UNAVAILABLE, {
status: 503,
headers: { "Cache-Control": "no-store" },
});
@@ -58,7 +58,7 @@ export async function POST(req: Request) {
}
const submitted = form.get("token") ?? "";
const locale = pickLocale(form.get("locale") ?? localeFromQuery);
if (submitted.length > MAX_TOKEN_CHARS) {
if (submitted.length > MAX_SECRET_CHARS) {
return new NextResponse("Token too long", {
status: 413,
headers: { "Cache-Control": "no-store" },
@@ -73,7 +73,7 @@ export async function POST(req: Request) {
});
}
const sid = await createSession(env.CURATED_KV);
const sid = await createSession(env.CURATED_KV, env.MAINTAINER_TOKEN);
if (!sid) {
return new NextResponse("Session storage unavailable", {
status: 503,
+1 -1
View File
@@ -9,7 +9,7 @@ export async function POST(request: Request) {
try {
const authEnv = await getAgentEnv();
const sid = request.headers.get("cookie")?.split(";").map(c => c.trim()).find(c => c.startsWith("mt_sid="))?.slice(7);
if (!authEnv.MAINTAINER_TOKEN || !await validateSession(authEnv.CURATED_KV, sid)) throw new MerchError(401, "unauthorized", "Maintainer sign-in is required.");
if (!await validateSession(authEnv.CURATED_KV, sid, authEnv.MAINTAINER_TOKEN)) throw new MerchError(401, "unauthorized", "Maintainer sign-in is required.");
const env = await merchEnv(), config = parseConfig(env.MERCH_CONFIG_JSON);
if (!config || request.headers.get("origin") !== new URL(config.siteOrigin).origin || !request.headers.get("content-type")?.startsWith("application/json")) throw new MerchError(403, "request_blocked", "Use the approved store origin.");
const raw = await readBoundedBody(request, 8192);
+1 -1
View File
@@ -39,7 +39,7 @@ async function checkAuth(req: Request, env: CommunityAgentEnv): Promise<{ ok: bo
}
}
if (!sid || !(await validateSession(env.CURATED_KV, sid))) {
if (!sid || !(await validateSession(env.CURATED_KV, sid, env.MAINTAINER_TOKEN))) {
return { ok: false, status: 401, error: "unauthorized" };
}
return { ok: true };
+26 -1
View File
@@ -4,6 +4,7 @@ import type { AgentEnv } from "@/lib/community-agent-tasks";
import { runFactsDrift } from "@/lib/facts-drift";
import { runLinkCheck, runSemanticDrift } from "@/lib/content-watch";
import { safeEqual } from "@/lib/community-agent";
import { CRON_SECRET_UNAVAILABLE, secretStrongEnough } from "@/lib/maintainer-token";
export const dynamic = "force-dynamic";
@@ -30,9 +31,33 @@ export async function GET(req: Request) {
);
}
if (!secretStrongEnough(env.CRON_SECRET)) {
console.warn(CRON_SECRET_UNAVAILABLE);
return NextResponse.json(
{ error: CRON_SECRET_UNAVAILABLE },
{ status: 503, headers: { "Cache-Control": "no-store" } }
);
}
try {
if (!env.ADMIN_LOGIN_LIMITER) throw new Error("Missing cron limiter");
const { success } = await env.ADMIN_LOGIN_LIMITER.limit({ key: "codewhale-web:cron-secret" });
if (!success) {
return NextResponse.json(
{ error: "too many attempts" },
{ status: 429, headers: { "Cache-Control": "no-store", "Retry-After": "60" } }
);
}
} catch {
return NextResponse.json(
{ error: "manual trigger temporarily unavailable" },
{ status: 503, headers: { "Cache-Control": "no-store", "Retry-After": "60" } }
);
}
const auth = req.headers.get("x-cron-secret") ?? "";
if (!(await safeEqual(auth, env.CRON_SECRET))) {
return NextResponse.json({ error: "unauthorized" }, { status: 401 });
return NextResponse.json({ error: "unauthorized" }, { status: 401, headers: { "Cache-Control": "no-store" } });
}
const { searchParams } = new URL(req.url);
+10 -4
View File
@@ -14,7 +14,7 @@ vi.mock("@/lib/community-agent", async (importOriginal) => {
import { POST } from "@/app/api/admin/login/route";
import { createSession, safeEqual, validateSession } from "@/lib/community-agent";
const FIXTURE_TOKEN = "local-admin-integration-fixture";
const FIXTURE_TOKEN = "local-admin-integration-fixture-0123456789";
const sessions = new Map<string, string>();
const kv = {
put: vi.fn(async (key: string, value: string) => { sessions.set(key, value); }),
@@ -57,9 +57,9 @@ describe("admin login with real credential and session helpers", () => {
const sid = response.cookies.get("mt_sid")?.value;
expect(sid).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(sessions.size).toBe(1);
expect(await validateSession(sessionKv, sid)).toBe(true);
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(true);
expect(safeEqual).toHaveBeenCalledExactlyOnceWith(FIXTURE_TOKEN, FIXTURE_TOKEN);
expect(createSession).toHaveBeenCalledExactlyOnceWith(sessionKv);
expect(createSession).toHaveBeenCalledExactlyOnceWith(sessionKv, FIXTURE_TOKEN);
const cookie = response.headers.get("Set-Cookie")?.toLowerCase();
expect(cookie).toContain("httponly");
expect(cookie).toContain("secure");
@@ -69,7 +69,13 @@ describe("admin login with real credential and session helpers", () => {
expect.any(String), expect.any(String), { expirationTtl: 86400 },
]);
sessions.clear();
expect(await validateSession(sessionKv, sid)).toBe(false);
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(false);
});
it("stops honouring a session after the maintainer token is rotated", async () => {
const sid = (await POST(request())).cookies.get("mt_sid")?.value;
expect(await validateSession(sessionKv, sid, FIXTURE_TOKEN)).toBe(true);
expect(await validateSession(sessionKv, sid, "rotated-integration-fixture-9876543210")).toBe(false);
});
it("rejects a wrong credential without creating a session", async () => {
+38 -4
View File
@@ -5,6 +5,9 @@ const mocks = vi.hoisted(() => ({
vi.mock("@/lib/community-agent", () => mocks);
import { POST } from "@/app/api/admin/login/route";
const STRONG_TOKEN = "local-fixture-token-0123456789-abcdefghij";
const LONE_SURROGATES = Array.from({ length: 16 }, (_, index) => String.fromCharCode(0xd800 + index)).join("").repeat(2);
function request(token = "wrong", ip = "127.0.0.1") {
return new Request("https://codewhale.net/api/admin/login?locale=en", {
method: "POST",
@@ -14,7 +17,7 @@ function request(token = "wrong", ip = "127.0.0.1") {
}
beforeEach(() => {
vi.resetAllMocks();
mocks.getAgentEnv.mockResolvedValue({ MAINTAINER_TOKEN: "configured", ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.getAgentEnv.mockResolvedValue({ MAINTAINER_TOKEN: STRONG_TOKEN, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.limit.mockResolvedValue({ success: true });
mocks.safeEqual.mockResolvedValue(false);
mocks.createSession.mockResolvedValue("session-id");
@@ -35,7 +38,7 @@ describe("admin login attempt boundary", () => {
});
it("does not parse or compare credentials after refusal", async () => {
mocks.limit.mockResolvedValue({ success: false });
const req = request("configured");
const req = request(STRONG_TOKEN);
const read = vi.spyOn(req, "text");
expect((await POST(req)).status).toBe(429);
expect(read).not.toHaveBeenCalled();
@@ -43,16 +46,47 @@ describe("admin login attempt boundary", () => {
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("fails closed if the binding is missing or unavailable", async () => {
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: "configured" });
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: STRONG_TOKEN });
expect((await POST(request())).status).toBe(503);
mocks.limit.mockRejectedValue(new Error("binding unavailable"));
expect((await POST(request())).status).toBe(503);
expect(mocks.safeEqual).not.toHaveBeenCalled();
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("refuses to run with a configured token below the minimum strength", async () => {
const weakTokens = [
"x", "configured", "a".repeat(31), "a".repeat(32), " ".repeat(40), "password".repeat(4),
"Password1".repeat(4), "0123456".repeat(5), "\u{1F433}".repeat(16), "L".repeat(600), LONE_SURROGATES,
];
for (const weak of weakTokens) {
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: weak, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
const response = await POST(request(weak));
expect(response.status).toBe(503);
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(await response.text()).toContain("at least 32 characters");
}
expect(mocks.limit).not.toHaveBeenCalled();
expect(mocks.safeEqual).not.toHaveBeenCalled();
expect(mocks.createSession).not.toHaveBeenCalled();
});
it("accepts a token of exactly the minimum length", async () => {
const exact = "abcdefghijklmnopqrstuvwxyz012345";
expect(exact).toHaveLength(32);
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: exact, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
expect((await POST(request(exact))).status).toBe(303);
});
it("accepts a 32-character hex secret with fewer than 16 distinct characters", async () => {
const hex = "3f9a3f9a1c7e1c7e3f9a1c7e5b2d5b2d";
expect(new Set(hex).size).toBeLessThan(16);
mocks.getAgentEnv.mockResolvedValueOnce({ MAINTAINER_TOKEN: hex, ADMIN_LOGIN_LIMITER: { limit: mocks.limit }, CURATED_KV: {} });
mocks.safeEqual.mockResolvedValue(true);
expect((await POST(request(hex))).status).toBe(303);
});
it("retains the authenticated session and redirect after an allowed attempt", async () => {
mocks.safeEqual.mockResolvedValue(true);
const response = await POST(request("configured"));
const response = await POST(request(STRONG_TOKEN));
expect(response.status).toBe(303);
expect(response.headers.get("Location")).toBe("https://codewhale.net/en/admin");
const cookie = response.headers.get("Set-Cookie");
+1 -1
View File
@@ -144,7 +144,7 @@ function stubAdminEnv(kv: FakeKv, lock?: FakeDraftClaimLock) {
mocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
...(lock ? { DRAFT_CLAIM_LOCK: lock } : {}),
MAINTAINER_TOKEN: "configured",
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
MAINTAINER_GITHUB_PAT: "ghp_test",
GITHUB_REPO: "codewhale-hq/CodeWhale",
});
+46 -23
View File
@@ -1,5 +1,5 @@
import { describe, it, expect, vi, beforeEach } from "vitest";
import { logUsage, validateSession } from "./community-agent";
import { createSession, logUsage, validateSession } from "./community-agent";
describe("validateSession", () => {
let mockKV: {
@@ -20,65 +20,88 @@ describe("validateSession", () => {
const VALID_SID = "a".repeat(40);
const SESSION_PREFIX = "session:admin:";
const TOKEN = "local-fixture-token-0123456789-abcdefghij";
const ROTATED = "rotated-fixture-token-9876543210-zyxwvutsrq";
it("should return false if kv is undefined", async () => {
const result = await validateSession(undefined, VALID_SID);
const result = await validateSession(undefined, VALID_SID, TOKEN);
expect(result).toBe(false);
});
it("should return false if sid is undefined or null", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, undefined)).toBe(false);
expect(await validateSession(kv, null)).toBe(false);
expect(await validateSession(kv, undefined, TOKEN)).toBe(false);
expect(await validateSession(kv, null, TOKEN)).toBe(false);
});
it("should return false if sid is empty", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "")).toBe(false);
expect(await validateSession(kv, "", TOKEN)).toBe(false);
});
it("should return false if sid length is less than 40", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "a".repeat(39))).toBe(false);
expect(await validateSession(kv, "a".repeat(39), TOKEN)).toBe(false);
});
it("should return false if sid length is greater than 64", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
expect(await validateSession(kv, "a".repeat(65))).toBe(false);
expect(await validateSession(kv, "a".repeat(65), TOKEN)).toBe(false);
});
it("should return false if sid contains invalid characters", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
// Length 40 but contains invalid char '!'
expect(await validateSession(kv, "a".repeat(39) + "!")).toBe(false);
expect(await validateSession(kv, "a".repeat(39) + "!", TOKEN)).toBe(false);
});
it("should return false if session is not found in KV", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
mockKV.get.mockResolvedValue(null);
const result = await validateSession(kv, VALID_SID);
const result = await validateSession(kv, VALID_SID, TOKEN);
expect(result).toBe(false);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + VALID_SID);
});
it("should return true if session is found in KV", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
mockKV.get.mockResolvedValue(JSON.stringify({ createdAt: Date.now() }));
const result = await validateSession(kv, VALID_SID);
expect(result).toBe(true);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + VALID_SID);
it("should return true for a session minted under the configured token", async () => {
const store = new Map<string, string>();
const kv = {
get: async (key: string) => store.get(key) ?? null,
put: async (key: string, value: string) => { store.set(key, value); },
} as unknown as Parameters<typeof validateSession>[0];
const sid = await createSession(kv, TOKEN);
expect(sid).toMatch(/^[A-Za-z0-9_-]{43}$/);
expect(await validateSession(kv, sid, TOKEN)).toBe(true);
});
it("should work with a 64 character sid", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
mockKV.get.mockResolvedValue("{}");
it("should refuse the same session once the configured token changes", async () => {
const store = new Map<string, string>();
const kv = {
get: async (key: string) => store.get(key) ?? null,
put: async (key: string, value: string) => { store.set(key, value); },
} as unknown as Parameters<typeof validateSession>[0];
const sid = await createSession(kv, TOKEN);
expect(await validateSession(kv, sid, ROTATED)).toBe(false);
expect(await validateSession(kv, sid, "short")).toBe(false);
expect(await validateSession(kv, sid, undefined)).toBe(false);
expect(await validateSession(kv, sid, TOKEN)).toBe(true);
});
const sid = "b".repeat(64);
const result = await validateSession(kv, sid);
expect(result).toBe(true);
expect(mockKV.get).toHaveBeenCalledWith(SESSION_PREFIX + sid);
it("should refuse a stored record with no token fingerprint or unparseable content", async () => {
const kv = mockKV as unknown as Parameters<typeof validateSession>[0];
for (const raw of [JSON.stringify({ createdAt: Date.now() }), "{}", "not json", JSON.stringify({ tokenFingerprint: 7 })]) {
mockKV.get.mockResolvedValue(raw);
expect(await validateSession(kv, VALID_SID, TOKEN)).toBe(false);
}
});
it("should not mint a session under a weak token", async () => {
const kv = mockKV as unknown as Parameters<typeof createSession>[0];
for (const weak of [undefined, "", "short", "a".repeat(32)]) {
expect(await createSession(kv, weak)).toBeNull();
}
expect(mockKV.put).not.toHaveBeenCalled();
});
});
+26 -6
View File
@@ -12,6 +12,7 @@
import type { DraftClaimLockNamespace, DraftClaimLockStub, DraftLockAction } from "./draft-claim-lock";
import { maintainerTokenUsable } from "./maintainer-token";
import { requestChat, type ChatMessage, type DeepSeekEnv } from "./deepseek";
export type { DeepSeekEnv } from "./deepseek";
@@ -722,6 +723,7 @@ export async function deleteDraft(kv: KVNamespace | undefined, key: string): Pro
const SESSION_PREFIX = "session:admin:";
const SESSION_TTL_SEC = 60 * 60 * 24; // 24h
const SESSION_TOKEN_DOMAIN = "codewhale-web:admin-session:v1:";
function toBase64Url(bytes: Uint8Array): string {
let s = "";
@@ -738,21 +740,39 @@ export async function safeEqual(a: string, b: string): Promise<boolean> {
return diff === 0;
}
export async function createSession(kv: KVNamespace | undefined): Promise<string | null> {
if (!kv) return null;
async function tokenFingerprint(token: string): Promise<string> {
const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(SESSION_TOKEN_DOMAIN + token)));
let hex = "";
for (const byte of digest) hex += byte.toString(16).padStart(2, "0");
return hex;
}
export async function createSession(kv: KVNamespace | undefined, token: string | undefined): Promise<string | null> {
if (!kv || !maintainerTokenUsable(token)) return null;
const bytes = new Uint8Array(32);
crypto.getRandomValues(bytes);
const sid = toBase64Url(bytes);
const value = JSON.stringify({ createdAt: Date.now() });
const value = JSON.stringify({ createdAt: Date.now(), tokenFingerprint: await tokenFingerprint(token) });
await kv.put(SESSION_PREFIX + sid, value, { expirationTtl: SESSION_TTL_SEC });
return sid;
}
export async function validateSession(kv: KVNamespace | undefined, sid: string | undefined | null): Promise<boolean> {
if (!kv || !sid) return false;
export async function validateSession(
kv: KVNamespace | undefined,
sid: string | undefined | null,
token: string | undefined,
): Promise<boolean> {
if (!kv || !sid || !maintainerTokenUsable(token)) return false;
if (!/^[A-Za-z0-9_-]{40,64}$/.test(sid)) return false;
const raw = await kv.get(SESSION_PREFIX + sid);
return raw !== null;
if (raw === null) return false;
let stored: unknown;
try {
stored = (JSON.parse(raw) as { tokenFingerprint?: unknown }).tokenFingerprint;
} catch {
return false;
}
return typeof stored === "string" && (await safeEqual(stored, await tokenFingerprint(token)));
}
export async function deleteSession(kv: KVNamespace | undefined, sid: string | undefined | null): Promise<void> {
+76
View File
@@ -0,0 +1,76 @@
import { beforeEach, describe, expect, it, vi } from "vitest";
const mocks = vi.hoisted(() => ({ getEnv: vi.fn(), safeEqual: vi.fn(), limit: vi.fn() }));
vi.mock("@/lib/kv", () => ({ getEnv: mocks.getEnv }));
vi.mock("@/lib/community-agent", () => ({ safeEqual: mocks.safeEqual }));
vi.mock("@/lib/facts-drift", () => ({ runFactsDrift: vi.fn() }));
vi.mock("@/lib/content-watch", () => ({ runLinkCheck: vi.fn(), runSemanticDrift: vi.fn() }));
import { GET } from "@/app/api/cron/route";
function request(secret = "wrong", ip = "127.0.0.1") {
return new Request("https://codewhale.net/api/cron?task=nope", {
headers: { "x-cron-secret": secret, "CF-Connecting-IP": ip },
});
}
beforeEach(() => {
vi.resetAllMocks();
mocks.getEnv.mockResolvedValue({ CRON_SECRET: "configured-cron-secret-0123456789-abcdef", ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
mocks.limit.mockResolvedValue({ success: true });
mocks.safeEqual.mockResolvedValue(false);
});
describe("manual cron trigger attempt boundary", () => {
it("bounds repeated guesses independently of the secret and forged IP", async () => {
let attempts = 0;
mocks.limit.mockImplementation(async () => ({ success: ++attempts <= 5 }));
for (let index = 0; index < 7; index++) {
const response = await GET(request(`guess-${index}`, `192.0.2.${index}`));
expect(response.status).toBe(index < 5 ? 401 : 429);
if (index >= 5) expect(response.headers.get("Retry-After")).toBe("60");
expect(response.headers.get("Cache-Control")).toBe("no-store");
}
expect(mocks.safeEqual).toHaveBeenCalledTimes(5);
expect(mocks.limit.mock.calls.map(([options]) => options.key)).toEqual(Array(7).fill("codewhale-web:cron-secret"));
});
it("does not compare the secret after refusal", async () => {
mocks.limit.mockResolvedValue({ success: false });
expect((await GET(request("configured-cron-secret-0123456789-abcdef"))).status).toBe(429);
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("fails closed if the binding is missing or unavailable", async () => {
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: "configured-cron-secret-0123456789-abcdef" });
expect((await GET(request())).status).toBe(503);
mocks.limit.mockRejectedValue(new Error("binding unavailable"));
expect((await GET(request())).status).toBe(503);
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("stays disabled without a configured secret and never consults the limiter", async () => {
mocks.getEnv.mockResolvedValue({ ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
expect((await GET(request())).status).toBe(503);
expect(mocks.limit).not.toHaveBeenCalled();
});
it("stays disabled for a secret below the minimum strength and never consults the limiter or compares", async () => {
const loneSurrogates = Array.from({ length: 16 }, (_, index) => String.fromCharCode(0xd800 + index)).join("").repeat(2);
const weak = ["x", "a".repeat(32), " ".repeat(40), "password".repeat(4), "Password1".repeat(4), "\u{1F433}".repeat(16), "0123456".repeat(5), "L".repeat(600), loneSurrogates];
for (const secret of weak) {
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: secret, ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
const response = await GET(request());
expect(response.status).toBe(503);
expect(response.headers.get("Cache-Control")).toBe("no-store");
expect(JSON.stringify(await response.json())).toContain("at least 32 characters");
}
expect(mocks.limit).not.toHaveBeenCalled();
expect(mocks.safeEqual).not.toHaveBeenCalled();
});
it("accepts a 32-character hex secret with fewer than 16 distinct characters", async () => {
const hex = "3f9a3f9a1c7e1c7e3f9a1c7e5b2d5b2d";
mocks.getEnv.mockResolvedValueOnce({ CRON_SECRET: hex, ADMIN_LOGIN_LIMITER: { limit: mocks.limit } });
mocks.safeEqual.mockResolvedValue(true);
expect((await GET(request(hex))).status).toBe(400);
});
it("still reaches task validation after an allowed, correct attempt", async () => {
mocks.safeEqual.mockResolvedValue(true);
expect((await GET(request("configured-cron-secret-0123456789-abcdef"))).status).toBe(400);
});
});
+1
View File
@@ -32,6 +32,7 @@ export async function readBoundedKvJson(kv: KVStreamNamespace | undefined, key:
interface CloudflareEnv extends MerchEnv {
DRAFT_CLAIM_LOCK?: DraftClaimLockNamespace;
CURATED_KV?: KVNamespace & KVStreamNamespace;
ADMIN_LOGIN_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> };
MERCH_INTEREST_LIMITER?: { limit(options: { key: string }): Promise<{ success: boolean }> };
MERCH_INTEREST_SITE_ORIGIN?: string;
DEEPSEEK_API_KEY?: string;
+25
View File
@@ -0,0 +1,25 @@
export const MIN_SECRET_CHARS = 32;
export const MAX_SECRET_CHARS = 512;
export const MIN_SECRET_DISTINCT_CHARS = 8;
const LONE_SURROGATE = /\p{Cs}/u;
export const MAINTAINER_TOKEN_UNAVAILABLE =
`Maintainer sign-in is unavailable: MAINTAINER_TOKEN must be set to a secret of at least ${MIN_SECRET_CHARS} characters ` +
`(at most ${MAX_SECRET_CHARS}, with at least ${MIN_SECRET_DISTINCT_CHARS} distinct characters; a shorter value repeated is refused).`;
export const CRON_SECRET_UNAVAILABLE =
`manual trigger disabled: CRON_SECRET must be a secret of at least ${MIN_SECRET_CHARS} characters ` +
`(at most ${MAX_SECRET_CHARS}, with at least ${MIN_SECRET_DISTINCT_CHARS} distinct characters; a shorter value repeated is refused)`;
export function secretStrongEnough(value: string | undefined): value is string {
if (typeof value !== "string" || value.length > MAX_SECRET_CHARS || LONE_SURROGATE.test(value)) return false;
const chars = [...value];
if (chars.length < MIN_SECRET_CHARS || new Set(chars).size < MIN_SECRET_DISTINCT_CHARS) return false;
for (let period = 1; period <= value.length / 2; period++) {
if (value.slice(period) === value.slice(0, value.length - period)) return false;
}
return true;
}
export const maintainerTokenUsable = secretStrongEnough;
+8 -2
View File
@@ -155,8 +155,8 @@ describe("durable merch interest registration", () => {
describe("private merch interest list and deletion", () => {
async function signedIn(): Promise<{ auth: CommunityAgentEnv; headers: Record<string, string> }> {
const auth = { CURATED_KV: env.CURATED_KV, MAINTAINER_TOKEN: "local-maintainer-fixture" };
const sid = await createSession(auth.CURATED_KV);
const auth = { CURATED_KV: env.CURATED_KV, MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij" };
const sid = await createSession(auth.CURATED_KV, auth.MAINTAINER_TOKEN);
return { auth, headers: { Cookie: "mt_sid=" + sid } };
}
it("requires a real stored maintainer session for reading or deleting contacts", async () => {
@@ -165,6 +165,12 @@ describe("private merch interest list and deletion", () => {
expect(list).not.toHaveBeenCalled();
expect(remove).not.toHaveBeenCalled();
});
it.each(["short", "rotated-fixture-token-9876543210-zyxwvutsrq"])("refuses an existing session once the configured maintainer token changes to %s", async (replacement) => {
const { auth, headers } = await signedIn();
const response = await handleAdminMerchInterest(new Request("https://codewhale.net/api/admin/merch/interest", { headers }), env, { ...auth, MAINTAINER_TOKEN: replacement });
expect(response.status).toBe(401);
expect(list).not.toHaveBeenCalled();
});
it("paginates only the private prefix and deletes an opaque id with same-origin CSRF", async () => {
await handleMerchInterest(request(), env);
await handleMerchInterest(request({ ...input(), email: "[email protected]" }), env);
+1 -1
View File
@@ -138,7 +138,7 @@ export async function handleMerchInterest(request: Request, env?: MerchInterestE
}
async function requireAdmin(request: Request, auth: CommunityAgentEnv) {
const sid = request.headers.get("cookie")?.split(";").map(cookie => cookie.trim()).find(cookie => cookie.startsWith("mt_sid="))?.slice(7);
if (!auth.MAINTAINER_TOKEN || !await validateSession(auth.CURATED_KV, sid)) throw new InterestError(401, "unauthorized", "Maintainer sign-in is required.");
if (!await validateSession(auth.CURATED_KV, sid, auth.MAINTAINER_TOKEN)) throw new InterestError(401, "unauthorized", "Maintainer sign-in is required.");
}
export async function handleAdminMerchInterest(request: Request, env?: MerchInterestEnv, authEnv?: CommunityAgentEnv): Promise<Response> {
try {
+2 -2
View File
@@ -73,7 +73,7 @@ describe("public security boundaries", () => {
kv.values.set("agent:state:latest", JSON.stringify({ state: "running" }));
securityMocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
MAINTAINER_TOKEN: "configured",
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
});
const response = await adminPost(new Request("https://codewhale.net/api/admin/post", {
@@ -121,7 +121,7 @@ describe("public security boundaries", () => {
securityMocks.getAgentEnv.mockResolvedValue({
CURATED_KV: kv,
MAINTAINER_TOKEN: "configured",
MAINTAINER_TOKEN: "local-fixture-token-0123456789-abcdefghij",
MAINTAINER_GITHUB_PAT: "ghp_test",
GITHUB_REPO: "codewhale-hq/CodeWhale",
});