mirror of
https://github.com/bitbaum/orangecat.git
synced 2026-12-04 08:24:20 +01:00
dependabot/github_actions/github/codeql-action-4.39.3
4
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
483cb9e0d6 |
refactor: one definition per concern, and slugs that survive a non-Latin name (#1059)
* refactor(lib): one sanitizeApiKey and one escapeHtml, with tests Two helpers that touch security-relevant material had drifted into copies: - sanitizeApiKey existed five times (transcribe route, groq, openai-compat, openrouter, health probes). It stands between a pasted credential and an Authorization header, so it now has one definition in src/lib/api-key.ts and a test. health-probes wanted the "did anything get stripped?" answer, which is sanitizeApiKeyChecked over the same regex rather than a sixth one. - escapeHtml existed four times across the email templates — the injection guard between a user-supplied name and an inbox. It is now exported once from templates/layout.ts, which all three callers already import. No behaviour change: the regex and the replacement chain are byte-identical to what every copy did. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(utils): one home for the display formatters that had drifted Four helper names were declared in three or four files each. Consolidated, with every call site printing byte-for-byte what it printed before — pinned by __tests__/unit/lib/display-formatters.test.ts. - formatDate x4 -> src/utils/dates.ts, which already owned one of them. The three copies were three DIFFERENT formats, so the module gained the two it was missing rather than flattening them: formatDateLong ("July 22, 2026") for article datelines, and formatIsoDay for 'YYYY-MM-DD' strings. formatIsoDay keeps the changelog's deliberate property of never building a Date: a calendar date has no timezone, and `new Date('2026-07-22')` is UTC midnight, which renders the day before west of Greenwich and renders it differently on the server than in the browser. - formatTimestamp x3 (identical) -> formatDateTimeOrDash in utils/locale.ts, next to the formatDateTime it wrapped. The two row components took it as a prop from their parent; they import it instead, so the prop is gone. - formatCountdown x3 -> src/utils/countdown.ts. These were not one helper that drifted but three formats sharing a name — 45 seconds read as "45s", "1m" or "0:45" depending on which file you imported from. They keep their three behaviours under names that say what they print. - readJson + errorMessage x3 in the browser payment clients -> the unwrapApiResponse that src/lib/api/client-response.ts already exports, and whose docblock warns about exactly these hand-rolled copies drifting. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * fix(slug): slugify transliterates, so a non-ASCII name is not deleted `slugify()` filtered to ASCII, which does not mean "strip accents" — it means "delete every letter that is not ASCII". `Café Genève` became `caf-genve`, `Grüße` became `gre`, and a Cyrillic or Japanese name produced the EMPTY STRING. Under a unique constraint an empty slug means the second such record cannot be saved at all, and the first one is addressed by a slug that identifies nobody — walked live on 2026-09-11, `Марина` became /profiles/someone and @someone. That was already known and already fixed, but in domain/profileClaims only: it kept its own `transliterate` and wrapped the broken slugify with it. Group creation, the Cat's organization handler and the entity create form all still went through the unwrapped path. So the transliteration moves into `slugify()` itself — German digraphs first (ß has no decomposition and would otherwise vanish), then NFKD plus a combining-mark strip for everything that decomposes, then a Cyrillic table for the script that does not. claimSlugFor keeps only what is specific to a claim: the person-<random> fallback. Also in this commit, same concern: - groups' `generateSlug` was `(name) => slugify(name)` — an alias, deleted; its one caller calls slugify, with a 'group' fallback so an unslugabble name cannot become the empty slug that ensureUniqueSlug would then extend. - slugify with randomSuffix no longer returns a slug starting with a dash when the base is empty. - scripts/cli/create-entity.ts deleted: a dead twin of create-entity.js, which is what `pnpm run create-entity` actually runs, carrying a third generateSlug. knip already listed it as unused. - formatAmount: the real implementation inside <CurrencyDisplay> moves to services/currency/formatting.ts as formatAmountSuffixed. Output is unchanged — it is deliberately not formatCurrency(), which prefixes BTC with ₿ where every card in the app suffixes the ticker. Tests: __tests__/unit/lib/slugify.test.ts covers the accented, German and Cyrillic cases plus the ASCII behaviour that must not have moved. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor: say the repeated blocks once — chat types, footer, Esplora readers Three places where the same thing was written out two to five times. - The Cat's tool-call vocabulary (ToolCallResultRef, ToolCallEvent, PrefillProposal) was defined twice: once by the pipeline that emits it and once by the panel that renders it, 55 lines of discriminated union that had to agree with nothing making them. The panel now re-exports the service's types. Type-only, so nothing enters the bundle. The two copies had already drifted: the service carries `handle?` on a result ref (the citation handle the UI needs to link the right source) and types `entityType` as the entity union rather than `string`. - <Footer> wrote out the same seventeen-line link column five times, and only two of the five carried the external-link branch — so which columns could hold an external link was an accident of which had been copied last. One <FooterColumn>. Renders identically: only `ecosystem` has external items today. - The Bitcoin service listed mempool.space and blockstream.info with byte-identical processBalance and processTransactions, 60 lines each. They both serve the Esplora API, so there is one reader for each now — one place for the satoshi arithmetic instead of one place to fix it and another to leave wrong. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor(timeline): the feed envelope is written once, not fourteen times Six feed functions across four files each spelled out the same three things by hand: the page window, the success envelope, and — twice per function, once for "no rows" and once for the catch — the empty envelope. Twenty copies of the same twenty-line object literal, which is why userFeeds.ts was the most-duplicated file in the repo (9 clones, 184 duplicated lines). The cost was not the lines. A field added to TimelineFeedResponse had to be remembered in all twenty places, and the ones that forgot it still compiled; `hasNext` was computed from `offset + limit` in fourteen separate expressions, any one of which could be edited alone. queries/feed-shape.ts now owns pageWindow(), feedResponse() and emptyFeed(). What differs between the feeds — which rows they fetch, and the RPC or view they fetch them from — stays in each file, which is the part that was ever worth reading. Two behaviours that looked accidental were kept deliberately and documented rather than "tidied": - emptyFeed echoes the requested limit WITHOUT clamping it to MAX_PAGE_SIZE. There are no rows for it to bound, and three call sites did exactly this. - emptyFeed with no pagination reports page 1: the early returns that never read their arguments (no session, follows nobody) did that, and the numbers are what the UI paginates on. userFeeds.ts 407 -> 281 lines, profileFeeds 87 -> 54, projectFeeds 122 -> 89, communityFeeds 94 -> 61, plus 95 shared. Existing timeline tests pass unchanged (62 files, 601 tests). Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * refactor: extract the preludes that PUT/DELETE and five seed scripts repeated Five more places where the same block was written out twice or five times. - entityCrudHandler's PUT and DELETE each carried the same thirty lines: authenticate, load the row, run the ownership check. Now authorizeEntityMutation(), taking the verb and the optional per-entity access check. A change to the 401, the not-found copy or the ownership rule could previously land on update and not on delete — and delete is the half where getting it wrong is permanent. - /api/projects/[id]/favorite: POST and DELETE both throttled the write, loaded the project and looked up the existing favourite. One helper in lib/api/projectFavorites.ts. It is called rateLimitedFavoriteContext for a reason, spelled out in its docblock: api-route-guards.test.ts reads route SOURCES for evidence of a write quota, and a helper called loadX would have hidden that evidence behind an import — the gate goes quiet while the protection is still there, which is the shape of a gate that later goes quiet when it is not. - messaging/api-helpers.server.ts declared ActorRow, GroupMembershipRow and GroupActorRow twice, 27 lines apart-but-identical. TypeScript merges identical interfaces, so it compiled and nobody noticed. - The group-activity and re-engagement email templates each wired their config into emailLayout + emailPlainText by hand. One renderEmail() in layout.ts. - Five owner-gated operational scripts opened with the same thirty lines: load .env.local, read the service-role key, refuse without ORANGECAT_OWNER_SEED=1, build an admin client. These run against the LIVE database with a key that bypasses RLS, so that gate is the only thing between a stray `npx tsx` and production — not a check to keep in five versions. scripts/lib/owner-gate.ts owns it; the client it returns carries its own supabaseUrl so the two scripts that print which database they are about to write to still can. Also: webhook signature verification stays duplicated between the app and packages/sdk, because the SDK ships to customers and cannot import from src/, and the app should not take a build dependency on a customer-facing package. What is new is that the copy can no longer drift silently: __tests__/unit/services/webhook-signature-parity.test.ts drives BOTH through the same vectors — replay, forged body, bumped timestamp, wrong secret, truncated and non-hex signatures, multi-signature rotation — and fails if they ever disagree. Both files now say so at the top. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 * test(slug): the assertions that pinned the limitation the fix removes #1051 landed NFKD for slugify while this branch was in flight, and its tests pinned what NFKD alone cannot do: `slugify('Марина') === ''`, and an article titled in Cyrillic slugging to the literal word "article". Both were true, both were documented as "callers transliterate first" — and this branch moves that transliteration into slugify, so neither is true any more. Updated rather than deleted, because the cases are the interesting ones: they now assert 'marina' and 'shcherbakov', plus the sharp s that NFKD deletes ('Straße' → 'strasse', not 'strae'). The fallback assertion survives where it still applies — a title with no letters at all. The two slug test files are merged into the one that came with #1051; keeping a second file for the same function would have been the thing this branch is about. Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012KAn51JHFcTrPeCjZDGXM8 --------- Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com> |
||
|
|
7b8b57bd4e |
feat(cat): the Cat proposes; Solon disposes — propose_governance_change (#660)
* feat(cat): the Cat proposes; Solon disposes — propose_governance_change OC3 of the Solon v1 plan: the Cat can now file a change to its own platform spending leash as a Solon governance proposal — and that is ALL it can do. The action is high-risk + always-confirmed (a human okays the filing before anything leaves the system), and the change only ever activates if the Bitcoin-signed Solon vote approves it and decision-verify re-verifies every signature locally (#657). - cat-actions: propose_governance_change (organization, high risk, requiresConfirmation) — flows through cat_pending_actions and cat_permissions like the other 49 actions - handlers/governance.ts: validate ceilings (per-action <= daily) → record a local draft version (decision-verify attaches the approved decision to it by content hash) → sign the proposer attestation with CAT_SOLON_PRIVKEY (the Cat's own key; user keys never exist here) → POST to Solon with the agent API key → store solon_proposal_id; Solon refusal marks the draft rejected so nothing lingers half-open. Env-gated, inert unconfigured. - bitcoin-message.ts grows the signing side (one key only) + solonProposalMessage(), byte-identical to Solon's proposalMessage() (golden-pinned) Prompt budget: description/params cut to fit the hard 54.6k static budget; the Groq-remaining ratchet raised 3,400 -> 3,650 with the argued reason in place (new enabled capability), per the mechanism's own convention. Test infra: jsdom suites get Node's TextEncoder/TextDecoder polyfill — server-side crypto modules are now importable from any suite. Tests (6 new): golden proposal-message strings, sign→verify roundtrip on the fixed key, unconfigured refusal (zero DB touches), ceiling validation, happy path (draft recorded, signature in the POST body verifies, proposal id stored), Solon-refusal marks draft rejected. verify green: 2153 tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * feat(governance): cast-vote script — the Cat's operator-run voting edge Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
318d5f1ed0 |
feat(governance): the decision edge — verify Solon votes locally, then obey them (#657)
* feat(governance): the decision edge — verify Solon votes locally, then obey them OC2 of the Solon v1 plan: the machinery that turns a finalized Solon vote into an activated allocation policy, with every claim re-established locally. "Verifiable, not trusted" is now enforced in code: - solon_trusted_keys: the honest trust anchor — a small, operator-pinned set of Solon member addresses/keys (scripts/solon/pin-trusted-keys.ts, owner-gated, pins from Solon's public roster and refuses non-ACTIVE members). A vote from an unpinned address refuses the whole decision. - src/services/solon/bitcoin-message.ts: OrangeCat's own Bitcoin signed-message verifier (BIP137 headers 27-42, P2PKH/P2WPKH/P2SH-P2WPKH candidate matching) — pinned byte-for-byte to Solon's signer by a fixed test vector generated there. The canonical vote message is re-derived, not read from the document, binding each vote to session + choice + voter. - src/services/solon/decision-verify.ts: fetches the decision document, re-verifies every signature against pinned keys with PINNED weights (the document's weights are never consulted), recomputes tally, quorum (against the pinned electorate) and threshold, re-hashes the content, and only then records the version with verified_at and activates it via activateVersion. Activation is automatic after verification — the signed vote IS the legitimation; a veto after the vote would make voting decorative. - POST /api/solon/events: HMAC webhook receiver (timing-safe, env-gated, inert without SOLON_WEBHOOK_SECRET). Doorbell, not courier: the payload only names the decision; verification fetches everything itself. - GET /api/cron/solon-sync: daily reconciliation over Solon's public proposals API — heals missed webhooks, grants no verification shortcuts. Test-infra enablers (never-twice): jest can now run node-environment suites (jest.setup.ts browser-global touches made conditional) and transform the ESM-only @noble/@scure packages (scoped js transform). Route-guard allowlists document why the webhook is HMAC-authed and unthrottled. Tests (13 new): the pinned cross-repo signature vector incl. the Electrum segwit quirk, canonical message byte-equality, and the refusal gauntlet — unpinned voter, tampered content, unbound session, empty votes, below-quorum, non-APPROVED outcomes (no DB writes) — plus the full happy path asserting verified_at is written and the version activates. verify green: 2143 tests. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> * fix(governance): a webhook-supplied decision id must prove it is a UUID before it touches a URL CodeQL flagged the fetch in decision-verify as request forgery: decision_id arrives from an HMAC-verified but still external payload and flowed into the request path unvalidated. Gate verifyAndApplyDecision on a strict UUID match (refused before any DB or network use) and encode the path segment. Test vector re-signed with a UUID session id; refusal test added. Co-Authored-By: Claude Fable 5 <noreply@anthropic.com> --------- Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com> Co-authored-by: Claude Fable 5 <noreply@anthropic.com> |
||
|
|
00780f5268 |
feat(governance): the Cat's platform leash becomes a Solon-governed artifact (#656)
OC0 of the Solon v1 plan: platform-wide limits on the Cat's spending get a
versioned, governed home — and changing them now has exactly one legitimate
path: a Bitcoin-signed Solon vote, re-verified locally.
- allocation_policies table (service-role-only RLS): versioned policy content
with content_hash (sha256 of canonical JSON — what Solon voters sign over),
status draft|active|superseded|rejected with a one-active-per-key partial
unique index, solon_proposal_id/solon_decision_id refs, decision_document
stored verbatim, and verified_at — set only by decision-verify (OC2) after
local signature re-verification. Idempotent DDL; already applied + recorded
on the box (needed to regenerate database.generated.ts), so deploy replays
it as a no-op.
- src/config/solon.ts — the ONE place OrangeCat knows its governance layer:
Solon org id/slug, policy key, and GENESIS_ALLOCATION_POLICY byte-identical
to Solon's seeded v1 so both version chains agree from the start.
- src/services/solon/canonical.ts — canonical JSON + contentHashOf, the
cross-repo hashing contract, pinned by golden-hash tests to the same values
as Solon's own tests (drift breaks CI, not prod verification).
- src/services/solon/allocation-policy.ts — getActiveAllocationPolicy (null
on missing/error: governance being unreachable must not brick payments) and
activateVersion, which refuses any row without verified_at + decision id.
- Enforcement at the single spend-cap choke point (checkSpendCaps): the
platform per-action ceiling and the platform-wide DAILY ceiling (all users
combined, derived from cat_action_log like the per-user budget — no new
bookkeeping state) apply as an additional min() over per-user caps. Denial
reasons name the policy version and point at /governance.
- Public record: GET /api/v1/governance + /governance page — every version,
its hash, and the Solon decision that legitimated it; the genesis version
is labeled bootstrap ("first change requires a Solon vote").
- scripts/solon/seed-genesis-policy.ts — owner-gated, idempotent, refuses to
overwrite history on hash mismatch. Already run against prod: v1 active,
content_hash 7778223670a5de2c…, second run verified as a no-op.
Tests: golden hashes (cross-repo pin incl. genesis), activateVersion refusal
matrix, platform ceiling enforcement (per-action, platform-daily across
users, stricter-of-user-and-platform, pre-genesis no-op). verify green:
2130 tests.
Co-authored-by: Georgy Butaev <41178744+g-but@users.noreply.github.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
|